lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 8ae7bb6746c6bf8ba546f83884614959f846e6c4 | 0 | ivy-supplements/bpm-beans,ivy-supplements/bpm-beans | package com.axonivy.ivy.process.element.blockchain.exec;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.math.BigInteger;
import java.util.Map;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import com.axonivy.ivy.process.element.blockchain.EthereumProperties;
import ch.ivyteam.di.restricted.DiCore;
import ch.ivyteam.ivy.application.IProcessModelVersion;
import ch.ivyteam.ivy.project.IvyProjectNavigationUtil;
import ch.ivyteam.ivy.security.exec.Sudo;
import ch.ivyteam.log.Logger;
import ch.ivyteam.util.IvyRuntimeException;
public final class EthereumExecutor
{
private static final BigInteger DEFAULT_GAS_PRIZE = BigInteger.valueOf(40000000000l);
private static final BigInteger DEFAULT_GAS_LIMIT = BigInteger.valueOf(1500000l);
private static final Logger LOGGER = Logger.getLogger(EthereumExecutor.class);
Contract ethContract;
Method contractMethod;
public EthereumExecutor(String contract, String function, Map<String, String> properties)
{
initialize(contract, function, properties);
}
private void initialize(String contract, String function, Map<String, String> properties)
{
String credentialsFile = properties.get(EthereumProperties.CREDENTIALS);
String password = properties.get(EthereumProperties.PASSWORD);
String url = properties.get(EthereumProperties.NETWORK_URL);
String contractAddress = properties.get(EthereumProperties.CONTRACT_ADDRESS);
if (StringUtils.isEmpty(contract) || StringUtils.isEmpty(function) || StringUtils.isEmpty(credentialsFile)
|| StringUtils.isEmpty(password) || StringUtils.isEmpty(url))
{
throw new IvyRuntimeException(
"Contract class, function name, Credentials, password and network URL are mandatory parameters.");
}
ethContract = loadOrDeployContract(contract, url, contractAddress, credentialsFile, password);
contractMethod = loadMethod(function, ethContract);
}
public RemoteCall<?> execute(Object[] callParams)
{
try
{
return (RemoteCall<?>) contractMethod.invoke(ethContract, callParams);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
{
throw new IvyRuntimeException("Could not execute method " + contractMethod.getName(), ex);
}
}
private Method loadMethod(String function, Contract contract)
{
Method[] methods = contract.getClass().getDeclaredMethods();
Method chosenMethod = null;
for (Method method : methods)
{
if (method.toString().equals(function))
{
chosenMethod = method;
break;
}
}
return chosenMethod;
}
private Web3j buildWeb3j(String url)
{
HttpService httpService = new HttpService(url);
return Web3j.build(httpService);
}
private Credentials loadCredentials(String passwd, String source) throws Exception
{
return WalletUtils.loadCredentials(passwd, source);
}
@SuppressWarnings("unchecked")
private Contract loadOrDeployContract(String clazz, String url, String contractAddress, String file, String passwd)
{
Web3j web3 = buildWeb3j(url);
Method accessMethod;
try
{
Credentials credentials = loadCredentials(passwd, file);
Class<? extends Contract> contractClass = (Class<? extends Contract>) loadClassWithCurrentClassloader(clazz);
if (StringUtils.isEmpty(contractAddress))
{
accessMethod = contractClass.getMethod("deploy", Web3j.class, Credentials.class, BigInteger.class, BigInteger.class);
Contract contract = (Contract) ((RemoteCall<?>) accessMethod.invoke(null, web3, credentials, DEFAULT_GAS_PRIZE, DEFAULT_GAS_LIMIT)).send();
if(!"0x1".equals(contract.getTransactionReceipt().get().getStatus()))
{
LOGGER.error("Could not deploy contract of class " + clazz + "; TxReceipt=" + contract.getTransactionReceipt().get());
}
LOGGER.info("Deployed new contract " + contractClass.getName() + " to address " + contract.getContractAddress());
return contract;
}
accessMethod = contractClass.getMethod("load", String.class, Web3j.class, Credentials.class, BigInteger.class, BigInteger.class);
return (Contract) accessMethod.invoke(null, contractAddress, web3, credentials, DEFAULT_GAS_PRIZE, DEFAULT_GAS_LIMIT);
}
catch (Exception ex)
{
throw new IvyRuntimeException("Could not get contract of class " + clazz, ex);
}
}
private static Class<?> loadClassWithCurrentClassloader(String fullyQualifiedClassName) throws ClassNotFoundException
{
try
{
return EthereumExecutor.class.getClassLoader().loadClass(fullyQualifiedClassName);
}
catch (ClassNotFoundException ex)
{
return loadClassWithProjectClassloader(fullyQualifiedClassName);
}
}
private static Class<?> loadClassWithProjectClassloader(String fullyQualifiedClassName) throws ClassNotFoundException
{
IProcessModelVersion pmv = DiCore.getGlobalInjector().getInstance(IProcessModelVersion.class);
ClassLoader projectClassLoader = Sudo.exec(() -> IvyProjectNavigationUtil.getIvyProject(pmv.getProject()).getProjectClassLoader());
return ClassUtils.getClass(projectClassLoader, fullyQualifiedClassName, false);
}
public Parameter[] getMethodParams()
{
return contractMethod.getParameters();
}
}
| blockchain-beans/src/com/axonivy/ivy/process/element/blockchain/exec/EthereumExecutor.java | package com.axonivy.ivy.process.element.blockchain.exec;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.math.BigInteger;
import java.util.Map;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import com.axonivy.ivy.process.element.blockchain.EthereumProperties;
import ch.ivyteam.di.restricted.DiCore;
import ch.ivyteam.ivy.application.IProcessModelVersion;
import ch.ivyteam.ivy.project.IvyProjectNavigationUtil;
import ch.ivyteam.ivy.security.exec.Sudo;
import ch.ivyteam.log.Logger;
import ch.ivyteam.util.IvyRuntimeException;
public final class EthereumExecutor
{
private static final BigInteger DEFAULT_GAS_PRIZE = BigInteger.valueOf(40000000000l);
private static final BigInteger DEFAULT_GAS_LIMIT = BigInteger.valueOf(1500000l);
private static final Logger LOGGER = Logger.getLogger(EthereumExecutor.class);
Contract ethContract;
Method contractMethod;
public EthereumExecutor(String contract, String function, Map<String, String> properties)
{
initialize(contract, function, properties);
}
private void initialize(String contract, String function, Map<String, String> properties)
{
String credentialsFile = properties.get(EthereumProperties.CREDENTIALS);
String password = properties.get(EthereumProperties.PASSWORD);
String url = properties.get(EthereumProperties.NETWORK_URL);
String contractAddress = properties.get(EthereumProperties.CONTRACT_ADDRESS);
if (StringUtils.isEmpty(credentialsFile) || StringUtils.isEmpty(password) || StringUtils.isEmpty(url))
{
throw new IvyRuntimeException("Credentials, password and network URL are mandatory parameters.");
}
ethContract = loadOrDeployContract(contract, url, contractAddress, credentialsFile, password);
contractMethod = loadMethod(function, ethContract);
}
public RemoteCall<?> execute(Object[] callParams)
{
try
{
return (RemoteCall<?>) contractMethod.invoke(ethContract, callParams);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
{
throw new IvyRuntimeException("Could not execute method " + contractMethod.getName(), ex);
}
}
private Method loadMethod(String function, Contract contract)
{
Method[] methods = contract.getClass().getDeclaredMethods();
Method chosenMethod = null;
for (Method method : methods)
{
if (method.toString().equals(function))
{
chosenMethod = method;
break;
}
}
return chosenMethod;
}
private Web3j buildWeb3j(String url)
{
HttpService httpService = new HttpService(url);
return Web3j.build(httpService);
}
private Credentials loadCredentials(String passwd, String source) throws Exception
{
return WalletUtils.loadCredentials(passwd, source);
}
@SuppressWarnings("unchecked")
private Contract loadOrDeployContract(String clazz, String url, String contractAddress, String file, String passwd)
{
Web3j web3 = buildWeb3j(url);
Method accessMethod;
try
{
Credentials credentials = loadCredentials(passwd, file);
Class<? extends Contract> contractClass = (Class<? extends Contract>) loadClassWithCurrentClassloader(clazz);
if (StringUtils.isEmpty(contractAddress))
{
accessMethod = contractClass.getMethod("deploy", Web3j.class, Credentials.class, BigInteger.class, BigInteger.class);
Contract contract = (Contract) ((RemoteCall<?>) accessMethod.invoke(null, web3, credentials, DEFAULT_GAS_PRIZE, DEFAULT_GAS_LIMIT)).send();
if(!"0x1".equals(contract.getTransactionReceipt().get().getStatus()))
{
LOGGER.error("Could not deploy contract of class " + clazz + "; TxReceipt=" + contract.getTransactionReceipt().get());
}
LOGGER.info("Deployed new contract " + contractClass.getName() + " to address " + contract.getContractAddress());
return contract;
}
accessMethod = contractClass.getMethod("load", String.class, Web3j.class, Credentials.class, BigInteger.class, BigInteger.class);
return (Contract) accessMethod.invoke(null, contractAddress, web3, credentials, DEFAULT_GAS_PRIZE, DEFAULT_GAS_LIMIT);
}
catch (Exception ex)
{
throw new IvyRuntimeException("Could not get contract of class " + clazz, ex);
}
}
private static Class<?> loadClassWithCurrentClassloader(String fullyQualifiedClassName) throws ClassNotFoundException
{
try
{
return EthereumExecutor.class.getClassLoader().loadClass(fullyQualifiedClassName);
}
catch (ClassNotFoundException ex)
{
return loadClassWithProjectClassloader(fullyQualifiedClassName);
}
}
private static Class<?> loadClassWithProjectClassloader(String fullyQualifiedClassName) throws ClassNotFoundException
{
IProcessModelVersion pmv = DiCore.getGlobalInjector().getInstance(IProcessModelVersion.class);
ClassLoader projectClassLoader = Sudo.exec(() -> IvyProjectNavigationUtil.getIvyProject(pmv.getProject()).getProjectClassLoader());
return ClassUtils.getClass(projectClassLoader, fullyQualifiedClassName, false);
}
public Parameter[] getMethodParams()
{
return contractMethod.getParameters();
}
}
| Added additional check for contract class and method. | blockchain-beans/src/com/axonivy/ivy/process/element/blockchain/exec/EthereumExecutor.java | Added additional check for contract class and method. |
|
Java | apache-2.0 | 71bd21a373c8e36c3316d5040035f6dd4a3c622e | 0 | Talend/components,Talend/components | package org.talend.components.salesforce.runtime;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class BulkResult {
Map<String, Object> values;
public BulkResult() {
values = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
}
public void setValue(String field, Object vlaue) {
values.put(field, vlaue);
}
public Object getValue(String fieldName) {
return values.get(fieldName);
}
public void copyValues(BulkResult result) {
if (result == null) {
return;
} else {
for (String key : result.values.keySet()) {
Object value = result.values.get(key);
if ("#N/A".equals(value)) {
value = null;
}
values.put(key, value);
}
}
}
} | components/components-salesforce/components-salesforce-runtime/src/main/java/org/talend/components/salesforce/runtime/BulkResult.java | package org.talend.components.salesforce.runtime;
import java.util.HashMap;
import java.util.Map;
public class BulkResult {
Map<String, Object> values;
public BulkResult() {
values = new HashMap<String, Object>();
}
public void setValue(String field, Object vlaue) {
values.put(field, vlaue);
}
public Object getValue(String fieldName) {
return values.get(fieldName);
}
public void copyValues(BulkResult result) {
if (result == null) {
return;
} else {
for (String key : result.values.keySet()) {
Object value = result.values.get(key);
if ("#N/A".equals(value)) {
value = null;
}
values.put(key, value);
}
}
}
} | fix(TDI-39501): make Bulk SOQL in salesforce case insensitive. (#985)
Salesforce is case insensitive. | components/components-salesforce/components-salesforce-runtime/src/main/java/org/talend/components/salesforce/runtime/BulkResult.java | fix(TDI-39501): make Bulk SOQL in salesforce case insensitive. (#985) |
|
Java | apache-2.0 | 4bfe5f759018298f45c67080a77279f700212348 | 0 | wso2/product-apim,dhanuka84/product-apim,dewmini/product-apim,nu1silva/product-apim,hevayo/product-apim,jaadds/product-apim,hevayo/product-apim,thilinicooray/product-apim,chamilaadhi/product-apim,thilinicooray/product-apim,dhanuka84/product-apim,nu1silva/product-apim,nu1silva/product-apim,pradeepmurugesan/product-apim,jaadds/product-apim,hevayo/product-apim,dhanuka84/product-apim,chamilaadhi/product-apim,lakmali/product-apim,pradeepmurugesan/product-apim,tharikaGitHub/product-apim,ChamNDeSilva/product-apim,nu1silva/product-apim,pradeepmurugesan/product-apim,dewmini/product-apim,irhamiqbal/product-apim,dhanuka84/product-apim,tharikaGitHub/product-apim,chamilaadhi/product-apim,rswijesena/product-apim,pradeepmurugesan/product-apim,chamilaadhi/product-apim,nu1silva/product-apim,chamilaadhi/product-apim,dewmini/product-apim,tharikaGitHub/product-apim,jaadds/product-apim,abimarank/product-apim,irhamiqbal/product-apim,tharikaGitHub/product-apim,sambaheerathan/product-apim,jaadds/product-apim,abimarank/product-apim,rswijesena/product-apim,irhamiqbal/product-apim,thilinicooray/product-apim,sambaheerathan/product-apim,wso2/product-apim,wso2/product-apim,dewmini/product-apim,hevayo/product-apim,wso2/product-apim,lakmali/product-apim,tharikaGitHub/product-apim,ChamNDeSilva/product-apim,wso2/product-apim,dewmini/product-apim,irhamiqbal/product-apim,tharindu1st/product-apim,thilinicooray/product-apim | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.apimgt.migration.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.migration.APIMigrationException;
import org.wso2.carbon.apimgt.migration.client.internal.ServiceHolder;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class StatDBUtil {
private static volatile DataSource dataSource = null;
private static final String DATA_SOURCE_NAME = "jdbc/WSO2AM_STATS_DB";
private static final String TABLE_API_DESTINATION_SUMMARY = "API_DESTINATION_SUMMARY";
private static final String TABLE_API_FAULT_SUMMARY = "API_FAULT_SUMMARY";
private static final String TABLE_API_REQUEST_SUMMARY = "API_REQUEST_SUMMARY";
private static final String TABLE_API_RESOURCE_USAGE_SUMMARY = "API_Resource_USAGE_SUMMARY";
private static final String TABLE_API_VERSION_USAGE_SUMMARY = "API_VERSION_USAGE_SUMMARY";
private static final Log log = LogFactory.getLog(StatDBUtil.class);
public static void initialize() throws APIMigrationException {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME);
} catch (NamingException e) {
throw new APIMigrationException("Error while looking up the data " +
"source: " + DATA_SOURCE_NAME, e);
}
}
public static void updateContext() throws APIMigrationException {
if (dataSource == null) {
throw new APIMigrationException("Stats Data source is not configured properly.");
}
updateResponseSummaryTable();
executeSQL(getCommonUpdateSQL(TABLE_API_DESTINATION_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_FAULT_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_REQUEST_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_RESOURCE_USAGE_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_VERSION_USAGE_SUMMARY));
}
private static void updateResponseSummaryTable() {
Connection connection = null;
Statement statement = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
String sql = "SELECT CONTEXT, VERSION, API_VERSION FROM API_REQUEST_SUMMARY GROUP BY CONTEXT, VERSION, API_VERSION";
connection = dataSource.getConnection();
statement = connection.createStatement();
connection.setAutoCommit(false);
statement.setFetchSize(50);
resultSet = statement.executeQuery(sql);
preparedStatement = connection.prepareStatement("UPDATE API_RESPONSE_SUMMARY SET CONTEXT = concat(?, '/', ?) " +
"WHERE CONTEXT = ? AND API_VERSION = ?");
while (resultSet.next()) {
final String context = resultSet.getString("CONTEXT");
final String version = resultSet.getString("VERSION");
if (!context.endsWith('/' + version)) {
preparedStatement.setString(1, context);
preparedStatement.setString(2, version);
preparedStatement.setString(3, context);
preparedStatement.setString(4, resultSet.getString("API_VERSION"));
preparedStatement.addBatch();
}
}
preparedStatement.executeBatch();
connection.commit();
} catch (SQLException e) {
log.error("SQLException when updating API_RESPONSE_SUMMARY table", e);
}
finally {
try {
if (preparedStatement != null) preparedStatement.close();
if (statement != null) statement.close();
if (resultSet != null) resultSet.close();
if (connection != null) connection.close();
}
catch (SQLException e) {
log.error("SQLException when closing resource", e);
}
}
}
private static String getCommonUpdateSQL(String table) {
return "UPDATE " + table + " SET CONTEXT = concat(CONTEXT,'/',VERSION) " +
"WHERE CONTEXT NOT LIKE concat('%', VERSION)";
}
private static void executeSQL(String sql) {
Connection connection = null;
Statement statement = null;
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
connection.setAutoCommit(false);
statement.execute(sql);
connection.commit();
} catch (SQLException e) {
log.error("SQLException when executing: " + sql, e);
}
finally {
try {
if (statement != null) { statement.close(); }
if (connection != null) { connection.close(); }
} catch (SQLException e) {
log.error("SQLException when closing resource", e);
}
}
}
public static boolean isTokenEncryptionEnabled() {
APIManagerConfiguration config = ServiceHolder.getAPIManagerConfigurationService().getAPIManagerConfiguration();
return Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_ENCRYPT_TOKENS));
}
}
| modules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/util/StatDBUtil.java | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.apimgt.migration.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.migration.APIMigrationException;
import org.wso2.carbon.apimgt.migration.client.internal.ServiceHolder;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class StatDBUtil {
private static volatile DataSource dataSource = null;
private static final String DATA_SOURCE_NAME = "jdbc/WSO2AM_STATS_DB";
private static final String TABLE_API_DESTINATION_SUMMARY = "API_DESTINATION_SUMMARY";
private static final String TABLE_API_FAULT_SUMMARY = "API_FAULT_SUMMARY";
private static final String TABLE_API_REQUEST_SUMMARY = "API_REQUEST_SUMMARY";
private static final String TABLE_API_RESOURCE_USAGE_SUMMARY = "API_Resource_USAGE_SUMMARY";
private static final String TABLE_API_VERSION_USAGE_SUMMARY = "API_VERSION_USAGE_SUMMARY";
private static final Log log = LogFactory.getLog(StatDBUtil.class);
public static void initialize() throws APIMigrationException {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME);
} catch (NamingException e) {
throw new APIMigrationException("Error while looking up the data " +
"source: " + DATA_SOURCE_NAME, e);
}
}
public static void updateContext() throws APIMigrationException {
if (dataSource == null) {
throw new APIMigrationException("Stats Data source is not configured properly.");
}
String responseSummarySQL = "UPDATE API_RESPONSE_SUMMARY " +
"SET CONTEXT = concat(API_RESPONSE_SUMMARY.CONTEXT,'/'," +
"(SELECT DISTINCT(VERSION) FROM WSO2AM_STATS_DB.API_REQUEST_SUMMARY WHERE CONTEXT NOT LIKE concat('%', VERSION))) " +
"WHERE API_VERSION = (SELECT DISTINCT(API_VERSION) FROM WSO2AM_STATS_DB.API_REQUEST_SUMMARY WHERE CONTEXT NOT LIKE concat('%', VERSION))";
executeSQL(responseSummarySQL);
executeSQL(getCommonUpdateSQL(TABLE_API_DESTINATION_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_FAULT_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_REQUEST_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_RESOURCE_USAGE_SUMMARY));
executeSQL(getCommonUpdateSQL(TABLE_API_VERSION_USAGE_SUMMARY));
}
private static String getCommonUpdateSQL(String table) {
return "UPDATE " + table + " SET CONTEXT = concat(CONTEXT,'/',VERSION) " +
"WHERE CONTEXT NOT LIKE concat('%', VERSION)";
}
private static void executeSQL(String sql) {
Connection connection = null;
Statement statement = null;
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
connection.setAutoCommit(false);
statement.execute(sql);
connection.commit();
} catch (SQLException e) {
log.error("SQLException when executing: " + sql, e);
}
finally {
try {
if (statement != null) { statement.close(); }
if (connection != null) { connection.close(); }
} catch (SQLException e) {
log.error("SQLException when closing resource", e);
}
}
}
public static boolean isTokenEncryptionEnabled() {
APIManagerConfiguration config = ServiceHolder.getAPIManagerConfigurationService().getAPIManagerConfiguration();
return Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_KEY_VALIDATOR_ENCRYPT_TOKENS));
}
}
| Fix for migrating API_REQUEST_SUMMARY stat table
| modules/distribution/resources/migration/wso2-api-migration-client/src/main/java/org/wso2/carbon/apimgt/migration/util/StatDBUtil.java | Fix for migrating API_REQUEST_SUMMARY stat table |
|
Java | apache-2.0 | 39da45adf45746f6aea3916c0810d159a18f2e8d | 0 | googleinterns/step230-2020,googleinterns/step230-2020,googleinterns/step230-2020 | package com.google.sps.image;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public final class ImageSelection {
private final Set<String> keywords;
private static final String USER_AGENT = "Mozilla/5.0 (X11; CrOS x86_64 13099.85.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.110 Safari/537.36";
private static final int MAX_NO_LETTERS = 50;
private static final int MAX_NO_KEYWORDS = 10;
public ImageSelection(Set<String> keywords) {
this.keywords = keywords;
}
private String addFilter(String url, String filter) {
return url + filter;
}
/**
* @return URL where the search will be made.
*/
public String generateSearchUrl() {
int addedWords = 0;
int addedLetters = 0;
String bingUrl = "https://www.bing.com/images/search?q=";
for (String word : keywords) {
addedLetters += word.length();
if (addedLetters >= MAX_NO_LETTERS) {
break;
}
bingUrl = bingUrl + "+" + word.replaceAll(" ", "+");
++addedWords;
if (addedWords >= MAX_NO_KEYWORDS) {
break;
}
}
// Free to share and use commercially license
final String licenseFilter = "&qft=+filterui:license-L2_L3_L4";
final String bingQueryParam = "&qs=HS&form=QBIR&scope=images&sp=-1&pq=hap&sc=8-3&cvid=44CA4B129FEF4B93B6F764BD083213D3&first=1&scenario=ImageBasicHover";
final String safeSearchFilter = "&adlt=strict";
bingUrl = addFilter(bingUrl, bingQueryParam);
bingUrl = addFilter(bingUrl, licenseFilter);
bingUrl = addFilter(bingUrl, safeSearchFilter);
return bingUrl;
}
/**
* This is an endpoint. Call this function to get a relevant image.
*
* @return URL of the first image scraped from Bing Image Search.
* @exception IOException if Bing doesn't map any image to the keywords.
*/
public String getBestImage() throws IOException {
List<String> imgSrc = new ArrayList<>();
Document doc = Jsoup.connect(generateSearchUrl()).userAgent(USER_AGENT).get();
Elements elements = doc.getElementsByTag("img");
for (Element element : elements) {
imgSrc.add(element.attr("abs:data-src"));
}
// Return first relevant image
for (String imageUrl : imgSrc) {
if (!imageUrl.isEmpty()) {
return imageUrl;
}
}
/**
* TODO: Multiple image selection.
* Relying on a single image is not enough.
* We must provide multiple images to the user.
*/
return "";
}
}
| src/main/java/com/google/sps/image/ImageSelection.java | package com.google.sps.image;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public final class ImageSelection {
private final Set<String> keywords;
private static final String USER_AGENT = "Mozilla/5.0 (X11; CrOS x86_64 13099.85.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.110 Safari/537.36";
private static final int MAX_NO_LETTERS = 50;
private static final int MAX_NO_KEYWORDS = 10;
public ImageSelection(Set<String> keywords) {
this.keywords = keywords;
}
public String addBingQueryParam(String url) {
final String bingQueryParam = "&qs=HS&form=QBIR&scope=images&sp=-1&pq=hap&sc=8-3&cvid=44CA4B129FEF4B93B6F764BD083213D3&first=1&scenario=ImageBasicHover";
url = url + bingQueryParam;
return url;
}
public String addLicenseFilter(String url) {
// Free to share and use commercially license
final String licenseFilter = "&qft=+filterui:license-L2_L3_L4";
url = url + licenseFilter;
return url;
}
public String addSafeSearchFilter(String url) {
final String safeSearchFilter = "&adlt=strict";
url = url + safeSearchFilter;
return url;
}
/**
* @return URL where the search will be made.
*/
public String generateSearchUrl() {
int addedWords = 0;
int addedLetters = 0;
String bingUrl = "https://www.bing.com/images/search?q=";
for (String word : keywords) {
addedLetters += word.length();
if (addedLetters >= MAX_NO_LETTERS) {
break;
}
bingUrl = bingUrl + "+" + word.replaceAll(" ", "+");
++addedWords;
if (addedWords >= MAX_NO_KEYWORDS) {
break;
}
}
bingUrl = addBingQueryParam(bingUrl);
bingUrl = addLicenseFilter(bingUrl);
bingUrl = addSafeSearchFilter(bingUrl);
return bingUrl;
}
public String getBestImage() throws IOException {
List<String> imgSrc = new ArrayList<>();
Document doc = Jsoup.connect(generateSearchUrl()).userAgent(USER_AGENT).get();
Elements elements = doc.getElementsByTag("img");
for (Element element : elements) {
imgSrc.add(element.attr("abs:data-src"));
}
// Return first relevant image
for (String imageUrl : imgSrc) {
if (!imageUrl.isEmpty()) {
return imageUrl;
}
}
/**
* TODO: Multiple image selection.
* Relying on a single image is not enough.
* We must provide multiple images to the user.
*/
return "";
}
}
| small changes
| src/main/java/com/google/sps/image/ImageSelection.java | small changes |
|
Java | mit | ed7af91f8af9341620b2d0f10f35b1da8f3cf46c | 0 | dylangsjackson/MissingNoEngine,dylangsjackson/MissingNoEngine,bradleysykes/game_leprechaun | src/model/effects/SpawnEffect.java | package model.effects;
import model.Effect;
import model.unit.Unit;
public class SpawnEffect extends Effect {
public SpawnEffect() {
super("Spawn Effect", null, "Spawnable Units");
}
public void addUnit(String unitID){
myReferences.add(unitID);
}
public void removeUnit(String unitID){
myReferences.remove(unitID);
}
@Override
public void enact(Unit target) {
// Tell Game Engine to create unit (provided the unit's ID)
// at a specified location.
// GameEngine.createUnit(id,x,y);
}
}
| removed spawn effect, now own ability
| src/model/effects/SpawnEffect.java | removed spawn effect, now own ability |
||
Java | mit | a8312a04bf5737330216f56d20e0c75310f7334a | 0 | ECSE321/TD | src/main/view/MapPanel.java | package main.view;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import main.model.GameLogic;
import main.model.critter.Critter;
import main.model.map.Tile;
import main.model.tower.Tower;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author justin
*/
@SuppressWarnings("serial")
public class MapPanel extends JPanel {
private GameLogic gameLogic;
Image pathImage = new ImageIcon("img/path.png").getImage();
Image grassImage = new ImageIcon("img/grass.png").getImage();
Image critterImage = new ImageIcon("img/critter.png").getImage();
Image towerImage = new ImageIcon("img/tower.png").getImage();
public MapPanel(GameLogic gameLogic) {
this.gameLogic = gameLogic;
this.setSize(100, 100);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawImage(pathImage, 10, 10, this);
/*
try {
List<Tile> tiles = gameLogic.getTilesList();
for(Tile t : tiles) {
if(t.isPath()) {
g.drawImage(pathImage, t.getPosition().getX(), t.getPosition().getY(), this);
} else {
g.drawImage(grassImage, t.getPosition().getX(), t.getPosition().getY(), this);
}
}
} catch (NullPointerException e) {
}
try {
List<Critter> critters = gameLogic.getCrittersList();
for(Critter c : critters) {
g.drawImage(critterImage, c.getPosition().getX(), c.getPosition().getY(), this);
System.out.println(c.getPosition().getX());
}
} catch (NullPointerException e) {
System.out.println("critterlist had a null pointer exception");
}
try {
List<Tower> towers = gameLogic.getTowersList();
for(Tower t : towers) {
g.drawImage(towerImage, t.getPosition().getX(), t.getPosition().getY(), this);
}
} catch (NullPointerException e) {
}
*/
}
}
| removes useless mappanel
| src/main/view/MapPanel.java | removes useless mappanel |
||
Java | mit | b33e69a22c30f1f77ce159b11951fc4923ea7bb8 | 0 | gurkenlabs/litiengine,gurkenlabs/litiengine | package de.gurkenlabs.litiengine.graphics;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import de.gurkenlabs.litiengine.Align;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.Valign;
import de.gurkenlabs.litiengine.gui.GuiProperties;
import de.gurkenlabs.litiengine.util.MathUtilities;
public final class TextRenderer {
private TextRenderer() {
throw new UnsupportedOperationException();
}
/**
* Draw text at the given coordinates. This variant of drawText() uses RenderingHints.VALUE_TEXT_ANTIALIAS_OFF as Anti-Aliasing method by
* standard. For other Anti-Aliasing options, please use the drawText()-variant with five parameters.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
*/
public static void render(final Graphics2D g, final String text, final double x, final double y) {
render(g, text, x, y, GuiProperties.getDefaultAppearance().getTextAntialiasing());
}
public static void render(final Graphics2D g, final String text, Point2D location) {
render(g, text, location.getX(), location.getY());
}
public static void render(final Graphics2D g, final String text, Align alignment, Valign verticalAlignment) {
render(g, text, alignment, verticalAlignment, 0, 0);
}
/**
* Draws text with the specified alignment.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param alignment
* The horizontal alignment.
* @param verticalAlignment
* The vertical alignment.
*/
public static void render(final Graphics2D g, final String text, Align alignment, Valign verticalAlignment, double offesetX, double offsetY) {
final Rectangle2D bounds = g.getClipBounds();
render(g, text, bounds, alignment, verticalAlignment, offesetX, offsetY, false);
}
public static void render(final Graphics2D g, final String text, Rectangle2D bounds, Align alignment, Valign verticalAlignment, boolean scaleFont) {
render(g, text, bounds, alignment, verticalAlignment, 0, 0, scaleFont);
}
/**
* Draws text within the given boundaries using the specified alignment and scales the font size, if desired.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param bounds
* the Rectangle defining the boundaries used for alignment and scaling.
* @param alignment
* The horizontal alignment.
* @param verticalAlignment
* The vertical alignment.
* @param scaleFont
* if true, scale the font so that the text will fit inside the given rectangle. If not, use the Graphics context's previous font size.
*/
public static void render(final Graphics2D g, final String text, Rectangle2D bounds, Align alignment, Valign verticalAlignment, double offsetX, double offsetY, boolean scaleFont) {
if (bounds == null) {
return;
}
float previousFontSize = g.getFont().getSize2D();
if (scaleFont) {
float currentFontSize = previousFontSize;
while ((getWidth(g, text) > bounds.getWidth() || getHeight(g, text) > bounds.getHeight()) && currentFontSize > .1f) {
currentFontSize -= .1f;
g.setFont(g.getFont().deriveFont(currentFontSize));
}
}
double locationX = bounds.getX() + alignment.getLocation(bounds.getWidth(), g.getFontMetrics().stringWidth(text)) + offsetX;
double locationY = bounds.getY() + verticalAlignment.getLocation(bounds.getHeight(), getHeight(g, text)) + g.getFontMetrics().getAscent() + offsetY;
render(g, text, locationX, locationY);
g.setFont(g.getFont().deriveFont(previousFontSize));
}
/**
* Draw text at the given coordinates. This variant of drawText() uses a provided AntiAliasing parameter.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param antiAliasing
* Configure whether or not to render the text with antialiasing.
* @see RenderingHints
*/
public static void render(final Graphics2D g, final String text, final double x, final double y, boolean antiAliasing) {
if (text == null || text.isEmpty()) {
return;
}
RenderingHints originalHints = g.getRenderingHints();
if (antiAliasing) {
enableAntiAliasing(g);
}
g.drawString(text, (float) x, (float) y);
g.setRenderingHints(originalHints);
}
public static void render(final Graphics2D g, final String text, Point2D location, boolean antiAliasing) {
render(g, text, location.getX(), location.getY(), antiAliasing);
}
public static void renderRotated(final Graphics2D g, final String text, final double x, final double y, final double angle, boolean antiAliasing) {
RenderingHints originalHints = g.getRenderingHints();
if (antiAliasing) {
enableAntiAliasing(g);
}
renderRotated(g, text, x, y, angle);
g.setRenderingHints(originalHints);
}
public static void renderRotated(final Graphics2D g, final String text, final double x, final double y, final double angle) {
AffineTransform oldTx = g.getTransform();
g.rotate(Math.toRadians(angle), x, y);
render(g, text, x, y);
g.setTransform(oldTx);
}
public static void renderRotated(final Graphics2D g, final String text, Point2D location, final double angle) {
renderRotated(g, text, location.getX(), location.getY(), angle);
}
public static void renderRotated(final Graphics2D g, final String text, Point2D location, final double angle, boolean antiAliasing) {
renderRotated(g, text, location.getX(), location.getY(), angle, antiAliasing);
}
/**
* Draw text at the given coordinates with a maximum line width for automatic line breaks. This variant of drawTextWithAutomaticLinebreaks() uses
* RenderingHints.VALUE_TEXT_ANTIALIAS_OFF as Anti-Aliasing method by
* standard. For other Anti-Aliasing options, please use the drawTextWithAutomaticLinebreaks()-variant with six parameters.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param lineWidth
* the max line width
*/
public static void renderWithLinebreaks(final Graphics2D g, final String text, final double x, final double y, final double lineWidth) {
renderWithLinebreaks(g, text, x, y, lineWidth, GuiProperties.getDefaultAppearance().getTextAntialiasing());
}
public static void renderWithLinebreaks(final Graphics2D g, final String text, Point2D location, final double lineWidth) {
renderWithLinebreaks(g, text, location.getX(), location.getY(), lineWidth);
}
/**
* Draw text at the given coordinates with a maximum line width for automatic line breaks and a provided Anti-Aliasing parameter.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param lineWidth
* the max line width
* @param antiAliasing
* Configure whether or not to render the text with antialiasing.
* @see RenderingHints
*/
public static void renderWithLinebreaks(final Graphics2D g, final String text, final double x, final double y, final double lineWidth, final boolean antiAliasing) {
if (text == null || text.isEmpty()) {
return;
}
RenderingHints originalHints = g.getRenderingHints();
if (antiAliasing) {
enableAntiAliasing(g);
}
final FontRenderContext frc = g.getFontRenderContext();
final AttributedString styledText = new AttributedString(text);
styledText.addAttribute(TextAttribute.FONT, g.getFont());
final AttributedCharacterIterator iterator = styledText.getIterator();
final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
measurer.setPosition(0);
float textY = (float) y;
while (measurer.getPosition() < text.length()) {
final TextLayout nextLayout = measurer.nextLayout((float) lineWidth);
textY += nextLayout.getAscent();
final float dx = (float) (nextLayout.isLeftToRight() ? 0 : lineWidth - nextLayout.getAdvance());
nextLayout.draw(g, (float) (x + dx), textY);
textY += nextLayout.getDescent() + nextLayout.getLeading();
}
g.setRenderingHints(originalHints);
}
public static void renderWithLinebreaks(final Graphics2D g, final String text, Point2D location, final double lineWidth, final boolean antiAliasing) {
renderWithLinebreaks(g, text, location.getX(), location.getY(), lineWidth, antiAliasing);
}
/**
* Draw text at the given coordinates with an outline in the provided color. This variant of drawTextWithShadow() doesn't use Anti-Aliasing.
* For other Anti-Aliasing options, please specify the boolean value that controls it.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param outlineColor
* the outline color
*/
public static void renderWithOutline(final Graphics2D g, final String text, final double x, final double y, final Color outlineColor) {
renderWithOutline(g, text, x, y, outlineColor, false);
}
public static void renderWithOutline(final Graphics2D g, final String text, Point2D location, final Color outlineColor) {
renderWithOutline(g, text, location.getX(), location.getY(), outlineColor);
}
public static void renderWithOutline(final Graphics2D g, final String text, final double x, final double y, final Color outlineColor, final boolean antiAliasing) {
float stroke = (float) MathUtilities.clamp((g.getFont().getSize2D() * 1 / 5f) * Math.log(Game.world().camera().getRenderScale()), 1, 100);
renderWithOutline(g, text, x, y, outlineColor, stroke, antiAliasing);
}
/**
* Draw text at the given coordinates with an outline in the provided color and a provided Anti-Aliasing parameter.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param outlineColor
* the outline color
* @param stroke
* the width of the outline
* @param antiAliasing
* the Anti-Aliasing object (e.g. RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
* @see RenderingHints
*/
public static void renderWithOutline(final Graphics2D g, final String text, final double x, final double y, final Color outlineColor, final float stroke, final boolean antiAliasing) {
if (text == null || text.isEmpty()) {
return;
}
Color fillColor = g.getColor();
BasicStroke outlineStroke = new BasicStroke(stroke);
// remember original settings
Color originalColor = g.getColor();
Stroke originalStroke = g.getStroke();
RenderingHints originalHints = g.getRenderingHints();
// create a glyph vector from your text
GlyphVector glyphVector = g.getFont().createGlyphVector(g.getFontRenderContext(), text);
// get the shape object
AffineTransform at = new AffineTransform();
at.translate(x, y);
Shape textShape = at.createTransformedShape(glyphVector.getOutline());
// activate anti aliasing for text rendering (if you want it to look nice)
if (antiAliasing) {
enableAntiAliasing(g);
}
g.setColor(outlineColor);
g.setStroke(outlineStroke);
g.draw(textShape); // draw outline
g.setColor(fillColor);
g.fill(textShape); // fill the shape
// reset to original settings after drawing
g.setColor(originalColor);
g.setStroke(originalStroke);
g.setRenderingHints(originalHints);
}
public static void renderWithOutline(final Graphics2D g, final String text, Point2D location, final Color outlineColor, final boolean antiAliasing) {
renderWithOutline(g, text, location.getX(), location.getY(), outlineColor, antiAliasing);
}
/**
* Retrieve the bounds of some text if it was to be drawn on the specified Graphics2D
*
* @param g
* The Graphics2D object to be drawn on
* @param text
* The string to calculate the bounds of
*
* @return The bounds of the specified String in the specified Graphics context.
*
* @see java.awt.FontMetrics#getStringBounds(String str, Graphics context)
*/
public static Rectangle2D getBounds(final Graphics2D g, final String text) {
return g.getFontMetrics().getStringBounds(text, g);
}
/**
* Retrieve the width of some text if it was to be drawn on the specified Graphics2D
*
* @param g
* The Graphics2D object to be drawn on
* @param text
* The string to retrieve the width of
* @return
* The width of the specified text
*/
public static double getWidth(final Graphics2D g, final String text) {
return getBounds(g, text).getWidth();
}
/**
* Retrieve the height of some text if it was to be drawn on the specified Graphics2D
*
* @param g
* The Graphics2D object to be drawn on
* @param text
* The string to retrieve the height of
* @return
* The height of the specified text
*/
public static double getHeight(final Graphics2D g, final String text) {
return getBounds(g, text).getHeight();
}
private static void enableAntiAliasing(final Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
}
| src/de/gurkenlabs/litiengine/graphics/TextRenderer.java | package de.gurkenlabs.litiengine.graphics;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import de.gurkenlabs.litiengine.Align;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.Valign;
import de.gurkenlabs.litiengine.gui.GuiProperties;
import de.gurkenlabs.litiengine.util.MathUtilities;
public final class TextRenderer {
private TextRenderer() {
throw new UnsupportedOperationException();
}
/**
* Draw text at the given coordinates. This variant of drawText() uses RenderingHints.VALUE_TEXT_ANTIALIAS_OFF as Anti-Aliasing method by
* standard. For other Anti-Aliasing options, please use the drawText()-variant with five parameters.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
*/
public static void render(final Graphics2D g, final String text, final double x, final double y) {
render(g, text, x, y, GuiProperties.getDefaultAppearance().getTextAntialiasing());
}
public static void render(final Graphics2D g, final String text, Point2D location) {
render(g, text, location.getX(), location.getY());
}
/**
* Draws text with the specified alignment.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param alignment
* The horizontal alignment.
* @param verticalAlignment
* The vertical alignment.
*/
public static void render(final Graphics2D g, final String text, Align alignment, Valign verticalAlignment) {
final Rectangle2D bounds = g.getClipBounds();
render(g, text, bounds, alignment, verticalAlignment, false);
}
/**
* Draws text within the given boundaries using the specified alignment and scales the font size, if desired.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param bounds
* the Rectangle defining the boundaries used for alignment and scaling.
* @param alignment
* The horizontal alignment.
* @param verticalAlignment
* The vertical alignment.
* @param scaleFont
* if true, scale the font so that the text will fit inside the given rectangle. If not, use the Graphics context's previous font size.
*/
public static void render(final Graphics2D g, final String text, Rectangle2D bounds, Align alignment, Valign verticalAlignment, boolean scaleFont) {
if (bounds == null) {
return;
}
float previousFontSize = g.getFont().getSize2D();
if (scaleFont) {
float currentFontSize = previousFontSize;
while ((getWidth(g, text) > bounds.getWidth() || getHeight(g, text) > bounds.getHeight()) && currentFontSize > .1f) {
currentFontSize -= .1f;
g.setFont(g.getFont().deriveFont(currentFontSize));
}
}
double locationX = bounds.getX() + alignment.getLocation(bounds.getWidth(), g.getFontMetrics().stringWidth(text));
double locationY = bounds.getY() + verticalAlignment.getLocation(bounds.getHeight(), getHeight(g, text)) + g.getFontMetrics().getAscent();
render(g, text, locationX, locationY);
g.setFont(g.getFont().deriveFont(previousFontSize));
}
/**
* Draw text at the given coordinates. This variant of drawText() uses a provided AntiAliasing parameter.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param antiAliasing
* Configure whether or not to render the text with antialiasing.
* @see RenderingHints
*/
public static void render(final Graphics2D g, final String text, final double x, final double y, boolean antiAliasing) {
if (text == null || text.isEmpty()) {
return;
}
RenderingHints originalHints = g.getRenderingHints();
if (antiAliasing) {
enableAntiAliasing(g);
}
g.drawString(text, (float) x, (float) y);
g.setRenderingHints(originalHints);
}
public static void render(final Graphics2D g, final String text, Point2D location, boolean antiAliasing) {
render(g, text, location.getX(), location.getY(), antiAliasing);
}
public static void renderRotated(final Graphics2D g, final String text, final double x, final double y, final double angle, boolean antiAliasing) {
RenderingHints originalHints = g.getRenderingHints();
if (antiAliasing) {
enableAntiAliasing(g);
}
renderRotated(g, text, x, y, angle);
g.setRenderingHints(originalHints);
}
public static void renderRotated(final Graphics2D g, final String text, final double x, final double y, final double angle) {
AffineTransform oldTx = g.getTransform();
g.rotate(Math.toRadians(angle), x, y);
render(g, text, x, y);
g.setTransform(oldTx);
}
public static void renderRotated(final Graphics2D g, final String text, Point2D location, final double angle) {
renderRotated(g, text, location.getX(), location.getY(), angle);
}
public static void renderRotated(final Graphics2D g, final String text, Point2D location, final double angle, boolean antiAliasing) {
renderRotated(g, text, location.getX(), location.getY(), angle, antiAliasing);
}
/**
* Draw text at the given coordinates with a maximum line width for automatic line breaks. This variant of drawTextWithAutomaticLinebreaks() uses
* RenderingHints.VALUE_TEXT_ANTIALIAS_OFF as Anti-Aliasing method by
* standard. For other Anti-Aliasing options, please use the drawTextWithAutomaticLinebreaks()-variant with six parameters.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param lineWidth
* the max line width
*/
public static void renderWithLinebreaks(final Graphics2D g, final String text, final double x, final double y, final double lineWidth) {
renderWithLinebreaks(g, text, x, y, lineWidth, GuiProperties.getDefaultAppearance().getTextAntialiasing());
}
public static void renderWithLinebreaks(final Graphics2D g, final String text, Point2D location, final double lineWidth) {
renderWithLinebreaks(g, text, location.getX(), location.getY(), lineWidth);
}
/**
* Draw text at the given coordinates with a maximum line width for automatic line breaks and a provided Anti-Aliasing parameter.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param lineWidth
* the max line width
* @param antiAliasing
* Configure whether or not to render the text with antialiasing.
* @see RenderingHints
*/
public static void renderWithLinebreaks(final Graphics2D g, final String text, final double x, final double y, final double lineWidth, final boolean antiAliasing) {
if (text == null || text.isEmpty()) {
return;
}
RenderingHints originalHints = g.getRenderingHints();
if (antiAliasing) {
enableAntiAliasing(g);
}
final FontRenderContext frc = g.getFontRenderContext();
final AttributedString styledText = new AttributedString(text);
styledText.addAttribute(TextAttribute.FONT, g.getFont());
final AttributedCharacterIterator iterator = styledText.getIterator();
final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
measurer.setPosition(0);
float textY = (float) y;
while (measurer.getPosition() < text.length()) {
final TextLayout nextLayout = measurer.nextLayout((float) lineWidth);
textY += nextLayout.getAscent();
final float dx = (float) (nextLayout.isLeftToRight() ? 0 : lineWidth - nextLayout.getAdvance());
nextLayout.draw(g, (float) (x + dx), textY);
textY += nextLayout.getDescent() + nextLayout.getLeading();
}
g.setRenderingHints(originalHints);
}
public static void renderWithLinebreaks(final Graphics2D g, final String text, Point2D location, final double lineWidth, final boolean antiAliasing) {
renderWithLinebreaks(g, text, location.getX(), location.getY(), lineWidth, antiAliasing);
}
/**
* Draw text at the given coordinates with an outline in the provided color. This variant of drawTextWithShadow() doesn't use Anti-Aliasing.
* For other Anti-Aliasing options, please specify the boolean value that controls it.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param outlineColor
* the outline color
*/
public static void renderWithOutline(final Graphics2D g, final String text, final double x, final double y, final Color outlineColor) {
renderWithOutline(g, text, x, y, outlineColor, false);
}
public static void renderWithOutline(final Graphics2D g, final String text, Point2D location, final Color outlineColor) {
renderWithOutline(g, text, location.getX(), location.getY(), outlineColor);
}
public static void renderWithOutline(final Graphics2D g, final String text, final double x, final double y, final Color outlineColor, final boolean antiAliasing) {
float stroke = (float) MathUtilities.clamp((g.getFont().getSize2D() * 1 / 5f) * Math.log(Game.world().camera().getRenderScale()), 1, 100);
renderWithOutline(g, text, x, y, outlineColor, stroke, antiAliasing);
}
/**
* Draw text at the given coordinates with an outline in the provided color and a provided Anti-Aliasing parameter.
*
* @param g
* the Graphics2D object to draw on
* @param text
* the String to be distributed over all generated lines
* @param x
* the min x coordinate
* @param y
* the min y coordinate
* @param outlineColor
* the outline color
* @param stroke
* the width of the outline
* @param antiAliasing
* the Anti-Aliasing object (e.g. RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)
* @see RenderingHints
*/
public static void renderWithOutline(final Graphics2D g, final String text, final double x, final double y, final Color outlineColor, final float stroke, final boolean antiAliasing) {
if (text == null || text.isEmpty()) {
return;
}
Color fillColor = g.getColor();
BasicStroke outlineStroke = new BasicStroke(stroke);
// remember original settings
Color originalColor = g.getColor();
Stroke originalStroke = g.getStroke();
RenderingHints originalHints = g.getRenderingHints();
// create a glyph vector from your text
GlyphVector glyphVector = g.getFont().createGlyphVector(g.getFontRenderContext(), text);
// get the shape object
AffineTransform at = new AffineTransform();
at.translate(x, y);
Shape textShape = at.createTransformedShape(glyphVector.getOutline());
// activate anti aliasing for text rendering (if you want it to look nice)
if (antiAliasing) {
enableAntiAliasing(g);
}
g.setColor(outlineColor);
g.setStroke(outlineStroke);
g.draw(textShape); // draw outline
g.setColor(fillColor);
g.fill(textShape); // fill the shape
// reset to original settings after drawing
g.setColor(originalColor);
g.setStroke(originalStroke);
g.setRenderingHints(originalHints);
}
public static void renderWithOutline(final Graphics2D g, final String text, Point2D location, final Color outlineColor, final boolean antiAliasing) {
renderWithOutline(g, text, location.getX(), location.getY(), outlineColor, antiAliasing);
}
/**
* Retrieve the bounds of some text if it was to be drawn on the specified Graphics2D
*
* @param g
* The Graphics2D object to be drawn on
* @param text
* The string to calculate the bounds of
*
* @return The bounds of the specified String in the specified Graphics context.
*
* @see java.awt.FontMetrics#getStringBounds(String str, Graphics context)
*/
public static Rectangle2D getBounds(final Graphics2D g, final String text) {
return g.getFontMetrics().getStringBounds(text, g);
}
/**
* Retrieve the width of some text if it was to be drawn on the specified Graphics2D
*
* @param g
* The Graphics2D object to be drawn on
* @param text
* The string to retrieve the width of
* @return
* The width of the specified text
*/
public static double getWidth(final Graphics2D g, final String text) {
return getBounds(g, text).getWidth();
}
/**
* Retrieve the height of some text if it was to be drawn on the specified Graphics2D
*
* @param g
* The Graphics2D object to be drawn on
* @param text
* The string to retrieve the height of
* @return
* The height of the specified text
*/
public static double getHeight(final Graphics2D g, final String text) {
return getBounds(g, text).getHeight();
}
private static void enableAntiAliasing(final Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
}
| Add some method overloads.
| src/de/gurkenlabs/litiengine/graphics/TextRenderer.java | Add some method overloads. |
|
Java | mit | 6de606024b4a2d389d02bf88bbdd1bdc56c8e474 | 0 | Shopify/mobile-buy-sdk-android,Shopify/mobile-buy-sdk-android,Shopify/mobile-buy-sdk-android | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Shopify 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.shopify.buy.dataprovider;
import com.shopify.buy.model.Checkout;
import com.shopify.buy.model.CreditCard;
import com.shopify.buy.model.GiftCard;
import com.shopify.buy.model.PaymentToken;
import com.shopify.buy.model.ShippingRate;
import java.util.List;
import rx.Observable;
/**
* Service that provides Checkout API endpoints.
*/
public interface CheckoutService {
/**
* Initiate the Shopify checkout process with a new Checkout object.
*
* @param checkout the {@link Checkout} object to use for initiating the checkout process, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask createCheckout(Checkout checkout, Callback<Checkout> callback);
/**
* Initiate the Shopify checkout process with a new Checkout object.
*
* @param checkout the {@link Checkout} object to use for initiating the checkout process, not null
* @return cold observable that emits created checkout object
*/
Observable<Checkout> createCheckout(Checkout checkout);
/**
* Update an existing Checkout's attributes.
*
* Only the following attributes will be updated, any others will be ignored:
* <ul>
* <li>{@link Checkout#email}</li>
* <li>{@link Checkout#shippingAddress}</li>
* <li>{@link Checkout#billingAddress}</li>
* <li>{@link Checkout#lineItems}</li>
* <li>{@link Checkout#discount}</li>
* <li>{@link Checkout#shippingRate}</li>
* <li>{@link Checkout#reservationTime}</li>
* </ul>
*
* @param checkout the {@link Checkout} attributes to be updated, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask updateCheckout(Checkout checkout, Callback<Checkout> callback);
/**
* Update an existing Checkout's attributes
*
* Only the following attributes will be updated, any others will be ignored:
* <ul>
* <li>{@link Checkout#email}</li>
* <li>{@link Checkout#shippingAddress}</li>
* <li>{@link Checkout#billingAddress}</li>
* <li>{@link Checkout#lineItems}</li>
* <li>{@link Checkout#discount}</li>
* <li>{@link Checkout#shippingRate}</li>
* <li>{@link Checkout#reservationTime}</li>
* </ul>
*
* @param checkout the {@link Checkout} to update, not null
* @return cold observable that emits updated checkout object
*/
Observable<Checkout> updateCheckout(Checkout checkout);
/**
* Complete the checkout and process the payment session
*
* @param paymentToken a {@link PaymentToken} associated with the checkout to be completed, not null if {@link Checkout#getPaymentDue()} is greater than 0
* @param checkoutToken checkout token associated with the specified payment token, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask completeCheckout(PaymentToken paymentToken, String checkoutToken, Callback<Checkout> callback);
/**
* Complete the checkout and process the payment session
*
* @param paymentToken a {@link PaymentToken} associated with the checkout to be completed, not null if {@link Checkout#getPaymentDue()} is greater than 0
* @param checkoutToken checkout token associated with the specified payment token, not null or empty
* @return cold observable that emits completed checkout
*/
Observable<Checkout> completeCheckout(PaymentToken paymentToken, String checkoutToken);
/**
* Get the status of the payment session associated with {@code checkout}. {@code callback} will be
* called with a boolean value indicating whether the session has completed or not.
*
* @param checkoutToken checkout token for the {@link Checkout} to get the completion status for, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancellable task
*/
CancellableTask getCheckoutCompletionStatus(String checkoutToken, final Callback<Boolean> callback);
/**
* Get the status of the payment session associated with {@code checkout}. {@code callback} will be
* called with a boolean value indicating whether the session has completed or not.
*
* @param checkoutToken checkout token for the {@link Checkout} to get the completion status for, not null or empty
* @return cold observable that emits a Boolean that indicates whether the checkout has been completed
*
*/
Observable<Boolean> getCheckoutCompletionStatus(String checkoutToken);
/**
* Fetch an existing Checkout from Shopify
*
* @param checkoutToken the token associated with the existing {@link Checkout}, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask getCheckout(String checkoutToken, Callback<Checkout> callback);
/**
* Fetch an existing Checkout from Shopify
*
* @param checkoutToken the token associated with the existing {@link Checkout}, not null or empty
* @return cold observable that emits requested existing checkout
*/
Observable<Checkout> getCheckout(String checkoutToken);
/**
* Fetch shipping rates for a given Checkout
*
* @param checkoutToken the {@link Checkout#token} from an existing Checkout, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask getShippingRates(String checkoutToken, Callback<List<ShippingRate>> callback);
/**
* Fetch shipping rates for a given Checkout
*
* @param checkoutToken the {@link Checkout#token} from an existing Checkout, not null or empty
* @return cold observable that emits requested list of shipping rates for a given checkout
*/
Observable<List<ShippingRate>> getShippingRates(String checkoutToken);
/**
* Post a credit card to Shopify's card server and associate it with a Checkout
*
* @param card the {@link CreditCard} to associate, not null
* @param checkout the {@link Checkout} to associate the card with, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask storeCreditCard(CreditCard card, Checkout checkout, Callback<PaymentToken> callback);
/**
* Post a credit card to Shopify's card server and associate it with a Checkout
*
* @param card the {@link CreditCard} to associate, not null
* @param checkout the {@link Checkout} to associate the card with, not null
* @return cold observable that emits payment token associated with specified checkout and credit card
*/
Observable<PaymentToken> storeCreditCard(CreditCard card, Checkout checkout);
/**
* Apply a gift card to a Checkout
*
* @param giftCardCode the gift card code for a gift card associated with the current Shop, not null
* @param checkout the {@link Checkout} object to apply the gift card to, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask applyGiftCard(String giftCardCode, Checkout checkout, Callback<Checkout> callback);
/**
* Apply a gift card to a Checkout
*
* @param giftCardCode the gift card code for a gift card associated with the current Shop, not null or empty
* @param checkout the {@link Checkout} object to apply the gift card to, not null
* @return cold observable that emits updated checkout
*/
Observable<Checkout> applyGiftCard(String giftCardCode, Checkout checkout);
/**
* Remove a gift card that was previously applied to a Checkout
*
* @param giftCardId the id of the {@link GiftCard} to remove from the {@link Checkout}, not null
* @param checkout the {@code Checkout} to remove the {@code GiftCard} from, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask removeGiftCard(Long giftCardId, Checkout checkout, Callback<Checkout> callback);
/**
* Remove a gift card that was previously applied to a Checkout
*
* @param giftCardId the id of the {@link GiftCard} to remove from the {@link Checkout}, not null
* @param checkout the {@code Checkout} to remove the {@code GiftCard} from, not null
* @return cold observable that emits updated checkout
*/
Observable<Checkout> removeGiftCard(Long giftCardId, Checkout checkout);
/**
* Release all product inventory reservations associated with the checkout by setting the `reservationTime` of the checkout to `0` and calling {@link #updateCheckout(Checkout, Callback) updateCheckout(Checkout, Callback)}.
* We recommend creating a new `Checkout` object from a `Cart` for further API calls.
*
* @param checkoutToken the token for the {@link Checkout} to expire, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask removeProductReservationsFromCheckout(String checkoutToken, Callback<Checkout> callback);
/**
* Release all product inventory reservations associated with the checkout by setting the `reservationTime` of the checkout to `0` and calling {@link #updateCheckout(Checkout, Callback) updateCheckout(Checkout, Callback)}.
* We recommend creating a new `Checkout` object from a `Cart` for further API calls.
*
* @param checkoutToken the {@link Checkout} to expire, not null or empty
* @return cold observable that emits updated checkout
*/
Observable<Checkout> removeProductReservationsFromCheckout(String checkoutToken);
}
| MobileBuy/buy/src/main/java/com/shopify/buy/dataprovider/CheckoutService.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Shopify 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.shopify.buy.dataprovider;
import com.shopify.buy.model.Checkout;
import com.shopify.buy.model.CreditCard;
import com.shopify.buy.model.GiftCard;
import com.shopify.buy.model.PaymentToken;
import com.shopify.buy.model.ShippingRate;
import java.util.List;
import rx.Observable;
/**
* Service that provides Checkout API endpoints.
*/
public interface CheckoutService {
/**
* Initiate the Shopify checkout process with a new Checkout object.
*
* @param checkout the {@link Checkout} object to use for initiating the checkout process, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask createCheckout(Checkout checkout, Callback<Checkout> callback);
/**
* Initiate the Shopify checkout process with a new Checkout object.
*
* @param checkout the {@link Checkout} object to use for initiating the checkout process, not null
* @return cold observable that emits created checkout object
*/
Observable<Checkout> createCheckout(Checkout checkout);
/**
* Update an existing Checkout's attributes.
*
* Only the following attributes will be updated, any others will be ignored:
* <ul>
* <li>{@link Checkout#email}</li>
* <li>{@link Checkout#shippingAddress}</li>
* <li>{@link Checkout#billingAddress}</li>
* <li>{@link Checkout#lineItems}</li>
* <li>{@link Checkout#discount}</li>
* <li>{@link Checkout#shippingRate}</li>
* <li>{@link Checkout#reservationTime}</li>
* </ul>
*
* @param checkout the {@link Checkout} attributes to be updated, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask updateCheckout(Checkout checkout, Callback<Checkout> callback);
/**
* Update an existing Checkout's attributes
*
* Only the following attributes will be updated, any others will be ignored:
* <ul>
* <li>{@link Checkout#email}</li>
* <li>{@link Checkout#shippingAddress}</li>
* <li>{@link Checkout#billingAddress}</li>
* <li>{@link Checkout#lineItems}</li>
* <li>{@link Checkout#discount}</li>
* <li>{@link Checkout#shippingRate}</li>
* <li>{@link Checkout#reservationTime}</li>
* </ul>
*
* @param checkout the {@link Checkout} to update, not null
* @return cold observable that emits updated checkout object
*/
Observable<Checkout> updateCheckout(Checkout checkout);
/**
* Complete the checkout and process the payment session
*
* @param paymentToken a {@link PaymentToken} associated with the checkout to be completed, not null if {@link Checkout#getPaymentDue()} is > 0
* @param checkoutToken checkout token associated with the specified payment token, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask completeCheckout(PaymentToken paymentToken, String checkoutToken, Callback<Checkout> callback);
/**
* Complete the checkout and process the payment session
*
* @param paymentToken a {@link PaymentToken} associated with the checkout to be completed, not null if {@link Checkout#getPaymentDue()} is > 0
* @param checkoutToken checkout token associated with the specified payment token, not null or empty
* @return cold observable that emits completed checkout
*/
Observable<Checkout> completeCheckout(PaymentToken paymentToken, String checkoutToken);
/**
* Get the status of the payment session associated with {@code checkout}. {@code callback} will be
* called with a boolean value indicating whether the session has completed or not.
*
* @param checkoutToken checkout token for the {@link Checkout} to get the completion status for, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancellable task
*/
CancellableTask getCheckoutCompletionStatus(String checkoutToken, final Callback<Boolean> callback);
/**
* Get the status of the payment session associated with {@code checkout}. {@code callback} will be
* called with a boolean value indicating whether the session has completed or not.
*
* @param checkoutToken checkout token for the {@link Checkout} to get the completion status for, not null or empty
* @return cold observable that emits a Boolean that indicates whether the checkout has been completed
*
*/
Observable<Boolean> getCheckoutCompletionStatus(String checkoutToken);
/**
* Fetch an existing Checkout from Shopify
*
* @param checkoutToken the token associated with the existing {@link Checkout}, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask getCheckout(String checkoutToken, Callback<Checkout> callback);
/**
* Fetch an existing Checkout from Shopify
*
* @param checkoutToken the token associated with the existing {@link Checkout}, not null or empty
* @return cold observable that emits requested existing checkout
*/
Observable<Checkout> getCheckout(String checkoutToken);
/**
* Fetch shipping rates for a given Checkout
*
* @param checkoutToken the {@link Checkout#token} from an existing Checkout, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask getShippingRates(String checkoutToken, Callback<List<ShippingRate>> callback);
/**
* Fetch shipping rates for a given Checkout
*
* @param checkoutToken the {@link Checkout#token} from an existing Checkout, not null or empty
* @return cold observable that emits requested list of shipping rates for a given checkout
*/
Observable<List<ShippingRate>> getShippingRates(String checkoutToken);
/**
* Post a credit card to Shopify's card server and associate it with a Checkout
*
* @param card the {@link CreditCard} to associate, not null
* @param checkout the {@link Checkout} to associate the card with, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask storeCreditCard(CreditCard card, Checkout checkout, Callback<PaymentToken> callback);
/**
* Post a credit card to Shopify's card server and associate it with a Checkout
*
* @param card the {@link CreditCard} to associate, not null
* @param checkout the {@link Checkout} to associate the card with, not null
* @return cold observable that emits payment token associated with specified checkout and credit card
*/
Observable<PaymentToken> storeCreditCard(CreditCard card, Checkout checkout);
/**
* Apply a gift card to a Checkout
*
* @param giftCardCode the gift card code for a gift card associated with the current Shop, not null
* @param checkout the {@link Checkout} object to apply the gift card to, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask applyGiftCard(String giftCardCode, Checkout checkout, Callback<Checkout> callback);
/**
* Apply a gift card to a Checkout
*
* @param giftCardCode the gift card code for a gift card associated with the current Shop, not null or empty
* @param checkout the {@link Checkout} object to apply the gift card to, not null
* @return cold observable that emits updated checkout
*/
Observable<Checkout> applyGiftCard(String giftCardCode, Checkout checkout);
/**
* Remove a gift card that was previously applied to a Checkout
*
* @param giftCardId the id of the {@link GiftCard} to remove from the {@link Checkout}, not null
* @param checkout the {@code Checkout} to remove the {@code GiftCard} from, not null
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask removeGiftCard(Long giftCardId, Checkout checkout, Callback<Checkout> callback);
/**
* Remove a gift card that was previously applied to a Checkout
*
* @param giftCardId the id of the {@link GiftCard} to remove from the {@link Checkout}, not null
* @param checkout the {@code Checkout} to remove the {@code GiftCard} from, not null
* @return cold observable that emits updated checkout
*/
Observable<Checkout> removeGiftCard(Long giftCardId, Checkout checkout);
/**
* Release all product inventory reservations associated with the checkout by setting the `reservationTime` of the checkout to `0` and calling {@link #updateCheckout(Checkout, Callback) updateCheckout(Checkout, Callback)}.
* We recommend creating a new `Checkout` object from a `Cart` for further API calls.
*
* @param checkoutToken the token for the {@link Checkout} to expire, not null or empty
* @param callback the {@link Callback} that will be used to indicate the response from the asynchronous network operation, not null
* @return cancelable task
*/
CancellableTask removeProductReservationsFromCheckout(String checkoutToken, Callback<Checkout> callback);
/**
* Release all product inventory reservations associated with the checkout by setting the `reservationTime` of the checkout to `0` and calling {@link #updateCheckout(Checkout, Callback) updateCheckout(Checkout, Callback)}.
* We recommend creating a new `Checkout` object from a `Cart` for further API calls.
*
* @param checkoutToken the {@link Checkout} to expire, not null or empty
* @return cold observable that emits updated checkout
*/
Observable<Checkout> removeProductReservationsFromCheckout(String checkoutToken);
}
| fix javadoc
| MobileBuy/buy/src/main/java/com/shopify/buy/dataprovider/CheckoutService.java | fix javadoc |
|
Java | epl-1.0 | 579dd6a98d3b8bc1ae0e6c820f1cda9c69075151 | 0 | opendaylight/ovsdb,opendaylight/ovsdb,opendaylight/ovsdb | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.ovsdb.southbound;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SouthboundUtil {
private static final Logger LOG = LoggerFactory.getLogger(SouthboundUtil.class);
private static InstanceIdentifierCodec instanceIdentifierCodec;
public static void setInstanceIdentifierCodec(InstanceIdentifierCodec iidc) {
instanceIdentifierCodec = iidc;
}
public static String serializeInstanceIdentifier(InstanceIdentifier<?> iid) {
return instanceIdentifierCodec.serialize(iid);
}
public static InstanceIdentifier<?> deserializeInstanceIdentifier(String iidString) {
InstanceIdentifier<?> result = null;
try {
result = instanceIdentifierCodec.bindingDeserializer(iidString);
} catch (DeserializationException e) {
LOG.warn("Unable to deserialize iidString", e);
}
return result;
}
public static Optional<OvsdbNodeAugmentation> getManagingNode(DataBroker db, OvsdbBridgeAttributes mn) {
Preconditions.checkNotNull(mn);
try {
OvsdbNodeRef ref = mn.getManagedBy();
if (ref != null && ref.getValue() != null) {
ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
@SuppressWarnings("unchecked") // Note: erasure makes this safe in combination with the typecheck below
InstanceIdentifier<Node> path = (InstanceIdentifier<Node>) ref.getValue();
CheckedFuture<Optional<Node>, ReadFailedException> nf = transaction.read(
LogicalDatastoreType.OPERATIONAL, path);
transaction.close();
Optional<Node> optional = nf.get();
if (optional != null && optional.isPresent()) {
OvsdbNodeAugmentation ovsdbNode = null;
if (optional.get() instanceof Node) {
ovsdbNode = optional.get().getAugmentation(OvsdbNodeAugmentation.class);
} else if (optional.get() instanceof OvsdbNodeAugmentation) {
ovsdbNode = (OvsdbNodeAugmentation) optional.get();
}
if (ovsdbNode != null) {
return Optional.of(ovsdbNode);
} else {
LOG.warn("OvsdbManagedNode {} claims to be managed by {} but "
+ "that OvsdbNode does not exist", mn, ref.getValue());
return Optional.absent();
}
} else {
LOG.warn("Mysteriously got back a thing which is *not* a topology Node: {}", optional);
return Optional.absent();
}
} else {
LOG.warn("Cannot find client for OvsdbManagedNode without a specified ManagedBy {}", mn);
return Optional.absent();
}
} catch (Exception e) {
LOG.warn("Failed to get OvsdbNode that manages OvsdbManagedNode {}", mn, e);
return Optional.absent();
}
}
}
| southbound/southbound-impl/src/main/java/org/opendaylight/ovsdb/southbound/SouthboundUtil.java | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.ovsdb.southbound;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAttributes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.CheckedFuture;
public class SouthboundUtil {
private static final Logger LOG = LoggerFactory.getLogger(SouthboundUtil.class);
private static InstanceIdentifierCodec instanceIdentifierCodec;
public static void setInstanceIdentifierCodec(InstanceIdentifierCodec iidc) {
instanceIdentifierCodec = iidc;
}
public static String serializeInstanceIdentifier(InstanceIdentifier<?> iid) {
return instanceIdentifierCodec.serialize(iid);
}
public static InstanceIdentifier<?> deserializeInstanceIdentifier(String iidString) {
InstanceIdentifier<?> result = null;
try {
result = instanceIdentifierCodec.bindingDeserializer(iidString);
} catch (DeserializationException e) {
LOG.warn("Unable to deserialize iidString",e);
}
return result;
}
public static Optional<OvsdbNodeAugmentation> getManagingNode(DataBroker db,OvsdbBridgeAttributes mn) {
Preconditions.checkNotNull(mn);
try {
OvsdbNodeRef ref = mn.getManagedBy();
if (ref != null && ref.getValue() != null) {
ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
@SuppressWarnings("unchecked") // Note: erasure makes this safe in combination with the typecheck below
InstanceIdentifier<Node> path = (InstanceIdentifier<Node>) ref.getValue();
CheckedFuture<Optional<Node>, ReadFailedException> nf = transaction.read(
LogicalDatastoreType.OPERATIONAL, path);
transaction.close();
Optional<Node> optional = nf.get();
if (optional != null && optional.isPresent() && optional.get() instanceof Node) {
OvsdbNodeAugmentation ovsdbNode = optional.get().getAugmentation(OvsdbNodeAugmentation.class);
if (ovsdbNode != null) {
return Optional.of(ovsdbNode);
} else {
LOG.warn("OvsdbManagedNode {} claims to be managed by {} but "
+ "that OvsdbNode does not exist", mn,ref.getValue());
return Optional.absent();
}
} else {
LOG.warn("Mysteriously got back a thing which is *not* a topology Node: {}",optional);
return Optional.absent();
}
} else {
LOG.warn("Cannot find client for OvsdbManagedNode without a specified ManagedBy {}",mn);
return Optional.absent();
}
} catch (Exception e) {
LOG.warn("Failed to get OvsdbNode that manages OvsdbManagedNode {}", mn, e);
return Optional.absent();
}
}
}
| changed getManagingNode(..) to expect augmented path.
In OvsdbBridgeAttributes 'managedBy' can be path to 'OvsdbNodeAugmentation' as well.
This can happen if the attribute is set via binding aware code.
Signed-off-by: Amit Mandke <[email protected]>
| southbound/southbound-impl/src/main/java/org/opendaylight/ovsdb/southbound/SouthboundUtil.java | changed getManagingNode(..) to expect augmented path. In OvsdbBridgeAttributes 'managedBy' can be path to 'OvsdbNodeAugmentation' as well. This can happen if the attribute is set via binding aware code. |
|
Java | epl-1.0 | 4f7ec0fd57c4652a158007ee61972dcd48e1a86b | 0 | elexis/elexis-3-core,elexis/elexis-3-core,elexis/elexis-3-core,sazgin/elexis-3-core,sazgin/elexis-3-core,elexis/elexis-3-core,sazgin/elexis-3-core,sazgin/elexis-3-core | /*******************************************************************************
* Copyright (c) 2009-2013, G. Weirich and Elexis
* 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:
* G. Weirich - initial implementation
* MEDEVIT <[email protected]> - major changes in 3.0
*******************************************************************************/
package ch.elexis.core.data.events;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.elexis.core.data.interfaces.events.MessageEvent;
import ch.elexis.core.data.status.ElexisStatus;
import ch.elexis.core.exceptions.ElexisException;
import ch.elexis.core.jdt.Nullable;
import ch.elexis.core.model.IPersistentObject;
import ch.elexis.data.Mandant;
import ch.elexis.data.Patient;
import ch.elexis.data.PersistentObject;
/**
* The Elexis event dispatcher system manages and distributes the information of changing, creating,
* deleting and selecting PersistentObjects. An event is fired when such an action occures. This
* might be due to a user interaction or to an non-interactive job.
*
* A view that handles user selection of PersistentObjects MUST fire an appropriate Event through
* ElexisEventdispatcher.getinstance().fire(ElexisEvent ee) Notification of deletion, modification
* and creation of PeristentObjects occurs transparently via the PersistentObject base class.
*
* A client that wishes to be informed on such events must register an ElexisEventListener. The
* catchElexisEvent() Method of this listener is called in a non-UI-thread an should be finished as
* fast as possible. If lengthy operations are neccessary, these must be sheduled in a separate
* thread, The Listener can specify objects, classes and event types it wants to be informed. If no
* such filter is given, it will be informed about all events.
*
* @since 3.0.0 major changes, switch to {@link ElexisContext}
*/
public final class ElexisEventDispatcher extends Job {
private final List<ElexisEventListener> listeners;
private static ElexisEventDispatcher theInstance;
private final Map<Class<?>, IElexisEventDispatcher> dispatchers;
private final PriorityQueue<ElexisEvent> eventQueue;
private final ArrayList<ElexisEvent> eventCopy;
private transient boolean bStop = false;
private final Logger log = LoggerFactory.getLogger(ElexisEventDispatcher.class.getName());
private final ElexisContext elexisUIContext;
public static ElexisEventDispatcher getInstance(){
if (theInstance == null) {
theInstance = new ElexisEventDispatcher();
theInstance.schedule();
}
return theInstance;
}
private ElexisEventDispatcher(){
super(ElexisEventDispatcher.class.getName());
setSystem(true);
setUser(false);
setPriority(Job.SHORT);
listeners = new LinkedList<ElexisEventListener>();
dispatchers = new HashMap<Class<?>, IElexisEventDispatcher>();
eventQueue = new PriorityQueue<ElexisEvent>(50);
eventCopy = new ArrayList<ElexisEvent>(50);
elexisUIContext = new ElexisContext();
}
/**
* It is possible to register a dispatcher for a given class. If such a dispatcher exists, as an
* event of this class is fired, the event will be routed through that dispatcher. Only one
* dispatcher can be registered for a given class. The main purpose of this feature is to allow
* plugins to take care of their data classes by themselves.
*
* @param eventClass
* A Subclass of PersistentObject the dispatcher will take care of
* @param ied
* the dispatcher to register
* @throws ElexisException
* if there is already a dispatcher registered for that class.
*/
public void registerDispatcher(final Class<? extends PersistentObject> eventClass,
final IElexisEventDispatcher ied) throws ElexisException{
if (dispatchers.get(eventClass) != null) {
throw new ElexisException(getClass(), "Duplicate dispatcher for "
+ eventClass.getName(), ElexisException.EE_DUPLICATE_DISPATCHER);
}
dispatchers.put(eventClass, ied);
}
/**
* Unregister a previously registered dispatcher
*
* @param ec
* the class the dispatcher takes care of
* @param ied
* the dispatcher to unregister
* @throws ElexisException
* if the dispatcher was not registered, or if the class was registered with a
* different dispatcher
*/
public void unregisterDispatcher(final Class<? extends PersistentObject> ec,
final IElexisEventDispatcher ied) throws ElexisException{
if (ied != dispatchers.get(ec)) {
throw new ElexisException(getClass(), "Tried to remove unowned dispatcher "
+ ec.getName(), ElexisException.EE_BAD_DISPATCHER);
}
}
/**
* Add listeners for ElexisEvents. The listener tells the system via its getElexisEventFilter
* method, what classes it will catch. If a dispatcher for that class was registered, the call
* will be routed to that dispatcher.
*
* @param el
* one ore more ElexisEventListeners that have to return valid values on
* el.getElexisEventFilter()
*/
public void addListeners(final ElexisEventListener... els){
synchronized (listeners) {
for (ElexisEventListener el : els) {
ElexisEvent event = el.getElexisEventFilter();
Class<?> cl = event.getObjectClass();
IElexisEventDispatcher ed = dispatchers.get(cl);
if (ed != null) {
ed.addListener(el);
} else {
listeners.add(el);
}
}
}
}
/**
* remove listeners. If a listener was added before, it will be removed. Otherwise nothing will
* happen
*
* @param el
* The Listener to remove
*/
public void removeListeners(ElexisEventListener... els){
synchronized (listeners) {
for (ElexisEventListener el : els) {
final ElexisEvent ev = el.getElexisEventFilter();
Class<?> cl = ev.getObjectClass();
IElexisEventDispatcher ed = dispatchers.get(cl);
if (ed != null) {
ed.removeListener(el);
} else {
listeners.remove(el);
}
}
}
}
/**
*
* @param me
* @since 3.0.0
*/
public void fireMessageEvent(MessageEvent me){
ElexisEvent ev =
new ElexisEvent(me, MessageEvent.class, ElexisEvent.EVENT_NOTIFICATION,
ElexisEvent.PRIORITY_SYNC);
fire(ev);
}
/**
* Fire an ElexisEvent. The class concerned is named in ee.getObjectClass. If a dispatcher for
* that class was registered, the event will be forwarded to that dispatcher. Otherwise, it will
* be sent to all registered listeners. The call to the dispatcher or the listener will always
* be in a separate thread and not in the UI thread.So care has to be taken if the callee has to
* change the UI Note: Only one Event is dispatched at a given time. If more events arrive, they
* will be pushed into a FIFO-Queue. If more than one equivalent event is pushed into the queue,
* only the last entered will be dispatched.
*
* @param ee
* the event to fire.
*/
public void fire(final ElexisEvent... ees){
for (ElexisEvent ee : ees) {
// Those are single events
if (ee.getPriority() == ElexisEvent.PRIORITY_SYNC
&& ee.getType() != ElexisEvent.EVENT_SELECTED) {
doDispatch(ee);
continue;
}
int eventType = ee.getType();
if (eventType == ElexisEvent.EVENT_SELECTED
|| eventType == ElexisEvent.EVENT_DESELECTED) {
List<ElexisEvent> eventsToThrow = null;
eventsToThrow =
elexisUIContext.setSelection(ee.getObjectClass(),
(eventType == ElexisEvent.EVENT_SELECTED) ? ee.getObject() : null);
for (ElexisEvent elexisEvent : eventsToThrow) {
IElexisEventDispatcher ied = dispatchers.get(elexisEvent.getObjectClass());
if (ied != null) {
ied.fire(elexisEvent);
}
synchronized (eventQueue) {
eventQueue.offer(elexisEvent);
}
}
continue;
} else if (eventType == ElexisEvent.EVENT_MANDATOR_CHANGED) {
elexisUIContext.setSelection(Mandant.class, ee.getObject());
}
IElexisEventDispatcher ied = dispatchers.get(ee.getObjectClass());
if (ied != null) {
ied.fire(ee);
}
synchronized (eventQueue) {
eventQueue.offer(ee);
}
}
}
/**
* Synchronously fire an {@link ElexisStatus} event.
*
* @param es
* an {@link ElexisStatus} describing the problem
* @since 3.0.0
*/
public static void fireElexisStatusEvent(ElexisStatus es){
ElexisEvent statusEvent =
new ElexisEvent(es, ElexisStatus.class, ElexisEvent.EVENT_ELEXIS_STATUS,
ElexisEvent.PRIORITY_SYNC);
getInstance().doDispatch(statusEvent);
}
/**
* find the last selected object of a given type
*
* @param template
* tha class defining the object to find
* @return the last object of the given type or null if no such object is selected
*/
public static IPersistentObject getSelected(final Class<?> template){
return getInstance().elexisUIContext.getSelected(template);
}
/**
* inform the system that an object has been selected
*
* @param po
* the object that is selected now
*/
public static void fireSelectionEvent(PersistentObject po){
if (po != null) {
getInstance().fire(new ElexisEvent(po, po.getClass(), ElexisEvent.EVENT_SELECTED));
}
}
/**
* inform the system, that several objects have been selected
*
* @param objects
*/
public static void fireSelectionEvents(PersistentObject... objects){
if (objects != null) {
ElexisEvent[] ees = new ElexisEvent[objects.length];
for (int i = 0; i < objects.length; i++) {
ees[i] =
new ElexisEvent(objects[i], objects[i].getClass(), ElexisEvent.EVENT_SELECTED);
}
getInstance().fire(ees);
}
}
/**
* inform the system, that no object of the specified type is selected anymore
*
* @param clazz
* the class of which selection was removed
*/
public static void clearSelection(Class<?> clazz){
if (clazz != null) {
getInstance().fire(new ElexisEvent(null, clazz, ElexisEvent.EVENT_DESELECTED));
}
}
/**
* inform the system, that all object of a specified class have to be reloaded from storage
*
* @param clazz
* the clazz whose objects are invalidated
*/
public static void reload(Class<?> clazz){
if (clazz != null) {
getInstance().fire(new ElexisEvent(null, clazz, ElexisEvent.EVENT_RELOAD));
}
}
/**
* inform the system, that the specified object has changed some values or properties
*
* @param po
* the object that was modified
*/
public static void update(PersistentObject po){
if (po != null) {
getInstance().fire(new ElexisEvent(po, po.getClass(), ElexisEvent.EVENT_UPDATE));
}
}
/**
* @return the currently selected {@link Patient}
*/
public @Nullable static Patient getSelectedPatient(){
return (Patient) getSelected(Patient.class);
}
/**
*
* @return the currently selected {@link Mandant}
* @since 3.1
*/
public @Nullable static Mandant getSelectedMandator() {
return (Mandant) getSelected(Mandant.class);
}
public void shutDown(){
bStop = true;
}
@Override
protected IStatus run(IProgressMonitor monitor){
// copy all events so doDispatch is outside of synchronization,
// and event handling can run code in display thread without deadlock
synchronized (eventQueue) {
while (!eventQueue.isEmpty()) {
eventCopy.add(eventQueue.poll());
}
eventQueue.notifyAll();
}
for (ElexisEvent event : eventCopy) {
doDispatch(event);
}
eventCopy.clear();
if (!bStop) {
this.schedule(30);
}
return Status.OK_STATUS;
}
private void doDispatch(final ElexisEvent ee){
if (ee != null) {
synchronized (listeners) {
for (final ElexisEventListener l : listeners) {
if (ee.matches(l.getElexisEventFilter())) {
l.catchElexisEvent(ee);
}
}
}
}
}
/**
* Let the dispatcher Thread empty the queue. If the queue is empty, this method returns
* immediately. Otherwise, the current thread waits until it is empty or the provided wasit time
* has expired.
*
* @param millis
* The time to wait bevor returning
* @return false if waiting was interrupted
*/
public boolean waitUntilEventQueueIsEmpty(long millis){
synchronized (eventQueue) {
if (!eventQueue.isEmpty()) {
try {
eventQueue.wait(millis);
return true;
} catch (InterruptedException e) {
// janusode
}
}
}
return false;
}
public void dump(){
StringBuilder sb = new StringBuilder();
sb.append("ElexisEventDispatcher dump: \n");
for (ElexisEventListener el : listeners) {
ElexisEvent filter = el.getElexisEventFilter();
sb.append(el.getClass().getName()).append(": ");
if (filter != null && filter.getObjectClass() != null
&& filter.getObjectClass().getName() != null) {
sb.append(filter.type).append(" / ").append(filter.getObjectClass().getName());
}
sb.append("\n");
}
sb.append("\n--------------\n");
log.debug(sb.toString());
}
}
| ch.elexis.core.data/src/ch/elexis/core/data/events/ElexisEventDispatcher.java | /*******************************************************************************
* Copyright (c) 2009-2013, G. Weirich and Elexis
* 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:
* G. Weirich - initial implementation
* MEDEVIT <[email protected]> - major changes in 3.0
*******************************************************************************/
package ch.elexis.core.data.events;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.elexis.core.data.interfaces.events.MessageEvent;
import ch.elexis.core.data.status.ElexisStatus;
import ch.elexis.core.exceptions.ElexisException;
import ch.elexis.core.model.IPersistentObject;
import ch.elexis.data.Mandant;
import ch.elexis.data.Patient;
import ch.elexis.data.PersistentObject;
/**
* The Elexis event dispatcher system manages and distributes the information of changing, creating,
* deleting and selecting PersistentObjects. An event is fired when such an action occures. This
* might be due to a user interaction or to an non-interactive job.
*
* A view that handles user selection of PersistentObjects MUST fire an appropriate Event through
* ElexisEventdispatcher.getinstance().fire(ElexisEvent ee) Notification of deletion, modification
* and creation of PeristentObjects occurs transparently via the PersistentObject base class.
*
* A client that wishes to be informed on such events must register an ElexisEventListener. The
* catchElexisEvent() Method of this listener is called in a non-UI-thread an should be finished as
* fast as possible. If lengthy operations are neccessary, these must be sheduled in a separate
* thread, The Listener can specify objects, classes and event types it wants to be informed. If no
* such filter is given, it will be informed about all events.
*
* @since 3.0.0 major changes, switch to {@link ElexisContext}
*/
public final class ElexisEventDispatcher extends Job {
private final List<ElexisEventListener> listeners;
private static ElexisEventDispatcher theInstance;
private final Map<Class<?>, IElexisEventDispatcher> dispatchers;
private final PriorityQueue<ElexisEvent> eventQueue;
private final ArrayList<ElexisEvent> eventCopy;
private transient boolean bStop = false;
private final Logger log = LoggerFactory.getLogger(ElexisEventDispatcher.class.getName());
private final ElexisContext elexisUIContext;
public static ElexisEventDispatcher getInstance(){
if (theInstance == null) {
theInstance = new ElexisEventDispatcher();
theInstance.schedule();
}
return theInstance;
}
private ElexisEventDispatcher(){
super(ElexisEventDispatcher.class.getName());
setSystem(true);
setUser(false);
setPriority(Job.SHORT);
listeners = new LinkedList<ElexisEventListener>();
dispatchers = new HashMap<Class<?>, IElexisEventDispatcher>();
eventQueue = new PriorityQueue<ElexisEvent>(50);
eventCopy = new ArrayList<ElexisEvent>(50);
elexisUIContext = new ElexisContext();
}
/**
* It is possible to register a dispatcher for a given class. If such a dispatcher exists, as an
* event of this class is fired, the event will be routed through that dispatcher. Only one
* dispatcher can be registered for a given class. The main purpose of this feature is to allow
* plugins to take care of their data classes by themselves.
*
* @param eventClass
* A Subclass of PersistentObject the dispatcher will take care of
* @param ied
* the dispatcher to register
* @throws ElexisException
* if there is already a dispatcher registered for that class.
*/
public void registerDispatcher(final Class<? extends PersistentObject> eventClass,
final IElexisEventDispatcher ied) throws ElexisException{
if (dispatchers.get(eventClass) != null) {
throw new ElexisException(getClass(), "Duplicate dispatcher for "
+ eventClass.getName(), ElexisException.EE_DUPLICATE_DISPATCHER);
}
dispatchers.put(eventClass, ied);
}
/**
* Unregister a previously registered dispatcher
*
* @param ec
* the class the dispatcher takes care of
* @param ied
* the dispatcher to unregister
* @throws ElexisException
* if the dispatcher was not registered, or if the class was registered with a
* different dispatcher
*/
public void unregisterDispatcher(final Class<? extends PersistentObject> ec,
final IElexisEventDispatcher ied) throws ElexisException{
if (ied != dispatchers.get(ec)) {
throw new ElexisException(getClass(), "Tried to remove unowned dispatcher "
+ ec.getName(), ElexisException.EE_BAD_DISPATCHER);
}
}
/**
* Add listeners for ElexisEvents. The listener tells the system via its getElexisEventFilter
* method, what classes it will catch. If a dispatcher for that class was registered, the call
* will be routed to that dispatcher.
*
* @param el
* one ore more ElexisEventListeners that have to return valid values on
* el.getElexisEventFilter()
*/
public void addListeners(final ElexisEventListener... els){
synchronized (listeners) {
for (ElexisEventListener el : els) {
ElexisEvent event = el.getElexisEventFilter();
Class<?> cl = event.getObjectClass();
IElexisEventDispatcher ed = dispatchers.get(cl);
if (ed != null) {
ed.addListener(el);
} else {
listeners.add(el);
}
}
}
}
/**
* remove listeners. If a listener was added before, it will be removed. Otherwise nothing will
* happen
*
* @param el
* The Listener to remove
*/
public void removeListeners(ElexisEventListener... els){
synchronized (listeners) {
for (ElexisEventListener el : els) {
final ElexisEvent ev = el.getElexisEventFilter();
Class<?> cl = ev.getObjectClass();
IElexisEventDispatcher ed = dispatchers.get(cl);
if (ed != null) {
ed.removeListener(el);
} else {
listeners.remove(el);
}
}
}
}
/**
*
* @param me
* @since 3.0.0
*/
public void fireMessageEvent(MessageEvent me){
ElexisEvent ev =
new ElexisEvent(me, MessageEvent.class, ElexisEvent.EVENT_NOTIFICATION,
ElexisEvent.PRIORITY_SYNC);
fire(ev);
}
/**
* Fire an ElexisEvent. The class concerned is named in ee.getObjectClass. If a dispatcher for
* that class was registered, the event will be forwarded to that dispatcher. Otherwise, it will
* be sent to all registered listeners. The call to the dispatcher or the listener will always
* be in a separate thread and not in the UI thread.So care has to be taken if the callee has to
* change the UI Note: Only one Event is dispatched at a given time. If more events arrive, they
* will be pushed into a FIFO-Queue. If more than one equivalent event is pushed into the queue,
* only the last entered will be dispatched.
*
* @param ee
* the event to fire.
*/
public void fire(final ElexisEvent... ees){
for (ElexisEvent ee : ees) {
// Those are single events
if (ee.getPriority() == ElexisEvent.PRIORITY_SYNC
&& ee.getType() != ElexisEvent.EVENT_SELECTED) {
doDispatch(ee);
continue;
}
int eventType = ee.getType();
if (eventType == ElexisEvent.EVENT_SELECTED
|| eventType == ElexisEvent.EVENT_DESELECTED) {
List<ElexisEvent> eventsToThrow = null;
eventsToThrow =
elexisUIContext.setSelection(ee.getObjectClass(),
(eventType == ElexisEvent.EVENT_SELECTED) ? ee.getObject() : null);
for (ElexisEvent elexisEvent : eventsToThrow) {
IElexisEventDispatcher ied = dispatchers.get(elexisEvent.getObjectClass());
if (ied != null) {
ied.fire(elexisEvent);
}
synchronized (eventQueue) {
eventQueue.offer(elexisEvent);
}
}
continue;
} else if (eventType == ElexisEvent.EVENT_MANDATOR_CHANGED) {
elexisUIContext.setSelection(Mandant.class, ee.getObject());
}
IElexisEventDispatcher ied = dispatchers.get(ee.getObjectClass());
if (ied != null) {
ied.fire(ee);
}
synchronized (eventQueue) {
eventQueue.offer(ee);
}
}
}
/**
* Synchronously fire an {@link ElexisStatus} event.
*
* @param es
* an {@link ElexisStatus} describing the problem
* @since 3.0.0
*/
public static void fireElexisStatusEvent(ElexisStatus es){
ElexisEvent statusEvent =
new ElexisEvent(es, ElexisStatus.class, ElexisEvent.EVENT_ELEXIS_STATUS,
ElexisEvent.PRIORITY_SYNC);
getInstance().doDispatch(statusEvent);
}
/**
* find the last selected object of a given type
*
* @param template
* tha class defining the object to find
* @return the last object of the given type or null if no such object is selected
*/
public static IPersistentObject getSelected(final Class<?> template){
return getInstance().elexisUIContext.getSelected(template);
}
/**
* inform the system that an object has been selected
*
* @param po
* the object that is selected now
*/
public static void fireSelectionEvent(PersistentObject po){
if (po != null) {
getInstance().fire(new ElexisEvent(po, po.getClass(), ElexisEvent.EVENT_SELECTED));
}
}
/**
* inform the system, that several objects have been selected
*
* @param objects
*/
public static void fireSelectionEvents(PersistentObject... objects){
if (objects != null) {
ElexisEvent[] ees = new ElexisEvent[objects.length];
for (int i = 0; i < objects.length; i++) {
ees[i] =
new ElexisEvent(objects[i], objects[i].getClass(), ElexisEvent.EVENT_SELECTED);
}
getInstance().fire(ees);
}
}
/**
* inform the system, that no object of the specified type is selected anymore
*
* @param clazz
* the class of which selection was removed
*/
public static void clearSelection(Class<?> clazz){
if (clazz != null) {
getInstance().fire(new ElexisEvent(null, clazz, ElexisEvent.EVENT_DESELECTED));
}
}
/**
* inform the system, that all object of a specified class have to be reloaded from storage
*
* @param clazz
* the clazz whose objects are invalidated
*/
public static void reload(Class<?> clazz){
if (clazz != null) {
getInstance().fire(new ElexisEvent(null, clazz, ElexisEvent.EVENT_RELOAD));
}
}
/**
* inform the system, that the specified object has changed some values or properties
*
* @param po
* the object that was modified
*/
public static void update(PersistentObject po){
if (po != null) {
getInstance().fire(new ElexisEvent(po, po.getClass(), ElexisEvent.EVENT_UPDATE));
}
}
/** shortcut */
public static Patient getSelectedPatient(){
return (Patient) getSelected(Patient.class);
}
public void shutDown(){
bStop = true;
}
@Override
protected IStatus run(IProgressMonitor monitor){
// copy all events so doDispatch is outside of synchronization,
// and event handling can run code in display thread without deadlock
synchronized (eventQueue) {
while (!eventQueue.isEmpty()) {
eventCopy.add(eventQueue.poll());
}
eventQueue.notifyAll();
}
for (ElexisEvent event : eventCopy) {
doDispatch(event);
}
eventCopy.clear();
if (!bStop) {
this.schedule(30);
}
return Status.OK_STATUS;
}
private void doDispatch(final ElexisEvent ee){
if (ee != null) {
synchronized (listeners) {
for (final ElexisEventListener l : listeners) {
if (ee.matches(l.getElexisEventFilter())) {
l.catchElexisEvent(ee);
}
}
}
}
}
/**
* Let the dispatcher Thread empty the queue. If the queue is empty, this method returns
* immediately. Otherwise, the current thread waits until it is empty or the provided wasit time
* has expired.
*
* @param millis
* The time to wait bevor returning
* @return false if waiting was interrupted
*/
public boolean waitUntilEventQueueIsEmpty(long millis){
synchronized (eventQueue) {
if (!eventQueue.isEmpty()) {
try {
eventQueue.wait(millis);
return true;
} catch (InterruptedException e) {
// janusode
}
}
}
return false;
}
public void dump(){
StringBuilder sb = new StringBuilder();
sb.append("ElexisEventDispatcher dump: \n");
for (ElexisEventListener el : listeners) {
ElexisEvent filter = el.getElexisEventFilter();
sb.append(el.getClass().getName()).append(": ");
if (filter != null && filter.getObjectClass() != null
&& filter.getObjectClass().getName() != null) {
sb.append(filter.type).append(" / ").append(filter.getObjectClass().getName());
}
sb.append("\n");
}
sb.append("\n--------------\n");
log.debug(sb.toString());
}
}
| Introduce ElexisEventDispatcher#getSelectedMandator() | ch.elexis.core.data/src/ch/elexis/core/data/events/ElexisEventDispatcher.java | Introduce ElexisEventDispatcher#getSelectedMandator() |
|
Java | agpl-3.0 | 8d175b0521864ea328ce24c0d5dce17eda0477f9 | 0 | akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow | /*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.gwt.client.surveyinstance.QuestionAnswerStoreDto;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.surveyinstance.SurveyInstanceServiceImpl;
import org.waterforpeople.mapping.app.web.dto.DataProcessorRequest;
import org.waterforpeople.mapping.app.web.dto.RawDataImportRequest;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyInstance;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.framework.rest.AbstractRestApiServlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.gallatinsystems.framework.rest.RestResponse;
import com.gallatinsystems.messaging.dao.MessageDao;
import com.gallatinsystems.messaging.domain.Message;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.Question.Type;
import com.gallatinsystems.survey.domain.Survey;
import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
public class RawDataRestServlet extends AbstractRestApiServlet {
private static final long serialVersionUID = 2409014651721639814L;
private SurveyInstanceDAO instanceDao;
public RawDataRestServlet() {
instanceDao = new SurveyInstanceDAO();
}
@Override
protected RestRequest convertRequest() throws Exception {
HttpServletRequest req = getRequest();
RestRequest restRequest = new RawDataImportRequest();
restRequest.populateFromHttpRequest(req);
return restRequest;
}
@Override
protected RestResponse handleRequest(RestRequest req) throws Exception {
SurveyInstanceServiceImpl sisi = new SurveyInstanceServiceImpl();
RawDataImportRequest importReq = (RawDataImportRequest) req;
if (RawDataImportRequest.SAVE_SURVEY_INSTANCE_ACTION.equals(importReq
.getAction())) {
List<QuestionAnswerStoreDto> dtoList = new ArrayList<QuestionAnswerStoreDto>();
if (importReq.getSurveyInstanceId() == null
&& importReq.getSurveyId() != null) {
// if the instanceID is null, we need to create one
createInstance(importReq);
}
for (Map.Entry<Long, String[]> item : importReq
.getQuestionAnswerMap().entrySet()) {
QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto();
qasDto.setQuestionID(item.getKey().toString());
qasDto.setSurveyInstanceId(importReq.getSurveyInstanceId());
qasDto.setValue(item.getValue()[0]);
qasDto.setType(item.getValue()[1]);
qasDto.setSurveyId(importReq.getSurveyId());
qasDto.setCollectionDate(importReq.getCollectionDate());
dtoList.add(qasDto);
}
sisi.updateQuestions(dtoList, true, false);
} else if (RawDataImportRequest.RESET_SURVEY_INSTANCE_ACTION
.equals(importReq.getAction())) {
SurveyInstance instance = instanceDao.getByKey(importReq
.getSurveyInstanceId());
List<QuestionAnswerStore> oldAnswers = instanceDao
.listQuestionAnswerStore(importReq.getSurveyInstanceId(),
null);
if (oldAnswers != null && oldAnswers.size() > 0) {
instanceDao.delete(oldAnswers);
if (instance != null) {
instance.setLastUpdateDateTime(new Date());
if (importReq.getSubmitter() != null
&& importReq.getSubmitter().trim().length() > 0
&& !"null".equalsIgnoreCase(importReq
.getSubmitter().trim())) {
instance.setSubmitterName(importReq.getSubmitter());
}
instance.setSurveyId(importReq.getSurveyId());
instanceDao.save(instance);
}
} else {
if (instance == null) {
instance = new SurveyInstance();
instance.setKey(KeyFactory.createKey(
SurveyInstance.class.getSimpleName(),
importReq.getSurveyInstanceId()));
instance.setSurveyId(importReq.getSurveyId());
instance.setCollectionDate(importReq.getCollectionDate());
instance.setSubmitterName(importReq.getSubmitter());
instanceDao.save(instance);
} else {
instance.setLastUpdateDateTime(new Date());
if (importReq.getSubmitter() != null
&& importReq.getSubmitter().trim().length() > 0
&& !"null".equalsIgnoreCase(importReq
.getSubmitter().trim())) {
instance.setSubmitterName(importReq.getSubmitter());
}
instance.setSurveyId(importReq.getSurveyId());
instanceDao.save(instance);
}
}
} else if (RawDataImportRequest.SAVE_FIXED_FIELD_SURVEY_INSTANCE_ACTION
.equals(importReq.getAction())) {
if (importReq.getFixedFieldValues() != null
&& importReq.getFixedFieldValues().size() > 0) {
// this method assumes we're always creating a new instance
SurveyInstance inst = createInstance(importReq);
QuestionDao questionDao = new QuestionDao();
List<Question> questionList = questionDao
.listQuestionsBySurvey(importReq.getSurveyId());
if (questionList != null
&& questionList.size() >= importReq
.getFixedFieldValues().size()) {
List<QuestionAnswerStore> answers = new ArrayList<QuestionAnswerStore>();
for (int i = 0; i < importReq.getFixedFieldValues().size(); i++) {
String val = importReq.getFixedFieldValues().get(i);
if (val != null && val.trim().length() > 0) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(questionList.get(i).getKey()
.getId()
+ "");
ans.setValue(val);
Type type = questionList.get(i).getType();
if (Type.GEO == type) {
ans.setType(QuestionType.GEO.toString());
} else if (Type.PHOTO == type) {
ans.setType("IMAGE");
} else {
ans.setType("VALUE");
}
ans.setSurveyId(importReq.getSurveyId());
ans.setSurveyInstanceId(importReq
.getSurveyInstanceId());
ans.setCollectionDate(importReq.getCollectionDate());
answers.add(ans);
}
}
if (answers.size() > 0) {
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
qasDao.save(answers);
sisi.sendProcessingMessages(inst);
}
} else {
log("No questions found for the survey id "
+ importReq.getSurveyId());
}
// todo: send processing message
}
} else if (RawDataImportRequest.UPDATE_SUMMARIES_ACTION
.equalsIgnoreCase(importReq.getAction())) {
// first rebuild the summaries
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION);
String backendPub = PropertyUtil.getProperty("backendpublish");
if (backendPub != null && "true".equals(backendPub)) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
Long surveyId = importReq.getSurveyId();
if (surveyId != null && surveyId > 0) {
options.param(DataProcessorRequest.SURVEY_ID_PARAM,
surveyId.toString());
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
// now remap to access point
if (surveyId != null) {
SurveyServiceImpl ssi = new SurveyServiceImpl();
ssi.rerunAPMappings(surveyId);
}
} else if (RawDataImportRequest.SAVE_MESSAGE_ACTION
.equalsIgnoreCase(importReq.getAction())) {
List<Long> ids = new ArrayList<Long>();
ids.add(importReq.getSurveyId());
SurveyUtils.notifyReportService(ids, "invalidate");
MessageDao mdao = new MessageDao();
Message msg = new Message();
SurveyDAO sdao = new SurveyDAO();
Survey s = sdao.getById(importReq.getSurveyId());
msg.setShortMessage("Spreadsheet processed");
msg.setObjectId(importReq.getSurveyId());
msg.setObjectTitle(s.getPath() + "/" + s.getName());
msg.setActionAbout("spreadsheetProcessed");
mdao.save(msg);
}
return null;
}
/**
* constructs and persists a new surveyInstance using the data from the
* import request
*
* @param importReq
* @return
*/
private SurveyInstance createInstance(RawDataImportRequest importReq) {
SurveyInstance inst = new SurveyInstance();
inst.setSurveyId(importReq.getSurveyId());
inst.setCollectionDate(importReq.getCollectionDate() != null ? importReq
.getCollectionDate() : new Date());
inst.setApproximateLocationFlag("False");
inst.setDeviceIdentifier("IMPORTER");
inst.setSurveyedLocaleId(importReq.getSurveyedLocaleId());
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
inst = instDao.save(inst);
// set the key so the subsequent logic can populate it in the
// QuestionAnswerStore objects
importReq.setSurveyInstanceId(inst.getKey().getId());
if (importReq.getCollectionDate() == null) {
importReq.setCollectionDate(inst.getCollectionDate());
}
return inst;
}
@Override
protected void writeOkResponse(RestResponse resp) throws Exception {
// no-op
}
}
| GAE/src/org/waterforpeople/mapping/app/web/RawDataRestServlet.java | /*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.waterforpeople.mapping.app.gwt.client.survey.QuestionDto.QuestionType;
import org.waterforpeople.mapping.app.gwt.client.surveyinstance.QuestionAnswerStoreDto;
import org.waterforpeople.mapping.app.gwt.server.survey.SurveyServiceImpl;
import org.waterforpeople.mapping.app.gwt.server.surveyinstance.SurveyInstanceServiceImpl;
import org.waterforpeople.mapping.app.web.dto.DataProcessorRequest;
import org.waterforpeople.mapping.app.web.dto.RawDataImportRequest;
import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyInstance;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.framework.rest.AbstractRestApiServlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.gallatinsystems.framework.rest.RestResponse;
import com.gallatinsystems.messaging.dao.MessageDao;
import com.gallatinsystems.messaging.domain.Message;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.Question.Type;
import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
public class RawDataRestServlet extends AbstractRestApiServlet {
private static final long serialVersionUID = 2409014651721639814L;
private SurveyInstanceDAO instanceDao;
public RawDataRestServlet() {
instanceDao = new SurveyInstanceDAO();
}
@Override
protected RestRequest convertRequest() throws Exception {
HttpServletRequest req = getRequest();
RestRequest restRequest = new RawDataImportRequest();
restRequest.populateFromHttpRequest(req);
return restRequest;
}
@Override
protected RestResponse handleRequest(RestRequest req) throws Exception {
SurveyInstanceServiceImpl sisi = new SurveyInstanceServiceImpl();
RawDataImportRequest importReq = (RawDataImportRequest) req;
if (RawDataImportRequest.SAVE_SURVEY_INSTANCE_ACTION.equals(importReq
.getAction())) {
List<QuestionAnswerStoreDto> dtoList = new ArrayList<QuestionAnswerStoreDto>();
if (importReq.getSurveyInstanceId() == null
&& importReq.getSurveyId() != null) {
// if the instanceID is null, we need to create one
createInstance(importReq);
}
for (Map.Entry<Long, String[]> item : importReq
.getQuestionAnswerMap().entrySet()) {
QuestionAnswerStoreDto qasDto = new QuestionAnswerStoreDto();
qasDto.setQuestionID(item.getKey().toString());
qasDto.setSurveyInstanceId(importReq.getSurveyInstanceId());
qasDto.setValue(item.getValue()[0]);
qasDto.setType(item.getValue()[1]);
qasDto.setSurveyId(importReq.getSurveyId());
qasDto.setCollectionDate(importReq.getCollectionDate());
dtoList.add(qasDto);
}
sisi.updateQuestions(dtoList, true, false);
} else if (RawDataImportRequest.RESET_SURVEY_INSTANCE_ACTION
.equals(importReq.getAction())) {
SurveyInstance instance = instanceDao.getByKey(importReq
.getSurveyInstanceId());
List<QuestionAnswerStore> oldAnswers = instanceDao
.listQuestionAnswerStore(importReq.getSurveyInstanceId(),
null);
if (oldAnswers != null && oldAnswers.size() > 0) {
instanceDao.delete(oldAnswers);
if (instance != null) {
instance.setLastUpdateDateTime(new Date());
if (importReq.getSubmitter() != null
&& importReq.getSubmitter().trim().length() > 0
&& !"null".equalsIgnoreCase(importReq
.getSubmitter().trim())) {
instance.setSubmitterName(importReq.getSubmitter());
}
instance.setSurveyId(importReq.getSurveyId());
instanceDao.save(instance);
}
} else {
if (instance == null) {
instance = new SurveyInstance();
instance.setKey(KeyFactory.createKey(
SurveyInstance.class.getSimpleName(),
importReq.getSurveyInstanceId()));
instance.setSurveyId(importReq.getSurveyId());
instance.setCollectionDate(importReq.getCollectionDate());
instance.setSubmitterName(importReq.getSubmitter());
instanceDao.save(instance);
} else {
instance.setLastUpdateDateTime(new Date());
if (importReq.getSubmitter() != null
&& importReq.getSubmitter().trim().length() > 0
&& !"null".equalsIgnoreCase(importReq
.getSubmitter().trim())) {
instance.setSubmitterName(importReq.getSubmitter());
}
instance.setSurveyId(importReq.getSurveyId());
instanceDao.save(instance);
}
}
} else if (RawDataImportRequest.SAVE_FIXED_FIELD_SURVEY_INSTANCE_ACTION
.equals(importReq.getAction())) {
if (importReq.getFixedFieldValues() != null
&& importReq.getFixedFieldValues().size() > 0) {
// this method assumes we're always creating a new instance
SurveyInstance inst = createInstance(importReq);
QuestionDao questionDao = new QuestionDao();
List<Question> questionList = questionDao
.listQuestionsBySurvey(importReq.getSurveyId());
if (questionList != null
&& questionList.size() >= importReq
.getFixedFieldValues().size()) {
List<QuestionAnswerStore> answers = new ArrayList<QuestionAnswerStore>();
for (int i = 0; i < importReq.getFixedFieldValues().size(); i++) {
String val = importReq.getFixedFieldValues().get(i);
if (val != null && val.trim().length() > 0) {
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID(questionList.get(i).getKey()
.getId()
+ "");
ans.setValue(val);
Type type = questionList.get(i).getType();
if (Type.GEO == type) {
ans.setType(QuestionType.GEO.toString());
} else if (Type.PHOTO == type) {
ans.setType("IMAGE");
} else {
ans.setType("VALUE");
}
ans.setSurveyId(importReq.getSurveyId());
ans.setSurveyInstanceId(importReq
.getSurveyInstanceId());
ans.setCollectionDate(importReq.getCollectionDate());
answers.add(ans);
}
}
if (answers.size() > 0) {
QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao();
qasDao.save(answers);
sisi.sendProcessingMessages(inst);
}
} else {
log("No questions found for the survey id "
+ importReq.getSurveyId());
}
// todo: send processing message
}
} else if (RawDataImportRequest.UPDATE_SUMMARIES_ACTION
.equalsIgnoreCase(importReq.getAction())) {
// first rebuild the summaries
TaskOptions options = TaskOptions.Builder.withUrl(
"/app_worker/dataprocessor").param(
DataProcessorRequest.ACTION_PARAM,
DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION);
String backendPub = PropertyUtil.getProperty("backendpublish");
if (backendPub != null && "true".equals(backendPub)) {
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
}
Long surveyId = importReq.getSurveyId();
if (surveyId != null && surveyId > 0) {
options.param(DataProcessorRequest.SURVEY_ID_PARAM,
surveyId.toString());
}
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getDefaultQueue();
queue.add(options);
// now remap to access point
if (surveyId != null) {
SurveyServiceImpl ssi = new SurveyServiceImpl();
ssi.rerunAPMappings(surveyId);
}
} else if (RawDataImportRequest.SAVE_MESSAGE_ACTION
.equalsIgnoreCase(importReq.getAction())) {
List<Long> ids = new ArrayList<Long>();
ids.add(importReq.getSurveyId());
SurveyUtils.notifyReportService(ids, "invalidate");
MessageDao mdao = new MessageDao();
Message msg = new Message();
msg.setShortMessage("Spreadsheet processed");
msg.setObjectId(importReq.getSurveyId());
msg.setActionAbout("spreadsheetProcessed");
mdao.save(msg);
}
return null;
}
/**
* constructs and persists a new surveyInstance using the data from the
* import request
*
* @param importReq
* @return
*/
private SurveyInstance createInstance(RawDataImportRequest importReq) {
SurveyInstance inst = new SurveyInstance();
inst.setSurveyId(importReq.getSurveyId());
inst.setCollectionDate(importReq.getCollectionDate() != null ? importReq
.getCollectionDate() : new Date());
inst.setApproximateLocationFlag("False");
inst.setDeviceIdentifier("IMPORTER");
inst.setSurveyedLocaleId(importReq.getSurveyedLocaleId());
SurveyInstanceDAO instDao = new SurveyInstanceDAO();
inst = instDao.save(inst);
// set the key so the subsequent logic can populate it in the
// QuestionAnswerStore objects
importReq.setSurveyInstanceId(inst.getKey().getId());
if (importReq.getCollectionDate() == null) {
importReq.setCollectionDate(inst.getCollectionDate());
}
return inst;
}
@Override
protected void writeOkResponse(RestResponse resp) throws Exception {
// no-op
}
}
| Issue #205 - Adds Object Title when saving the message
| GAE/src/org/waterforpeople/mapping/app/web/RawDataRestServlet.java | Issue #205 - Adds Object Title when saving the message |
|
Java | agpl-3.0 | c57351e27cc15ee8eeda2b9931d8fec7014f188e | 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 | 70d417d6-2e62-11e5-9284-b827eb9e62be | hello.java | 70cea6d4-2e62-11e5-9284-b827eb9e62be | 70d417d6-2e62-11e5-9284-b827eb9e62be | hello.java | 70d417d6-2e62-11e5-9284-b827eb9e62be |
|
Java | agpl-3.0 | 4b02e6faf3dc374e3fa9121c5810c60c1599d25c | 0 | pughlab/cbioportal,cBioPortal/cbioportal,onursumer/cbioportal,angelicaochoa/cbioportal,HectorWon/cbioportal,adamabeshouse/cbioportal,jjgao/cbioportal,yichaoS/cbioportal,istemi-bahceci/cbioportal,shrumit/cbioportal-gsoc-final,zhx828/cbioportal,n1zea144/cbioportal,n1zea144/cbioportal,onursumer/cbioportal,mandawilson/cbioportal,zheins/cbioportal,pughlab/cbioportal,kalletlak/cbioportal,leedonghn4/cbioportal,istemi-bahceci/cbioportal,cBioPortal/cbioportal,holtgrewe/cbioportal,adamabeshouse/cbioportal,mandawilson/cbioportal,zhx828/cbioportal,yichaoS/cbioportal,bengusty/cbioportal,xmao/cbioportal,zhx828/cbioportal,mandawilson/cbioportal,zheins/cbioportal,pughlab/cbioportal,leedonghn4/cbio-portal-webgl,IntersectAustralia/cbioportal,inodb/cbioportal,HectorWon/cbioportal,sheridancbio/cbioportal,yichaoS/cbioportal,fcriscuo/cbioportal,inodb/cbioportal,istemi-bahceci/cbioportal,d3b-center/pedcbioportal,HectorWon/cbioportal,adamabeshouse/cbioportal,leedonghn4/cbioportal,zhx828/cbioportal,HectorWon/cbioportal,fcriscuo/cbioportal,pughlab/cbioportal,d3b-center/pedcbioportal,leedonghn4/cbioportal,sheridancbio/cbioportal,IntersectAustralia/cbioportal,leedonghn4/cbioportal,IntersectAustralia/cbioportal,gsun83/cbioportal,kalletlak/cbioportal,bengusty/cbioportal,bengusty/cbioportal,sheridancbio/cbioportal,kalletlak/cbioportal,xmao/cbioportal,xmao/cbioportal,angelicaochoa/cbioportal,bihealth/cbioportal,mandawilson/cbioportal,d3b-center/pedcbioportal,j-hudecek/cbioportal,n1zea144/cbioportal,yichaoS/cbioportal,fcriscuo/cbioportal,leedonghn4/cbio-portal-webgl,kalletlak/cbioportal,shrumit/cbioportal-gsoc-final,n1zea144/cbioportal,IntersectAustralia/cbioportal,n1zea144/cbioportal,cBioPortal/cbioportal,zhx828/cbioportal,shrumit/cbioportal-gsoc-final,jjgao/cbioportal,leedonghn4/cbio-portal-webgl,jjgao/cbioportal,yichaoS/cbioportal,yichaoS/cbioportal,HectorWon/cbioportal,bihealth/cbioportal,n1zea144/cbioportal,shrumit/cbioportal-gsoc-final,holtgrewe/cbioportal,leedonghn4/cbio-portal-webgl,gsun83/cbioportal,inodb/cbioportal,fcriscuo/cbioportal,adamabeshouse/cbioportal,bihealth/cbioportal,HectorWon/cbioportal,mandawilson/cbioportal,bengusty/cbioportal,angelicaochoa/cbioportal,inodb/cbioportal,j-hudecek/cbioportal,angelicaochoa/cbioportal,adamabeshouse/cbioportal,IntersectAustralia/cbioportal,n1zea144/cbioportal,d3b-center/pedcbioportal,kalletlak/cbioportal,zheins/cbioportal,cBioPortal/cbioportal,kalletlak/cbioportal,kalletlak/cbioportal,inodb/cbioportal,zhx828/cbioportal,IntersectAustralia/cbioportal,sheridancbio/cbioportal,d3b-center/pedcbioportal,xmao/cbioportal,inodb/cbioportal,d3b-center/pedcbioportal,gsun83/cbioportal,xmao/cbioportal,bengusty/cbioportal,zhx828/cbioportal,j-hudecek/cbioportal,cBioPortal/cbioportal,leedonghn4/cbioportal,adamabeshouse/cbioportal,onursumer/cbioportal,gsun83/cbioportal,onursumer/cbioportal,fcriscuo/cbioportal,istemi-bahceci/cbioportal,fcriscuo/cbioportal,j-hudecek/cbioportal,j-hudecek/cbioportal,zheins/cbioportal,leedonghn4/cbio-portal-webgl,bihealth/cbioportal,onursumer/cbioportal,angelicaochoa/cbioportal,zheins/cbioportal,leedonghn4/cbioportal,shrumit/cbioportal-gsoc-final,shrumit/cbioportal-gsoc-final,j-hudecek/cbioportal,angelicaochoa/cbioportal,shrumit/cbioportal-gsoc-final,cBioPortal/cbioportal,jjgao/cbioportal,sheridancbio/cbioportal,yichaoS/cbioportal,jjgao/cbioportal,zheins/cbioportal,jjgao/cbioportal,bihealth/cbioportal,pughlab/cbioportal,xmao/cbioportal,holtgrewe/cbioportal,istemi-bahceci/cbioportal,mandawilson/cbioportal,angelicaochoa/cbioportal,pughlab/cbioportal,gsun83/cbioportal,jjgao/cbioportal,bengusty/cbioportal,holtgrewe/cbioportal,onursumer/cbioportal,holtgrewe/cbioportal,sheridancbio/cbioportal,bihealth/cbioportal,leedonghn4/cbio-portal-webgl,gsun83/cbioportal,pughlab/cbioportal,inodb/cbioportal,bihealth/cbioportal,d3b-center/pedcbioportal,mandawilson/cbioportal,IntersectAustralia/cbioportal,adamabeshouse/cbioportal,holtgrewe/cbioportal,gsun83/cbioportal,istemi-bahceci/cbioportal | /** Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center.
**
** 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
** 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. The software and
** documentation provided hereunder is on an "as is" basis, and
** Memorial Sloan-Kettering Cancer Center
** has no obligations to provide maintenance, support,
** updates, enhancements or modifications. In no event shall
** Memorial Sloan-Kettering Cancer Center
** be liable to any party for direct, indirect, special,
** incidental or consequential damages, including lost profits, arising
** out of the use of this software and its documentation, even if
** Memorial Sloan-Kettering Cancer Center
** has been advised of the possibility of such damage. 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.mskcc.cbio.portal.servlet;
import java.io.*;
import java.util.*;
import org.json.simple.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONValue;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.model.*;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
/**
* Get the top co-expressed genes for queried genes
*
* @param : cancer study id
* @param : queried genes
* @return : JSON objects of co-expression under the same cancer_study
* (but always the mrna genetic profile)
*/
public class GetCoExpressionJSON extends HttpServlet {
/**
* Handles HTTP GET Request.
*
* @param httpServletRequest HttpServletRequest
* @param httpServletResponse HttpServletResponse
* @throws ServletException
*/
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
doPost(httpServletRequest, httpServletResponse);
}
/**
* Handles the HTTP POST Request.
*
* @param httpServletRequest HttpServletRequest
* @param httpServletResponse HttpServletResponse
* @throws ServletException
*/
protected void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
String cancerStudyIdentifier = httpServletRequest.getParameter("cancer_study_id");
String geneListStr = httpServletRequest.getParameter("gene_list");
//Convert gene symbol (string) to gene ID (int)
DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();
String[] geneList = geneListStr.split("\\s+");
Collection<Long> queryGenes = new ArrayList<Long>();
for (String gene_item : geneList) {
CanonicalGene geneObj = daoGeneOptimized.getGene(gene_item);
queryGenes.add(geneObj.getEntrezGeneId());
}
//Find the qualified genetic profile under the queried cancer study
CancerStudy cs = DaoCancerStudy.getCancerStudyByStableId(cancerStudyIdentifier);
ArrayList<GeneticProfile> gps = DaoGeneticProfile.getAllGeneticProfiles(cs.getInternalId());
GeneticProfile final_gp = null;
for (GeneticProfile gp : gps) {
// TODO: support miRNA later
if (gp.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION) {
//rna seq profile (no z-scores applied) holds the highest priority)
if (gp.getStableId().toLowerCase().contains("rna_seq") &&
!gp.getStableId().toLowerCase().contains("zscores")) {
final_gp = gp;
break;
} else if (!gp.getStableId().toLowerCase().contains("zscores")) {
final_gp = gp;
}
}
}
if (final_gp != null) {
try {
//Get the alteration value for all genes under input cancer study
Map<Long,double[]> map = getExpressionMap(final_gp.getGeneticProfileId());
int mapSize = map.size();
//Set the threshold
double coExpScoreThreshold = 0.3;
//Get the gene list (all genes)
List<Long> genes = new ArrayList<Long>(map.keySet());
//Init spearman and pearson
PearsonsCorrelation pearsonsCorrelation = new PearsonsCorrelation();
//SpearmansCorrelation spearmansCorrelation = new SpearmansCorrelation();
//Init result container
JSONObject result = new JSONObject();
for (Long i_queryGene : queryGenes) {
JSONObject _obj = new JSONObject();
for (int i = 0; i < mapSize; i++) {
double[] query_gene_exp = map.get(i_queryGene);
long compared_gene_id = genes.get(i);
double[] compared_gene_exp = map.get(compared_gene_id);
if (compared_gene_exp != null && query_gene_exp != null) {
double pearson = pearsonsCorrelation.correlation(query_gene_exp, compared_gene_exp);
// double spearman = spearmansCorrelation.correlation(query_gene_exp, compared_gene_exp);
if ((pearson > coExpScoreThreshold || pearson < (-1) * coExpScoreThreshold ) &&
//(spearman > coExpScoreThreshold || spearman < (-1) * coExpScoreThreshold) &&
(compared_gene_id != i_queryGene)){
JSONObject _scores = new JSONObject();
_scores.put("pearson", pearson);
//_scores.put("spearman", spearman);
_obj.put(compared_gene_id, _scores);
}
}
}
result.put(i_queryGene, _obj);
}
httpServletResponse.setContentType("application/json");
PrintWriter out = httpServletResponse.getWriter();
JSONValue.writeJSONString(result, out);
} catch (DaoException e) {
System.out.println(e.getMessage());
}
} else {
httpServletResponse.setContentType("text/html");
PrintWriter out = httpServletResponse.getWriter();
out.print("Error: No genetic profiles available for: " + cancerStudyIdentifier);
out.flush();
}
}
private Map<Long,double[]> getExpressionMap(int profileId) throws DaoException {
ArrayList<String> orderedCaseList = DaoGeneticProfileCases.getOrderedCaseList(profileId);
int nCases = orderedCaseList.size();
DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance();
Map<Long, HashMap<String, String>> mapStr = daoGeneticAlteration.getGeneticAlterationMap(profileId, null);
Map<Long, double[]> map = new HashMap<Long, double[]>(mapStr.size());
for (Map.Entry<Long, HashMap<String, String>> entry : mapStr.entrySet()) {
Long gene = entry.getKey();
Map<String, String> mapCaseValueStr = entry.getValue();
double[] values = new double[nCases];
for (int i = 0; i < nCases; i++) {
String caseId = orderedCaseList.get(i);
String value = mapCaseValueStr.get(caseId);
Double d;
try {
d = Double.valueOf(value);
} catch (Exception e) {
d = Double.NaN;
}
if (d!=null && !d.isNaN()) {
values[i]=d;
}
}
map.put(gene, values);
}
return map;
}
} | core/src/main/java/org/mskcc/cbio/portal/servlet/GetCoExpressionJSON.java | /** Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center.
**
** 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
** 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. The software and
** documentation provided hereunder is on an "as is" basis, and
** Memorial Sloan-Kettering Cancer Center
** has no obligations to provide maintenance, support,
** updates, enhancements or modifications. In no event shall
** Memorial Sloan-Kettering Cancer Center
** be liable to any party for direct, indirect, special,
** incidental or consequential damages, including lost profits, arising
** out of the use of this software and its documentation, even if
** Memorial Sloan-Kettering Cancer Center
** has been advised of the possibility of such damage. 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.mskcc.cbio.portal.servlet;
import java.io.*;
import java.util.*;
import org.json.simple.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONValue;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.model.*;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
/**
* Get the top co-expressed genes for queried genes
*
* @param : cancer study id
* @param : queried genes
* @return : JSON objects of co-expression under the same cancer_study
* (but always the mrna genetic profile)
*/
public class GetCoExpressionJSON extends HttpServlet {
/**
* Handles HTTP GET Request.
*
* @param httpServletRequest HttpServletRequest
* @param httpServletResponse HttpServletResponse
* @throws ServletException
*/
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
doPost(httpServletRequest, httpServletResponse);
}
/**
* Handles the HTTP POST Request.
*
* @param httpServletRequest HttpServletRequest
* @param httpServletResponse HttpServletResponse
* @throws ServletException
*/
protected void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
String cancerStudyIdentifier = httpServletRequest.getParameter("cancer_study_id");
String geneListStr = httpServletRequest.getParameter("gene_list");
//Convert gene symbol (string) to gene ID (int)
DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();
String[] geneList = geneListStr.split("\\s+");
Collection<Long> queryGenes = new ArrayList<Long>();
for (String gene_item : geneList) {
CanonicalGene geneObj = daoGeneOptimized.getGene(gene_item);
queryGenes.add(geneObj.getEntrezGeneId());
}
//Find the qualified genetic profile under the queried cancer study
CancerStudy cs = DaoCancerStudy.getCancerStudyByStableId(cancerStudyIdentifier);
ArrayList<GeneticProfile> gps = DaoGeneticProfile.getAllGeneticProfiles(cs.getInternalId());
GeneticProfile final_gp = null;
for (GeneticProfile gp : gps) {
// TODO: support miRNA later
if (gp.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION) {
//rna seq profile (no z-scores applied) holds the highest priority)
if (gp.getStableId().toLowerCase().contains("rna_seq") &&
!gp.getStableId().toLowerCase().contains("zscores")) {
final_gp = gp;
break;
} else if (!gp.getStableId().toLowerCase().contains("zscores")) {
final_gp = gp;
}
}
}
if (final_gp != null) {
try {
//Get the alteration value for all genes under input cancer study
Map<Long,double[]> map = getExpressionMap(final_gp.getGeneticProfileId());
int mapSize = map.size();
//Get the gene list (all genes)
List<Long> genes = new ArrayList<Long>(map.keySet());
//Init spearman and pearson
PearsonsCorrelation pearsonsCorrelation = new PearsonsCorrelation();
SpearmansCorrelation spearmansCorrelation = new SpearmansCorrelation();
//Init result container
JSONObject result = new JSONObject();
for (Long i_queryGene : queryGenes) {
JSONObject _obj = new JSONObject();
for (int i = 0; i < mapSize; i++) {
double[] query_gene_exp = map.get(i_queryGene);
long compared_gene_id = genes.get(i);
double[] compared_gene_exp = map.get(compared_gene_id);
double pearson = pearsonsCorrelation.correlation(query_gene_exp, compared_gene_exp);
double spearman = spearmansCorrelation.correlation(query_gene_exp, compared_gene_exp);
JSONObject _scores = new JSONObject();
_scores.put("pearson", pearson);
_scores.put("spearman", spearman);
_obj.put(compared_gene_id, _scores);
}
result.put(i_queryGene, _obj);
httpServletResponse.setContentType("application/json");
PrintWriter out = httpServletResponse.getWriter();
JSONValue.writeJSONString(result, out);
}
} catch (DaoException e) {
System.out.println(e.getMessage());
}
} else {
httpServletResponse.setContentType("application/text");
PrintWriter out = httpServletResponse.getWriter();
out.print("Error: No genetic profiles available for: " + cancerStudyIdentifier);
out.flush();
}
}
private Map<Long,double[]> getExpressionMap(int profileId) throws DaoException {
ArrayList<String> orderedCaseList = DaoGeneticProfileCases.getOrderedCaseList(profileId);
int nCases = orderedCaseList.size();
DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance();
Map<Long, HashMap<String, String>> mapStr = daoGeneticAlteration.getGeneticAlterationMap(profileId, null);
Map<Long, double[]> map = new HashMap<Long, double[]>(mapStr.size());
for (Map.Entry<Long, HashMap<String, String>> entry : mapStr.entrySet()) {
Long gene = entry.getKey();
Map<String, String> mapCaseValueStr = entry.getValue();
double[] values = new double[nCases];
for (int i = 0; i < nCases; i++) {
String caseId = orderedCaseList.get(i);
String value = mapCaseValueStr.get(caseId);
Double d;
try {
d = Double.valueOf(value);
} catch (Exception e) {
d = Double.NaN;
}
if (d!=null && !d.isNaN()) {
values[i]=d;
}
}
map.put(gene, values);
}
return map;
}
} | calc v3
| core/src/main/java/org/mskcc/cbio/portal/servlet/GetCoExpressionJSON.java | calc v3 |
|
Java | agpl-3.0 | 7f6b65b91290d2ab0a4c7753dde5f77c032e46bf | 0 | VolumetricPixels/Politics | /*
* This file is part of Politics.
*
* Copyright (c) 2012-2012, VolumetricPixels <http://volumetricpixels.com/>
* Politics is licensed under the Affero General Public License Version 3.
*
* 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 com.volumetricpixels.politics.universe;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.map.hash.TLongObjectHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import org.bson.types.BasicBSONList;
import org.spout.api.Server;
import org.spout.api.Spout;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.volumetricpixels.politics.Politics;
import com.volumetricpixels.politics.PoliticsPlugin;
import com.volumetricpixels.politics.data.Storable;
import com.volumetricpixels.politics.group.Citizen;
import com.volumetricpixels.politics.group.Group;
import com.volumetricpixels.politics.group.GroupLevel;
import com.volumetricpixels.politics.plot.PoliticsWorld;
/**
* Represents a headless group of all groups within its scope.
*/
public class Universe implements Storable {
/**
* The name of the universe.
*/
private final String name;
/**
* Contains the rules of this universe.
*/
private final UniverseRules rules;
/**
* Contains the worlds in which this universe is part of.
*/
private List<PoliticsWorld> worlds;
/**
* The groups in this universe manager.
*/
private List<Group> groups;
/**
* Contains the immediate children of each group.
*/
private Map<Group, Set<Group>> children;
/**
* Groups in the given levels.
*/
private Map<GroupLevel, List<Group>> levels;
/**
* Cache containing citizens.
*/
private LoadingCache<String, Citizen> citizenCache;
/**
* C'tor
*/
public Universe(String name, UniverseRules properties) {
this(name, properties, new ArrayList<PoliticsWorld>(), new ArrayList<Group>(), new HashMap<Group, Set<Group>>());
}
/**
* C'tor
*
* @param name
* @param properties
* @param worlds
* @param groups
* @param children
*/
public Universe(String name, UniverseRules properties, List<PoliticsWorld> worlds, List<Group> groups, Map<Group, Set<Group>> children) {
this.name = name;
this.rules = properties;
this.worlds = worlds;
this.groups = groups;
this.children = children;
buildCitizenCache();
levels = new HashMap<GroupLevel, List<Group>>();
for (Group group : groups) {
getInternalGroups(group.getLevel()).add(group);
}
}
/**
* Builds the citizen cache.
*/
private void buildCitizenCache() {
// Build cache
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
builder.maximumSize(((Server) Spout.getEngine()).getMaxPlayers());
builder.expireAfterAccess(10L, TimeUnit.MINUTES);
citizenCache = builder.build(new CacheLoader<String, Citizen>() {
@Override
public Citizen load(String name) throws Exception {
Set<Group> myGroups = new HashSet<Group>();
for (Group group : groups) {
if (group.isImmediateMember(name)) {
myGroups.add(group);
}
}
return new Citizen(name, myGroups, Universe.this);
}
});
}
/**
* Gets the name of this Universe.
*
* @return
*/
public String getName() {
return name;
}
/**
* Gets the rules of this universe.
*
* @return
*/
public UniverseRules getRules() {
return rules;
}
/**
* Gets a list of all groups in the universe.
*
* @return
*/
public List<Group> getGroups() {
return new ArrayList<Group>(groups);
}
/**
* Gets a list of all worlds this universe is part of.
*
* @return
*/
public List<PoliticsWorld> getWorlds() {
return new ArrayList<PoliticsWorld>(worlds);
}
/**
* Gets a list of all groups with the given level in this universe.
*
* @param level
* @return
*/
public List<Group> getGroups(GroupLevel level) {
return new ArrayList<Group>(getInternalGroups(level));
}
/**
* Gets the internal groups corresponding with the given level.
*
* @param level
* @return
*/
private List<Group> getInternalGroups(GroupLevel level) {
List<Group> levelGroups = levels.get(level);
if (levelGroups == null) {
levelGroups = new ArrayList<Group>();
levels.put(level, levelGroups);
}
return levelGroups;
}
/**
* Gets the child groups of the given group.
*
* @param group
* @return
*/
public Set<Group> getChildGroups(Group group) {
return new HashSet<Group>(getInternalChildGroups(group));
}
/**
* Gets the internal child groups of the given group.
*
* @param group
* @return
*/
private Set<Group> getInternalChildGroups(Group group) {
if (group == null) {
return new HashSet<Group>();
}
Set<Group> childs = children.get(group);
if (childs == null) {
return new HashSet<Group>();
}
return childs;
}
/**
* Adds the given child as a child for the given group.
*
* @param group
* @param child
* @return True if the group could be made a child
*/
public boolean addChildGroup(Group group, Group child) {
if (!group.getLevel().canBeChild(child.getLevel())) {
return false;
}
Set<Group> childs = children.get(group);
if (childs == null) {
childs = new HashSet<Group>();
}
childs.add(child);
return true;
}
/**
* Removes the given child group from the children of the given group.
*
* @param group
* @param child
* @return True if the child was removed, false if the child was not a child
* in the first place
*/
public boolean removeChildGroup(Group group, Group child) {
Set<Group> childs = children.get(group);
if (childs == null) {
return false;
}
return childs.remove(child);
}
/**
* Creates a new group with the given level.
*
* @param level
* @return
*/
public Group createGroup(GroupLevel level) {
Group group = new Group(Politics.getUniverseManager().nextId(), level);
// Update the three lists
groups.add(group);
getInternalGroups(level).add(group);
return group;
}
/**
* Destroys the given group and removes it from memory.
*
* @param group
*/
public void destroyGroup(Group group) {
destroyGroup(group, false);
}
/**
* Destroys the given group and removes it from memory.
*
* @param group
* The group to destroy
* @param deep
* True if child groups should be deleted
*/
public void destroyGroup(Group group, boolean deep) {
groups.remove(group);
getInternalGroups(group.getLevel()).remove(group);
for (String member : group.getPlayers()) {
invalidateCitizen(member);
}
if (deep) {
for (Group child : group.getGroups()) {
destroyGroup(child, true);
}
}
children.remove(group);
// This can be expensive -- beware!
for (Set<Group> childrenOfAGroup : children.values()) {
if (childrenOfAGroup.contains(group)) {
childrenOfAGroup.remove(group);
}
}
}
/**
* Gets the citizen corresponding with the given player name.
*
* @param player
* @return
*/
public Citizen getCitizen(String player) {
try {
return citizenCache.get(player);
} catch (ExecutionException ex) {
PoliticsPlugin.logger().log(Level.SEVERE, "Could not load a citizen! This is a PROBLEM!", ex);
return null;
}
}
/**
* Invalidates the given citizen.
*
* @param citizen
*/
public void invalidateCitizen(String citizen) {
citizenCache.invalidate(citizen);
}
@Override
public BasicBSONObject toBSONObject() {
BasicBSONObject bson = new BasicBSONObject();
bson.put("name", name);
bson.put("rules", rules.getName());
BasicBSONList groupsBson = new BasicBSONList();
BasicBSONObject childrenBson = new BasicBSONObject();
for (Group group : groups) {
// groups
groupsBson.add(group.toBSONObject());
// children
BasicBSONList children = new BasicBSONList();
for (Group child : group.getGroups()) {
children.add(child.getUid());
}
childrenBson.put(Long.toHexString(group.getUid()), children);
}
bson.put("groups", groupsBson);
bson.put("children", childrenBson);
return bson;
}
/**
* Converts the given bson object into a new Universe.
*
* @param object
* @return
*/
public static Universe fromBSONObject(BSONObject object) {
if (!(object instanceof BasicBSONObject)) {
throw new IllegalStateException("object is not a BasicBsonObject! ERROR ERROR ERROR!");
}
BasicBSONObject bobject = (BasicBSONObject) object;
String aname = bobject.getString("name");
String rulesName = bobject.getString("rules");
UniverseRules rules = Politics.getUniverseManager().getRules(rulesName);
if (rules == null) {
throw new IllegalStateException("Rules do not exist!");
}
List<PoliticsWorld> worlds = new ArrayList<PoliticsWorld>();
Object worldsObj = bobject.get("worlds");
if (!(worldsObj instanceof BasicBSONList)) {
throw new IllegalStateException("GroupWorlds object is not a list!!! ASDFASDF");
}
BasicBSONList worldsBson = (BasicBSONList) worldsObj;
for (Object worldName : worldsBson) {
String name = worldName.toString();
PoliticsWorld world = Politics.getPlotManager().getWorld(name);
if (world == null) {
PoliticsPlugin.logger().log(Level.WARNING, "GroupWorld `" + name + "' could not be found! (Did you delete it?)");
} else {
worlds.add(world);
}
}
Object groupsObj = bobject.get("groups");
if (!(groupsObj instanceof BasicBSONList)) {
throw new IllegalStateException("groups isn't a list?! wtfhax?");
}
BasicBSONList groupsBson = (BasicBSONList) groupsObj;
TLongObjectMap<Group> groups = new TLongObjectHashMap<Group>();
for (Object groupBson : groupsBson) {
if (!(groupBson instanceof BasicBSONObject)) {
throw new IllegalStateException("Invalid group!");
}
Group c = Group.fromBSONObject(rules, (BasicBSONObject) groupBson);
groups.put(c.getUid(), c);
}
Map<Group, Set<Group>> children = new HashMap<Group, Set<Group>>();
Object childrenObj = bobject.get("children");
if (!(childrenObj instanceof BasicBSONObject)) {
throw new IllegalStateException("Missing children report!");
}
BasicBSONObject childrenBson = (BasicBSONObject) childrenObj;
for (Entry<String, Object> childEntry : childrenBson.entrySet()) {
String groupId = childEntry.getKey();
long uid = Long.parseLong(groupId, 16);
Group c = groups.get(uid);
if (c == null) {
throw new IllegalStateException("Unknown group id " + Long.toHexString(uid));
}
Object childsObj = childEntry.getValue();
if (!(childsObj instanceof BasicBSONList)) {
throw new IllegalStateException("No bson list found for childsObj");
}
Set<Group> childrenn = new HashSet<Group>();
BasicBSONList childs = (BasicBSONList) childsObj;
for (Object childN : childs) {
long theuid = (Long) childN;
Group ch = groups.get(theuid);
childrenn.add(ch);
}
children.put(c, childrenn);
}
List<Group> groupz = new ArrayList<Group>(groups.valueCollection());
Universe universe = new Universe(aname, rules, worlds, groupz, children);
for (Group group : groupz) {
group.initialize(universe);
}
return universe;
}
}
| src/main/java/com/volumetricpixels/politics/universe/Universe.java | /*
* This file is part of Politics.
*
* Copyright (c) 2012-2012, VolumetricPixels <http://volumetricpixels.com/>
* Politics is licensed under the Affero General Public License Version 3.
*
* 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 com.volumetricpixels.politics.universe;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.map.hash.TLongObjectHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.bson.BSONObject;
import org.bson.BasicBSONObject;
import org.bson.types.BasicBSONList;
import org.spout.api.Server;
import org.spout.api.Spout;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.volumetricpixels.politics.Politics;
import com.volumetricpixels.politics.PoliticsPlugin;
import com.volumetricpixels.politics.data.Storable;
import com.volumetricpixels.politics.group.Citizen;
import com.volumetricpixels.politics.group.Group;
import com.volumetricpixels.politics.group.GroupLevel;
import com.volumetricpixels.politics.plot.PoliticsWorld;
/**
* Represents a headless group of all groups within its scope.
*/
public class Universe implements Storable {
/**
* The name of the universe.
*/
private final String name;
/**
* Contains the rules of this universe.
*/
private final UniverseRules rules;
/**
* Contains the worlds in which this universe is part of.
*/
private List<PoliticsWorld> worlds;
/**
* The groups in this universe manager.
*/
private List<Group> groups;
/**
* Contains the immediate children of each group.
*/
private Map<Group, Set<Group>> children;
/**
* Groups in the given levels.
*/
private Map<GroupLevel, List<Group>> levels;
/**
* Cache containing citizens.
*/
private LoadingCache<String, Citizen> citizenCache;
/**
* C'tor
*/
public Universe(String name, UniverseRules properties) {
this(name, properties, new ArrayList<PoliticsWorld>(), new ArrayList<Group>(), new HashMap<Group, Set<Group>>());
}
/**
* C'tor
*
* @param name
* @param properties
* @param worlds
* @param groups
* @param children
*/
public Universe(String name, UniverseRules properties, List<PoliticsWorld> worlds, List<Group> groups, Map<Group, Set<Group>> children) {
this.name = name;
this.rules = properties;
this.worlds = worlds;
this.groups = groups;
this.children = children;
buildCitizenCache();
levels = new HashMap<GroupLevel, List<Group>>();
for (Group group : groups) {
getInternalGroups(group.getLevel()).add(group);
}
}
/**
* Builds the citizen cache.
*/
private void buildCitizenCache() {
// Build cache
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
builder.maximumSize(((Server) Spout.getEngine()).getMaxPlayers());
builder.expireAfterAccess(10L, TimeUnit.MINUTES);
citizenCache = builder.build(new CacheLoader<String, Citizen>() {
@Override
public Citizen load(String name) throws Exception {
Set<Group> myGroups = new HashSet<Group>();
for (Group group : groups) {
if (group.isImmediateMember(name)) {
myGroups.add(group);
}
}
return new Citizen(name, myGroups, Universe.this);
}
});
}
/**
* Gets the name of this Universe.
*
* @return
*/
public String getName() {
return name;
}
/**
* Gets the rules of this universe.
*
* @return
*/
public UniverseRules getRules() {
return rules;
}
/**
* Gets a list of all groups in the universe.
*
* @return
*/
public List<Group> getGroups() {
return new ArrayList<Group>(groups);
}
/**
* Gets a list of all worlds this universe is part of.
*
* @return
*/
public List<PoliticsWorld> getWorlds() {
return new ArrayList<PoliticsWorld>(worlds);
}
/**
* Gets a list of all groups with the given level in this universe.
*
* @param level
* @return
*/
public List<Group> getGroups(GroupLevel level) {
return new ArrayList<Group>(getInternalGroups(level));
}
/**
* Gets the internal groups corresponding with the given level.
*
* @param level
* @return
*/
private List<Group> getInternalGroups(GroupLevel level) {
List<Group> levelGroups = levels.get(level);
if (levelGroups == null) {
levelGroups = new ArrayList<Group>();
levels.put(level, levelGroups);
}
return levelGroups;
}
/**
* Gets the child groups of the given group.
*
* @param group
* @return
*/
public Set<Group> getChildGroups(Group group) {
return new HashSet<Group>(getInternalChildGroups(group));
}
/**
* Gets the internal child groups of the given group.
*
* @param group
* @return
*/
private Set<Group> getInternalChildGroups(Group group) {
if (group == null) {
return new HashSet<Group>();
}
Set<Group> childs = children.get(group);
if (childs == null) {
return new HashSet<Group>();
}
return childs;
}
/**
* Adds the given child as a child for the given group.
*
* @param group
* @param child
* @return True if the group could be made a child
*/
public boolean addChildGroup(Group group, Group child) {
if (!group.getLevel().canBeChild(child.getLevel())) {
return false;
}
Set<Group> childs = children.get(group);
if (childs == null) {
childs = new HashSet<Group>();
}
childs.add(child);
return true;
}
/**
* Removes the given child group from the children of the given group.
*
* @param group
* @param child
* @return True if the child was removed, false if the child was not a child
* in the first place
*/
public boolean removeChildGroup(Group group, Group child) {
Set<Group> childs = children.get(group);
if (childs == null) {
return false;
}
return childs.remove(child);
}
/**
* Creates a new group with the given level.
*
* @param level
* @return
*/
public Group createGroup(GroupLevel level) {
Group group = new Group(Politics.getUniverseManager().nextId(), level);
// Update the three lists
groups.add(group);
getInternalGroups(level).add(group);
return group;
}
/**
* Destroys the given group and removes it from memory.
*
* @param group
*/
public void destroyGroup(Group group) {
destroyGroup(group, false);
}
/**
* Destroys the given group and removes it from memory.
*
* @param group
* The group to destroy
* @param deep
* True if child groups should be deleted
*/
public void destroyGroup(Group group, boolean deep) {
groups.remove(group);
getInternalGroups(group.getLevel()).remove(group);
for (String member : group.getPlayers()) {
invalidateCitizen(member);
}
if (deep) {
for (Group child : group.getGroups()) {
destroyGroup(child, true);
}
}
// TODO remove the group from the children tree
}
/**
* Gets the citizen corresponding with the given player name.
*
* @param player
* @return
*/
public Citizen getCitizen(String player) {
try {
return citizenCache.get(player);
} catch (ExecutionException ex) {
PoliticsPlugin.logger().log(Level.SEVERE, "Could not load a citizen! This is a PROBLEM!", ex);
return null;
}
}
/**
* Invalidates the given citizen.
*
* @param citizen
*/
public void invalidateCitizen(String citizen) {
citizenCache.invalidate(citizen);
}
@Override
public BasicBSONObject toBSONObject() {
BasicBSONObject bson = new BasicBSONObject();
bson.put("name", name);
bson.put("rules", rules.getName());
BasicBSONList groupsBson = new BasicBSONList();
BasicBSONObject childrenBson = new BasicBSONObject();
for (Group group : groups) {
// groups
groupsBson.add(group.toBSONObject());
// children
BasicBSONList children = new BasicBSONList();
for (Group child : group.getGroups()) {
children.add(child.getUid());
}
childrenBson.put(Long.toHexString(group.getUid()), children);
}
bson.put("groups", groupsBson);
bson.put("children", childrenBson);
return bson;
}
/**
* Converts the given bson object into a new Universe.
*
* @param object
* @return
*/
public static Universe fromBSONObject(BSONObject object) {
if (!(object instanceof BasicBSONObject)) {
throw new IllegalStateException("object is not a BasicBsonObject! ERROR ERROR ERROR!");
}
BasicBSONObject bobject = (BasicBSONObject) object;
String aname = bobject.getString("name");
String rulesName = bobject.getString("rules");
UniverseRules rules = Politics.getUniverseManager().getRules(rulesName);
if (rules == null) {
throw new IllegalStateException("Rules do not exist!");
}
List<PoliticsWorld> worlds = new ArrayList<PoliticsWorld>();
Object worldsObj = bobject.get("worlds");
if (!(worldsObj instanceof BasicBSONList)) {
throw new IllegalStateException("GroupWorlds object is not a list!!! ASDFASDF");
}
BasicBSONList worldsBson = (BasicBSONList) worldsObj;
for (Object worldName : worldsBson) {
String name = worldName.toString();
PoliticsWorld world = Politics.getPlotManager().getWorld(name);
if (world == null) {
PoliticsPlugin.logger().log(Level.WARNING, "GroupWorld `" + name + "' could not be found! (Did you delete it?)");
} else {
worlds.add(world);
}
}
Object groupsObj = bobject.get("groups");
if (!(groupsObj instanceof BasicBSONList)) {
throw new IllegalStateException("groups isn't a list?! wtfhax?");
}
BasicBSONList groupsBson = (BasicBSONList) groupsObj;
TLongObjectMap<Group> groups = new TLongObjectHashMap<Group>();
for (Object groupBson : groupsBson) {
if (!(groupBson instanceof BasicBSONObject)) {
throw new IllegalStateException("Invalid group!");
}
Group c = Group.fromBSONObject(rules, (BasicBSONObject) groupBson);
groups.put(c.getUid(), c);
}
Map<Group, Set<Group>> children = new HashMap<Group, Set<Group>>();
Object childrenObj = bobject.get("children");
if (!(childrenObj instanceof BasicBSONObject)) {
throw new IllegalStateException("Missing children report!");
}
BasicBSONObject childrenBson = (BasicBSONObject) childrenObj;
for (Entry<String, Object> childEntry : childrenBson.entrySet()) {
String groupId = childEntry.getKey();
long uid = Long.parseLong(groupId, 16);
Group c = groups.get(uid);
if (c == null) {
throw new IllegalStateException("Unknown group id " + Long.toHexString(uid));
}
Object childsObj = childEntry.getValue();
if (!(childsObj instanceof BasicBSONList)) {
throw new IllegalStateException("No bson list found for childsObj");
}
Set<Group> childrenn = new HashSet<Group>();
BasicBSONList childs = (BasicBSONList) childsObj;
for (Object childN : childs) {
long theuid = (Long) childN;
Group ch = groups.get(theuid);
childrenn.add(ch);
}
children.put(c, childrenn);
}
List<Group> groupz = new ArrayList<Group>(groups.valueCollection());
Universe universe = new Universe(aname, rules, worlds, groupz, children);
for (Group group : groupz) {
group.initialize(universe);
}
return universe;
}
}
| Finished up the destroyGroup method.
Signed-off-by: Ian Macalinao <[email protected]>
| src/main/java/com/volumetricpixels/politics/universe/Universe.java | Finished up the destroyGroup method. Signed-off-by: Ian Macalinao <[email protected]> |
|
Java | agpl-3.0 | be1a8a218e4b6b3333d831bfb0d544ece1724aa6 | 0 | laurianed/scheduling,laurianed/scheduling,zeineb/scheduling,fviale/scheduling,ShatalovYaroslav/scheduling,jrochas/scheduling,mbenguig/scheduling,yinan-liu/scheduling,jrochas/scheduling,sandrineBeauche/scheduling,sandrineBeauche/scheduling,tobwiens/scheduling,laurianed/scheduling,lpellegr/scheduling,ow2-proactive/scheduling,mbenguig/scheduling,lpellegr/scheduling,jrochas/scheduling,zeineb/scheduling,youribonnaffe/scheduling,laurianed/scheduling,ow2-proactive/scheduling,tobwiens/scheduling,marcocast/scheduling,ow2-proactive/scheduling,lpellegr/scheduling,ow2-proactive/scheduling,youribonnaffe/scheduling,jrochas/scheduling,yinan-liu/scheduling,sandrineBeauche/scheduling,paraita/scheduling,sgRomaric/scheduling,marcocast/scheduling,yinan-liu/scheduling,lpellegr/scheduling,ShatalovYaroslav/scheduling,zeineb/scheduling,ShatalovYaroslav/scheduling,ow2-proactive/scheduling,mbenguig/scheduling,lpellegr/scheduling,fviale/scheduling,youribonnaffe/scheduling,laurianed/scheduling,zeineb/scheduling,tobwiens/scheduling,ShatalovYaroslav/scheduling,fviale/scheduling,paraita/scheduling,tobwiens/scheduling,mbenguig/scheduling,paraita/scheduling,paraita/scheduling,sgRomaric/scheduling,ShatalovYaroslav/scheduling,sandrineBeauche/scheduling,zeineb/scheduling,marcocast/scheduling,fviale/scheduling,yinan-liu/scheduling,paraita/scheduling,tobwiens/scheduling,ow2-proactive/scheduling,yinan-liu/scheduling,jrochas/scheduling,tobwiens/scheduling,laurianed/scheduling,sgRomaric/scheduling,yinan-liu/scheduling,sandrineBeauche/scheduling,mbenguig/scheduling,marcocast/scheduling,zeineb/scheduling,sandrineBeauche/scheduling,marcocast/scheduling,lpellegr/scheduling,youribonnaffe/scheduling,ShatalovYaroslav/scheduling,tobwiens/scheduling,sgRomaric/scheduling,marcocast/scheduling,laurianed/scheduling,sandrineBeauche/scheduling,zeineb/scheduling,fviale/scheduling,youribonnaffe/scheduling,sgRomaric/scheduling,mbenguig/scheduling,jrochas/scheduling,paraita/scheduling,youribonnaffe/scheduling,ow2-proactive/scheduling,marcocast/scheduling,ShatalovYaroslav/scheduling,mbenguig/scheduling,yinan-liu/scheduling,fviale/scheduling,fviale/scheduling,paraita/scheduling,lpellegr/scheduling,jrochas/scheduling,youribonnaffe/scheduling,sgRomaric/scheduling,sgRomaric/scheduling | package functionalTests;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.xml.VariableContract;
import org.objectweb.proactive.core.xml.VariableContractType;
import org.objectweb.proactive.extra.gcmdeployment.API;
import org.objectweb.proactive.extra.gcmdeployment.GCMApplication.GCMApplicationDescriptor;
import org.objectweb.proactive.extra.gcmdeployment.core.GCMVirtualNode;
/**
* If a VariableContract is needed, before() and after() can be overridden.
*
* @author cmathieu
*
*/
public class FunctionalTestDefaultNodes extends FunctionalTest {
public enum DeploymentType {
_0x0("0x0.xml"), _1x1("1x1.xml"), _1x2("1x2.xml"), _2x1("2x1.xml"), _4x1("4x1.xml"), _2x2("2x2.xml");
public String filename;
private DeploymentType(String filename) {
this.filename = filename;
}
}
static final File applicationDescriptor = new File(FunctionalTest.class.getResource(
"/functionalTests/_CONFIG/JunitApp.xml").getFile());
static public final String VN_NAME = "nodes";
static public final String VAR_DEPDESCRIPTOR = "deploymentDescriptor";
static public final String VAR_JVMARG = "jvmargDefinedByTest";
GCMApplicationDescriptor gcmad;
DeploymentType deploymentType;
public VariableContract vContract;
public FunctionalTestDefaultNodes(DeploymentType type) {
this.deploymentType = type;
vContract = new VariableContract();
vContract.setVariableFromProgram(VAR_DEPDESCRIPTOR, "localhost/" + type.filename,
VariableContractType.DescriptorDefaultVariable);
}
@Before
public void before() throws Exception {
startDeployment();
}
@After
public void after() throws Exception {
gcmad.kill();
}
public void startDeployment() throws ProActiveException {
if (gcmad != null) {
throw new IllegalStateException("deployment already started");
}
gcmad = API.getGCMApplicationDescriptor(applicationDescriptor, vContract);
gcmad.startDeployment();
}
public Node getANode() {
return getANodeFrom(VN_NAME);
}
private Node getANodeFrom(String vnName) {
if (gcmad == null || !gcmad.isStarted()) {
throw new IllegalStateException("deployment is not started");
}
GCMVirtualNode vn = gcmad.getVirtualNode(vnName);
return vn.getANode();
}
}
| src/Tests/functionalTests/FunctionalTestDefaultNodes.java | package functionalTests;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.xml.VariableContract;
import org.objectweb.proactive.core.xml.VariableContractType;
import org.objectweb.proactive.extra.gcmdeployment.API;
import org.objectweb.proactive.extra.gcmdeployment.GCMApplication.GCMApplicationDescriptor;
import org.objectweb.proactive.extra.gcmdeployment.core.GCMVirtualNode;
/**
* If a VariableContract is needed, before() and after() can be overridden.
*
* @author cmathieu
*
*/
public class FunctionalTestDefaultNodes extends FunctionalTest {
public enum DeploymentType {
_0x0("0x0.xml"), _1x1("1x1.xml"), _1x2("1x2.xml"), _2x1("2x1.xml"), _4x1("4x1.xml"), _2x2("2x2.xml");
public String filename;
private DeploymentType(String filename) {
this.filename = filename;
}
}
static final File applicationDescriptor = new File(FunctionalTest.class.getResource(
"/functionalTests/_CONFIG/JunitApp.xml").getFile());
static public final String VN_NAME = "nodes";
static public final String VAR_DEPDESCRIPTOR = "deploymentDescriptor";
GCMApplicationDescriptor gcmad;
DeploymentType deploymentType;
VariableContract vContract;
public FunctionalTestDefaultNodes(DeploymentType type) {
this.deploymentType = type;
vContract = new VariableContract();
vContract.setVariableFromProgram(VAR_DEPDESCRIPTOR, "localhost/" + type.filename,
VariableContractType.DescriptorDefaultVariable);
}
@Before
public void before() throws Exception {
startDeployment();
}
@After
public void after() throws Exception {
gcmad.kill();
}
public void startDeployment() throws ProActiveException {
if (gcmad != null) {
throw new IllegalStateException("deployment already started");
}
gcmad = API.getGCMApplicationDescriptor(applicationDescriptor, vContract);
gcmad.startDeployment();
}
public Node getANode() {
return getANodeFrom(VN_NAME);
}
private Node getANodeFrom(String vnName) {
if (gcmad == null || !gcmad.isStarted()) {
throw new IllegalStateException("deployment is not started");
}
GCMVirtualNode vn = gcmad.getVirtualNode(vnName);
return vn.getANode();
}
}
| Allow acces to vContract to subclasses
Added VAR_JVMARG
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@8002 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/Tests/functionalTests/FunctionalTestDefaultNodes.java | Allow acces to vContract to subclasses Added VAR_JVMARG |
|
Java | agpl-3.0 | 02d99a6ea71b662eef6311fd92968b9b71347f29 | 0 | kostasDrk/metafox,kostasDrk/metafox |
import ast.ASTNode;
import ast.ASTVisitor;
import ast.ASTVisitorException;
import ast.AnonymousFunctionCall;
import ast.ArrayDef;
import ast.AssignmentExpression;
import ast.BinaryExpression;
import ast.Operator;
import ast.Block;
import ast.BreakStatement;
import ast.ContinueStatement;
import ast.DoubleLiteral;
import ast.Expression;
import ast.ExpressionStatement;
import ast.ExtendedCall;
import ast.FalseLiteral;
import ast.ForStatement;
import ast.FunctionDef;
import ast.FunctionDefExpression;
import ast.IdentifierExpression;
import ast.IfStatement;
import ast.IndexedElement;
import ast.IntegerLiteral;
import ast.LvalueCall;
import ast.Member;
import ast.MethodCall;
import ast.NormCall;
import ast.NullLiteral;
import ast.ObjectDefinition;
import ast.Program;
import ast.ReturnStatement;
import ast.Statement;
import ast.StringLiteral;
import ast.TermExpressionStmt;
import ast.TrueLiteral;
import ast.UnaryExpression;
import ast.WhileStatement;
import ast.MetaSyntax;
import ast.MetaEscape;
import ast.MetaExecute;
import ast.utils.ASTUtils;
import environment.EnvironmentStack;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import symbols.value.Value;
import symbols.value.Value_t;
import symbols.value.StaticVal;
import symbols.value.DynamicVal;
import dataStructures.FoxObject;
import dataStructures.FoxArray;
import libraryFunctions.LibraryFunction_t;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import static utils.Constants.BREAK;
import static utils.Constants.CONTINUE;
import static utils.Constants.RETURN;
import static utils.Constants.FUNCTION_ENV_INIT_SCOPE;
import static utils.Constants.LIBRARY_FUNC_ARG;
import static utils.Constants.NULL;
public class ExecutionASTVisitor implements ASTVisitor {
private final EnvironmentStack _envStack;
private int _scope;
private int _inFunction;
private int _inLoop;
private boolean _inMeta;
private void enterScopeSpace() {
//System.out.println("EnterScopeSpace");
_scope++;
_envStack.enterBlock(_scope);
}
private void exitScopeSpace() {
//System.out.println("ExitScopeSpace");
_envStack.exitBlock();
_scope--;
}
private void enterFunctionSpace() {
//System.out.println("EnterFunctionSpace");
_scope = FUNCTION_ENV_INIT_SCOPE;
_inFunction++;
_envStack.enterFunction();
}
private Value exitFunctionSpace() {
//System.out.println("ExitFunctionSpace");
_inFunction--;
Value value = _envStack.exitFunction();
_scope = _envStack.topEnvScope();
return value;
}
private void enterLoopSpace() {
//System.out.println("EnterLoopSpace");
_inLoop++;
}
private void exitLoopSpace() {
//System.out.println("ExitLoopSpace");
_inLoop--;
}
private void enterMetaSpace(){
_inMeta = true;
}
private void exitMetaSpace(){
_inMeta = false;
}
private void setNodeIsLValueIfMember(ASTNode node) {
//System.out.print("SetNodeIsLValueIfMember: ");
if (node instanceof Member) {
((Member) node).setIsLValue();
//System.out.println("TRUE");
} else {
//System.out.println("FALSE");
}
}
public ExecutionASTVisitor() {
_envStack = new EnvironmentStack();
_scope = 0;
_inFunction = 0;
_inLoop = 0;
_inMeta = false;
}
@Override
public Value visit(Program node) throws ASTVisitorException {
//System.out.println("-Program");
for (Statement stmt : node.getStatements()) {
if (stmt != null) {
stmt.accept(this);
}
}
// //System.out.println(_envStack.toString());
return null;
}
@Override
public Value visit(ExpressionStatement node) throws ASTVisitorException {
//System.out.println("-ExpressionStatement");
Value val = null;
val = node.getExpression().accept(this);
return null;
}
@Override
public Value visit(AssignmentExpression node) throws ASTVisitorException {
//System.out.println("-AssignmentExpression");
setNodeIsLValueIfMember(node.getLvalue());
Value left = node.getLvalue().accept(this);
setNodeIsLValueIfMember(node.getExpression());
Value right = node.getExpression().accept(this);
_envStack.setValue((DynamicVal) left, right);
// System.out.println(_envStack.toString());
return left;
}
@Override
public Value visit(BinaryExpression node) throws ASTVisitorException {
//System.out.println("-BinaryExpression");
Value result = null;
Value left = node.getExpression1().accept(this);
Value right = node.getExpression2().accept(this);
Operator op = node.getOperator();
// Handle possible meta operands
if(left.isAST() || right.isAST()){
BinaryExpression binAST = null;
if(left.isAST() && !right.isAST())
binAST = new BinaryExpression(op, ((Expression) left.getData()), node.getExpression2());
else if(!left.isAST() && right.isAST())
binAST = new BinaryExpression(op, node.getExpression1(), (Expression) right.getData());
else
binAST = new BinaryExpression(op, (Expression) left.getData(), (Expression) right.getData());
result = new StaticVal<ASTNode>(Value_t.AST, binAST);
return result;
}
String leftInfo = (left instanceof DynamicVal) ? ((DynamicVal) left).getErrorInfo() + "(" + left.getType() + ")" : left.getData() + "(" + left.getType() + ")";
leftInfo = "'" + left.getData() + "' (" + left.getType() + ")";
String rightInfo = (right instanceof DynamicVal) ? ((DynamicVal) right).getErrorInfo() + "(" + right.getType() + ")" : right.getData() + "(" + right.getType() + ")";
rightInfo = "'" + right.getData() + "' (" + right.getType() + ")";
// String typeError = "Incompatible operand types for '" + node.getOperator() + "': " + left.getType() + " and " + right.getType();
String typeError = "Incompatible operand types for '" + node.getOperator() + "': " + leftInfo + " and " + rightInfo;
if (left.isUndefined() || left.isNull() || right.isUndefined() || right.isNull()) {
ASTUtils.error(node, typeError);
}
if ((!left.isNumeric() || !right.isNumeric()) && (!left.isBoolean() || !right.isBoolean())) {
if ((left.isString() || right.isString()) && op.equals(Operator.PLUS)) {
result = new StaticVal(Value_t.STRING, (String) left.getData().toString() + (String) right.getData().toString());
// //System.out.println("RESULT: "+result.getData());
return result;
} else {
ASTUtils.error(node, typeError);
}
}
if (left.isNumeric()) {
Double leftVal = (left.isReal()) ? (Double) left.getData() : ((Integer) left.getData()).doubleValue();
Double rightVal = (right.isReal()) ? (Double) right.getData() : ((Integer) right.getData()).doubleValue();
Double resultVal;
boolean realResult;
if (op.isLogical()) {
if (op.equals(Operator.CMP_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (Double.compare(leftVal, rightVal) == 0));
} else if (op.equals(Operator.NOT_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (Double.compare(leftVal, rightVal) != 0));
} else if (op.equals(Operator.GREATER_OR_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal >= rightVal));
} else if (op.equals(Operator.GREATER)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal > rightVal));
} else if (op.equals(Operator.LESS_OR_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal <= rightVal));
} else if (op.equals(Operator.LESS)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal < rightVal));
} else {
ASTUtils.error(node, typeError);
}
} else {
realResult = (left.isReal() || right.isReal());
if (op.equals(Operator.PLUS)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal + rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal + rightVal)).intValue());
} else if (op.equals(Operator.MINUS)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal - rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal - rightVal)).intValue());
} else if (op.equals(Operator.MUL)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal * rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal * rightVal)).intValue());
} else if (op.equals(Operator.DIV)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal / rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal / rightVal)).intValue());
} else if (op.equals(Operator.MOD)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal % rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal % rightVal)).intValue());
}
}
} else{
// Boolean values
Boolean leftVal = (Boolean) left.getData();
Boolean rightVal = (Boolean) right.getData();
if (op.equals(Operator.LOGIC_AND)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal && rightVal));
} else if (op.equals(Operator.LOGIC_OR)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal || rightVal));
} else if (op.equals(Operator.CMP_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (Objects.equals(leftVal, rightVal)));
} else if (op.equals(Operator.NOT_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (!Objects.equals(leftVal, rightVal)));
} else {
ASTUtils.error(node, typeError);
}
}
// //System.out.println("RESULT: "+result.getData());
return result;
}
@Override
public Value visit(TermExpressionStmt node) throws ASTVisitorException {
//System.out.println("-TermExpressionStmt");
Value result = node.getExpression().accept(this);
return result;
}
@Override
public Value visit(UnaryExpression node) throws ASTVisitorException {
//System.out.println("-UnaryExpression");
Operator op = node.getOperator();
Value returnVal = new StaticVal();
if (node.getExpression() != null) {
setNodeIsLValueIfMember(node.getExpression());
Value value = node.getExpression().accept(this);
if (op.equals(Operator.MINUS)) {
if (value.isInteger()) {
returnVal = new StaticVal(value.getType(), -(int) value.getData());
} else if (value.isReal()) {
returnVal = new StaticVal(value.getType(), -(double) value.getData());
} else {
String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo()
+ "' should be numeric type for operation '" + op.toString() + "'.";
ASTUtils.error(node, msg);
}
} else if (op.equals(Operator.LOGIC_NOT)) {
if (value.isBoolean()) {
returnVal = new StaticVal(Value_t.BOOLEAN, !(boolean) value.getData());
} else if (value.isInteger() || value.isReal() || value.isString() || value.isUserFunction() || value.isLibraryFunction() || value.isTable() || value.isObject()) {
returnVal = new StaticVal(Value_t.BOOLEAN, Boolean.FALSE);
} else if (value.isNull()) {
returnVal = new StaticVal(Value_t.BOOLEAN, Boolean.TRUE);
} else {
String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo()
+ "' can not converted to boolean type.";
ASTUtils.error(node, msg);
}
}
} else {
setNodeIsLValueIfMember(node.getLvalue());
Value value = node.getLvalue().accept(this);
StaticVal assignVal = null;
if (value.isInteger()) {
int data = op.equals(Operator.PLUS_PLUS) ? (int) value.getData() + 1 : (int) value.getData() - 1;
assignVal = new StaticVal(value.getType(), data);
} else if (value.isReal()) {
double data = op.equals(Operator.PLUS_PLUS) ? (double) value.getData() + 1 : (double) value.getData() - 1;
assignVal = new StaticVal(value.getType(), data);
} else {
String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo()
+ "' should be numeric type for operation '" + op.toString() + "'.";
ASTUtils.error(node, msg);
}
_envStack.setValue((DynamicVal) value, assignVal);
}
return returnVal;
}
@Override
public Value visit(IdentifierExpression node) throws ASTVisitorException {
//System.out.println("-IdentifierExpression");
String name = node.getIdentifier();
Value symbolInfo;
//if variable has :: at the front it is "global"
if (!node.isLocal()) {
symbolInfo = _envStack.lookupGlobalScope(name);
if (symbolInfo == null) {
String msg = "Global variable: " + name + " doesn't exist";
ASTUtils.error(node, msg);
}
} else {
symbolInfo = _envStack.lookupAll(name);
if (symbolInfo == null) {
_envStack.insertSymbol(name);
symbolInfo = _envStack.lookupCurrentScope(name); // Retrieve newly added symbol
}
}
return symbolInfo;
}
@Override
public Value visit(Member node) throws ASTVisitorException {
//System.out.println("-Member");
Value lvalue = null;
Value key = null;
Value retVal;
String id = node.getIdentifier();
if ((node.getLvalue() != null) && (id != null)) { // lvalue.id
lvalue = node.getLvalue().accept(this);
if (!lvalue.isObject()) {
String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Object type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
// key = _envStack.lookupAll(node.getIdentifier());
key = new StaticVal(Value_t.STRING, node.getIdentifier());
} else if ((node.getLvalue() != null) && (node.getExpression() != null)) { // lvalue [exp]
lvalue = node.getLvalue().accept(this);
if (!lvalue.isObject() && !lvalue.isTable()) {
String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Object or Array type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
key = node.getExpression().accept(this);
if(key.getData() != null && lvalue.isObject())
key = new StaticVal(Value_t.STRING, node.getExpression().accept(this).getData().toString());
else
key = node.getExpression().accept(this);
} else if ((id != null) && (node.getCall() != null)) { // call.id
lvalue = node.getCall().accept(this);
if (!lvalue.isObject()) {
//Cast error Think about this add all other cases of downcasts of the ExecutionASTVisitor. what to do?
//String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' it's not Object type to get member '" + id + "'.";
String msg = "Return value is not Object type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
key = _envStack.lookupAll(node.getIdentifier());
} else if ((node.getCall() != null) && (node.getExpression() != null)) { // call (expr)
lvalue = node.getCall().accept(this);
if (!lvalue.isObject() && !lvalue.isTable()) {
//Cast error Think about this add all other cases of downcasts of the ExecutionASTVisitor. what to do?
//String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' it's not Object or Array type to get member '" + id + "'.";
String msg = "Return value is not Object or Array type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
key = node.getExpression().accept(this);
} else {
//fatal error Think how to manage this errors.
}
Value value = (lvalue.isObject()) ? ((FoxObject)lvalue.getData()).get(key) : ((FoxArray)lvalue.getData()).get(key);
if (value == null) {
if (node.isLValue()) {
String errorInfo = "Object." + "id.";
retVal = new DynamicVal(errorInfo);
if(lvalue.isObject())
((FoxObject)lvalue.getData()).put(key, retVal);
else
((FoxArray)lvalue.getData()).put(key, retVal);
// lvalue.put(key, retVal);
} else {
retVal = NULL;
}
} else {
retVal = value;
}
return retVal;
}
@Override
public Value visit(ExtendedCall node) throws ASTVisitorException {
//System.out.println("-ExtendedCall");
Value retVal = NULL;
Value function = node.getCall().accept(this);
if (function.isUserFunction()) {
String functionName = ((FunctionDef) function.getData()).getFuncName();
node.setLvalueCall(functionName, node.getNormCall());
retVal = node.getLvalueCall().accept(this);
} else {
String errorCode = "ExtendedCall";
ASTUtils.fatalError(node, errorCode);
}
return retVal;
}
@Override
public Value visit(LvalueCall node) throws ASTVisitorException {
//System.out.println("-LvalueCall");
Value lvalue = node.getLvalue().accept(this);
//System.out.println(lvalue);
if (node.getCallSuffix() instanceof NormCall) {
if (!lvalue.isUserFunction() && !lvalue.isLibraryFunction()) {
String msg = "Function call: Symbol-" + ((DynamicVal) lvalue).getErrorInfo()
+ " is not Type-Function, but Type-" + lvalue.getType() + ".";
ASTUtils.error(node, msg);
}
} else if (node.getCallSuffix() instanceof MethodCall) {
if (!lvalue.isObject()) {
String msg = "Function call using lvalue..id(elist): Symbol-" + ((DynamicVal) lvalue).getErrorInfo()
+ " is not Type-Object, but Type-" + lvalue.getType() + ".";
ASTUtils.error(node, msg);
}
}
if (lvalue.isUserFunction()) {
//Get Actual Arguments
Value parameters = node.getCallSuffix().accept(this);
HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData();
enterFunctionSpace();
int count = 0;
ArrayList<IdentifierExpression> arguments = ((FunctionDef) lvalue.getData()).getArguments();
if (arguments.size() != actualArguments.size()) {
String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires " + arguments.size() + " arguments"
+ ": " + actualArguments.size() + " found.";
ASTUtils.error(node, msg);
}
for (IdentifierExpression argument : arguments) {
String name = argument.getIdentifier();
//System.out.println(name);
String errorInfo = name;
DynamicVal argumentInfo = new DynamicVal(actualArguments.get(count), errorInfo);
_envStack.insertSymbol(name, argumentInfo);
count++;
}
((FunctionDef) lvalue.getData()).getBody().accept(this);
} else if (lvalue.isLibraryFunction()) {
//Get Actual Arguments
Value parameters = node.getCallSuffix().accept(this);
HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData();
enterFunctionSpace();
/*if (actualArguments.size() < 1) {
String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires at least ONE argument"
+ ": " + actualArguments.size() + " found.";
ASTUtils.error(node, msg);
}*/
for (int i = 0; i < actualArguments.size(); i++) {
String errorInfo = LIBRARY_FUNC_ARG + i;
DynamicVal argumentInfo = new DynamicVal(actualArguments.get(i), errorInfo);
_envStack.insertSymbol(LIBRARY_FUNC_ARG + i, argumentInfo);
}
try {
Method method = (Method) lvalue.getData();
method.invoke(null, _envStack.getFunctionEnv());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(ExecutionASTVisitor.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (lvalue.isObject()) {
//Get lvalue
FoxObject fobject = (FoxObject)lvalue.getData();
//Get ..id
String id = ((MethodCall) node.getCallSuffix()).getIdentifier();
Value key = new StaticVal(Value_t.STRING, id);
// Value function = objectData.get(key);
Value function = fobject.get(key);
if (!function.isUserFunction() && !function.isLibraryFunction()) {
String msg = "Function call using lvalue..id(elist): Symbmol- 'lvalue." + id
+ "' is not Type-Function, but Type-" + lvalue.getType() + ".";
ASTUtils.error(node, msg);
}
//Get Actual Arguments
Value parameters = node.getCallSuffix().accept(this);
HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData();
ArrayList<IdentifierExpression> arguments = ((FunctionDef) function.getData()).getArguments();
enterFunctionSpace();
if (arguments.size() != (actualArguments.size() + 1)) {
String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires " + arguments.size() + " arguments"
+ ": " + actualArguments.size() + " found.";
ASTUtils.error(node, msg);
}
int count = 0;
String name = arguments.get(count).getIdentifier();
String errorInfo = name;
DynamicVal argumentInfo = new DynamicVal(lvalue, errorInfo);
_envStack.insertSymbol(name, argumentInfo);
for (count = 1; count < arguments.size(); count++) {
name = arguments.get(count).getIdentifier();
//System.out.println(name);
errorInfo = name;
argumentInfo = new DynamicVal(actualArguments.get(count - 1), errorInfo);
_envStack.insertSymbol(name, argumentInfo);
count++;
}
Value bodyRet = ((FunctionDef) function.getData()).getBody().accept(this);
}
Value ret = exitFunctionSpace();
if (ret.getType().equals(Value_t.ERROR)) {
String msg = "Error during Function Execution @'" + ((DynamicVal) lvalue).getErrorInfo() + "' - " + ret.getData();
ASTUtils.error(node, msg);
}
//System.out.println(_envStack.toString());
return ret;
}
@Override
public Value visit(AnonymousFunctionCall node) throws ASTVisitorException {
//System.out.println("-AnonymousFunctionCall");
Value function = node.getFunctionDef().accept(this);
Value returnValue = node.getLvalueCall().accept(this);
return returnValue;
}
@Override
public Value visit(NormCall node) throws ASTVisitorException {
//System.out.println("-NormCall");
HashMap<Integer, Value> arguments = new HashMap<>();
int count = 0;
for (Expression expression : node.getExpressionList()) {
Value argValue = expression.accept(this);
arguments.put(count, argValue);
//System.out.println(argValue);
count++;
}
//Change to fox Table.
return new StaticVal(Value_t.UNDEFINED, arguments);
}
@Override
public Value visit(MethodCall node) throws ASTVisitorException {
//System.out.println("-MethodCall");
Value arguments = node.getNormCall().accept(this);
return arguments;
}
@Override
public Value visit(ObjectDefinition node) throws ASTVisitorException {
//System.out.println("-ObjectDefinition");
HashMap<Value, Value> objectData = new HashMap<>();
if (!node.getIndexedElementList().isEmpty()) {
for (IndexedElement indexed : node.getIndexedElementList()) {
ArrayList<Value> data = (ArrayList<Value>) indexed.accept(this).getData();
String errorInfo = "Object.(" + data.get(0) + ")";
Value value = new DynamicVal(data.get(1), errorInfo);
Value name = new StaticVal(Value_t.STRING, data.get(0).getData().toString());
objectData.put(name, value);
// objectData.put(data.get(0), value);
}
}
FoxObject fobject = new FoxObject(objectData);
return new StaticVal(Value_t.OBJECT, fobject);
}
@Override
public Value visit(IndexedElement node) throws ASTVisitorException {
//System.out.println("-IndexedElement");
ArrayList<Value> objectData = new ArrayList<>();
if(node.getExpression1() instanceof IdentifierExpression)
objectData.add(new StaticVal(Value_t.STRING, ((IdentifierExpression)node.getExpression1()).getIdentifier()));
else
objectData.add(node.getExpression1().accept(this));
objectData.add(node.getExpression2().accept(this));
return new StaticVal(Value_t.UNDEFINED, objectData);
}
@Override
public Value visit(ArrayDef node) throws ASTVisitorException {
//System.out.println("-ArrayDef");
HashMap<Value, Value> arrayData = new HashMap<>();
int count = 0;
if (node.getExpressionList() != null) {
for (Expression expression : node.getExpressionList()) {
Value index = new StaticVal(Value_t.INTEGER, count);
Value value = expression.accept(this);
String errorInfo = "Object.(" + count + ")";
Value element = new DynamicVal(value, errorInfo);
arrayData.put(index, element);
count++;
}
}
FoxArray farray = new FoxArray(arrayData);
return new StaticVal(Value_t.TABLE, farray);
}
@Override
public Value visit(Block node) throws ASTVisitorException {
//System.out.println("-Block");
Value ret = null;
enterScopeSpace();
for (Statement stmt : node.getStatementList()) {
ret = stmt.accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) {
return ret;
}
}
}
exitScopeSpace();
return ret;
}
@Override
public Value visit(FunctionDefExpression node) throws ASTVisitorException {
//System.out.println("-FunctionDefExpression");
node.getFunctionDef().accept(this);
return null;
}
@Override
public Value visit(FunctionDef node) throws ASTVisitorException {
//System.out.println("-FunctionDef");
String name = node.getFuncName();
/*Function Name*/
DynamicVal funcInfo = _envStack.lookupCurrentScope(name);
boolean isLibraryFunction = LibraryFunction_t.isLibraryFunction(name);
if (funcInfo != null) {
boolean isUserFunction = funcInfo.getType() == Value_t.USER_FUNCTION;
String msg;
if (isUserFunction) {
msg = "Redeclaration of User-Function: " + name + ".";
} else if (isLibraryFunction) {
msg = "User-Function shadows Library-Function: " + name + ".";
} else {
//Think to remove this else statment.
msg = "User-Function already declared as Variable: " + name + ".";
}
ASTUtils.error(node, msg);
} else {
if (isLibraryFunction) {
String msg = "User-Function Shadows Library-Function: " + name + ".";
ASTUtils.error(node, msg);
}
}
String errorInfo = name;
funcInfo = new DynamicVal(Value_t.USER_FUNCTION, node, errorInfo);
_envStack.insertSymbol(name, funcInfo);
/*Function ONLY Check Arguments*/
enterScopeSpace();
for (IdentifierExpression argument : node.getArguments()) {
name = argument.getIdentifier();
Value argInfo = _envStack.lookupCurrentScope(name);
if (argInfo != null) {
String msg = "Redeclaration of Formal-Argument: " + name + ".";
ASTUtils.error(node, msg);
}
if (LibraryFunction_t.isLibraryFunction(name)) {
String msg = "Formal-Argument shadows Library-Function: " + name + ".";
ASTUtils.error(node, msg);
}
_envStack.insertSymbol(name);
}
exitScopeSpace();
return funcInfo;
}
@Override
public Value visit(IntegerLiteral node) throws ASTVisitorException {
//System.out.println("-IntegerLiteral");
return new StaticVal(Value_t.INTEGER, node.getLiteral());
}
@Override
public Value visit(DoubleLiteral node) throws ASTVisitorException {
//System.out.println("-DoubleLiteral");
return new StaticVal(Value_t.REAL, node.getLiteral());
}
@Override
public Value visit(StringLiteral node) throws ASTVisitorException {
//System.out.println("-StringLiteral");
return new StaticVal(Value_t.STRING, node.getLiteral());
}
@Override
public Value visit(NullLiteral node) throws ASTVisitorException {
//System.out.println("-NullLiteral");
return NULL;
}
@Override
public Value visit(TrueLiteral node) throws ASTVisitorException {
//System.out.println("-TrueLiteral");
return new StaticVal(Value_t.BOOLEAN, Boolean.TRUE);
}
@Override
public Value visit(FalseLiteral node) throws ASTVisitorException {
//System.out.println("-FalseLiteral");
return new StaticVal(Value_t.BOOLEAN, Boolean.FALSE);
}
@Override
public Value visit(IfStatement node) throws ASTVisitorException {
//System.out.println("-IfStatement");
Value val = node.getExpression().accept(this);
Value ret = null;
if(!val.isBoolean())
ASTUtils.error(node, "If expression must be boolean: "+val.getType()+" given");
if ((Boolean) val.getData()) {
ret = node.getStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) {
return ret;
}
}
} else {
if (node.getElseStatement() != null) {
ret = node.getElseStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) {
return ret;
}
}
}
}
return ret;
}
@Override
public Value visit(WhileStatement node) throws ASTVisitorException {
//System.out.println("-WhileStatement");
Value val = node.getExpression().accept(this);
Value ret;
if(!val.isBoolean())
ASTUtils.error(node, "While expression must be boolean: "+val.getType()+" given");
enterLoopSpace();
while ((Boolean) ((Value) node.getExpression().accept(this)).getData()) {
ret = node.getStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK)) {
break;
} else if (ret.getData().equals(CONTINUE)) {
continue;
}else if(ret.getData().equals(RETURN)){
exitLoopSpace();
return ret;
}
}
}
exitLoopSpace();
return null;
}
@Override
public Value visit(ForStatement node) throws ASTVisitorException {
//System.out.println("-ForStatement");
Value ret;
enterLoopSpace();
for (Expression expression : node.getExpressionList1()) {
expression.accept(this);
}
Value val = node.getExpression().accept(this);
if(!val.isBoolean())
ASTUtils.error(node, "For expression must be boolean: "+val.getType()+" given");
while ((Boolean) ((Value) node.getExpression().accept(this)).getData()) {
ret = node.getStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK)) {
break;
} else if (ret.getData().equals(CONTINUE)) {
for (Expression expression : node.getExpressionList2()) {
expression.accept(this);
}
continue;
}else if(ret.getData().equals(RETURN)){
return ret;
}
}
for (Expression expression : node.getExpressionList2()) {
expression.accept(this);
}
}
exitLoopSpace();
return null;
}
@Override
public Value visit(BreakStatement node) throws ASTVisitorException {
//System.out.println("-BreakStatement");
if (_inLoop == 0) {
ASTUtils.error(node, "Use of 'break' while not in a loop.");
}
return new StaticVal(Value_t.STRING, BREAK);
}
@Override
public Value visit(ContinueStatement node) throws ASTVisitorException {
//System.out.println("-ContinueStatement");
if (_inLoop == 0) {
ASTUtils.error(node, "Use of 'continue' while not in a loop.");
}
return new StaticVal(Value_t.STRING, CONTINUE);
}
@Override
public Value visit(ReturnStatement node) throws ASTVisitorException {
//System.out.println("-ReturnStatement");
Value ret = null;
if (_inFunction == 0) {
ASTUtils.error(node, "Use of 'return' while not in a function.");
}
if (node.getExpression() != null) {
ret = node.getExpression().accept(this);
_envStack.setReturnValue(ret);
}
return new StaticVal(Value_t.STRING, RETURN);
}
@Override
public Value visit(MetaSyntax node) throws ASTVisitorException{
if(node.getExpression() != null){
if(_inMeta)
return node.getExpression().accept(this);
else
return new StaticVal<ASTNode>(Value_t.AST, node.getExpression());
}else{
if(_inMeta)
for(Statement stmt : node.getStatementList())
stmt.accept(this);
else
return new StaticVal<ArrayList<Statement>>(Value_t.AST, node.getStatementList());
}
return new StaticVal();
}
@Override
public Value visit(MetaEscape node) throws ASTVisitorException{
Value exprVal = node.getExpression().accept(this);
if(!exprVal.isAST()){
String msg = ".~ requires an identifier holding an AST: "+exprVal.getType()+" found";
ASTUtils.error(node, msg);
}
return exprVal;
}
@Override
public Value visit(MetaExecute node) throws ASTVisitorException{
Value ret = new StaticVal();
enterMetaSpace();
Value exprVal = node.getExpression().accept(this);
if(!exprVal.isAST()){
String msg = "'.!' requires an AST: "+exprVal.getType()+" found";
ASTUtils.error(node, msg);
}
if(exprVal.getData() instanceof Expression){
Expression astExpr = (Expression) exprVal.getData();
ret = astExpr.accept(this);
while(ret.isAST()){
ret = ((Expression) ret.getData()).accept(this);
}
}else{
for(Statement stmt : (ArrayList<Statement>) exprVal.getData())
stmt.accept(this);
}
exitMetaSpace();
return ret;
}
}
| src/ExecutionASTVisitor.java |
import ast.ASTNode;
import ast.ASTVisitor;
import ast.ASTVisitorException;
import ast.AnonymousFunctionCall;
import ast.ArrayDef;
import ast.AssignmentExpression;
import ast.BinaryExpression;
import ast.Operator;
import ast.Block;
import ast.BreakStatement;
import ast.ContinueStatement;
import ast.DoubleLiteral;
import ast.Expression;
import ast.ExpressionStatement;
import ast.ExtendedCall;
import ast.FalseLiteral;
import ast.ForStatement;
import ast.FunctionDef;
import ast.FunctionDefExpression;
import ast.IdentifierExpression;
import ast.IfStatement;
import ast.IndexedElement;
import ast.IntegerLiteral;
import ast.LvalueCall;
import ast.Member;
import ast.MethodCall;
import ast.NormCall;
import ast.NullLiteral;
import ast.ObjectDefinition;
import ast.Program;
import ast.ReturnStatement;
import ast.Statement;
import ast.StringLiteral;
import ast.TermExpressionStmt;
import ast.TrueLiteral;
import ast.UnaryExpression;
import ast.WhileStatement;
import ast.MetaSyntax;
import ast.MetaEscape;
import ast.MetaExecute;
import ast.utils.ASTUtils;
import environment.EnvironmentStack;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import symbols.value.Value;
import symbols.value.Value_t;
import symbols.value.StaticVal;
import symbols.value.DynamicVal;
import dataStructures.FoxObject;
import dataStructures.FoxArray;
import libraryFunctions.LibraryFunction_t;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import static utils.Constants.BREAK;
import static utils.Constants.CONTINUE;
import static utils.Constants.RETURN;
import static utils.Constants.FUNCTION_ENV_INIT_SCOPE;
import static utils.Constants.LIBRARY_FUNC_ARG;
import static utils.Constants.NULL;
public class ExecutionASTVisitor implements ASTVisitor {
private final EnvironmentStack _envStack;
private int _scope;
private int _inFunction;
private int _inLoop;
private boolean _inMeta;
private void enterScopeSpace() {
//System.out.println("EnterScopeSpace");
_scope++;
_envStack.enterBlock(_scope);
}
private void exitScopeSpace() {
//System.out.println("ExitScopeSpace");
_envStack.exitBlock();
_scope--;
}
private void enterFunctionSpace() {
//System.out.println("EnterFunctionSpace");
_scope = FUNCTION_ENV_INIT_SCOPE;
_inFunction++;
_envStack.enterFunction();
}
private Value exitFunctionSpace() {
//System.out.println("ExitFunctionSpace");
_inFunction--;
Value value = _envStack.exitFunction();
_scope = _envStack.topEnvScope();
return value;
}
private void enterLoopSpace() {
//System.out.println("EnterLoopSpace");
_inLoop++;
}
private void exitLoopSpace() {
//System.out.println("ExitLoopSpace");
_inLoop--;
}
private void enterMetaSpace(){
_inMeta = true;
}
private void exitMetaSpace(){
_inMeta = false;
}
private void setNodeIsLValueIfMember(ASTNode node) {
//System.out.print("SetNodeIsLValueIfMember: ");
if (node instanceof Member) {
((Member) node).setIsLValue();
//System.out.println("TRUE");
} else {
//System.out.println("FALSE");
}
}
public ExecutionASTVisitor() {
_envStack = new EnvironmentStack();
_scope = 0;
_inFunction = 0;
_inLoop = 0;
_inMeta = false;
}
@Override
public Value visit(Program node) throws ASTVisitorException {
//System.out.println("-Program");
for (Statement stmt : node.getStatements()) {
if (stmt != null) {
stmt.accept(this);
}
}
// //System.out.println(_envStack.toString());
return null;
}
@Override
public Value visit(ExpressionStatement node) throws ASTVisitorException {
//System.out.println("-ExpressionStatement");
Value val = null;
val = node.getExpression().accept(this);
return null;
}
@Override
public Value visit(AssignmentExpression node) throws ASTVisitorException {
//System.out.println("-AssignmentExpression");
setNodeIsLValueIfMember(node.getLvalue());
Value left = node.getLvalue().accept(this);
setNodeIsLValueIfMember(node.getExpression());
Value right = node.getExpression().accept(this);
_envStack.setValue((DynamicVal) left, right);
// System.out.println(_envStack.toString());
return left;
}
@Override
public Value visit(BinaryExpression node) throws ASTVisitorException {
//System.out.println("-BinaryExpression");
Value result = null;
Value left = node.getExpression1().accept(this);
Value right = node.getExpression2().accept(this);
Operator op = node.getOperator();
// Handle possible meta operands
if(left.isAST() || right.isAST()){
BinaryExpression binAST = null;
if(left.isAST() && !right.isAST())
binAST = new BinaryExpression(op, ((Expression) left.getData()), node.getExpression2());
else if(!left.isAST() && right.isAST())
binAST = new BinaryExpression(op, node.getExpression1(), (Expression) right.getData());
else
binAST = new BinaryExpression(op, (Expression) left.getData(), (Expression) right.getData());
result = new StaticVal<ASTNode>(Value_t.AST, binAST);
return result;
}
String leftInfo = (left instanceof DynamicVal) ? ((DynamicVal) left).getErrorInfo() + "(" + left.getType() + ")" : left.getData() + "(" + left.getType() + ")";
leftInfo = "'" + left.getData() + "' (" + left.getType() + ")";
String rightInfo = (right instanceof DynamicVal) ? ((DynamicVal) right).getErrorInfo() + "(" + right.getType() + ")" : right.getData() + "(" + right.getType() + ")";
rightInfo = "'" + right.getData() + "' (" + right.getType() + ")";
// String typeError = "Incompatible operand types for '" + node.getOperator() + "': " + left.getType() + " and " + right.getType();
String typeError = "Incompatible operand types for '" + node.getOperator() + "': " + leftInfo + " and " + rightInfo;
if (left.isUndefined() || left.isNull() || right.isUndefined() || right.isNull()) {
ASTUtils.error(node, typeError);
}
if ((!left.isNumeric() || !right.isNumeric()) && (!left.isBoolean() || !right.isBoolean())) {
if ((left.isString() || right.isString()) && op.equals(Operator.PLUS)) {
result = new StaticVal(Value_t.STRING, (String) left.getData().toString() + (String) right.getData().toString());
// //System.out.println("RESULT: "+result.getData());
return result;
} else {
ASTUtils.error(node, typeError);
}
}
if (left.isNumeric()) {
Double leftVal = (left.isReal()) ? (Double) left.getData() : ((Integer) left.getData()).doubleValue();
Double rightVal = (right.isReal()) ? (Double) right.getData() : ((Integer) right.getData()).doubleValue();
Double resultVal;
boolean realResult;
if (op.isLogical()) {
if (op.equals(Operator.CMP_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (Double.compare(leftVal, rightVal) == 0));
} else if (op.equals(Operator.NOT_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (Double.compare(leftVal, rightVal) != 0));
} else if (op.equals(Operator.GREATER_OR_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal >= rightVal));
} else if (op.equals(Operator.GREATER)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal > rightVal));
} else if (op.equals(Operator.LESS_OR_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal <= rightVal));
} else if (op.equals(Operator.LESS)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal < rightVal));
} else {
ASTUtils.error(node, typeError);
}
} else {
realResult = (left.isReal() || right.isReal());
if (op.equals(Operator.PLUS)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal + rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal + rightVal)).intValue());
} else if (op.equals(Operator.MINUS)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal - rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal - rightVal)).intValue());
} else if (op.equals(Operator.MUL)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal * rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal * rightVal)).intValue());
} else if (op.equals(Operator.DIV)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal / rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal / rightVal)).intValue());
} else if (op.equals(Operator.MOD)) {
result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal % rightVal)
: new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal % rightVal)).intValue());
}
}
} else{
// Boolean values
Boolean leftVal = (Boolean) left.getData();
Boolean rightVal = (Boolean) right.getData();
if (op.equals(Operator.LOGIC_AND)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal && rightVal));
} else if (op.equals(Operator.LOGIC_OR)) {
result = new StaticVal<>(Value_t.BOOLEAN, (leftVal || rightVal));
} else if (op.equals(Operator.CMP_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (Objects.equals(leftVal, rightVal)));
} else if (op.equals(Operator.NOT_EQUAL)) {
result = new StaticVal<>(Value_t.BOOLEAN, (!Objects.equals(leftVal, rightVal)));
} else {
ASTUtils.error(node, typeError);
}
}
// //System.out.println("RESULT: "+result.getData());
return result;
}
@Override
public Value visit(TermExpressionStmt node) throws ASTVisitorException {
//System.out.println("-TermExpressionStmt");
Value result = node.getExpression().accept(this);
return result;
}
@Override
public Value visit(UnaryExpression node) throws ASTVisitorException {
//System.out.println("-UnaryExpression");
Operator op = node.getOperator();
Value returnVal = new StaticVal();
if (node.getExpression() != null) {
setNodeIsLValueIfMember(node.getExpression());
Value value = node.getExpression().accept(this);
if (op.equals(Operator.MINUS)) {
if (value.isInteger()) {
returnVal = new StaticVal(value.getType(), -(int) value.getData());
} else if (value.isReal()) {
returnVal = new StaticVal(value.getType(), -(double) value.getData());
} else {
String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo()
+ "' should be numeric type for operation '" + op.toString() + "'.";
ASTUtils.error(node, msg);
}
} else if (op.equals(Operator.LOGIC_NOT)) {
if (value.isBoolean()) {
returnVal = new StaticVal(Value_t.BOOLEAN, !(boolean) value.getData());
} else if (value.isInteger() || value.isReal() || value.isString() || value.isUserFunction() || value.isLibraryFunction() || value.isTable() || value.isObject()) {
returnVal = new StaticVal(Value_t.BOOLEAN, Boolean.FALSE);
} else if (value.isNull()) {
returnVal = new StaticVal(Value_t.BOOLEAN, Boolean.TRUE);
} else {
String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo()
+ "' can not converted to boolean type.";
ASTUtils.error(node, msg);
}
}
} else {
setNodeIsLValueIfMember(node.getLvalue());
Value value = node.getLvalue().accept(this);
StaticVal assignVal = null;
if (value.isInteger()) {
int data = op.equals(Operator.PLUS_PLUS) ? (int) value.getData() + 1 : (int) value.getData() - 1;
assignVal = new StaticVal(value.getType(), data);
} else if (value.isReal()) {
double data = op.equals(Operator.PLUS_PLUS) ? (double) value.getData() + 1 : (double) value.getData() - 1;
assignVal = new StaticVal(value.getType(), data);
} else {
String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo()
+ "' should be numeric type for operation '" + op.toString() + "'.";
ASTUtils.error(node, msg);
}
_envStack.setValue((DynamicVal) value, assignVal);
}
return returnVal;
}
@Override
public Value visit(IdentifierExpression node) throws ASTVisitorException {
//System.out.println("-IdentifierExpression");
String name = node.getIdentifier();
Value symbolInfo;
//if variable has :: at the front it is "global"
if (!node.isLocal()) {
symbolInfo = _envStack.lookupGlobalScope(name);
if (symbolInfo == null) {
String msg = "Global variable: " + name + " doesn't exist";
ASTUtils.error(node, msg);
}
} else {
symbolInfo = _envStack.lookupAll(name);
if (symbolInfo == null) {
_envStack.insertSymbol(name);
symbolInfo = _envStack.lookupCurrentScope(name); // Retrieve newly added symbol
}
}
return symbolInfo;
}
@Override
public Value visit(Member node) throws ASTVisitorException {
//System.out.println("-Member");
Value lvalue = null;
Value key = null;
Value retVal;
String id = node.getIdentifier();
if ((node.getLvalue() != null) && (id != null)) { // lvalue.id
lvalue = node.getLvalue().accept(this);
if (!lvalue.isObject()) {
String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Object type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
// key = _envStack.lookupAll(node.getIdentifier());
key = new StaticVal(Value_t.STRING, node.getIdentifier());
} else if ((node.getLvalue() != null) && (node.getExpression() != null)) { // lvalue [exp]
lvalue = node.getLvalue().accept(this);
if (!lvalue.isObject() && !lvalue.isTable()) {
String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Object or Array type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
key = node.getExpression().accept(this);
if(key.getData() != null && lvalue.isObject())
key = new StaticVal(Value_t.STRING, node.getExpression().accept(this).getData().toString());
else
key = node.getExpression().accept(this);
} else if ((id != null) && (node.getCall() != null)) { // call.id
lvalue = node.getCall().accept(this);
if (!lvalue.isObject()) {
//Cast error Think about this add all other cases of downcasts of the ExecutionASTVisitor. what to do?
//String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' it's not Object type to get member '" + id + "'.";
String msg = "Return value is not Object type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
key = _envStack.lookupAll(node.getIdentifier());
} else if ((node.getCall() != null) && (node.getExpression() != null)) { // call (expr)
lvalue = node.getCall().accept(this);
if (!lvalue.isObject() && !lvalue.isTable()) {
//Cast error Think about this add all other cases of downcasts of the ExecutionASTVisitor. what to do?
//String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' it's not Object or Array type to get member '" + id + "'.";
String msg = "Return value is not Object or Array type to get member '" + id + "'.";
ASTUtils.error(node, msg);
}
key = node.getExpression().accept(this);
} else {
//fatal error Think how to manage this errors.
}
Value value = (lvalue.isObject()) ? ((FoxObject)lvalue.getData()).get(key) : ((FoxArray)lvalue.getData()).get(key);
if (value == null) {
if (node.isLValue()) {
String errorInfo = "Object." + "id.";
retVal = new DynamicVal(errorInfo);
if(lvalue.isObject())
((FoxObject)lvalue.getData()).put(key, retVal);
else
((FoxArray)lvalue.getData()).put(key, retVal);
// lvalue.put(key, retVal);
} else {
retVal = NULL;
}
} else {
retVal = value;
}
return retVal;
}
@Override
public Value visit(ExtendedCall node) throws ASTVisitorException {
//System.out.println("-ExtendedCall");
Value retVal = NULL;
Value function = node.getCall().accept(this);
if (function.isUserFunction()) {
String functionName = ((FunctionDef) function.getData()).getFuncName();
node.setLvalueCall(functionName, node.getNormCall());
retVal = node.getLvalueCall().accept(this);
} else {
String errorCode = "ExtendedCall";
ASTUtils.fatalError(node, errorCode);
}
return retVal;
}
@Override
public Value visit(LvalueCall node) throws ASTVisitorException {
//System.out.println("-LvalueCall");
Value lvalue = node.getLvalue().accept(this);
//System.out.println(lvalue);
if (node.getCallSuffix() instanceof NormCall) {
if (!lvalue.isUserFunction() && !lvalue.isLibraryFunction()) {
String msg = "Function call: Symbol-" + ((DynamicVal) lvalue).getErrorInfo()
+ " is not Type-Function, but Type-" + lvalue.getType() + ".";
ASTUtils.error(node, msg);
}
} else if (node.getCallSuffix() instanceof MethodCall) {
if (!lvalue.isObject()) {
String msg = "Function call using lvalue..id(elist): Symbol-" + ((DynamicVal) lvalue).getErrorInfo()
+ " is not Type-Object, but Type-" + lvalue.getType() + ".";
ASTUtils.error(node, msg);
}
}
if (lvalue.isUserFunction()) {
//Get Actual Arguments
Value parameters = node.getCallSuffix().accept(this);
HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData();
enterFunctionSpace();
int count = 0;
ArrayList<IdentifierExpression> arguments = ((FunctionDef) lvalue.getData()).getArguments();
if (arguments.size() != actualArguments.size()) {
String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires " + arguments.size() + " arguments"
+ ": " + actualArguments.size() + " found.";
ASTUtils.error(node, msg);
}
for (IdentifierExpression argument : arguments) {
String name = argument.getIdentifier();
//System.out.println(name);
String errorInfo = name;
DynamicVal argumentInfo = new DynamicVal(actualArguments.get(count), errorInfo);
_envStack.insertSymbol(name, argumentInfo);
count++;
}
((FunctionDef) lvalue.getData()).getBody().accept(this);
} else if (lvalue.isLibraryFunction()) {
//Get Actual Arguments
Value parameters = node.getCallSuffix().accept(this);
HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData();
enterFunctionSpace();
/*if (actualArguments.size() < 1) {
String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires at least ONE argument"
+ ": " + actualArguments.size() + " found.";
ASTUtils.error(node, msg);
}*/
for (int i = 0; i < actualArguments.size(); i++) {
String errorInfo = LIBRARY_FUNC_ARG + i;
DynamicVal argumentInfo = new DynamicVal(actualArguments.get(i), errorInfo);
_envStack.insertSymbol(LIBRARY_FUNC_ARG + i, argumentInfo);
}
try {
Method method = (Method) lvalue.getData();
method.invoke(null, _envStack.getFunctionEnv());
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(ExecutionASTVisitor.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (lvalue.isObject()) {
//Get lvalue
FoxObject fobject = (FoxObject)lvalue.getData();
//Get ..id
String id = ((MethodCall) node.getCallSuffix()).getIdentifier();
Value key = new StaticVal(Value_t.STRING, id);
// Value function = objectData.get(key);
Value function = fobject.get(key);
if (!function.isUserFunction() && !function.isLibraryFunction()) {
String msg = "Function call using lvalue..id(elist): Symbmol- 'lvalue." + id
+ "' is not Type-Function, but Type-" + lvalue.getType() + ".";
ASTUtils.error(node, msg);
}
//Get Actual Arguments
Value parameters = node.getCallSuffix().accept(this);
HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData();
ArrayList<IdentifierExpression> arguments = ((FunctionDef) function.getData()).getArguments();
enterFunctionSpace();
if (arguments.size() != (actualArguments.size() + 1)) {
String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires " + arguments.size() + " arguments"
+ ": " + actualArguments.size() + " found.";
ASTUtils.error(node, msg);
}
int count = 0;
String name = arguments.get(count).getIdentifier();
String errorInfo = name;
DynamicVal argumentInfo = new DynamicVal(lvalue, errorInfo);
_envStack.insertSymbol(name, argumentInfo);
for (count = 1; count < arguments.size(); count++) {
name = arguments.get(count).getIdentifier();
//System.out.println(name);
errorInfo = name;
argumentInfo = new DynamicVal(actualArguments.get(count - 1), errorInfo);
_envStack.insertSymbol(name, argumentInfo);
count++;
}
Value bodyRet = ((FunctionDef) function.getData()).getBody().accept(this);
}
Value ret = exitFunctionSpace();
if (ret.getType().equals(Value_t.ERROR)) {
String msg = "Error during Function Execution @'" + ((DynamicVal) lvalue).getErrorInfo() + "' - " + ret.getData();
ASTUtils.error(node, msg);
}
//System.out.println(_envStack.toString());
return ret;
}
@Override
public Value visit(AnonymousFunctionCall node) throws ASTVisitorException {
//System.out.println("-AnonymousFunctionCall");
Value function = node.getFunctionDef().accept(this);
Value returnValue = node.getLvalueCall().accept(this);
return returnValue;
}
@Override
public Value visit(NormCall node) throws ASTVisitorException {
//System.out.println("-NormCall");
HashMap<Integer, Value> arguments = new HashMap<>();
int count = 0;
for (Expression expression : node.getExpressionList()) {
Value argValue = expression.accept(this);
arguments.put(count, argValue);
//System.out.println(argValue);
count++;
}
//Change to fox Table.
return new StaticVal(Value_t.UNDEFINED, arguments);
}
@Override
public Value visit(MethodCall node) throws ASTVisitorException {
//System.out.println("-MethodCall");
Value arguments = node.getNormCall().accept(this);
return arguments;
}
@Override
public Value visit(ObjectDefinition node) throws ASTVisitorException {
//System.out.println("-ObjectDefinition");
HashMap<Value, Value> objectData = new HashMap<>();
if (!node.getIndexedElementList().isEmpty()) {
for (IndexedElement indexed : node.getIndexedElementList()) {
ArrayList<Value> data = (ArrayList<Value>) indexed.accept(this).getData();
String errorInfo = "Object.(" + data.get(0) + ")";
Value value = new DynamicVal(data.get(1), errorInfo);
Value name = new StaticVal(Value_t.STRING, data.get(0).getData().toString());
objectData.put(name, value);
// objectData.put(data.get(0), value);
}
}
FoxObject fobject = new FoxObject(objectData);
return new StaticVal(Value_t.OBJECT, fobject);
}
@Override
public Value visit(IndexedElement node) throws ASTVisitorException {
//System.out.println("-IndexedElement");
ArrayList<Value> objectData = new ArrayList<>();
if(node.getExpression1() instanceof IdentifierExpression)
objectData.add(new StaticVal(Value_t.STRING, ((IdentifierExpression)node.getExpression1()).getIdentifier()));
else
objectData.add(node.getExpression1().accept(this));
objectData.add(node.getExpression2().accept(this));
return new StaticVal(Value_t.UNDEFINED, objectData);
}
@Override
public Value visit(ArrayDef node) throws ASTVisitorException {
//System.out.println("-ArrayDef");
HashMap<Value, Value> arrayData = new HashMap<>();
int count = 0;
if (node.getExpressionList() != null) {
for (Expression expression : node.getExpressionList()) {
Value index = new StaticVal(Value_t.INTEGER, count);
Value value = expression.accept(this);
String errorInfo = "Object.(" + count + ")";
Value element = new DynamicVal(value, errorInfo);
arrayData.put(index, element);
count++;
}
}
FoxArray farray = new FoxArray(arrayData);
return new StaticVal(Value_t.TABLE, farray);
}
@Override
public Value visit(Block node) throws ASTVisitorException {
//System.out.println("-Block");
Value ret = null;
enterScopeSpace();
for (Statement stmt : node.getStatementList()) {
ret = stmt.accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) {
return ret;
}
}
}
exitScopeSpace();
return ret;
}
@Override
public Value visit(FunctionDefExpression node) throws ASTVisitorException {
//System.out.println("-FunctionDefExpression");
node.getFunctionDef().accept(this);
return null;
}
@Override
public Value visit(FunctionDef node) throws ASTVisitorException {
//System.out.println("-FunctionDef");
String name = node.getFuncName();
/*Function Name*/
DynamicVal symbolInfo = _envStack.lookupCurrentScope(name);
boolean isLibraryFunction = LibraryFunction_t.isLibraryFunction(name);
if (symbolInfo != null) {
boolean isUserFunction = symbolInfo.getType() == Value_t.USER_FUNCTION;
String msg;
if (isUserFunction) {
msg = "Redeclaration of User-Function: " + name + ".";
} else if (isLibraryFunction) {
msg = "User-Function shadows Library-Function: " + name + ".";
} else {
//Think to remove this else statment.
msg = "User-Function already declared as Variable: " + name + ".";
}
ASTUtils.error(node, msg);
} else {
if (isLibraryFunction) {
String msg = "User-Function Shadows Library-Function: " + name + ".";
ASTUtils.error(node, msg);
}
}
String errorInfo = name;
symbolInfo = new DynamicVal(Value_t.USER_FUNCTION, node, errorInfo);
_envStack.insertSymbol(name, symbolInfo);
/*Function ONLY Check Arguments*/
enterScopeSpace();
for (IdentifierExpression argument : node.getArguments()) {
name = argument.getIdentifier();
symbolInfo = _envStack.lookupCurrentScope(name);
if (symbolInfo != null) {
String msg = "Redeclaration of Formal-Argument: " + name + ".";
ASTUtils.error(node, msg);
}
if (LibraryFunction_t.isLibraryFunction(name)) {
String msg = "Formal-Argument shadows Library-Function: " + name + ".";
ASTUtils.error(node, msg);
}
_envStack.insertSymbol(name);
}
exitScopeSpace();
return symbolInfo;
}
@Override
public Value visit(IntegerLiteral node) throws ASTVisitorException {
//System.out.println("-IntegerLiteral");
return new StaticVal(Value_t.INTEGER, node.getLiteral());
}
@Override
public Value visit(DoubleLiteral node) throws ASTVisitorException {
//System.out.println("-DoubleLiteral");
return new StaticVal(Value_t.REAL, node.getLiteral());
}
@Override
public Value visit(StringLiteral node) throws ASTVisitorException {
//System.out.println("-StringLiteral");
return new StaticVal(Value_t.STRING, node.getLiteral());
}
@Override
public Value visit(NullLiteral node) throws ASTVisitorException {
//System.out.println("-NullLiteral");
return NULL;
}
@Override
public Value visit(TrueLiteral node) throws ASTVisitorException {
//System.out.println("-TrueLiteral");
return new StaticVal(Value_t.BOOLEAN, Boolean.TRUE);
}
@Override
public Value visit(FalseLiteral node) throws ASTVisitorException {
//System.out.println("-FalseLiteral");
return new StaticVal(Value_t.BOOLEAN, Boolean.FALSE);
}
@Override
public Value visit(IfStatement node) throws ASTVisitorException {
//System.out.println("-IfStatement");
Value val = node.getExpression().accept(this);
Value ret = null;
if(!val.isBoolean())
ASTUtils.error(node, "If expression must be boolean: "+val.getType()+" given");
if ((Boolean) val.getData()) {
ret = node.getStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) {
return ret;
}
}
} else {
if (node.getElseStatement() != null) {
ret = node.getElseStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) {
return ret;
}
}
}
}
return ret;
}
@Override
public Value visit(WhileStatement node) throws ASTVisitorException {
//System.out.println("-WhileStatement");
Value val = node.getExpression().accept(this);
Value ret;
if(!val.isBoolean())
ASTUtils.error(node, "While expression must be boolean: "+val.getType()+" given");
enterLoopSpace();
while ((Boolean) ((Value) node.getExpression().accept(this)).getData()) {
ret = node.getStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK)) {
break;
} else if (ret.getData().equals(CONTINUE)) {
continue;
}else if(ret.getData().equals(RETURN)){
exitLoopSpace();
return ret;
}
}
}
exitLoopSpace();
return null;
}
@Override
public Value visit(ForStatement node) throws ASTVisitorException {
//System.out.println("-ForStatement");
Value ret;
enterLoopSpace();
for (Expression expression : node.getExpressionList1()) {
expression.accept(this);
}
Value val = node.getExpression().accept(this);
if(!val.isBoolean())
ASTUtils.error(node, "For expression must be boolean: "+val.getType()+" given");
while ((Boolean) ((Value) node.getExpression().accept(this)).getData()) {
ret = node.getStatement().accept(this);
if (ret != null) {
if (ret.getData().equals(BREAK)) {
break;
} else if (ret.getData().equals(CONTINUE)) {
for (Expression expression : node.getExpressionList2()) {
expression.accept(this);
}
continue;
}else if(ret.getData().equals(RETURN)){
return ret;
}
}
for (Expression expression : node.getExpressionList2()) {
expression.accept(this);
}
}
exitLoopSpace();
return null;
}
@Override
public Value visit(BreakStatement node) throws ASTVisitorException {
//System.out.println("-BreakStatement");
if (_inLoop == 0) {
ASTUtils.error(node, "Use of 'break' while not in a loop.");
}
return new StaticVal(Value_t.STRING, BREAK);
}
@Override
public Value visit(ContinueStatement node) throws ASTVisitorException {
//System.out.println("-ContinueStatement");
if (_inLoop == 0) {
ASTUtils.error(node, "Use of 'continue' while not in a loop.");
}
return new StaticVal(Value_t.STRING, CONTINUE);
}
@Override
public Value visit(ReturnStatement node) throws ASTVisitorException {
//System.out.println("-ReturnStatement");
Value ret = null;
if (_inFunction == 0) {
ASTUtils.error(node, "Use of 'return' while not in a function.");
}
if (node.getExpression() != null) {
ret = node.getExpression().accept(this);
_envStack.setReturnValue(ret);
}
return new StaticVal(Value_t.STRING, RETURN);
}
@Override
public Value visit(MetaSyntax node) throws ASTVisitorException{
if(node.getExpression() != null){
if(_inMeta)
return node.getExpression().accept(this);
else
return new StaticVal<ASTNode>(Value_t.AST, node.getExpression());
}else{
if(_inMeta)
for(Statement stmt : node.getStatementList())
stmt.accept(this);
else
return new StaticVal<ArrayList<Statement>>(Value_t.AST, node.getStatementList());
}
return new StaticVal();
}
@Override
public Value visit(MetaEscape node) throws ASTVisitorException{
Value exprVal = node.getExpression().accept(this);
if(!exprVal.isAST()){
String msg = ".~ requires an identifier holding an AST: "+exprVal.getType()+" found";
ASTUtils.error(node, msg);
}
return exprVal;
}
@Override
public Value visit(MetaExecute node) throws ASTVisitorException{
Value ret = new StaticVal();
enterMetaSpace();
Value exprVal = node.getExpression().accept(this);
if(!exprVal.isAST()){
String msg = "'.!' requires an AST: "+exprVal.getType()+" found";
ASTUtils.error(node, msg);
}
if(exprVal.getData() instanceof Expression){
Expression astExpr = (Expression) exprVal.getData();
ret = astExpr.accept(this);
while(ret.isAST()){
ret = ((Expression) ret.getData()).accept(this);
}
}else{
for(Statement stmt : (ArrayList<Statement>) exprVal.getData())
stmt.accept(this);
}
exitMetaSpace();
return ret;
}
}
| [ExecutionsASTVisitor - FunctionDef: Fix bug] Return function.
| src/ExecutionASTVisitor.java | [ExecutionsASTVisitor - FunctionDef: Fix bug] Return function. |
|
Java | agpl-3.0 | f80e823d7fa07497866c80875cb43a82d0633483 | 0 | marioestradarosa/axelor-development-kit,marioestradarosa/axelor-development-kit,axelor/axelor-development-kit,donsunsoft/axelor-development-kit,donsunsoft/axelor-development-kit,marioestradarosa/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,axelor/axelor-development-kit,donsunsoft/axelor-development-kit,marioestradarosa/axelor-development-kit,donsunsoft/axelor-development-kit | package com.axelor.meta.views;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;
import com.axelor.db.JPA;
import com.axelor.db.mapper.Mapper;
import com.axelor.meta.db.MetaSelect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
@XmlType
@JsonTypeName("field")
public class Field extends SimpleWidget {
@XmlAttribute
private String widget;
@XmlAttribute
private Boolean canSelect;
@XmlAttribute
private Boolean canNew;
@XmlAttribute
private Boolean canRemove;
@XmlAttribute
private Boolean canView;
@XmlAttribute
private String onChange;
@XmlAttribute
private String onSelect;
@XmlAttribute
private String domain;
@XmlAttribute
private Boolean required;
@XmlAttribute
private String requiredIf;
@XmlAttribute
private String validIf;
@XmlAttribute
private Integer width;
@XmlAttribute(name = "min")
private String minSize;
@XmlAttribute(name = "max")
private String maxSize;
@XmlAttribute
private String fgColor;
@XmlAttribute
private String bgColor;
@XmlAttribute
private String selection;
@XmlAttribute(name = "edit-window")
private String editWindow;
@XmlAttribute(name = "form-view")
private String formView;
@XmlAttribute(name = "grid-view")
private String gridView;
@XmlAttribute(name = "summary-view")
private String summaryView;
private Hilite hilite;
@XmlElements({
@XmlElement(name = "form", type = FormView.class),
@XmlElement(name = "grid", type = GridView.class)
})
private List<AbstractView> views;
@Override
public String getTitle() {
String title = super.getTitle();
if (title == null || "".equals(title.trim())) {
return JPA.translate(this.getName(), this.getModel(), null);
}
return title;
}
public String getWidget() {
return widget;
}
public void setWidget(String widget) {
this.widget = widget;
}
public Boolean getCanSelect() {
return canSelect;
}
public void setCanSelect(Boolean canSelect) {
this.canSelect = canSelect;
}
public Boolean getCanNew() {
return canNew;
}
public void setCanNew(Boolean canNew) {
this.canNew = canNew;
}
public Boolean getCanRemove() {
return canRemove;
}
public void setCanRemove(Boolean canRemove) {
this.canRemove = canRemove;
}
public Boolean getCanView() {
return canView;
}
public void setCanView(Boolean canView) {
this.canView = canView;
}
public String getOnChange() {
return onChange;
}
public void setOnChange(String onChange) {
this.onChange = onChange;
}
public String getOnSelect() {
return onSelect;
}
public void setOnSelect(String onSelect) {
this.onSelect = onSelect;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getRequiredIf() {
return requiredIf;
}
public void setRequiredIf(String requiredIf) {
this.requiredIf = requiredIf;
}
public String getValidIf() {
return validIf;
}
public void setValidIf(String validIf) {
this.validIf = validIf;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
@JsonIgnore
public String getSelection() {
return selection;
}
@JsonProperty("selection")
public List<Object> getSelectionList() {
if (selection == null || "".equals(selection.trim()))
return null;
List<MetaSelect> items = MetaSelect.all().filter("self.key = ?", selection).fetch();
List<Object> all = Lists.newArrayList();
for(MetaSelect ms : items) {
all.add(ImmutableMap.of("value", ms.getValue(), "title", JPA.translate(ms.getTitle())));
}
return all;
}
public void setSelection(String selection) {
this.selection = selection;
}
public Hilite getHilite() {
return hilite;
}
public void setHilite(Hilite hilite) {
this.hilite = hilite;
}
public List<AbstractView> getViews() {
if(views != null && this.getTarget() != null) {
for (AbstractView abstractView : views) {
abstractView.setModel(this.getTarget());
}
}
return views;
}
public void setViews(List<AbstractView> views) {
this.views = views;
}
public String getMinSize() {
return minSize;
}
public void setMinSize(String minSize) {
this.minSize = minSize;
}
public String getMaxSize() {
return maxSize;
}
public void setMaxSize(String maxSize) {
this.maxSize = maxSize;
}
public String getFgColor() {
return fgColor;
}
public void setFgColor(String fgColor) {
this.fgColor = fgColor;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getEditWindow() {
return editWindow;
}
public void setEditWindow(String editWindow) {
this.editWindow = editWindow;
}
public String getFormView() {
return formView;
}
public void setFormView(String formView) {
this.formView = formView;
}
public String getGridView() {
return gridView;
}
public void setGridView(String gridView) {
this.gridView = gridView;
}
public String getSummaryView() {
return summaryView;
}
public void setSummaryView(String summaryView) {
this.summaryView = summaryView;
}
private String getTarget() {
Mapper mapper = null;
try {
mapper = Mapper.of(Class.forName(this.getModel()));
return mapper.getProperty(getName()).getTarget().getName();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (NullPointerException e) {
}
return null;
}
}
| axelor-meta/src/main/java/com/axelor/meta/views/Field.java | package com.axelor.meta.views;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;
import com.axelor.db.JPA;
import com.axelor.db.mapper.Mapper;
import com.axelor.db.mapper.Property;
import com.axelor.meta.db.MetaSelect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
@XmlType
@JsonTypeName("field")
public class Field extends SimpleWidget {
@XmlAttribute
private String widget;
@XmlAttribute
private Boolean canSelect;
@XmlAttribute
private Boolean canNew;
@XmlAttribute
private Boolean canRemove;
@XmlAttribute
private Boolean canView;
@XmlAttribute
private String onChange;
@XmlAttribute
private String onSelect;
@XmlAttribute
private String domain;
@XmlAttribute
private Boolean required;
@XmlAttribute
private String requiredIf;
@XmlAttribute
private String validIf;
@XmlAttribute
private Integer width;
@XmlAttribute(name = "min")
private String minSize;
@XmlAttribute(name = "max")
private String maxSize;
@XmlAttribute
private String fgColor;
@XmlAttribute
private String bgColor;
@XmlAttribute
private String selection;
@XmlAttribute(name = "edit-window")
private String editWindow;
@XmlAttribute(name = "form-view")
private String formView;
@XmlAttribute(name = "grid-view")
private String gridView;
@XmlAttribute(name = "summary-view")
private String summaryView;
private Hilite hilite;
@XmlElements({
@XmlElement(name = "form", type = FormView.class),
@XmlElement(name = "grid", type = GridView.class)
})
private List<AbstractView> views;
@Override
public String getTitle() {
String title = super.getTitle();
if (title == null || "".equals(title.trim())) {
return JPA.translate(this.getName(), this.getModel(), null);
}
return title;
}
public String getWidget() {
return widget;
}
public void setWidget(String widget) {
this.widget = widget;
}
public Boolean getCanSelect() {
return canSelect;
}
public void setCanSelect(Boolean canSelect) {
this.canSelect = canSelect;
}
public Boolean getCanNew() {
return canNew;
}
public void setCanNew(Boolean canNew) {
this.canNew = canNew;
}
public Boolean getCanRemove() {
return canRemove;
}
public void setCanRemove(Boolean canRemove) {
this.canRemove = canRemove;
}
public Boolean getCanView() {
return canView;
}
public void setCanView(Boolean canView) {
this.canView = canView;
}
public String getOnChange() {
return onChange;
}
public void setOnChange(String onChange) {
this.onChange = onChange;
}
public String getOnSelect() {
return onSelect;
}
public void setOnSelect(String onSelect) {
this.onSelect = onSelect;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getRequiredIf() {
return requiredIf;
}
public void setRequiredIf(String requiredIf) {
this.requiredIf = requiredIf;
}
public String getValidIf() {
return validIf;
}
public void setValidIf(String validIf) {
this.validIf = validIf;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
@JsonIgnore
public String getSelection() {
return selection;
}
@JsonProperty("selection")
public List<Object> getSelectionList() {
if (selection == null || "".equals(selection.trim()))
return null;
List<MetaSelect> items = MetaSelect.all().filter("self.key = ?", selection).fetch();
List<Object> all = Lists.newArrayList();
for(MetaSelect ms : items) {
all.add(ImmutableMap.of("value", ms.getValue(), "title", JPA.translate(ms.getTitle())));
}
return all;
}
public void setSelection(String selection) {
this.selection = selection;
}
public Hilite getHilite() {
return hilite;
}
public void setHilite(Hilite hilite) {
this.hilite = hilite;
}
public List<AbstractView> getViews() {
if(views != null) {
for (AbstractView abstractView : views) {
abstractView.setModel(this.getTarget());
}
}
return views;
}
public void setViews(List<AbstractView> views) {
this.views = views;
}
public String getMinSize() {
return minSize;
}
public void setMinSize(String minSize) {
this.minSize = minSize;
}
public String getMaxSize() {
return maxSize;
}
public void setMaxSize(String maxSize) {
this.maxSize = maxSize;
}
public String getFgColor() {
return fgColor;
}
public void setFgColor(String fgColor) {
this.fgColor = fgColor;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getEditWindow() {
return editWindow;
}
public void setEditWindow(String editWindow) {
this.editWindow = editWindow;
}
public String getFormView() {
return formView;
}
public void setFormView(String formView) {
this.formView = formView;
}
public String getGridView() {
return gridView;
}
public void setGridView(String gridView) {
this.gridView = gridView;
}
public String getSummaryView() {
return summaryView;
}
public void setSummaryView(String summaryView) {
this.summaryView = summaryView;
}
private String getTarget() {
Mapper mapper = null;
try {
mapper = Mapper.of(Class.forName((super.getModel())));
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
Property prop = mapper.getProperty(getName());
return prop.getTarget().getName();
}
}
| Fixed NPE issue.
| axelor-meta/src/main/java/com/axelor/meta/views/Field.java | Fixed NPE issue. |
|
Java | apache-2.0 | f5ab62879f07b3432e66ddb429190cc1d8e4588d | 0 | brabenetz/xmlunit,xmlunit/xmlunit.net,brabenetz/xmlunit,xmlunit/xmlunit.net,xmlunit/xmlunit,xmlunit/xmlunit | /*
This file is licensed 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.xmlunit.validation;
import java.util.Arrays;
import javax.xml.transform.Source;
/**
* Validates a piece of XML against a schema given in a supported
* language or the defintion of such a schema itself.
*/
public abstract class Validator {
private String schemaURI;
private Source[] sourceLocations;
/**
* The URI (or for example the System ID in case of a DTD) that
* identifies the schema to validate or use during validation.
*/
public void setSchemaURI(String uri) {
this.schemaURI = uri;
}
protected String getSchemaURI() {
return schemaURI;
}
/**
* Where to find the schema.
*/
public void setSchemaSources(Source... s) {
if (s != null) {
sourceLocations = Arrays.copyOf(s, s.length);
} else {
sourceLocations = null;
}
}
/**
* Where to find the schema.
*/
public final void setSchemaSource(Source s) {
setSchemaSources(s == null ? null : new Source[] {s});
}
protected Source[] getSchemaSources() {
return sourceLocations == null ? new Source[0] : sourceLocations;
}
/**
* Validates a schema.
*
* @throws UnsupportedOperationException if the language's
* implementation doesn't support schema validation
*/
public abstract ValidationResult validateSchema();
/**
* Validates an instance against the schema.
*/
public abstract ValidationResult validateInstance(Source instance);
/**
* Factory that obtains a Validator instance based on the schema language.
*
* @see Languages
*/
public static Validator forLanguage(String language) {
if (!Languages.XML_DTD_NS_URI.equals(language)) {
return new JAXPValidator(language);
}
return new ParsingValidator(Languages.XML_DTD_NS_URI);
}
}
| src/main/java-core/org/xmlunit/validation/Validator.java | /*
This file is licensed 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.xmlunit.validation;
import java.util.Arrays;
import javax.xml.transform.Source;
/**
* Validates a piece of XML against a schema given in a supported
* language or the defintion of such a schema itself.
*/
public abstract class Validator {
private String schemaURI;
private Source[] sourceLocations;
/**
* The URI (or for example the System ID in case of a DTD) that
* identifies the schema to validate or use during validation.
*/
public void setSchemaURI(String uri) {
this.schemaURI = uri;
}
protected String getSchemaURI() {
return schemaURI;
}
/**
* Where to find the schema.
*/
public void setSchemaSources(Source[] s) {
if (s != null) {
sourceLocations = Arrays.copyOf(s, s.length);
} else {
sourceLocations = null;
}
}
/**
* Where to find the schema.
*/
public final void setSchemaSource(Source s) {
setSchemaSources(s == null ? null : new Source[] {s});
}
protected Source[] getSchemaSources() {
return sourceLocations == null ? new Source[0] : sourceLocations;
}
/**
* Validates a schema.
*
* @throws UnsupportedOperationException if the language's
* implementation doesn't support schema validation
*/
public abstract ValidationResult validateSchema();
/**
* Validates an instance against the schema.
*/
public abstract ValidationResult validateInstance(Source instance);
/**
* Factory that obtains a Validator instance based on the schema language.
*
* @see Languages
*/
public static Validator forLanguage(String language) {
if (!Languages.XML_DTD_NS_URI.equals(language)) {
return new JAXPValidator(language);
}
return new ParsingValidator(Languages.XML_DTD_NS_URI);
}
}
| use varargs for schema sources
| src/main/java-core/org/xmlunit/validation/Validator.java | use varargs for schema sources |
|
Java | apache-2.0 | d98d33756c03029a89d549f34e9204f58772a3dc | 0 | researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds | /*
* Copyright 2012 Research Studios Austria Forschungsges.m.b.H.
*
* 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 won.bot.framework.eventbot.action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import won.bot.framework.bot.context.BotContext;
import won.bot.framework.eventbot.EventListenerContext;
import won.bot.framework.eventbot.action.impl.mail.model.SubscribeStatus;
import won.bot.framework.eventbot.action.impl.mail.model.WonURI;
import won.bot.framework.eventbot.action.impl.mail.receive.MailContentExtractor;
import won.bot.framework.eventbot.event.Event;
import won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent;
import won.bot.framework.eventbot.filter.impl.AcceptOnceFilter;
import won.bot.framework.eventbot.filter.impl.OriginalMessageUriRemoteResponseEventFilter;
import won.bot.framework.eventbot.filter.impl.OriginalMessageUriResponseEventFilter;
import won.bot.framework.eventbot.listener.EventListener;
import won.bot.framework.eventbot.listener.impl.ActionOnEventListener;
import won.protocol.message.WonMessage;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
/**
* User: fkleedorfer
* Date: 02.02.14
*/
public class EventBotActionUtils {
private static final Logger logger = LoggerFactory.getLogger(EventBotActionUtils.class);
private static final String MAIL_USER_SUBSCRIBE_COLLECTION = "user_subscribe_status";
private static final String MAIL_USER_CACHED_MAILS_COLLECTION = "user_cached_mails";
private static final String MAIL_URIMIMEMESSAGERELATIONS_NAME = "uriMimeMessageRelations";
private static final String MAIL_MAILIDURIRELATIONS_NAME = "mailIdUriRelations";
private static final String MAIL_MAILADRESSURIRELATIONS_NAME = "mailAdressUriRelations";
public static void rememberInList(EventListenerContext ctx, URI uri, String uriListName) {
if (uriListName != null && uriListName.trim().length() > 0){
ctx.getBotContext().appendToNamedNeedUriList(uri, uriListName);
logger.debug("remembering need in NamedNeedList {} ", uri);
} else {
throw new IllegalArgumentException("'uriListName' must not not be null or empty");
}
}
public static void rememberInNodeListIfNamePresent(EventListenerContext ctx, URI uri){
ctx.getBotContext().rememberNodeUri(uri);
}
public static void removeFromList(EventListenerContext ctx, URI uri, String uriListName) {
if (uriListName != null && uriListName.trim().length() > 0){
ctx.getBotContext().removeNeedUriFromNamedNeedUriList(uri, uriListName);
logger.debug("removing need from NamedNeedList {} ", uri);
} else {
throw new IllegalArgumentException("'uriListName' must not not be null or empty");
}
}
//************************************************ Mail2WonBot Context Methods *************************************
//Util Methods to Get/Remove/Add Uri -> MimeMessage Relation
public static void removeUriMimeMessageRelation(EventListenerContext context, URI needURI) {
context.getBotContext().removeFromObjectMap(MAIL_URIMIMEMESSAGERELATIONS_NAME, needURI.toString());
}
public static MimeMessage getMimeMessageForURI(EventListenerContext context, URI uri) throws MessagingException {
// use the empty default session here for reconstructing the mime message
byte[] byteMsg = (byte[]) context.getBotContext().loadFromObjectMap(MAIL_URIMIMEMESSAGERELATIONS_NAME, uri.toString());
ByteArrayInputStream is = new ByteArrayInputStream(byteMsg);
return new MimeMessage(Session.getDefaultInstance(new Properties(), null), is);
}
public static void addUriMimeMessageRelation(EventListenerContext context, URI needURI, MimeMessage mimeMessage)
throws IOException, MessagingException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
mimeMessage.writeTo(os);
context.getBotContext().saveToObjectMap(MAIL_URIMIMEMESSAGERELATIONS_NAME, needURI.toString(), os.toByteArray());
}
//Util Methods to Get/Remove/Add MailId -> URI Relation
public static void removeMailIdWonURIRelation(EventListenerContext context, String mailId) {
context.getBotContext().removeFromObjectMap(MAIL_MAILIDURIRELATIONS_NAME, mailId);
}
public static WonURI getWonURIForMailId(EventListenerContext context, String mailId) {
return (WonURI) context.getBotContext().loadFromObjectMap(MAIL_MAILIDURIRELATIONS_NAME, mailId);
}
public static void addMailIdWonURIRelation(EventListenerContext context, String mailId, WonURI uri) {
context.getBotContext().saveToObjectMap(MAIL_MAILIDURIRELATIONS_NAME, mailId, uri);
}
//Util Methods to Get/Remove/Add MailId -> URI Relation
public static List<WonURI> getWonURIsForMailAddress(EventListenerContext context, String mailAddress) {
List<WonURI> uriList = new LinkedList<>();
List<Object> objectList = context.getBotContext().loadFromListMap(MAIL_MAILADRESSURIRELATIONS_NAME, mailAddress);
for(Object o : objectList){
uriList.add((WonURI) o);
}
return uriList;
}
public static void addMailAddressWonURIRelation(EventListenerContext context, String mailAddress, WonURI uri) {
context.getBotContext().addToListMap(MAIL_MAILADRESSURIRELATIONS_NAME, mailAddress, uri);
}
public static void addCachedMailsForMailAddress(BotContext botContext, MimeMessage mimeMessage) throws IOException, MessagingException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
mimeMessage.writeTo(os);
botContext.addToListMap(MAIL_USER_CACHED_MAILS_COLLECTION, MailContentExtractor.getMailSender(mimeMessage), os.toByteArray());
}
public static Collection<MimeMessage> loadCachedMailsForMailAddress(BotContext botContext, String mailAddress) throws MessagingException {
List<MimeMessage> mimeMessages = new LinkedList<>();
List<Object> objectList = botContext.loadFromListMap(MAIL_USER_CACHED_MAILS_COLLECTION, mailAddress);
for (Object o : objectList) {
// use the empty default session here for reconstructing the mime message
byte[] byteMsg = (byte[]) o;
ByteArrayInputStream is = new ByteArrayInputStream(byteMsg);
mimeMessages.add(new MimeMessage(Session.getDefaultInstance(new Properties(), null), is));
}
return mimeMessages;
}
public static void removeCachedMailsForMailAddress(BotContext botContext, String mailAddress) {
botContext.dropCollection(mailAddress);
}
public static void setSubscribeStatusForMailAddress(
BotContext botContext, String mailAddress, SubscribeStatus status) {
botContext.saveToObjectMap(MAIL_USER_SUBSCRIBE_COLLECTION, mailAddress, status);
}
public static SubscribeStatus getSubscribeStatusForMailAddress(BotContext botContext, String mailAddress) {
String status = (String) botContext.loadFromObjectMap(MAIL_USER_SUBSCRIBE_COLLECTION, mailAddress);
return (status != null) ? SubscribeStatus.valueOf(status) : SubscribeStatus.NO_RESPONSE;
}
//************************************************ TelegramBot Context Methods *************************************
public static void addChatIdWonURIRelation(EventListenerContext context, String mapName, Long chatId, WonURI uri) {
context.getBotContext().saveToObjectMap(mapName, chatId.toString(), uri);
}
public static void addURIChatIdRelation(EventListenerContext context, String mapName, URI uri, Long chatId) {
context.getBotContext().saveToObjectMap(mapName, uri.toString(), chatId);
}
public static Long getChatIdForURI(EventListenerContext context, String mapName, URI uri) {
return (Long) context.getBotContext().loadFromObjectMap(mapName, uri.toString());
}
public static void addMessageIdWonURIRelation(EventListenerContext context, String mapName, Integer messageId, WonURI wonURI) {
context.getBotContext().saveToObjectMap(mapName, messageId.toString(), wonURI);
}
public static WonURI getWonURIForMessageId(EventListenerContext context, String mapName, Integer messageId) {
return (WonURI) context.getBotContext().loadFromObjectMap(mapName, messageId.toString());
}
//************************************************ EventListener ***************************************************
/**
* Creates a listener that waits for the response to the specified message. If a SuccessResponse is received,
* the successCallback is executed, if a FailureResponse is received, the failureCallback is executed.
* @param outgoingMessage
* @param successCallback
* @param failureCallback
* @param context
* @return
*/
public static EventListener makeAndSubscribeResponseListener(final WonMessage outgoingMessage,
final EventListener successCallback,
final EventListener failureCallback,
EventListenerContext context) {
//create an event listener that processes the response to the wonMessage we're about to send
EventListener listener = new ActionOnEventListener(context,
new AcceptOnceFilter(OriginalMessageUriResponseEventFilter.forWonMessage(outgoingMessage)),
new BaseEventBotAction(context)
{
@Override
protected void doRun(final Event event) throws Exception {
if (event instanceof SuccessResponseEvent) {
successCallback.onEvent(event);
} else if (event instanceof FailureResponseEvent){
failureCallback.onEvent(event);
}
}
}
);
context.getEventBus().subscribe(SuccessResponseEvent.class, listener);
context.getEventBus().subscribe(FailureResponseEvent.class, listener);
return listener;
}
/**
* Creates a listener that waits for the remote response to the specified message. If a SuccessResponse is received,
* the successCallback is executed, if a FailureResponse is received, the failureCallback is executed.
* @param outgoingMessage
* @param successCallback
* @param failureCallback
* @param context
* @return
*/
public static EventListener makeAndSubscribeRemoteResponseListener(final WonMessage outgoingMessage,
final EventListener successCallback,
final EventListener failureCallback,
EventListenerContext context) {
//create an event listener that processes the remote response to the wonMessage we're about to send
EventListener listener = new ActionOnEventListener(context,
new AcceptOnceFilter(OriginalMessageUriRemoteResponseEventFilter.forWonMessage(outgoingMessage)),
new BaseEventBotAction(context)
{
@Override
protected void doRun(final Event event) throws Exception {
if (event instanceof SuccessResponseEvent) {
successCallback.onEvent(event);
} else if (event instanceof FailureResponseEvent){
failureCallback.onEvent(event);
}
}
}
);
context.getEventBus().subscribe(SuccessResponseEvent.class, listener);
context.getEventBus().subscribe(FailureResponseEvent.class, listener);
return listener;
}
}
| webofneeds/won-bot/src/main/java/won/bot/framework/eventbot/action/EventBotActionUtils.java | /*
* Copyright 2012 Research Studios Austria Forschungsges.m.b.H.
*
* 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 won.bot.framework.eventbot.action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import won.bot.framework.bot.context.BotContext;
import won.bot.framework.eventbot.EventListenerContext;
import won.bot.framework.eventbot.action.impl.mail.model.SubscribeStatus;
import won.bot.framework.eventbot.action.impl.mail.model.WonURI;
import won.bot.framework.eventbot.action.impl.mail.receive.MailContentExtractor;
import won.bot.framework.eventbot.event.Event;
import won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent;
import won.bot.framework.eventbot.filter.impl.AcceptOnceFilter;
import won.bot.framework.eventbot.filter.impl.OriginalMessageUriRemoteResponseEventFilter;
import won.bot.framework.eventbot.filter.impl.OriginalMessageUriResponseEventFilter;
import won.bot.framework.eventbot.listener.EventListener;
import won.bot.framework.eventbot.listener.impl.ActionOnEventListener;
import won.protocol.message.WonMessage;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
/**
* User: fkleedorfer
* Date: 02.02.14
*/
public class EventBotActionUtils {
private static final Logger logger = LoggerFactory.getLogger(EventBotActionUtils.class);
private static final String MAIL_USER_SUBSCRIBE_COLLECTION = "user_subscribe_status";
private static final String MAIL_USER_CACHED_MAILS_COLLECTION = "user_cached_mails";
private static final String MAIL_URIMIMEMESSAGERELATIONS_NAME = "uriMimeMessageRelations";
private static final String MAIL_MAILIDURIRELATIONS_NAME = "mailIdUriRelations";
public static void rememberInList(EventListenerContext ctx, URI uri, String uriListName) {
if (uriListName != null && uriListName.trim().length() > 0){
ctx.getBotContext().appendToNamedNeedUriList(uri, uriListName);
logger.debug("remembering need in NamedNeedList {} ", uri);
} else {
throw new IllegalArgumentException("'uriListName' must not not be null or empty");
}
}
public static void rememberInNodeListIfNamePresent(EventListenerContext ctx, URI uri){
ctx.getBotContext().rememberNodeUri(uri);
}
public static void removeFromList(EventListenerContext ctx, URI uri, String uriListName) {
if (uriListName != null && uriListName.trim().length() > 0){
ctx.getBotContext().removeNeedUriFromNamedNeedUriList(uri, uriListName);
logger.debug("removing need from NamedNeedList {} ", uri);
} else {
throw new IllegalArgumentException("'uriListName' must not not be null or empty");
}
}
//************************************************ Mail2WonBot Context Methods *************************************
//Util Methods to Get/Remove/Add Uri -> MimeMessage Relation
public static void removeUriMimeMessageRelation(EventListenerContext context, URI needURI) {
context.getBotContext().removeFromObjectMap(MAIL_URIMIMEMESSAGERELATIONS_NAME, needURI.toString());
}
public static MimeMessage getMimeMessageForURI(EventListenerContext context, URI uri) throws MessagingException {
// use the empty default session here for reconstructing the mime message
byte[] byteMsg = (byte[]) context.getBotContext().loadFromObjectMap(MAIL_URIMIMEMESSAGERELATIONS_NAME, uri.toString());
ByteArrayInputStream is = new ByteArrayInputStream(byteMsg);
return new MimeMessage(Session.getDefaultInstance(new Properties(), null), is);
}
public static void addUriMimeMessageRelation(EventListenerContext context, URI needURI, MimeMessage mimeMessage)
throws IOException, MessagingException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
mimeMessage.writeTo(os);
context.getBotContext().saveToObjectMap(MAIL_URIMIMEMESSAGERELATIONS_NAME, needURI.toString(), os.toByteArray());
}
//Util Methods to Get/Remove/Add MailId -> URI Relation
public static void removeMailIdWonURIRelation(EventListenerContext context, String mailId) {
context.getBotContext().removeFromObjectMap(MAIL_MAILIDURIRELATIONS_NAME, mailId);
}
public static WonURI getWonURIForMailId(EventListenerContext context, String mailId) {
return (WonURI) context.getBotContext().loadFromObjectMap(MAIL_MAILIDURIRELATIONS_NAME, mailId);
}
public static void addMailIdWonURIRelation(EventListenerContext context, String mailId, WonURI uri) {
context.getBotContext().saveToObjectMap(MAIL_MAILIDURIRELATIONS_NAME, mailId, uri);
}
public static void addCachedMailsForMailAddress(BotContext botContext, MimeMessage mimeMessage) throws IOException, MessagingException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
mimeMessage.writeTo(os);
botContext.addToListMap(MAIL_USER_CACHED_MAILS_COLLECTION, MailContentExtractor.getMailSender(mimeMessage), os.toByteArray());
}
public static Collection<MimeMessage> loadCachedMailsForMailAddress(BotContext botContext, String mailAddress)
throws MessagingException {
List<MimeMessage> mimeMessages = new LinkedList<>();
List<Object> objectList = botContext.loadFromListMap(MAIL_USER_CACHED_MAILS_COLLECTION, mailAddress);
for (Object o : objectList) {
// use the empty default session here for reconstructing the mime message
byte[] byteMsg = (byte[]) o;
ByteArrayInputStream is = new ByteArrayInputStream(byteMsg);
mimeMessages.add(new MimeMessage(Session.getDefaultInstance(new Properties(), null), is));
}
return mimeMessages;
}
public static void removeCachedMailsForMailAddress(BotContext botContext, String mailAddress) {
botContext.dropCollection(mailAddress);
}
public static void setSubscribeStatusForMailAddress(
BotContext botContext, String mailAddress, SubscribeStatus status) {
botContext.saveToObjectMap(MAIL_USER_SUBSCRIBE_COLLECTION, mailAddress, status);
}
public static SubscribeStatus getSubscribeStatusForMailAddress(BotContext botContext, String mailAddress) {
String status = (String) botContext.loadFromObjectMap(MAIL_USER_SUBSCRIBE_COLLECTION, mailAddress);
return (status != null) ? SubscribeStatus.valueOf(status) : SubscribeStatus.NO_RESPONSE;
}
//************************************************ TelegramBot Context Methods *************************************
public static void addChatIdWonURIRelation(EventListenerContext context, String mapName, Long chatId, WonURI uri) {
context.getBotContext().saveToObjectMap(mapName, chatId.toString(), uri);
}
public static void addURIChatIdRelation(EventListenerContext context, String mapName, URI uri, Long chatId) {
context.getBotContext().saveToObjectMap(mapName, uri.toString(), chatId);
}
public static Long getChatIdForURI(EventListenerContext context, String mapName, URI uri) {
return (Long) context.getBotContext().loadFromObjectMap(mapName, uri.toString());
}
public static void addMessageIdWonURIRelation(EventListenerContext context, String mapName, Integer messageId, WonURI wonURI) {
context.getBotContext().saveToObjectMap(mapName, messageId.toString(), wonURI);
}
public static WonURI getWonURIForMessageId(EventListenerContext context, String mapName, Integer messageId) {
return (WonURI) context.getBotContext().loadFromObjectMap(mapName, messageId.toString());
}
//************************************************ EventListener ***************************************************
/**
* Creates a listener that waits for the response to the specified message. If a SuccessResponse is received,
* the successCallback is executed, if a FailureResponse is received, the failureCallback is executed.
* @param outgoingMessage
* @param successCallback
* @param failureCallback
* @param context
* @return
*/
public static EventListener makeAndSubscribeResponseListener(final WonMessage outgoingMessage,
final EventListener successCallback,
final EventListener failureCallback,
EventListenerContext context) {
//create an event listener that processes the response to the wonMessage we're about to send
EventListener listener = new ActionOnEventListener(context,
new AcceptOnceFilter(OriginalMessageUriResponseEventFilter.forWonMessage(outgoingMessage)),
new BaseEventBotAction(context)
{
@Override
protected void doRun(final Event event) throws Exception {
if (event instanceof SuccessResponseEvent) {
successCallback.onEvent(event);
} else if (event instanceof FailureResponseEvent){
failureCallback.onEvent(event);
}
}
}
);
context.getEventBus().subscribe(SuccessResponseEvent.class, listener);
context.getEventBus().subscribe(FailureResponseEvent.class, listener);
return listener;
}
/**
* Creates a listener that waits for the remote response to the specified message. If a SuccessResponse is received,
* the successCallback is executed, if a FailureResponse is received, the failureCallback is executed.
* @param outgoingMessage
* @param successCallback
* @param failureCallback
* @param context
* @return
*/
public static EventListener makeAndSubscribeRemoteResponseListener(final WonMessage outgoingMessage,
final EventListener successCallback,
final EventListener failureCallback,
EventListenerContext context) {
//create an event listener that processes the remote response to the wonMessage we're about to send
EventListener listener = new ActionOnEventListener(context,
new AcceptOnceFilter(OriginalMessageUriRemoteResponseEventFilter.forWonMessage(outgoingMessage)),
new BaseEventBotAction(context)
{
@Override
protected void doRun(final Event event) throws Exception {
if (event instanceof SuccessResponseEvent) {
successCallback.onEvent(event);
} else if (event instanceof FailureResponseEvent){
failureCallback.onEvent(event);
}
}
}
);
context.getEventBus().subscribe(SuccessResponseEvent.class, listener);
context.getEventBus().subscribe(FailureResponseEvent.class, listener);
return listener;
}
}
| added new context listmap to represent all the needuris created by a single mail address
| webofneeds/won-bot/src/main/java/won/bot/framework/eventbot/action/EventBotActionUtils.java | added new context listmap to represent all the needuris created by a single mail address |
|
Java | apache-2.0 | e6a07f4f7e2288c5633a885961b9591348b22b27 | 0 | smartcommunitylab/AAC,smartcommunitylab/AAC,smartcommunitylab/AAC,smartcommunitylab/AAC | /**
* Copyright 2015-2019 Smart Community Lab, FBK
*
* 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 it.smartcommunitylab.aac.model;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.util.StringUtils;
import it.smartcommunitylab.aac.repository.UserRepository;
/**
* DB mapper for the client app information
*
* @author raman
*
*/
public class ClientDetailsRowMapper implements RowMapper<ClientDetails> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private static ObjectMapper mapper = new ObjectMapper();
private final UserRepository userRepository;
public ClientDetailsRowMapper(UserRepository userRepository) {
super();
this.userRepository = userRepository;
}
public ClientDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
BaseClientDetails details = new BaseClientDetails(rs.getString("client_id"), rs.getString("resource_ids"),
rs.getString("scope"), rs.getString("authorized_grant_types"), rs.getString("authorities"),
rs.getString("web_server_redirect_uri"));
details.setClientSecret(rs.getString("client_secret"));
if (rs.getObject("access_token_validity") != null) {
details.setAccessTokenValiditySeconds(rs.getInt("access_token_validity"));
}
if (rs.getObject("refresh_token_validity") != null) {
details.setRefreshTokenValiditySeconds(rs.getInt("refresh_token_validity"));
}
String json = rs.getString("additional_information");
if (json != null) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> additionalInformation = mapper.readValue(json, Map.class);
details.setAdditionalInformation(additionalInformation);
} catch (Exception e) {
logger.warn("Could not decode JSON for additional information: " + details, e);
}
} else {
details.setAdditionalInformation(new HashMap<String, Object>());
}
// merge developer roles into authorities
it.smartcommunitylab.aac.model.User developer = userRepository.findOne(rs.getLong("developerId"));
if (developer != null) {
List<GrantedAuthority> list = new LinkedList<GrantedAuthority>();
if (details.getAuthorities() != null) list.addAll(details.getAuthorities());
list.addAll(developer.getRoles()/*.stream().filter(r -> !StringUtils.isEmpty(r.getContext())).collect(Collectors.toList())*/);
details.setAuthorities(list);
}
return details;
}
}
| src/main/java/it/smartcommunitylab/aac/model/ClientDetailsRowMapper.java | /**
* Copyright 2015-2019 Smart Community Lab, FBK
*
* 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 it.smartcommunitylab.aac.model;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.util.StringUtils;
import it.smartcommunitylab.aac.repository.UserRepository;
/**
* DB mapper for the client app information
*
* @author raman
*
*/
public class ClientDetailsRowMapper implements RowMapper<ClientDetails> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private static ObjectMapper mapper = new ObjectMapper();
private final UserRepository userRepository;
public ClientDetailsRowMapper(UserRepository userRepository) {
super();
this.userRepository = userRepository;
}
public ClientDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
BaseClientDetails details = new BaseClientDetails(rs.getString("client_id"), rs.getString("resource_ids"),
rs.getString("scope"), rs.getString("authorized_grant_types"), rs.getString("authorities"),
rs.getString("web_server_redirect_uri"));
details.setClientSecret(rs.getString("client_secret"));
if (rs.getObject("access_token_validity") != null) {
details.setAccessTokenValiditySeconds(rs.getInt("access_token_validity"));
}
if (rs.getObject("refresh_token_validity") != null) {
details.setRefreshTokenValiditySeconds(rs.getInt("refresh_token_validity"));
}
String json = rs.getString("additional_information");
if (json != null) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> additionalInformation = mapper.readValue(json, Map.class);
details.setAdditionalInformation(additionalInformation);
} catch (Exception e) {
logger.warn("Could not decode JSON for additional information: " + details, e);
}
} else {
details.setAdditionalInformation(new HashMap<String, Object>());
}
// merge developer roles into authorities
it.smartcommunitylab.aac.model.User developer = userRepository.findOne(rs.getLong("developerId"));
if (developer != null) {
List<GrantedAuthority> list = new LinkedList<GrantedAuthority>();
if (details.getAuthorities() != null) list.addAll(details.getAuthorities());
list.addAll(developer.getRoles().stream().filter(r -> !StringUtils.isEmpty(r.getContext())).collect(Collectors.toList()));
details.setAuthorities(list);
}
return details;
}
}
| Role extraction fix | src/main/java/it/smartcommunitylab/aac/model/ClientDetailsRowMapper.java | Role extraction fix |
|
Java | apache-2.0 | e359f39300732db6c7c9a8e0bf474ccf3f3d236d | 0 | bruceadowns/amza,bruceadowns/amza,jivesoftware/amza,jivesoftware/amza,jivesoftware/amza,jivesoftware/amza,bruceadowns/amza,bruceadowns/amza | /*
* $Revision$
* $Date$
*
* Copyright (C) 1999-$year$ Jive Software. All rights reserved.
*
* This software is the proprietary information of Jive Software. Use is subject to license terms.
*/
package com.jivesoftware.os.amza.service.filer;
import com.jivesoftware.os.amza.api.filer.IFiler;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
/**
*
* @author jonathan.colt
*/
public class ByteBufferBackedFiler implements IFiler {
final ByteBuffer buffer;
public ByteBufferBackedFiler(ByteBuffer buffer) {
this.buffer = buffer;
}
@Override
public Object lock() {
return this;
}
public ByteBufferBackedFiler duplicate() {
return new ByteBufferBackedFiler(buffer.duplicate());
}
@Override
public void seek(long position) throws IOException {
buffer.position((int) position); // what a pain! limited to an int!
}
@Override
public long skip(long position) throws IOException {
int p = buffer.position();
p += position;
buffer.position(p);
return p;
}
@Override
public long length() throws IOException {
return buffer.capacity();
}
@Override
public void setLength(long len) throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public long getFilePointer() throws IOException {
return buffer.position();
}
@Override
public void eof() throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public void flush(boolean fsync) throws IOException {
if (fsync && buffer instanceof MappedByteBuffer) {
try {
((MappedByteBuffer) buffer).force();
} catch (UnsupportedOperationException e) {
// HMMM
}
}
}
@Override
public int read() throws IOException {
int remaining = buffer.remaining();
if (remaining == 0) {
return -1;
}
byte b = buffer.get();
return b & 0xFF;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int _offset, int _len) throws IOException {
int remaining = buffer.remaining();
if (remaining == 0) {
return -1;
}
int count = Math.min(_len, remaining);
buffer.get(b, _offset, count);
return count;
}
@Override
public void close() throws IOException {
}
@Override
public void write(byte[] b, int _offset, int _len) throws IOException {
buffer.put(b, _offset, _len);
}
}
| amza-service/src/main/java/com/jivesoftware/os/amza/service/filer/ByteBufferBackedFiler.java | /*
* $Revision$
* $Date$
*
* Copyright (C) 1999-$year$ Jive Software. All rights reserved.
*
* This software is the proprietary information of Jive Software. Use is subject to license terms.
*/
package com.jivesoftware.os.amza.service.filer;
import com.jivesoftware.os.amza.api.filer.IFiler;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
/**
*
* @author jonathan.colt
*/
public class ByteBufferBackedFiler implements IFiler {
final ByteBuffer buffer;
public ByteBufferBackedFiler(ByteBuffer buffer) {
this.buffer = buffer;
}
@Override
public Object lock() {
return this;
}
public ByteBufferBackedFiler duplicate() {
return new ByteBufferBackedFiler(buffer.duplicate());
}
@Override
public void seek(long position) throws IOException {
buffer.position((int) position); // what a pain! limited to an int!
}
@Override
public long skip(long position) throws IOException {
int p = buffer.position();
p += position;
buffer.position(p);
return p;
}
@Override
public long length() throws IOException {
return buffer.capacity();
}
@Override
public void setLength(long len) throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public long getFilePointer() throws IOException {
return buffer.position();
}
@Override
public void eof() throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public void flush(boolean fsync) throws IOException {
if (fsync && buffer instanceof MappedByteBuffer) {
((MappedByteBuffer) buffer).force();
}
}
@Override
public int read() throws IOException {
int remaining = buffer.remaining();
if (remaining == 0) {
return -1;
}
byte b = buffer.get();
return b & 0xFF;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int _offset, int _len) throws IOException {
int remaining = buffer.remaining();
if (remaining == 0) {
return -1;
}
int count = Math.min(_len, remaining);
buffer.get(b, _offset, count);
return count;
}
@Override
public void close() throws IOException {
}
@Override
public void write(byte[] b, int _offset, int _len) throws IOException {
buffer.put(b, _offset, _len);
}
}
| Added handling around ByteBufferBackedFiler.flush
| amza-service/src/main/java/com/jivesoftware/os/amza/service/filer/ByteBufferBackedFiler.java | Added handling around ByteBufferBackedFiler.flush |
|
Java | apache-2.0 | 3c7ff6ff65419209d50fb440c7c42c3d714c5f71 | 0 | ivanjelinek/mall-csfd-ingestion | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package elasticparser;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Ivan Jelinek
*/
class Ingest {
private String hostES = "localhost";
private String portES = "9200";
private String pathToData = "C:\\Users\\jelineiv\\Dropbox\\The Analytical Company\\data";
public Ingest() {
createIndex("csfd");
createIndex("mall");
prepareMapping("csfd", "negative");
prepareMapping("csfd", "neutral");
prepareMapping("csfd", "positive");
prepareMapping("mall", "negative");
prepareMapping("mall", "neutral");
prepareMapping("mall", "positive");
loadFile(pathToData + "/csfd/negative.txt", "csfd", "negative");
loadFile(pathToData + "/csfd/positive.txt", "csfd", "positive");
loadFile(pathToData + "/csfd/neutral.txt", "csfd", "neutral");
loadFile(pathToData + "/mallcz/negative.txt", "mall", "negative");
loadFile(pathToData + "/mallcz/positive.txt", "mall", "positive");
loadFile(pathToData + "/mallcz/neutral.txt", "mall", "neutral");
}
private void loadFile(String soubor, String index, String type) {
try {
BufferedReader br = new BufferedReader(new FileReader(soubor));
String line = br.readLine();
int i = 1;
while (line != null) {
line = line.replaceAll("\\\\", "");
line = "{ \"body\" : \"" + line.replaceAll("\"", "") + "\"}";
URL url = new URL("http://" + hostES + ":" + portES + "/" + index + "/" + type + "/" + i);
System.out.println(sendRQ(url, "PUT", line));
/* HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write(line);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
*/
line = br.readLine();
i++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void createIndex(String index) {
try {
String analyzer = "{\"settings\": {\"analysis\": {\"filter\": {\"czech_stop\": {\"type\": \"stop\",\"stopwords\": \"_czech_\"},\"czech_keywords\": {\"type\": \"keyword_marker\",\"keywords\": [\"x\"]}, \"czech_stemmer\": { \"type\": \"stemmer\", \"language\": \"czech\"}},\"analyzer\": {\"czech\": {\"tokenizer\": \"standard\",\"filter\": [ \"lowercase\",\"czech_stop\", \"czech_keywords\", \"czech_stemmer\"]}}}}}";
URL url = new URL("http://" + hostES + ":" + portES + "/" + index + "/");
System.out.println(sendRQ(url, "PUT", analyzer));
} catch (MalformedURLException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void prepareMapping(String index, String typ) {
String mappingBody = "{\"properties\": {\"czech\": {\"type\":\"string\",\"analyzer\": \"czech\"}}}";
try {
System.out.println(sendRQ(new URL("http://" + hostES + ":" + portES+"/" + index + "/_mapping/" + typ), "POST", mappingBody));
String f = "f";
} catch (MalformedURLException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String sendRQ(String hostES, String portES, String index, String typ, String method, String message) {
String urlString = "";
try {
if (typ == null) {
urlString = "http://" + hostES + ":" + portES + "/" + index + "/";
} else {
urlString = "http://" + hostES + ":" + portES + "/" + index + "/" + typ;
}
URL url = new URL(urlString);
return sendRQ(url, method, message);
} catch (MalformedURLException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
private String sendRQ(URL url, String method) {
return sendRQ(url, method, "");
}
private String sendRQ(URL url, String method, String message) {
try {
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod(method);
if (!method.equals("GET")) {
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write(message);
out.close();
}
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
return response.toString();
} catch (MalformedURLException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
| src/elasticparser/Ingest.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package elasticparser;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Ivan
*/
class Ingest {
private String hostES = "localhost";
private String portES = "9200";
private String pathToData = "C:\\Users\\jelineiv\\Dropbox\\The Analytical Company\\data";
public Ingest() {
createIndex("csfd");
createIndex("mall");
prepareMapping("csfd", "negative");
prepareMapping("csfd", "neutral");
prepareMapping("csfd", "positive");
prepareMapping("mall", "negative");
prepareMapping("mall", "neutral");
prepareMapping("mall", "positive");
loadFile(pathToData + "/csfd/negative.txt", "csfd", "negative");
loadFile(pathToData + "/csfd/positive.txt", "csfd", "positive");
loadFile(pathToData + "/csfd/neutral.txt", "csfd", "neutral");
loadFile(pathToData + "/mallcz/negative.txt", "mall", "negative");
loadFile(pathToData + "/mallcz/positive.txt", "mall", "positive");
loadFile(pathToData + "/mallcz/neutral.txt", "mall", "neutral");
//loadFile("negative.txt", "mall", "negative");
}
private void loadFile(String soubor, String index, String type) {
try {
BufferedReader br = new BufferedReader(new FileReader(soubor));
String line = br.readLine();
int i = 1;
while (line != null) {
URL url = new URL("http://" + hostES + ":" + portES + "/" + index + "/" + type + "/" + i);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
line = line.replaceAll("\\\\", "");
line = "{ \"body\" : \"" + line.replaceAll("\"", "") + "\"}";
// System.out.println(line);
out.write(line);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
line = br.readLine();
i++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void createIndex(String index) {
try {
URL url = new URL("http://" + hostES + ":" + portES + "/" + index + "/");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
String analyzer = "{\"settings\": {\"analysis\": {\"filter\": {\"czech_stop\": {\"type\": \"stop\",\"stopwords\": \"_czech_\"},\"czech_keywords\": {\"type\": \"keyword_marker\",\"keywords\": [\"x\"]}, \"czech_stemmer\": { \"type\": \"stemmer\", \"language\": \"czech\"}},\"analyzer\": {\"czech\": {\"tokenizer\": \"standard\",\"filter\": [ \"lowercase\",\"czech_stop\", \"czech_keywords\", \"czech_stemmer\"]}}}}}";
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write(analyzer);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
} catch (MalformedURLException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void prepareMapping(String index, String typ) {
String mappingBody = "{\"czech\": {\"properties\": {\"czech\": {\"type\":\"string\",\"analyzer\": \"czech\"}}}}";
String response = sendRQ(hostES, portES, index, typ, "POST", mappingBody);
}
private String sendRQ(String hostES, String portES, String index, String typ, String method, String message) {
String urlString = "";
try {
if (typ == null) {
urlString = "http://" + hostES + ":" + portES + "/" + index + "/";
} else {
urlString = "http://" + hostES + ":" + portES + "/" + index + "/" + typ;
}
URL url = new URL(urlString);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod(method);
if (!method.equals("GET")) {
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write(message);
out.close();
}
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
return response.toString();
} catch (MalformedURLException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Ingest.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
| analyzer completed | src/elasticparser/Ingest.java | analyzer completed |
|
Java | apache-2.0 | 74d677f2bae51cd693f4aa241a24ba75d1157af9 | 0 | ocpsoft/rewrite,chkal/rewrite,jsight/rewrite,chkal/rewrite,ocpsoft/rewrite,chkal/rewrite,ocpsoft/rewrite,chkal/rewrite,jsight/rewrite,jsight/rewrite,jsight/rewrite,ocpsoft/rewrite,chkal/rewrite,ocpsoft/rewrite,jsight/rewrite | /*
* Copyright 2011 <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*
* 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.ocpsoft.rewrite.servlet.config;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.ocpsoft.common.util.Assert;
import org.ocpsoft.rewrite.config.Condition;
import org.ocpsoft.rewrite.config.ConfigurationRuleParameterBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.param.ConfigurableParameter;
import org.ocpsoft.rewrite.param.Parameter;
import org.ocpsoft.rewrite.param.ParameterStore;
import org.ocpsoft.rewrite.param.Parameterized;
import org.ocpsoft.rewrite.param.ParameterizedPattern;
import org.ocpsoft.rewrite.param.ParameterizedPatternParser;
import org.ocpsoft.rewrite.param.RegexConstraint;
import org.ocpsoft.rewrite.param.RegexParameterizedPatternParser;
import org.ocpsoft.rewrite.servlet.config.bind.RequestBinding;
import org.ocpsoft.rewrite.servlet.http.event.HttpOutboundServletRewrite;
import org.ocpsoft.rewrite.servlet.http.event.HttpServletRewrite;
import org.ocpsoft.rewrite.servlet.spi.RequestParameterProvider;
import org.ocpsoft.rewrite.servlet.util.URLBuilder;
import org.ocpsoft.urlbuilder.Address;
/**
* A {@link Condition} that inspects the value of {@link HttpServletRewrite#getRequestPath()}
*
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
public class Path extends HttpCondition implements Parameterized
{
private final ParameterizedPatternParser expression;
private boolean withRequestBinding = false;
private String captureIn;
private Path(final String pattern)
{
Assert.notNull(pattern, "Path must not be null.");
this.expression = new RegexParameterizedPatternParser("[^/]+", pattern);
}
/**
* Create a {@link Condition} that compares the current {@link Address#getPath()} to the given pattern.
* <p>
* The given pattern may be parameterized:
* <p>
* <code>
* /example/{param} <br>
* /example/{param1}/sub/{param2} <br>
* ...
* </code>
* <p>
*
* @param pattern {@link ParameterizedPattern} matching the path.
*
* @see ConfigurationRuleParameterBuilder#where(String)
*/
public static Path matches(final String pattern)
{
return new Path(pattern);
}
/**
* Capture the entire path portion of the {@link Address} into the given {@link Parameter}.
*
* @param param the name of the {@link Parameter} to which the entire path portion of the {@link Address} will be
* bound.
*/
public static Path captureIn(final String param)
{
Path path = new Path("{" + param + "}");
path.captureIn = param;
return path;
}
/**
* Bind each path {@link Parameter} to the corresponding request parameter by name.
* <p>
*
* @see {@link ConfigurationRuleParameterBuilder#where(String)} {@link HttpServletRequest#getParameterMap()}
* {@link RequestParameterProvider}
*/
public Path withRequestBinding()
{
withRequestBinding = true;
return this;
}
@Override
public boolean evaluateHttp(final HttpServletRewrite event, final EvaluationContext context)
{
String url = null;
if (event instanceof HttpOutboundServletRewrite)
{
url = ((HttpOutboundServletRewrite) event).getOutboundAddress().getPath();
if(url == null) //e.g an external url like http://ocpsoft.org (without trailing slash) or an anchor link have a null path
return false;
}
else
url = URLBuilder.createFrom(event.getInboundAddress().getPath()).decode().toPath();
if (url.startsWith(event.getContextPath()))
url = url.substring(event.getContextPath().length());
return (expression.matches(event, context, url));
}
/**
* Get the underlying {@link ParameterizedPattern} for this {@link Path}
*/
public ParameterizedPatternParser getExpression()
{
return expression;
}
@Override
public String toString()
{
return expression.toString();
}
@Override
public Set<String> getRequiredParameterNames()
{
Set<String> result = new HashSet<String>();
if (captureIn != null)
result.add(captureIn);
else
result.addAll(expression.getRequiredParameterNames());
return result;
}
@Override
public void setParameterStore(ParameterStore store)
{
if (captureIn != null)
{
Parameter<?> parameter = store.get(captureIn);
if (parameter instanceof ConfigurableParameter<?>)
((ConfigurableParameter<?>) parameter).constrainedBy(new RegexConstraint(".*"));
}
if (withRequestBinding)
{
for (String param : getRequiredParameterNames()) {
Parameter<?> parameter = store.get(param);
if (parameter instanceof ConfigurableParameter<?>)
((ConfigurableParameter<?>) parameter).bindsTo(RequestBinding.parameter(param));
}
withRequestBinding = true;
}
expression.setParameterStore(store);
}
} | config-servlet/src/main/java/org/ocpsoft/rewrite/servlet/config/Path.java | /*
* Copyright 2011 <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*
* 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.ocpsoft.rewrite.servlet.config;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.ocpsoft.common.util.Assert;
import org.ocpsoft.rewrite.config.Condition;
import org.ocpsoft.rewrite.config.ConfigurationRuleParameterBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
import org.ocpsoft.rewrite.param.ConfigurableParameter;
import org.ocpsoft.rewrite.param.Parameter;
import org.ocpsoft.rewrite.param.ParameterStore;
import org.ocpsoft.rewrite.param.Parameterized;
import org.ocpsoft.rewrite.param.ParameterizedPattern;
import org.ocpsoft.rewrite.param.ParameterizedPatternParser;
import org.ocpsoft.rewrite.param.RegexConstraint;
import org.ocpsoft.rewrite.param.RegexParameterizedPatternParser;
import org.ocpsoft.rewrite.servlet.config.bind.RequestBinding;
import org.ocpsoft.rewrite.servlet.http.event.HttpOutboundServletRewrite;
import org.ocpsoft.rewrite.servlet.http.event.HttpServletRewrite;
import org.ocpsoft.rewrite.servlet.spi.RequestParameterProvider;
import org.ocpsoft.rewrite.servlet.util.URLBuilder;
import org.ocpsoft.urlbuilder.Address;
/**
* A {@link Condition} that inspects the value of {@link HttpServletRewrite#getRequestPath()}
*
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
public class Path extends HttpCondition implements Parameterized
{
private final ParameterizedPatternParser expression;
private boolean withRequestBinding = false;
private String captureIn;
private Path(final String pattern)
{
Assert.notNull(pattern, "Path must not be null.");
this.expression = new RegexParameterizedPatternParser("[^/]+", pattern);
}
/**
* Create a {@link Condition} that compares the current {@link Address#getPath()} to the given pattern.
* <p>
* The given pattern may be parameterized:
* <p>
* <code>
* /example/{param} <br>
* /example/{param1}/sub/{param2} <br>
* ...
* </code>
* <p>
*
* @param pattern {@link ParameterizedPattern} matching the path.
*
* @see ConfigurationRuleParameterBuilder#where(String)
*/
public static Path matches(final String pattern)
{
return new Path(pattern);
}
/**
* Capture the entire path portion of the {@link Address} into the given {@link Parameter}.
*
* @param param the name of the {@link Parameter} to which the entire path portion of the {@link Address} will be
* bound.
*/
public static Path captureIn(final String param)
{
Path path = new Path("{" + param + "}");
path.captureIn = param;
return path;
}
/**
* Bind each path {@link Parameter} to the corresponding request parameter by name.
* <p>
*
* @see {@link ConfigurationRuleParameterBuilder#where(String)} {@link HttpServletRequest#getParameterMap()}
* {@link RequestParameterProvider}
*/
public Path withRequestBinding()
{
withRequestBinding = true;
return this;
}
@Override
public boolean evaluateHttp(final HttpServletRewrite event, final EvaluationContext context)
{
String url = null;
if (event instanceof HttpOutboundServletRewrite)
url = ((HttpOutboundServletRewrite) event).getOutboundAddress().getPath();
else
url = URLBuilder.createFrom(event.getInboundAddress().getPath()).decode().toPath();
if (url.startsWith(event.getContextPath()))
url = url.substring(event.getContextPath().length());
return (expression.matches(event, context, url));
}
/**
* Get the underlying {@link ParameterizedPattern} for this {@link Path}
*/
public ParameterizedPatternParser getExpression()
{
return expression;
}
@Override
public String toString()
{
return expression.toString();
}
@Override
public Set<String> getRequiredParameterNames()
{
Set<String> result = new HashSet<String>();
if (captureIn != null)
result.add(captureIn);
else
result.addAll(expression.getRequiredParameterNames());
return result;
}
@Override
public void setParameterStore(ParameterStore store)
{
if (captureIn != null)
{
Parameter<?> parameter = store.get(captureIn);
if (parameter instanceof ConfigurableParameter<?>)
((ConfigurableParameter<?>) parameter).constrainedBy(new RegexConstraint(".*"));
}
if (withRequestBinding)
{
for (String param : getRequiredParameterNames()) {
Parameter<?> parameter = store.get(param);
if (parameter instanceof ConfigurableParameter<?>)
((ConfigurableParameter<?>) parameter).bindsTo(RequestBinding.parameter(param));
}
withRequestBinding = true;
}
expression.setParameterStore(store);
}
} | Patch for https://github.com/ocpsoft/rewrite/issues/117 | config-servlet/src/main/java/org/ocpsoft/rewrite/servlet/config/Path.java | Patch for https://github.com/ocpsoft/rewrite/issues/117 |
|
Java | apache-2.0 | a2dc18118abf698c62a84910091d04d9c49c3d91 | 0 | jeffbrown/grailsnolib,jeffbrown/grailsnolib | /*
* Copyright 2004-2005 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.codehaus.groovy.grails.web.metaclass;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since 0.2
*
* Created: Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private static final int BUFFER_SIZE = 8192;
private static final String TEXT_HTML = "text/html";
public RenderDynamicMethod() {
super(METHOD_PATTERN);
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if(response.getContentType() == null)
response.setContentType(TEXT_HTML);
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
String text = arguments[0].toString();
renderView = renderText(text, response);
}
else if(arguments[0] instanceof Closure) {
Closure closure = (Closure) arguments[arguments.length - 1];
renderView = renderMarkup(closure, response);
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
Closure callable = (Closure) arguments[arguments.length - 1];
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
renderView = renderRico(callable, response);
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)){
renderView = renderJSON(callable, response);
}
else {
renderView = renderMarkup(callable, response);
}
}
else if(arguments[arguments.length - 1] instanceof String) {
String text = (String) arguments[arguments.length - 1];
renderView = renderText(text, out);
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
renderView = renderText(text, out);
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
Object modelObject = argMap.get(ARGUMENT_MODEL);
renderView(viewName, modelObject, target, webRequest, application, controller);
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
Object bean = argMap.get(ARGUMENT_BEAN);
renderTemplateForBean(t, binding, bean, var, out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
renderTemplateForCollection(t, binding, colObject, var, out);
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
renderTemplateForModel(t, modelObject, target, out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
Object object = arguments[0];
renderView = renderObject(object, out);
}
try {
if(!renderView) {
out.flush();
}
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
private boolean renderObject(Object object, Writer out) {
boolean renderView;
try {
out.write(DefaultGroovyMethods.inspect(object));
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error obtaining response writer: " + e.getMessage(), e);
}
return renderView;
}
private void renderTemplateForModel(Template template, Object modelObject, Object target, Writer out) throws IOException {
if(modelObject instanceof Map) {
Writable w = template.make((Map)modelObject);
w.writeTo(out);
}
else {
Writable w = template.make(new BeanMap(target));
w.writeTo(out);
}
}
private void renderTemplateForCollection(Template template, Map binding, Object colObject, String var, Writer out) throws IOException {
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = template.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, colObject);
else
binding.put(var, colObject);
Writable w = template.make(binding);
w.writeTo(out);
}
}
private void renderTemplateForBean(Template template, Map binding, Object bean, String varName, Writer out) throws IOException {
if(StringUtils.isBlank(varName)) {
binding.put(DEFAULT_ARGUMENT, bean);
}
else
binding.put(varName, bean);
Writable w = template.make(binding);
w.writeTo(out);
}
private void renderView(String viewName, Object modelObject, Object target, GrailsWebRequest webRequest, GrailsApplication application, GroovyObject controller) {
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
if(controllerClass == null && webRequest.getControllerName() != null) {
controllerClass = (GrailsControllerClass)application.getArtefactByLogicalPropertyName(ControllerArtefactHandler.TYPE, webRequest.getControllerName());
}
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/")) {
viewName = '/' + viewName;
}
viewUri = viewName;
}
else {
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else if(controllerClass.getClazz().isInstance(target)) {
model = new BeanMap(target);
}
else {
model = new HashMap();
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
private boolean renderJSON(Closure callable, HttpServletResponse response) {
boolean renderView;
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+callable+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ callable });
return renderView;
}
private boolean renderRico(Closure callable, HttpServletResponse response) {
boolean renderView;
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+callable+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{callable});
return renderView;
}
private boolean renderMarkup(Closure closure, HttpServletResponse response) {
boolean renderView;
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(closure);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+closure+"]: " + e.getMessage(),e);
}
renderView = false;
return renderView;
}
private boolean renderText(String text, HttpServletResponse response) {
try {
PrintWriter writer = response.getWriter();
return renderText(text, writer);
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
private boolean renderText(String text, Writer writer) {
try {
writer.write(text);
return false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
private boolean isJSONResponse(HttpServletResponse response) {
return response.getContentType() != null && response.getContentType().indexOf("text/json")>-1;
}
}
| src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java | /*
* Copyright 2004-2005 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.codehaus.groovy.grails.web.metaclass;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.ControllerArtefactHandler;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.metaclass.AbstractDynamicMethodInvocation;
import org.codehaus.groovy.grails.web.pages.GSPResponseWriter;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since 0.2
*
* Created: Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicMethodInvocation {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private static final String ARGUMENT_TO = "to";
private static final int BUFFER_SIZE = 8192;
public RenderDynamicMethod() {
super(METHOD_PATTERN);
}
public Object invoke(Object target, String methodName, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
GrailsApplication application = webRequest.getAttributes().getGrailsApplication();
HttpServletRequest request = webRequest.getCurrentRequest();
HttpServletResponse response = webRequest.getCurrentResponse();
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if(response.getContentType() == null)
response.setContentType("text/html");
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
String contentType = argMap.get(ARGUMENT_CONTENT_TYPE).toString();
String encoding = argMap.get(ARGUMENT_ENCODING).toString();
response.setContentType(contentType + ";charset=" + encoding);
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
response.setContentType(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
else {
out = GSPResponseWriter.getInstance(response,BUFFER_SIZE);
}
webRequest.setOut(out);
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Closure callable = (Closure)arguments[arguments.length - 1];
Writable markup = (Writable)b.bind(callable);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefact(ControllerArtefactHandler.TYPE,
target.getClass().getName());
if(controllerClass == null && webRequest.getControllerName() != null) {
controllerClass = (GrailsControllerClass)application.getArtefactByLogicalPropertyName(ControllerArtefactHandler.TYPE, webRequest.getControllerName());
}
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/")) {
viewName = '/' + viewName;
}
viewUri = viewName;
}
else {
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else if(controllerClass.getClazz().isInstance(target)) {
model = new BeanMap(target);
}
else {
model = new HashMap();
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
}
}
else {
try {
out.write(DefaultGroovyMethods.inspect(arguments[0]));
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error obtaining response writer: " + e.getMessage(), e);
}
}
try {
if(!renderView) out.flush();
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
webRequest.setRenderView(renderView);
return null;
}
private boolean isJSONResponse(HttpServletResponse response) {
return response.getContentType() != null && response.getContentType().indexOf("text/json")>-1;
}
}
| refactored some of the code
git-svn-id: 29aad96320b2a07b98332cd568fc1316025c072f@6650 1cfb16fd-6d17-0410-8ff1-b7e8e1e2867d
| src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java | refactored some of the code |
|
Java | apache-2.0 | db1d79d17daccdd0e2228711a0798f4932feee9c | 0 | ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf | /*
* $Log: ShowConfiguration.java,v $
* Revision 1.3 2004-03-23 17:02:52 L190409
* corrected some typos and solved some warnings
*
*/
package nl.nn.adapterframework.webcontrol.action;
import nl.nn.adapterframework.util.StringResolver;
import nl.nn.adapterframework.util.AppConstants;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Shows the configuration (with resolved variables).
* <p>If the property <code>showConfiguration.resolve.variables</code>, in
* {@link nl.nn.adapterframework.util.AppConstants AppConstants} is <code>true</code>
* the variables (${variable}) in the configuration.xml are resolved. </p>
* <p>For security-reasons you might set this value to <code>false</code>, so that passwords
* configured in the <code>environment entries</code> of the application server are not revealed.</p>
* <p>$Id: ShowConfiguration.java,v 1.3 2004-03-23 17:02:52 L190409 Exp $</p>
* @author Johan Verrips
* @see nl.nn.adapterframework.configuration.Configuration
*/
public final class ShowConfiguration extends ActionBase {
public static final String version="$Id: ShowConfiguration.java,v 1.3 2004-03-23 17:02:52 L190409 Exp $";
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Initialize action
initAction(request);
DynaActionForm configurationPropertiesForm = getPersistentForm(mapping, form, request);
configurationPropertiesForm.set("logLevel", Logger.getRootLogger().getLevel().toString());
configurationPropertiesForm.set("logIntermediaryResults", new Boolean(false));
if (AppConstants.getInstance().getResolvedProperty("log.logIntermediaryResults")!=null) {
if (AppConstants.getInstance().getResolvedProperty("log.logIntermediaryResults").equalsIgnoreCase("true")) {
configurationPropertiesForm.set("logIntermediaryResults", new Boolean(true));
}
}
URL configURL = config.getConfigurationURL();
String result = "";
try {
// Read all the text returned by the server
BufferedReader in =
new BufferedReader(new InputStreamReader(configURL.openStream()));
String str;
String lineSeparator=SystemUtils.LINE_SEPARATOR;
if (null==lineSeparator) lineSeparator="\n";
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
result += str+lineSeparator;
}
in.close();
if (AppConstants.getInstance().getBoolean("showConfiguration.resolve.variables", true))
result=StringResolver.substVars(result, AppConstants.getInstance());
} catch (MalformedURLException e) {
result =
"<b>error occured retrieving configurationfile:" + e.getMessage() + "</b>";
} catch (IOException e) {
result =
"<b>error occured retrieving configurationfile:" + e.getMessage() + "</b>";
}
request.setAttribute("configXML", result);
// Forward control to the specified success URI
log.debug("forward to success");
return (mapping.findForward("success"));
}
}
| JavaSource/nl/nn/adapterframework/webcontrol/action/ShowConfiguration.java | package nl.nn.adapterframework.webcontrol.action;
import nl.nn.adapterframework.util.StringResolver;
import nl.nn.adapterframework.util.AppConstants;
import org.apache.commons.lang.SystemUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Shows the configuration (with resolved variables).
* <p>If the property <code>showConfiguration.resolve.variables</code>, in
* {@link nl.nn.adapterframework.util.AppConstants AppConstants} is <code>true</code>
* the variables (${variable}) in the configuration.xml are resolved. </p>
* <p>For security-reasons you might set this value to <code>false</code>, so that passwords
* configured in the <code>environment entries</code> of the application server are not revealed.</p>
* <p>$Id: ShowConfiguration.java,v 1.2 2004-02-04 10:02:09 a1909356#db2admin Exp $</p>
* @author Johan Verrips
* @see nl.nn.adapterframework.configuration.Configuration
*/
public final class ShowConfiguration extends ActionBase {
public static final String version="$Id: ShowConfiguration.java,v 1.2 2004-02-04 10:02:09 a1909356#db2admin Exp $";
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Initialize action
initAction(request);
DynaActionForm configurationPropertiesForm = getPersistentForm(mapping, form, request);
configurationPropertiesForm.set("logLevel", log.getRootLogger().getLevel().toString());
configurationPropertiesForm.set("logIntermediaryResults", new Boolean(false));
if (AppConstants.getInstance().getResolvedProperty("log.logIntermediaryResults")!=null) {
if (AppConstants.getInstance().getResolvedProperty("log.logIntermediaryResults").equalsIgnoreCase("true")) {
configurationPropertiesForm.set("logIntermediaryResults", new Boolean(true));
}
}
URL configURL = config.getConfigurationURL();
String result = "";
try {
// Read all the text returned by the server
BufferedReader in =
new BufferedReader(new InputStreamReader(configURL.openStream()));
String str;
String lineSeperator=SystemUtils.LINE_SEPARATOR;
if (null==lineSeperator) lineSeperator="\n";
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
result += str+lineSeperator;
}
in.close();
if (AppConstants.getInstance().getBoolean("showConfiguration.resolve.variables", true))
result=StringResolver.substVars(result, AppConstants.getInstance());
} catch (MalformedURLException e) {
result =
"<b>error occured retrieving configurationfile:" + e.getMessage() + "</b>";
} catch (IOException e) {
result =
"<b>error occured retrieving configurationfile:" + e.getMessage() + "</b>";
}
request.setAttribute("configXML", result);
// Forward control to the specified success URI
log.debug("forward to success");
return (mapping.findForward("success"));
}
}
| corrected some typos and solved some warnings
| JavaSource/nl/nn/adapterframework/webcontrol/action/ShowConfiguration.java | corrected some typos and solved some warnings |
|
Java | apache-2.0 | 9402d0348b73c41a0172574fe5210c3a3c78ac03 | 0 | ayltai/Newspaper | package com.github.ayltai.newspaper;
import android.app.Activity;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.WindowManager;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.github.ayltai.newspaper.util.MoreViewMatchers;
import com.github.ayltai.newspaper.util.SuppressFBWarnings;
@RunWith(AndroidJUnit4.class)
@LargeTest
public final class MainActivityTest {
@SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
@Rule
public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(MainActivity.class);
@SuppressWarnings("deprecation")
@Before
public void setUp() {
final Activity activity = this.activityRule.getActivity();
// Makes sure the device is unlocked
activity.runOnUiThread(() -> activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
}
@Test
public void openFirstItemThenSwipeThroughAllTabs() {
// Switches to "HK" tab
Espresso.onView(ViewMatchers.withId(R.id.navigate_next))
.perform(ViewActions.click());
// Opens first item
Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.recyclerView), ViewMatchers.isDisplayed()))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, ViewActions.click()));
// Asserts that the title is expected
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(ViewMatchers.withText("馬時亨冀3月就票價機制達協議 不覺得有驚天動地改變")));
Espresso.pressBack();
// Switches to "Top" tab
Espresso.onView(ViewMatchers.withId(R.id.navigate_previous))
.perform(ViewActions.click());
// Swipes through all tabs
final String[] shortCategories = InstrumentationRegistry.getTargetContext().getResources().getStringArray(R.array.pref_category_short_entries);
final String[] longCategories = InstrumentationRegistry.getTargetContext().getResources().getStringArray(R.array.pref_category_entries);
for (int i = 0; i < shortCategories.length; i++) {
final String longCategory = longCategories[i];
Espresso.onView(ViewMatchers.withId(R.id.collapsingToolbarLayout))
.check(ViewAssertions.matches(MoreViewMatchers.withTitle(longCategory)));
Espresso.onView(Matchers.allOf(ViewMatchers.withText(shortCategories[i]), ViewMatchers.isDescendantOfA(ViewMatchers.withId(R.id.tabLayout))))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(R.id.navigate_next))
.perform(ViewActions.click());
}
}
}
| app/src/androidTest/java/com/github/ayltai/newspaper/MainActivityTest.java | package com.github.ayltai.newspaper;
import android.app.Activity;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.WindowManager;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.github.ayltai.newspaper.util.MoreViewMatchers;
import com.github.ayltai.newspaper.util.SuppressFBWarnings;
@RunWith(AndroidJUnit4.class)
@LargeTest
public final class MainActivityTest {
@SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
@Rule
public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(MainActivity.class);
@SuppressWarnings("deprecation")
@Before
public void setUp() {
final Activity activity = this.activityRule.getActivity();
// Makes sure the device is unlocked
activity.runOnUiThread(() -> activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
}
@Test
public void swipeThroughAllTabs() {
final String[] shortCategories = InstrumentationRegistry.getTargetContext().getResources().getStringArray(R.array.pref_category_short_entries);
final String[] longCategories = InstrumentationRegistry.getTargetContext().getResources().getStringArray(R.array.pref_category_entries);
for (int i = 0; i < shortCategories.length; i++) {
final String longCategory = longCategories[i];
Espresso.onView(ViewMatchers.withId(R.id.collapsingToolbarLayout))
.check(ViewAssertions.matches(MoreViewMatchers.withTitle(longCategory)));
Espresso.onView(Matchers.allOf(ViewMatchers.withText(shortCategories[i]), ViewMatchers.isDescendantOfA(ViewMatchers.withId(R.id.tabLayout))))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withId(R.id.navigate_next))
.perform(ViewActions.click());
}
}
@Test
public void openFirstItem() {
// Switches to "HK" tab
Espresso.onView(ViewMatchers.withId(R.id.navigate_next))
.perform(ViewActions.click());
// Opens first item
Espresso.onView(Matchers.allOf(ViewMatchers.withId(R.id.recyclerView), ViewMatchers.isDisplayed()))
.perform(RecyclerViewActions.actionOnItemAtPosition(0, ViewActions.click()));
// Asserts that the title is expected
Espresso.onView(ViewMatchers.withId(R.id.title))
.check(ViewAssertions.matches(ViewMatchers.withText("馬時亨冀3月就票價機制達協議 不覺得有驚天動地改變")));
}
}
| Update instrumental tests to avoid using a closed Realm instance
| app/src/androidTest/java/com/github/ayltai/newspaper/MainActivityTest.java | Update instrumental tests to avoid using a closed Realm instance |
|
Java | apache-2.0 | 6dce9f97bb54a361585a05f4ce5d38780d3decbc | 0 | industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector | /*-
* ========================LICENSE_START=================================
* IDS Core Platform Webconsole
* %%
* Copyright (C) 2017 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api;
import de.fhg.aisec.ids.api.Result;
import de.fhg.aisec.ids.api.RouteResult;
import de.fhg.aisec.ids.api.policy.PAP;
import de.fhg.aisec.ids.api.router.*;
import de.fhg.aisec.ids.webconsole.WebConsoleComponent;
import de.fhg.aisec.ids.webconsole.api.data.ValidationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.*;
/**
* REST API interface for "data pipes" in the connector.
*
* This implementation uses Camel Routes as data pipes, i.e. the API methods allow inspection of camel routes in different camel contexts.
*
* The API will be available at http://localhost:8181/cxf/api/v1/routes/<method>.
*
* @author Julian Schuette ([email protected])
*
*/
@Path("/routes")
public class RouteApi {
private static final Logger LOG = LoggerFactory.getLogger(RouteApi.class);
/**
* Returns map from camel context to list of camel routes.
*
* Example:
*
* {"camel-1":["Route(demo-route)[[From[timer://simpleTimer?period\u003d10000]] -\u003e [SetBody[simple{This is a demo body!}], Log[The message contains ${body}]]]"]}
*
* @return The resulting route objects
*/
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public List<RouteObject> list() {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return Collections.emptyList();
}
return rm.get().getRoutes();
}
@GET
@Path("/get/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") String id) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("RouteManager not present").build();
}
RouteObject oRoute = rm.get().getRoute(id);
if (oRoute == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Route not found").build();
}
return Response.ok(oRoute).build();
}
@GET
@Path("/getAsString/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response getAsString(@PathParam("id") String id) {
Optional<RouteManager> rmOpt = WebConsoleComponent.getRouteManager();
if (!rmOpt.isPresent()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("RouteManager not present").build();
}
String routeAsString = rmOpt.get().getRouteAsString(id);
if (routeAsString == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Route not found").build();
}
return Response.ok(routeAsString).build();
}
/**
* Stop a route based on an id.
*/
@GET
@Path("/startroute/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Result startRoute(@PathParam("id") String id) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
rm.get().startRoute(id);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return new Result(false, e.getMessage());
}
return new Result();
}
return new Result();
}
@POST
@Path("/save/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public RouteResult saveRoute(@PathParam("id") String id, String routeDefinition) {
RouteResult result = new RouteResult();
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
result.setMessage("No Route Manager present!");
result.setSuccessful(false);
return result;
}
try {
result.setRoute(rm.get().saveRoute(id, routeDefinition));
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
result.setSuccessful(false);
result.setMessage(e.getMessage());
}
return result;
}
@PUT
@Path("/add")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Result addRoute(String routeDefinition) {
Result result = new Result();
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
result.setMessage("No Route Manager present!");
result.setSuccessful(false);
return result;
}
try {
rm.get().addRoute(routeDefinition);
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
result.setSuccessful(false);
result.setMessage(e.getMessage());
}
return result;
}
/**
* Stop a route based on its id.
*/
@GET
@Path("/stoproute/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Result stopRoute(@PathParam("id") String id) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
rm.get().stopRoute(id);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return new Result(false, e.getMessage());
}
return new Result();
}
return new Result(false, "No route manager");
}
/**
* Get runtime metrics of a route
*/
@GET
@Path("/metrics/{id}")
public RouteMetrics getMetrics(@PathParam("id") String routeId) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
return rm.get().getRouteMetrics().get(routeId);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return null;
}
}
return null;
}
/**
* Get aggregated runtime metrics of all routes
*/
@GET
@Path("/metrics")
public RouteMetrics getMetrics() {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
Map<String, RouteMetrics> currentMetrics = rm.get().getRouteMetrics();
return aggregateMetrics(currentMetrics.values());
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
}
}
return null;
}
/**
* Aggregates metrics of several rules
*
* @param currentMetrics List of RouteMetrics to process
* @return The aggregated RouteMetrics object
*/
private RouteMetrics aggregateMetrics(Collection<RouteMetrics> currentMetrics) {
RouteMetrics metrics = new RouteMetrics();
metrics.setCompleted(currentMetrics.stream().mapToLong(RouteMetrics::getCompleted).sum());
metrics.setFailed(currentMetrics.stream().mapToLong(RouteMetrics::getFailed).sum());
metrics.setFailuresHandled(currentMetrics.stream().mapToLong(RouteMetrics::getFailuresHandled).sum());
metrics.setInflight(currentMetrics.stream().mapToLong(RouteMetrics::getInflight).sum());
metrics.setMaxProcessingTime(currentMetrics.stream().mapToLong(RouteMetrics::getMaxProcessingTime)
.max().orElse(0));
// This is technically nonsense, as average values of average values are not really
// the average values of the single elements, but it's the best aggregation we can get.
metrics.setMeanProcessingTime((long) currentMetrics.stream().mapToLong(RouteMetrics::getMeanProcessingTime)
.filter(i -> i < 0).average().orElse(.0));
metrics.setMinProcessingTime(currentMetrics.stream().mapToLong(RouteMetrics::getMinProcessingTime)
.min().orElse(0));
metrics.setCompleted(currentMetrics.stream().mapToLong(RouteMetrics::getCompleted).sum());
return metrics;
}
/**
* Retrieve list of supported components (aka protocols which can be addressed by Camel)
*
* @return List of supported protocols
*/
@GET
@Path("/components")
@Produces("application/json")
public List<RouteComponent> getComponents() {
RouteManager rm = WebConsoleComponent.getRouteManagerOrThrowSUE();
return rm.listComponents();
}
/**
* Retrieve list of currently installed endpoints (aka URIs to/from which routes exist)
*/
@GET
@Path("/list_endpoints")
public Map<String, String> listEndpoints() {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return new HashMap<>();
}
return rm.get().listEndpoints();
}
@GET
@Path("/validate/{routeId}")
@Produces(MediaType.APPLICATION_JSON)
public Response validate(@PathParam("routeId") String routeId) {
Optional<PAP> pap = WebConsoleComponent.getPolicyAdministrationPoint();
if (!pap.isPresent()) {
return Response.serverError().entity("PolicyAdministrationPoint not available").build();
}
RouteVerificationProof rvp = pap.get().verifyRoute(routeId);
ValidationInfo vi = new ValidationInfo();
vi.valid = rvp.isValid();
if (!rvp.isValid()) {
vi.counterExamples = rvp.getCounterExamples();
}
return Response.ok(vi).build();
}
@GET
@Path("/prolog/{routeId}")
@Produces(MediaType.TEXT_PLAIN)
public Response getRouteProlog(@PathParam("routeId") String routeId) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return Response.serverError().entity("RouteManager not available").build();
}
return Response.ok(rm.get().getRouteAsProlog(routeId)).build();
}
} | ids-webconsole/src/main/java/de/fhg/aisec/ids/webconsole/api/RouteApi.java | /*-
* ========================LICENSE_START=================================
* IDS Core Platform Webconsole
* %%
* Copyright (C) 2017 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api;
import java.util.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import de.fhg.aisec.ids.api.RouteResult;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.fhg.aisec.ids.api.Result;
import de.fhg.aisec.ids.api.policy.PAP;
import de.fhg.aisec.ids.api.router.RouteComponent;
import de.fhg.aisec.ids.api.router.RouteManager;
import de.fhg.aisec.ids.api.router.RouteMetrics;
import de.fhg.aisec.ids.api.router.RouteObject;
import de.fhg.aisec.ids.api.router.RouteVerificationProof;
import de.fhg.aisec.ids.webconsole.WebConsoleComponent;
import de.fhg.aisec.ids.webconsole.api.data.ValidationInfo;
/**
* REST API interface for "data pipes" in the connector.
*
* This implementation uses Camel Routes as data pipes, i.e. the API methods allow inspection of camel routes in different camel contexts.
*
* The API will be available at http://localhost:8181/cxf/api/v1/routes/<method>.
*
* @author Julian Schuette ([email protected])
*
*/
@Path("/routes")
public class RouteApi {
private static final Logger LOG = LoggerFactory.getLogger(RouteApi.class);
/**
* Returns map from camel context to list of camel routes.
*
* Example:
*
* {"camel-1":["Route(demo-route)[[From[timer://simpleTimer?period\u003d10000]] -\u003e [SetBody[simple{This is a demo body!}], Log[The message contains ${body}]]]"]}
*
* @return The resulting route objects
*/
@GET
@Path("list")
@Produces(MediaType.APPLICATION_JSON)
public List<RouteObject> list() {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return Collections.emptyList();
}
return rm.get().getRoutes();
}
@GET
@Path("/get/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") String id) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("RouteManager not present").build();
}
RouteObject oRoute = rm.get().getRoute(id);
if (oRoute == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Route not found").build();
}
return Response.ok(oRoute).build();
}
@GET
@Path("/getAsString/{id}")
@Produces(MediaType.TEXT_PLAIN)
public Response getAsString(@PathParam("id") String id) {
Optional<RouteManager> rmOpt = WebConsoleComponent.getRouteManager();
if (!rmOpt.isPresent()) {
return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("RouteManager not present").build();
}
String routeAsString = rmOpt.get().getRouteAsString(id);
if (routeAsString == null) {
return Response.status(Response.Status.NOT_FOUND).entity("Route not found").build();
}
return Response.ok(routeAsString).build();
}
/**
* Stop a route based on an id.
*/
@GET
@Path("/startroute/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Result startRoute(@PathParam("id") String id) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
rm.get().startRoute(id);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return new Result(false, e.getMessage());
}
return new Result();
}
return new Result();
}
@POST
@Path("/save/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public RouteResult saveRoute(@PathParam("id") String id, String routeDefinition) {
RouteResult result = new RouteResult();
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
result.setMessage("No Route Manager present!");
result.setSuccessful(false);
return result;
}
try {
result.setRoute(rm.get().saveRoute(id, routeDefinition));
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
result.setSuccessful(false);
result.setMessage(e.getMessage());
}
return result;
}
@PUT
@Path("/add")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Result addRoute(String routeDefinition) {
Result result = new Result();
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
result.setMessage("No Route Manager present!");
result.setSuccessful(false);
return result;
}
try {
rm.get().addRoute(routeDefinition);
} catch (Exception e) {
LOG.warn(e.getMessage(), e);
result.setSuccessful(false);
result.setMessage(e.getMessage());
}
return result;
}
/**
* Stop a route based on its id.
*/
@GET
@Path("/stoproute/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Result stopRoute(@PathParam("id") String id) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
rm.get().stopRoute(id);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return new Result(false, e.getMessage());
}
return new Result();
}
return new Result(false, "No route manager");
}
/**
* Get runtime metrics of a route
*/
@GET
@Path("/metrics/{id}")
public RouteMetrics getMetrics(@PathParam("id") String routeId) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
return rm.get().getRouteMetrics().get(routeId);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return null;
}
}
return null;
}
/**
* Get aggregated runtime metrics of all routes
*/
@GET
@Path("/metrics")
public RouteMetrics getMetrics() {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (rm.isPresent()) {
try {
Map<String, RouteMetrics> currentMetrics = rm.get().getRouteMetrics();
return aggregateMetrics(currentMetrics.values());
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
}
}
return null;
}
/**
* Aggregates metrics of several rules
*
* @param currentMetrics
* @return
*/
private RouteMetrics aggregateMetrics(Collection<RouteMetrics> currentMetrics) {
RouteMetrics metrics = new RouteMetrics();
currentMetrics.parallelStream().forEach(m -> {
metrics.setCompleted(metrics.getCompleted() + m.getCompleted());
metrics.setFailed(metrics.getFailed() + m.getFailed());
metrics.setFailuresHandled(metrics.getFailuresHandled() + m.getFailuresHandled());
metrics.setInflight(metrics.getInflight() + m.getInflight());
metrics.setMaxProcessingTime(Math.max(metrics.getMaxProcessingTime(), m.getMaxProcessingTime()));
metrics.setMeanProcessingTime(metrics.getMeanProcessingTime() + m.getMeanProcessingTime());
metrics.setMinProcessingTime(Math.min(metrics.getMinProcessingTime(), m.getMinProcessingTime()));
metrics.setCompleted(metrics.getCompleted() + m.getCompleted());
});
int metricsCount = currentMetrics.size();
metrics.setMeanProcessingTime(metrics.getMeanProcessingTime()/(metricsCount!=0?metricsCount:1));
return metrics;
}
/**
* Retrieve list of supported components (aka protocols which can be addressed by Camel)
*
* @return List of supported protocols
*/
@GET
@Path("/components")
@Produces("application/json")
public List<RouteComponent> getComponents() {
RouteManager rm = WebConsoleComponent.getRouteManagerOrThrowSUE();
return rm.listComponents();
}
/**
* Retrieve list of currently installed endpoints (aka URIs to/from which routes exist)
*/
@GET
@Path("/list_endpoints")
public Map<String, String> listEndpoints() {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return new HashMap<>();
}
return rm.get().listEndpoints();
}
@GET
@Path("/validate/{routeId}")
@Produces(MediaType.APPLICATION_JSON)
public Response validate(@PathParam("routeId") String routeId) {
Optional<PAP> pap = WebConsoleComponent.getPolicyAdministrationPoint();
if (!pap.isPresent()) {
return Response.serverError().entity("PolicyAdministrationPoint not available").build();
}
RouteVerificationProof rvp = pap.get().verifyRoute(routeId);
ValidationInfo vi = new ValidationInfo();
vi.valid = rvp.isValid();
if (!rvp.isValid()) {
vi.counterExamples = rvp.getCounterExamples();
}
return Response.ok(vi).build();
}
@GET
@Path("/prolog/{routeId}")
@Produces(MediaType.TEXT_PLAIN)
public Response getRouteProlog(@PathParam("routeId") String routeId) {
Optional<RouteManager> rm = WebConsoleComponent.getRouteManager();
if (!rm.isPresent()) {
return Response.serverError().entity("RouteManager not available").build();
}
return Response.ok(rm.get().getRouteAsProlog(routeId)).build();
}
} | improved/fixed aggregation function
| ids-webconsole/src/main/java/de/fhg/aisec/ids/webconsole/api/RouteApi.java | improved/fixed aggregation function |
|
Java | apache-2.0 | 543770e6d38e75bf68c48a467f9a3effc52769ae | 0 | Praveen2112/presto,11xor6/presto,smartnews/presto,dain/presto,electrum/presto,losipiuk/presto,smartnews/presto,smartnews/presto,11xor6/presto,electrum/presto,Praveen2112/presto,erichwang/presto,smartnews/presto,dain/presto,11xor6/presto,electrum/presto,ebyhr/presto,11xor6/presto,erichwang/presto,dain/presto,losipiuk/presto,Praveen2112/presto,dain/presto,ebyhr/presto,electrum/presto,losipiuk/presto,losipiuk/presto,Praveen2112/presto,erichwang/presto,electrum/presto,smartnews/presto,ebyhr/presto,ebyhr/presto,erichwang/presto,Praveen2112/presto,losipiuk/presto,11xor6/presto,erichwang/presto,ebyhr/presto,dain/presto | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.testng.services;
import com.google.common.annotations.VisibleForTesting;
import org.testng.IClassListener;
import org.testng.ITestClass;
import org.testng.annotations.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static com.google.common.base.Throwables.getStackTraceAsString;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.testng.services.Listeners.reportListenerFailure;
import static java.util.stream.Collectors.joining;
/**
* Detects test methods which are annotaded with @Flaky annotation but are
* missing explicit @Test annotation
*/
public class FlakyAnnotationVerifier
implements IClassListener
{
@Override
public void onBeforeClass(ITestClass testClass)
{
try {
reportMethodsWithFlakyAndNoTestAnnotation(testClass);
}
catch (RuntimeException | Error e) {
reportListenerFailure(
FlakyAnnotationVerifier.class,
"Failed to process %s: \n%s",
testClass,
getStackTraceAsString(e));
}
}
private void reportMethodsWithFlakyAndNoTestAnnotation(ITestClass testClass)
{
Class<?> realClass = testClass.getRealClass();
if (realClass.getSuperclass() != null &&
"io.prestosql.tempto.internal.convention.ConventionBasedTestProxyGenerator$ConventionBasedTestProxy".equals(realClass.getSuperclass().getName())) {
// Ignore tempto generated convention tests.
return;
}
if (realClass.getName().startsWith("io.prestosql.testng.services.TestFlakyAnnotationVerifier")) {
// ignore test of FlakyAnnotationVerifier and internal classes
return;
}
List<Method> unannotatedTestMethods = findMethodsWithFlakyAndNoTestAnnotation(realClass);
if (!unannotatedTestMethods.isEmpty()) {
reportListenerFailure(
FlakyAnnotationVerifier.class,
"Test class %s has methods which are marked as @Flaky but are not explicitly annotated with @Test:%s",
realClass.getName(),
unannotatedTestMethods.stream()
.map(Method::toString)
.collect(joining("\n\t\t", "\n\t\t", "")));
}
}
@VisibleForTesting
static List<Method> findMethodsWithFlakyAndNoTestAnnotation(Class<?> realClass)
{
return Arrays.stream(realClass.getMethods())
.filter(method -> hasOrInheritsAnnotation(method, Flaky.class))
.filter(method -> !method.isAnnotationPresent(Test.class))
.collect(toImmutableList());
}
@Override
public void onAfterClass(ITestClass testClass) {}
private static boolean hasOrInheritsAnnotation(Method method, Class<? extends Annotation> annotationClass)
{
while (method != null) {
if (method.isAnnotationPresent(annotationClass)) {
return true;
}
method = getSuperMethod(method).orElse(null);
}
return false;
}
private static Optional<Method> getSuperMethod(Method method)
{
// Simplistic override detection; this is not correct in presence of generics and bridge methods.
try {
Class<?> superclass = method.getDeclaringClass().getSuperclass();
if (superclass == null) {
return Optional.empty();
}
return Optional.of(superclass.getMethod(method.getName(), method.getParameterTypes()));
}
catch (NoSuchMethodException e) {
return Optional.empty();
}
}
}
| presto-testng-services/src/main/java/io/prestosql/testng/services/FlakyAnnotationVerifier.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.testng.services;
import com.google.common.annotations.VisibleForTesting;
import org.testng.IClassListener;
import org.testng.ITestClass;
import org.testng.annotations.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static com.google.common.base.Throwables.getStackTraceAsString;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.testng.services.Listeners.reportListenerFailure;
import static java.util.stream.Collectors.joining;
/**
* Detects test methods which are annotaded with @Flaky annotation but are
* missing explicit @Test annotation
*/
public class FlakyAnnotationVerifier
implements IClassListener
{
@Override
public void onBeforeClass(ITestClass testClass)
{
try {
reportMethodsWithFlakyAndNoTestAnnotation(testClass);
}
catch (RuntimeException | Error e) {
reportListenerFailure(
FlakyAnnotationVerifier.class,
"Failed to process %s: \n%s",
testClass,
getStackTraceAsString(e));
}
}
private void reportMethodsWithFlakyAndNoTestAnnotation(ITestClass testClass)
{
Class<?> realClass = testClass.getRealClass();
if (realClass.getSuperclass() != null &&
"io.prestosql.tempto.internal.convention.ConventionBasedTestProxyGenerator$ConventionBasedTestProxy".equals(realClass.getSuperclass().getName())) {
// Ignore tempto generated convention tests.
return;
}
if (realClass.getName().startsWith("io.prestosql.testng.services.TestFlakyAnnotationVerifier")) {
// ignore test of FlakyAnnotationVerifier and internal classes
return;
}
List<Method> unannotatedTestMethods = findMethodsWithFlakyAndNoTestAnnotation(realClass);
if (!unannotatedTestMethods.isEmpty()) {
reportListenerFailure(
FlakyAnnotationVerifier.class,
"Test class %s has methods which are marked as @Flaky but are not explicitly annotated with @Test:%s",
realClass.getName(),
unannotatedTestMethods.stream()
.map(Method::toString)
.collect(joining("\n\t\t", "\n\t\t", "")));
}
}
@VisibleForTesting
static List<Method> findMethodsWithFlakyAndNoTestAnnotation(Class<?> realClass)
{
return Arrays.stream(realClass.getMethods())
.filter(method -> hasOrInheritsAnnotation(method, Flaky.class))
.filter(method -> !method.isAnnotationPresent(Test.class))
.collect(toImmutableList());
}
@Override
public void onAfterClass(ITestClass testClass) {}
private static boolean hasOrInheritsAnnotation(Method method, Class<? extends Annotation> annotationClass)
{
Optional<Method> currentMethod = Optional.of(method);
while (currentMethod.isPresent()) {
if (currentMethod.get().isAnnotationPresent(annotationClass)) {
return true;
}
currentMethod = getSuperMethod(currentMethod.get());
}
return false;
}
private static Optional<Method> getSuperMethod(Method method)
{
// Simplistic override detection; this is not correct in presence of generics and bridge methods.
try {
Class<?> superclass = method.getDeclaringClass().getSuperclass();
if (superclass == null) {
return Optional.empty();
}
return Optional.of(superclass.getMethod(method.getName(), method.getParameterTypes()));
}
catch (NoSuchMethodException e) {
return Optional.empty();
}
}
}
| Do not use Optional for loop control
| presto-testng-services/src/main/java/io/prestosql/testng/services/FlakyAnnotationVerifier.java | Do not use Optional for loop control |
|
Java | apache-2.0 | 221537601fb64b7dfc4a5e9f088243248aa19484 | 0 | jeremylong/DependencyCheck,hansjoachim/DependencyCheck,wmaintw/DependencyCheck,hansjoachim/DependencyCheck,dwvisser/DependencyCheck,stefanneuhaus/DependencyCheck,recena/DependencyCheck,awhitford/DependencyCheck,stevespringett/DependencyCheck,wmaintw/DependencyCheck,adilakhter/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,dwvisser/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,recena/DependencyCheck,stefanneuhaus/DependencyCheck,adilakhter/DependencyCheck,stefanneuhaus/DependencyCheck,hansjoachim/DependencyCheck,colezlaw/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,dwvisser/DependencyCheck,wmaintw/DependencyCheck,colezlaw/DependencyCheck,dwvisser/DependencyCheck,dwvisser/DependencyCheck,stevespringett/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,recena/DependencyCheck,stevespringett/DependencyCheck,colezlaw/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,colezlaw/DependencyCheck,recena/DependencyCheck,colezlaw/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,hansjoachim/DependencyCheck,recena/DependencyCheck,recena/DependencyCheck,jeremylong/DependencyCheck,wmaintw/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,colezlaw/DependencyCheck,dwvisser/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,stevespringett/DependencyCheck,stefanneuhaus/DependencyCheck,adilakhter/DependencyCheck,wmaintw/DependencyCheck,stevespringett/DependencyCheck,adilakhter/DependencyCheck,stevespringett/DependencyCheck,wmaintw/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,hansjoachim/DependencyCheck,hansjoachim/DependencyCheck,adilakhter/DependencyCheck | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2014 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.nvdcve;
import java.io.File;
import java.sql.Driver;
import java.sql.DriverManager;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Jeremy Long <[email protected]>
*/
public class DriverLoaderTest {
public DriverLoaderTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of load method, of class DriverLoader.
*/
@Test
public void testLoad_String() throws Exception {
String className = "org.h2.Driver";
Driver d = null;
try {
d = DriverLoader.load(className);
} finally {
if (d != null) {
DriverManager.deregisterDriver(d);
}
}
}
/**
* Test of load method, of class DriverLoader; expecting an exception due to a bad driver class name.
*/
@Test(expected = DriverLoadException.class)
public void testLoad_String_ex() throws Exception {
String className = "bad.Driver";
Driver d = DriverLoader.load(className);
}
/**
* Test of load method, of class DriverLoader.
*/
@Test
public void testLoad_String_String() throws Exception {
String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
File driver = new File(testClassPath, "../../src/test/resources/mysql-connector-java-5.1.27-bin.jar");
assertTrue("MySQL Driver JAR file not found in src/test/resources?", driver.isFile());
Driver d = null;
try {
d = DriverLoader.load(className, driver.getAbsolutePath());
d = DriverManager.getDriver("jdbc:mysql://localhost:3306/dependencycheck");
assertNotNull(d);
} finally {
if (d != null) {
DriverManager.deregisterDriver(d);
}
}
}
/**
* Test of load method, of class DriverLoader.
*/
@Test
public void testLoad_String_String_multiple_paths() throws Exception {
final String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
final File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
final File dir1 = new File(testClassPath, "../../src/test/");
final File dir2 = new File(testClassPath, "../../src/test/resources/");
final String paths = String.format("%s" + File.pathSeparator + "%s", dir1.getAbsolutePath(), dir2.getAbsolutePath());
Driver d = null;
try {
d = DriverLoader.load(className, paths);
} finally {
if (d != null) {
DriverManager.deregisterDriver(d);
}
}
}
/**
* Test of load method, of class DriverLoader with an incorrect class name.
*/
@Test(expected = DriverLoadException.class)
public void testLoad_String_String_badClassName() throws Exception {
String className = "com.mybad.jdbc.Driver";
//we know this is in target/test-classes
File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
File driver = new File(testClassPath, "../../src/test/resources/mysql-connector-java-5.1.27-bin.jar");
assertTrue("MySQL Driver JAR file not found in src/test/resources?", driver.isFile());
Driver d = DriverLoader.load(className, driver.getAbsolutePath());
}
/**
* Test of load method, of class DriverLoader with an incorrect class path.
*/
@Test(expected = DriverLoadException.class)
public void testLoad_String_String_badPath() throws Exception {
String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
File driver = new File(testClassPath, "../../src/test/bad/mysql-connector-java-5.1.27-bin.jar");
Driver d = DriverLoader.load(className, driver.getAbsolutePath());
}
}
| dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/DriverLoaderTest.java | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2014 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.data.nvdcve;
import java.io.File;
import java.sql.Driver;
import java.sql.DriverManager;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Jeremy Long <[email protected]>
*/
public class DriverLoaderTest {
public DriverLoaderTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of load method, of class DriverLoader.
*/
@Test
public void testLoad_String() throws Exception {
String className = "org.h2.Driver";
DriverLoader.load(className);
}
/**
* Test of load method, of class DriverLoader; expecting an exception due to a bad driver class name.
*/
@Test(expected = DriverLoadException.class)
public void testLoad_String_ex() throws Exception {
String className = "bad.Driver";
DriverLoader.load(className);
}
/**
* Test of load method, of class DriverLoader.
*/
@Test
public void testLoad_String_String() throws Exception {
String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
File driver = new File(testClassPath, "../../src/test/resources/mysql-connector-java-5.1.27-bin.jar");
assertTrue("MySQL Driver JAR file not found in src/test/resources?", driver.isFile());
DriverLoader.load(className, driver.getAbsolutePath());
Driver d = DriverManager.getDriver("jdbc:mysql://localhost:3306/dependencycheck");
assertNotNull(d);
}
/**
* Test of load method, of class DriverLoader.
*/
@Test
public void testLoad_String_String_multiple_paths() throws Exception {
final String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
final File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
final File dir1 = new File(testClassPath, "../../src/test/");
final File dir2 = new File(testClassPath, "../../src/test/resources/");
final String paths = String.format("%s" + File.pathSeparator + "%s", dir1.getAbsolutePath(), dir2.getAbsolutePath());
DriverLoader.load(className, paths);
}
/**
* Test of load method, of class DriverLoader with an incorrect class name.
*/
@Test(expected = DriverLoadException.class)
public void testLoad_String_String_badClassName() throws Exception {
String className = "com.mybad.jdbc.Driver";
//we know this is in target/test-classes
File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
File driver = new File(testClassPath, "../../src/test/resources/mysql-connector-java-5.1.27-bin.jar");
assertTrue("MySQL Driver JAR file not found in src/test/resources?", driver.isFile());
DriverLoader.load(className, driver.getAbsolutePath());
}
/**
* Test of load method, of class DriverLoader with an incorrect class path.
*/
@Test(expected = DriverLoadException.class)
public void testLoad_String_String_badPath() throws Exception {
String className = "com.mysql.jdbc.Driver";
//we know this is in target/test-classes
File testClassPath = (new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath())).getParentFile();
File driver = new File(testClassPath, "../../src/test/bad/mysql-connector-java-5.1.27-bin.jar");
DriverLoader.load(className, driver.getAbsolutePath());
}
}
| updated so compilation/tests work on linux
Former-commit-id: 3759e9438065138e6339aa3a56c81c08215406e4 | dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/DriverLoaderTest.java | updated so compilation/tests work on linux |
|
Java | apache-2.0 | e0cd93f461049a281bce95a1315a06e2e8e62ad9 | 0 | Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/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.ui.perspective;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.*;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.DBeaverPreferences;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.app.DBPDataSourceRegistry;
import org.jkiss.dbeaver.model.app.DBPRegistryListener;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.navigator.*;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceListener;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.DBSObjectSelector;
import org.jkiss.dbeaver.registry.DataSourceProviderRegistry;
import org.jkiss.dbeaver.registry.DataSourceRegistry;
import org.jkiss.dbeaver.runtime.jobs.DataSourceJob;
import org.jkiss.dbeaver.ui.IActionConstants;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.actions.DataSourcePropertyTester;
import org.jkiss.dbeaver.ui.controls.CSmartSelector;
import org.jkiss.dbeaver.ui.controls.DatabaseLabelProviders;
import org.jkiss.dbeaver.ui.controls.SelectDataSourceCombo;
import org.jkiss.dbeaver.ui.dialogs.SelectObjectDialog;
import org.jkiss.dbeaver.ui.editors.EditorUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.ref.SoftReference;
import java.text.MessageFormat;
import java.util.*;
/**
* DataSource Toolbar
*/
public class DataSourceManagementToolbar implements DBPRegistryListener, DBPEventListener, DBPPreferenceListener, INavigatorListener {
private static final Log log = Log.getLog(DataSourceManagementToolbar.class);
private static DataSourceManagementToolbar toolBarInstance;
private IWorkbenchWindow workbenchWindow;
private IWorkbenchPart activePart;
private IPageListener pageListener;
private IPartListener partListener;
private Text resultSetSize;
private SelectDataSourceCombo connectionCombo;
private CSmartSelector<DBNDatabaseNode> databaseCombo;
private SoftReference<DBPDataSourceContainer> curDataSourceContainer = null;
private final List<DBPDataSourceRegistry> handledRegistries = new ArrayList<>();
private final List<DatabaseListReader> dbListReads = new ArrayList<>();
private volatile IFile activeFile;
private volatile String currentDatabaseInstanceName;
private class DatabaseListReader extends DataSourceJob {
private final List<DBNDatabaseNode> nodeList = new ArrayList<>();
// Remote instance node
private DBSObject active;
private boolean enabled;
public DatabaseListReader(@NotNull DBCExecutionContext context) {
super(CoreMessages.toolbar_datasource_selector_action_read_databases, context);
setSystem(true);
this.enabled = false;
}
@Override
public IStatus run(DBRProgressMonitor monitor) {
final DBPDataSource dataSource = getExecutionContext().getDataSource();
DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (objectContainer == null || objectSelector == null) {
return Status.CANCEL_STATUS;
}
try {
monitor.beginTask(CoreMessages.toolbar_datasource_selector_action_read_databases, 1);
currentDatabaseInstanceName = null;
Class<? extends DBSObject> childType = objectContainer.getChildType(monitor);
if (childType == null || !DBSObjectContainer.class.isAssignableFrom(childType)) {
enabled = false;
} else {
enabled = true;
DBNModel navigatorModel = DBeaverCore.getInstance().getNavigatorModel();
DBSObject defObject = objectSelector.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// Default object can be object container + object selector (e.g. in PG)
objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
currentDatabaseInstanceName = defObject.getName();
objectContainer = (DBSObjectContainer) defObject;
defObject = objectSelector.getDefaultObject();
}
}
Collection<? extends DBSObject> children = objectContainer.getChildren(monitor);
active = defObject;
// Cache navigator nodes
if (children != null) {
for (DBSObject child : children) {
if (DBUtils.getAdapter(DBSObjectContainer.class, child) != null) {
DBNDatabaseNode node = navigatorModel.getNodeByObject(monitor, child, false);
if (node != null) {
nodeList.add(node);
}
}
}
}
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}
public static DataSourceManagementToolbar getInstance() {
return toolBarInstance;
}
public DataSourceManagementToolbar(IWorkbenchWindow workbenchWindow) {
toolBarInstance = this;
this.workbenchWindow = workbenchWindow;
DBeaverCore.getInstance().getNavigatorModel().addListener(this);
final ISelectionListener selectionListener = (part, selection) -> {
if (part == activePart && selection instanceof IStructuredSelection) {
final Object element = ((IStructuredSelection) selection).getFirstElement();
if (element != null) {
if (RuntimeUtils.getObjectAdapter(element, DBSObject.class) != null) {
updateControls(false);
}
}
}
};
pageListener = new AbstractPageListener() {
@Override
public void pageClosed(IWorkbenchPage page) {
page.removePartListener(partListener);
page.removeSelectionListener(selectionListener);
}
@Override
public void pageOpened(IWorkbenchPage page) {
page.addPartListener(partListener);
page.addSelectionListener(selectionListener);
}
};
partListener = new AbstractPartListener() {
@Override
public void partActivated(IWorkbenchPart part) {
setActivePart(part);
}
@Override
public void partClosed(IWorkbenchPart part) {
if (part == activePart) {
setActivePart(null);
}
}
};
}
public void showConnectionSelector() {
connectionCombo.showConnectionSelector();
}
private void dispose() {
DBeaverCore.getInstance().getNavigatorModel().removeListener(this);
IWorkbenchPage activePage = workbenchWindow.getActivePage();
if (activePage != null) {
pageListener.pageClosed(activePage);
}
DataSourceProviderRegistry.getInstance().removeDataSourceRegistryListener(this);
for (DBPDataSourceRegistry registry : handledRegistries) {
registry.removeDataSourceListener(this);
}
setActivePart(null);
this.workbenchWindow.removePageListener(pageListener);
}
@Override
public void handleRegistryLoad(DBPDataSourceRegistry registry) {
registry.addDataSourceListener(this);
handledRegistries.add(registry);
}
@Override
public void handleRegistryUnload(DBPDataSourceRegistry registry) {
handledRegistries.remove(registry);
registry.removeDataSourceListener(this);
}
@Nullable
private static IAdaptable getActiveObject(IWorkbenchPart activePart) {
if (activePart instanceof IEditorPart) {
return ((IEditorPart) activePart).getEditorInput();
} else if (activePart instanceof IViewPart) {
return activePart;
} else {
return null;
}
}
@Nullable
private DBPDataSourceContainer getDataSourceContainer() {
return getDataSourceContainer(activePart);
}
@Nullable
private static DBPDataSourceContainer getDataSourceContainer(IWorkbenchPart part) {
if (part == null) {
return null;
}
if (part instanceof IDataSourceContainerProvider) {
return ((IDataSourceContainerProvider) part).getDataSourceContainer();
}
final IAdaptable activeObject = getActiveObject(part);
if (activeObject == null) {
return null;
}
if (activeObject instanceof IDataSourceContainerProvider) {
return ((IDataSourceContainerProvider) activeObject).getDataSourceContainer();
} else if (activeObject instanceof DBPContextProvider) {
DBCExecutionContext executionContext = ((DBPContextProvider) activeObject).getExecutionContext();
if (executionContext != null) {
return executionContext.getDataSource().getContainer();
}
}
return null;
}
@Nullable
private IDataSourceContainerProviderEx getActiveDataSourceUpdater() {
if (activePart instanceof IDataSourceContainerProviderEx) {
return (IDataSourceContainerProviderEx) activePart;
} else {
final IAdaptable activeObject = getActiveObject(activePart);
if (activeObject == null) {
return null;
}
return activeObject instanceof IDataSourceContainerProviderEx ? (IDataSourceContainerProviderEx) activeObject : null;
}
}
private List<? extends DBPDataSourceContainer> getAvailableDataSources() {
//Get project from active editor
final IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
if (activeEditor != null && activeEditor.getEditorInput() instanceof IFileEditorInput) {
final IFile curFile = ((IFileEditorInput) activeEditor.getEditorInput()).getFile();
if (curFile != null) {
DBPDataSourceContainer fileDataSource = EditorUtils.getFileDataSource(curFile);
if (fileDataSource != null) {
return fileDataSource.getRegistry().getDataSources();
}
final DataSourceRegistry dsRegistry = DBeaverCore.getInstance().getProjectRegistry().getDataSourceRegistry(curFile.getProject());
if (dsRegistry != null) {
return dsRegistry.getDataSources();
}
}
}
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer != null) {
return dataSourceContainer.getRegistry().getDataSources();
} else {
return DataSourceRegistry.getAllDataSources();
}
}
private IProject getActiveProject() {
//Get project from active editor
final IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
if (activeEditor != null && activeEditor.getEditorInput() instanceof IFileEditorInput) {
final IFile curFile = ((IFileEditorInput) activeEditor.getEditorInput()).getFile();
if (curFile != null) {
return curFile.getProject();
}
}
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer != null) {
return dataSourceContainer.getRegistry().getProject();
} else {
return DBeaverCore.getInstance().getProjectRegistry().getActiveProject();
}
}
public void setActivePart(@Nullable IWorkbenchPart part) {
if (!(part instanceof IEditorPart)) {
if (part == null || part.getSite() == null || part.getSite().getPage() == null) {
part = null;
} else {
// Toolbar works only with active editor
// Other parts just doesn't matter
part = part.getSite().getPage().getActiveEditor();
}
}
if (connectionCombo != null && !connectionCombo.isDisposed()) {
final int selConnection = connectionCombo.getSelectionIndex();
DBPDataSourceContainer visibleContainer = null;
if (selConnection > 0) {
visibleContainer = connectionCombo.getItem(selConnection);
}
DBPDataSourceContainer newContainer = getDataSourceContainer(part);
if (activePart != part || activePart == null || visibleContainer != newContainer) {
// Update previous statuses
DBPDataSourceContainer oldContainer = getDataSourceContainer(activePart);
activePart = part;
if (oldContainer != newContainer) {
if (oldContainer != null) {
oldContainer.getPreferenceStore().removePropertyChangeListener(this);
}
oldContainer = getDataSourceContainer();
if (oldContainer != null) {
// Update editor actions
oldContainer.getPreferenceStore().addPropertyChangeListener(this);
}
}
// Update controls and actions
updateControls(true);
}
}
if (part != null) {
final IEditorInput editorInput = ((IEditorPart) part).getEditorInput();
activeFile = EditorUtils.getFileFromInput(editorInput);
} else {
activeFile = null;
}
}
private void fillDataSourceList(boolean force) {
if (connectionCombo.isDisposed()) {
return;
}
final List<? extends DBPDataSourceContainer> dataSources = getAvailableDataSources();
boolean update = force;
if (!update) {
// Check if there are any changes
final List<DBPDataSourceContainer> oldDataSources = new ArrayList<>(connectionCombo.getItems());
if (oldDataSources.size() == dataSources.size()) {
for (int i = 0; i < dataSources.size(); i++) {
if (dataSources.get(i) != oldDataSources.get(i)) {
update = true;
break;
}
}
} else {
update = true;
}
}
if (update) {
connectionCombo.setRedraw(false);
}
try {
if (update) {
connectionCombo.removeAll();
connectionCombo.addItem(null);
}
int selectionIndex = 0;
if (activePart != null) {
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (!CommonUtils.isEmpty(dataSources)) {
for (int i = 0; i < dataSources.size(); i++) {
DBPDataSourceContainer ds = dataSources.get(i);
if (ds == null) {
continue;
}
if (update) {
connectionCombo.addItem(ds);
}
if (dataSourceContainer == ds) {
selectionIndex = i + 1;
}
}
}
}
connectionCombo.select(selectionIndex);
connectionCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_datasource_tooltip + "\n" + connectionCombo.getText());
} finally {
if (update) {
connectionCombo.setRedraw(true);
}
}
}
@Override
public void handleDataSourceEvent(final DBPEvent event) {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
if (event.getAction() == DBPEvent.Action.OBJECT_ADD ||
event.getAction() == DBPEvent.Action.OBJECT_REMOVE ||
(event.getAction() == DBPEvent.Action.OBJECT_UPDATE && event.getObject() == getDataSourceContainer()) ||
(event.getAction() == DBPEvent.Action.OBJECT_SELECT && Boolean.TRUE.equals(event.getEnabled()) &&
DBUtils.getContainer(event.getObject()) == getDataSourceContainer())
) {
UIUtils.asyncExec(
() -> updateControls(true)
);
}
// This is a hack. We need to update main toolbar. By design toolbar should be updated along with command state
// but in fact it doesn't. I don't know better way than trigger update explicitly.
// TODO: replace with something smarter
if (event.getAction() == DBPEvent.Action.OBJECT_UPDATE && event.getEnabled() != null) {
DataSourcePropertyTester.firePropertyChange(DataSourcePropertyTester.PROP_CONNECTED);
DataSourcePropertyTester.firePropertyChange(DataSourcePropertyTester.PROP_TRANSACTIONAL);
UIUtils.asyncExec(
() -> {
IWorkbenchWindow workbenchWindow = UIUtils.getActiveWorkbenchWindow();
if (workbenchWindow instanceof WorkbenchWindow) {
((WorkbenchWindow) workbenchWindow).updateActionBars();
}
}
);
}
}
private void updateControls(boolean force) {
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
// Update resultset max size
if (resultSetSize != null && !resultSetSize.isDisposed()) {
if (dataSourceContainer == null) {
resultSetSize.setEnabled(false);
resultSetSize.setText(""); //$NON-NLS-1$
} else {
resultSetSize.setEnabled(true);
resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS)));
}
}
// Update datasources combo
updateDataSourceList(force);
updateDatabaseList(force);
}
private void changeResultSetSize() {
DBPDataSourceContainer dsContainer = getDataSourceContainer();
if (dsContainer != null) {
String rsSize = resultSetSize.getText();
if (rsSize.length() == 0) {
rsSize = "1"; //$NON-NLS-1$
}
DBPPreferenceStore store = dsContainer.getPreferenceStore();
store.setValue(DBeaverPreferences.RESULT_SET_MAX_ROWS, rsSize);
PrefUtils.savePreferenceStore(store);
}
}
private void updateDataSourceList(boolean force) {
if (connectionCombo != null && !connectionCombo.isDisposed()) {
IDataSourceContainerProviderEx containerProvider = getActiveDataSourceUpdater();
if (containerProvider == null) {
connectionCombo.removeAll();
connectionCombo.setEnabled(false);
} else {
connectionCombo.setEnabled(true);
}
fillDataSourceList(force);
}
}
private void updateDatabaseList(boolean force) {
if (!force) {
DBPDataSourceContainer dsContainer = getDataSourceContainer();
if (curDataSourceContainer != null && dsContainer == curDataSourceContainer.get()) {
// The same DS container - nothing to change in DB list
return;
}
}
// Update databases combo
fillDatabaseCombo();
}
private void fillDatabaseCombo() {
if (databaseCombo != null && !databaseCombo.isDisposed()) {
final DBPDataSourceContainer dsContainer = getDataSourceContainer();
databaseCombo.setEnabled(dsContainer != null);
if (dsContainer != null && dsContainer.isConnected()) {
final DBPDataSource dataSource = dsContainer.getDataSource();
if (dataSource != null) {
synchronized (dbListReads) {
for (DatabaseListReader reader : dbListReads) {
if (reader.getExecutionContext().getDataSource() == dataSource) {
return;
}
}
DatabaseListReader databaseReader = new DatabaseListReader(dataSource.getDefaultInstance().getDefaultContext(true));
databaseReader.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(final IJobChangeEvent event) {
UIUtils.syncExec(() -> fillDatabaseList((DatabaseListReader) event.getJob()));
}
});
dbListReads.add(databaseReader);
databaseReader.schedule();
}
}
curDataSourceContainer = new SoftReference<>(dsContainer);
} else {
curDataSourceContainer = null;
databaseCombo.removeAll();
databaseCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_database_tooltip);
}
}
}
private synchronized void fillDatabaseList(DatabaseListReader reader) {
synchronized (dbListReads) {
dbListReads.remove(reader);
}
if (databaseCombo.isDisposed()) {
return;
}
databaseCombo.setRedraw(false);
try {
databaseCombo.removeAll();
if (reader.active == null) {
databaseCombo.addItem(null);
}
if (!reader.enabled) {
databaseCombo.setEnabled(false);
return;
}
Collection<DBNDatabaseNode> dbList = reader.nodeList;
if (dbList != null && !dbList.isEmpty()) {
for (DBNDatabaseNode node : dbList) {
databaseCombo.addItem(node);
}
}
if (reader.active != null) {
int dbCount = databaseCombo.getItemCount();
for (int i = 0; i < dbCount; i++) {
if (databaseCombo.getItem(i) != null && databaseCombo.getItem(i).getObject() == reader.active) {
databaseCombo.select(i);
break;
}
}
}
databaseCombo.setEnabled(reader.enabled);
databaseCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_database_tooltip + "\n" + databaseCombo.getText());
} finally {
if (!databaseCombo.isDisposed()) {
databaseCombo.setRedraw(true);
}
}
}
private void changeDataSourceSelection(final DBPDataSourceContainer selectedDataSource) {
if (connectionCombo == null || connectionCombo.isDisposed()) {
return;
}
final IDataSourceContainerProviderEx dataSourceUpdater = getActiveDataSourceUpdater();
if (dataSourceUpdater == null) {
return;
}
final AbstractJob updateJob = new AbstractJob("Change active database") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
dataSourceUpdater.setDataSourceContainer(selectedDataSource);
return Status.OK_STATUS;
}
};
updateJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
UIUtils.asyncExec(() -> updateControls(false));
}
});
updateJob.schedule();
}
private void changeDataBaseSelection(DBNDatabaseNode node) {
DBPDataSourceContainer dsContainer = getDataSourceContainer();
final String newName = node.getNodeName();
if (dsContainer != null && dsContainer.isConnected()) {
final DBPDataSource dataSource = dsContainer.getDataSource();
new AbstractJob("Change active database") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
DBSObjectContainer oc = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector os = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (os != null) {
final DBSObject defObject = os.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// USe seconds level of active object
DBSObjectSelector os2 = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (os2 != null && os2.supportsDefaultChange()) {
oc = (DBSObjectContainer) defObject;
os = os2;
}
}
}
if (oc != null && os != null && os.supportsDefaultChange()) {
DBSObject newChild = oc.getChild(monitor, newName);
if (newChild != null) {
os.setDefaultObject(monitor, newChild);
} else {
throw new DBException(MessageFormat.format(CoreMessages.toolbar_datasource_selector_error_database_not_found, newName));
}
} else {
throw new DBException(CoreMessages.toolbar_datasource_selector_error_database_change_not_supported);
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
@Override
public void preferenceChange(PreferenceChangeEvent event) {
if (event.getProperty().equals(DBeaverPreferences.RESULT_SET_MAX_ROWS) && !resultSetSize.isDisposed()) {
if (event.getNewValue() != null) {
resultSetSize.setText(event.getNewValue().toString());
}
}
}
Control createControl(Composite parent) {
workbenchWindow.addPageListener(pageListener);
IWorkbenchPage activePage = workbenchWindow.getActivePage();
if (activePage != null) {
pageListener.pageOpened(activePage);
}
// Register as datasource listener in all datasources
// We need it because at this moment there could be come already loaded registries (on startup)
DataSourceProviderRegistry.getInstance().addDataSourceRegistryListener(DataSourceManagementToolbar.this);
for (DataSourceRegistry registry : DataSourceRegistry.getAllRegistries()) {
handleRegistryLoad(registry);
}
Composite comboGroup = new Composite(parent, SWT.NONE);
RowLayout layout = new RowLayout(SWT.HORIZONTAL);
layout.marginTop = 0;
layout.marginBottom = 0;
layout.marginWidth = 5;
layout.marginHeight = 0;
comboGroup.setLayout(layout);
final int fontHeight = UIUtils.getFontHeight(parent);
int comboWidth = fontHeight * 20;
connectionCombo = new SelectDataSourceCombo(comboGroup) {
@Override
protected IProject getActiveProject() {
return DataSourceManagementToolbar.this.getActiveProject();
}
@Override
protected void onDataSourceChange(DBPDataSourceContainer dataSource) {
changeDataSourceSelection(dataSource);
}
};
RowData rd = new RowData();
rd.width = comboWidth;
connectionCombo.setLayoutData(rd);
connectionCombo.setVisibleItemCount(15);
connectionCombo.setWidthHint(comboWidth);
connectionCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_datasource_tooltip);
connectionCombo.addItem(null);
connectionCombo.select(0);
comboWidth = fontHeight * 16;
databaseCombo = new CSmartSelector<DBNDatabaseNode>(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER,
new DatabaseLabelProviders.DatabaseLabelProvider() {
@Override
public String getText(Object element) {
if (currentDatabaseInstanceName == null) {
return super.getText(element);
} else {
return super.getText(element) + "@" + currentDatabaseInstanceName;
}
}
}) {
@Override
protected void dropDown(boolean drop) {
if (!drop) {
return;
}
showDatabaseSelector();
}
};
rd = new RowData();
rd.width = comboWidth;
databaseCombo.setLayoutData(rd);
databaseCombo.setVisibleItemCount(15);
databaseCombo.setWidthHint(comboWidth);
databaseCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_database_tooltip);
databaseCombo.addItem(null);
databaseCombo.select(0);
resultSetSize = new Text(comboGroup, SWT.BORDER);
resultSetSize.setTextLimit(10);
rd = new RowData();
rd.width = fontHeight * 4;
resultSetSize.setLayoutData(rd);
resultSetSize.setToolTipText(CoreMessages.toolbar_datasource_selector_resultset_segment_size);
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer != null) {
resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS)));
}
//resultSetSize.setDigits(7);
resultSetSize.addVerifyListener(UIUtils.getIntegerVerifyListener(Locale.getDefault()));
resultSetSize.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
changeResultSetSize();
}
});
comboGroup.addDisposeListener(e -> DataSourceManagementToolbar.this.dispose());
UIUtils.asyncExec(() -> {
if (workbenchWindow != null && workbenchWindow.getActivePage() != null) {
setActivePart(workbenchWindow.getActivePage().getActivePart());
}
});
return comboGroup;
}
void showDatabaseSelector() {
DBNDatabaseNode selectedDB = databaseCombo.getSelectedItem();
List<DBNDatabaseNode> items = new ArrayList<>(databaseCombo.getItems());
items.removeIf(Objects::isNull);
if (items.isEmpty()) {
return;
}
SelectObjectDialog<DBNDatabaseNode> dialog = new SelectObjectDialog<>(databaseCombo.getShell(),
"Choose catalog/schema",
true,
"SchemaSelector",
items,
selectedDB == null ? null : Collections.singletonList(selectedDB));
dialog.setModeless(true);
if (dialog.open() == IDialogConstants.CANCEL_ID) {
return;
}
DBNDatabaseNode node = dialog.getSelectedObject();
if (node != null) {
databaseCombo.select(node);
}
changeDataBaseSelection(node);
}
@Override
public void nodeChanged(DBNEvent event) {
if (activeFile == null) {
return;
}
final DBNNode node = event.getNode();
if (node instanceof DBNResource && activeFile.equals(((DBNResource) node).getResource())) {
final int selConnection = connectionCombo.getSelectionIndex();
if (selConnection > 0 && activeFile != null) {
DBPDataSourceContainer visibleContainer = connectionCombo.getItem(selConnection);
DBPDataSourceContainer newContainer = EditorUtils.getFileDataSource(activeFile);
if (newContainer != visibleContainer) {
updateControls(true);
}
}
}
}
public static class ToolbarContribution extends WorkbenchWindowControlContribution {
public ToolbarContribution() {
super(IActionConstants.TOOLBAR_DATASOURCE);
}
@Override
protected Control createControl(Composite parent) {
DataSourceManagementToolbar toolbar = new DataSourceManagementToolbar(UIUtils.getActiveWorkbenchWindow());
return toolbar.createControl(parent);
}
}
}
| plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/perspective/DataSourceManagementToolbar.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.ui.perspective;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.*;
import org.eclipse.ui.internal.WorkbenchWindow;
import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.DBeaverPreferences;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.app.DBPDataSourceRegistry;
import org.jkiss.dbeaver.model.app.DBPRegistryListener;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.navigator.*;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceListener;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.DBSObjectSelector;
import org.jkiss.dbeaver.registry.DataSourceProviderRegistry;
import org.jkiss.dbeaver.registry.DataSourceRegistry;
import org.jkiss.dbeaver.runtime.jobs.DataSourceJob;
import org.jkiss.dbeaver.ui.IActionConstants;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.actions.DataSourcePropertyTester;
import org.jkiss.dbeaver.ui.controls.CSmartSelector;
import org.jkiss.dbeaver.ui.controls.DatabaseLabelProviders;
import org.jkiss.dbeaver.ui.controls.SelectDataSourceCombo;
import org.jkiss.dbeaver.ui.dialogs.SelectObjectDialog;
import org.jkiss.dbeaver.ui.editors.EditorUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.ref.SoftReference;
import java.text.MessageFormat;
import java.util.*;
/**
* DataSource Toolbar
*/
public class DataSourceManagementToolbar implements DBPRegistryListener, DBPEventListener, DBPPreferenceListener, INavigatorListener {
private static final Log log = Log.getLog(DataSourceManagementToolbar.class);
private static DataSourceManagementToolbar toolBarInstance;
private IWorkbenchWindow workbenchWindow;
private IWorkbenchPart activePart;
private IPageListener pageListener;
private IPartListener partListener;
private Text resultSetSize;
private SelectDataSourceCombo connectionCombo;
private CSmartSelector<DBNDatabaseNode> databaseCombo;
private SoftReference<DBPDataSourceContainer> curDataSourceContainer = null;
private final List<DBPDataSourceRegistry> handledRegistries = new ArrayList<>();
private final List<DatabaseListReader> dbListReads = new ArrayList<>();
private volatile IFile activeFile;
private static class DatabaseListReader extends DataSourceJob {
private final List<DBNDatabaseNode> nodeList = new ArrayList<>();
private DBSObject active;
private boolean enabled;
public DatabaseListReader(@NotNull DBCExecutionContext context) {
super(CoreMessages.toolbar_datasource_selector_action_read_databases, context);
setSystem(true);
this.enabled = false;
}
@Override
public IStatus run(DBRProgressMonitor monitor) {
final DBPDataSource dataSource = getExecutionContext().getDataSource();
DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (objectContainer == null || objectSelector == null) {
return Status.CANCEL_STATUS;
}
try {
monitor.beginTask(CoreMessages.toolbar_datasource_selector_action_read_databases, 1);
Class<? extends DBSObject> childType = objectContainer.getChildType(monitor);
if (childType == null || !DBSObjectContainer.class.isAssignableFrom(childType)) {
enabled = false;
} else {
enabled = true;
DBSObject defObject = objectSelector.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// Default object can be object container + object selector (e.g. in PG)
objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
objectContainer = (DBSObjectContainer) defObject;
defObject = objectSelector.getDefaultObject();
}
}
Collection<? extends DBSObject> children = objectContainer.getChildren(monitor);
active = defObject;
// Cache navigator nodes
if (children != null) {
DBNModel navigatorModel = DBeaverCore.getInstance().getNavigatorModel();
for (DBSObject child : children) {
if (DBUtils.getAdapter(DBSObjectContainer.class, child) != null) {
DBNDatabaseNode node = navigatorModel.getNodeByObject(monitor, child, false);
if (node != null) {
nodeList.add(node);
}
}
}
}
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}
public static DataSourceManagementToolbar getInstance() {
return toolBarInstance;
}
public DataSourceManagementToolbar(IWorkbenchWindow workbenchWindow) {
toolBarInstance = this;
this.workbenchWindow = workbenchWindow;
DBeaverCore.getInstance().getNavigatorModel().addListener(this);
final ISelectionListener selectionListener = new ISelectionListener() {
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part == activePart && selection instanceof IStructuredSelection) {
final Object element = ((IStructuredSelection) selection).getFirstElement();
if (element != null) {
if (RuntimeUtils.getObjectAdapter(element, DBSObject.class) != null) {
updateControls(false);
}
}
}
}
};
pageListener = new AbstractPageListener() {
@Override
public void pageClosed(IWorkbenchPage page) {
page.removePartListener(partListener);
page.removeSelectionListener(selectionListener);
}
@Override
public void pageOpened(IWorkbenchPage page) {
page.addPartListener(partListener);
page.addSelectionListener(selectionListener);
}
};
partListener = new AbstractPartListener() {
@Override
public void partActivated(IWorkbenchPart part) {
setActivePart(part);
}
@Override
public void partClosed(IWorkbenchPart part) {
if (part == activePart) {
setActivePart(null);
}
}
};
}
public void showConnectionSelector() {
connectionCombo.showConnectionSelector();
}
private void dispose() {
DBeaverCore.getInstance().getNavigatorModel().removeListener(this);
IWorkbenchPage activePage = workbenchWindow.getActivePage();
if (activePage != null) {
pageListener.pageClosed(activePage);
}
DataSourceProviderRegistry.getInstance().removeDataSourceRegistryListener(this);
for (DBPDataSourceRegistry registry : handledRegistries) {
registry.removeDataSourceListener(this);
}
setActivePart(null);
this.workbenchWindow.removePageListener(pageListener);
}
@Override
public void handleRegistryLoad(DBPDataSourceRegistry registry) {
registry.addDataSourceListener(this);
handledRegistries.add(registry);
}
@Override
public void handleRegistryUnload(DBPDataSourceRegistry registry) {
handledRegistries.remove(registry);
registry.removeDataSourceListener(this);
}
@Nullable
private static IAdaptable getActiveObject(IWorkbenchPart activePart) {
if (activePart instanceof IEditorPart) {
return ((IEditorPart) activePart).getEditorInput();
} else if (activePart instanceof IViewPart) {
return activePart;
} else {
return null;
}
}
@Nullable
private DBPDataSourceContainer getDataSourceContainer() {
return getDataSourceContainer(activePart);
}
@Nullable
private static DBPDataSourceContainer getDataSourceContainer(IWorkbenchPart part) {
if (part == null) {
return null;
}
if (part instanceof IDataSourceContainerProvider) {
return ((IDataSourceContainerProvider) part).getDataSourceContainer();
}
final IAdaptable activeObject = getActiveObject(part);
if (activeObject == null) {
return null;
}
if (activeObject instanceof IDataSourceContainerProvider) {
return ((IDataSourceContainerProvider) activeObject).getDataSourceContainer();
} else if (activeObject instanceof DBPContextProvider) {
DBCExecutionContext executionContext = ((DBPContextProvider) activeObject).getExecutionContext();
if (executionContext != null) {
return executionContext.getDataSource().getContainer();
}
}
return null;
}
@Nullable
private IDataSourceContainerProviderEx getActiveDataSourceUpdater() {
if (activePart instanceof IDataSourceContainerProviderEx) {
return (IDataSourceContainerProviderEx) activePart;
} else {
final IAdaptable activeObject = getActiveObject(activePart);
if (activeObject == null) {
return null;
}
return activeObject instanceof IDataSourceContainerProviderEx ? (IDataSourceContainerProviderEx) activeObject : null;
}
}
private List<? extends DBPDataSourceContainer> getAvailableDataSources() {
//Get project from active editor
final IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
if (activeEditor != null && activeEditor.getEditorInput() instanceof IFileEditorInput) {
final IFile curFile = ((IFileEditorInput) activeEditor.getEditorInput()).getFile();
if (curFile != null) {
DBPDataSourceContainer fileDataSource = EditorUtils.getFileDataSource(curFile);
if (fileDataSource != null) {
return fileDataSource.getRegistry().getDataSources();
}
final DataSourceRegistry dsRegistry = DBeaverCore.getInstance().getProjectRegistry().getDataSourceRegistry(curFile.getProject());
if (dsRegistry != null) {
return dsRegistry.getDataSources();
}
}
}
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer != null) {
return dataSourceContainer.getRegistry().getDataSources();
} else {
return DataSourceRegistry.getAllDataSources();
}
}
private IProject getActiveProject() {
//Get project from active editor
final IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
if (activeEditor != null && activeEditor.getEditorInput() instanceof IFileEditorInput) {
final IFile curFile = ((IFileEditorInput) activeEditor.getEditorInput()).getFile();
if (curFile != null) {
return curFile.getProject();
}
}
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer != null) {
return dataSourceContainer.getRegistry().getProject();
} else {
return DBeaverCore.getInstance().getProjectRegistry().getActiveProject();
}
}
public void setActivePart(@Nullable IWorkbenchPart part) {
if (!(part instanceof IEditorPart)) {
if (part == null || part.getSite() == null || part.getSite().getPage() == null) {
part = null;
} else {
// Toolbar works only with active editor
// Other parts just doesn't matter
part = part.getSite().getPage().getActiveEditor();
}
}
if (connectionCombo != null && !connectionCombo.isDisposed()) {
final int selConnection = connectionCombo.getSelectionIndex();
DBPDataSourceContainer visibleContainer = null;
if (selConnection > 0) {
visibleContainer = connectionCombo.getItem(selConnection);
}
DBPDataSourceContainer newContainer = getDataSourceContainer(part);
if (activePart != part || activePart == null || visibleContainer != newContainer) {
// Update previous statuses
DBPDataSourceContainer oldContainer = getDataSourceContainer(activePart);
activePart = part;
if (oldContainer != newContainer) {
if (oldContainer != null) {
oldContainer.getPreferenceStore().removePropertyChangeListener(this);
}
oldContainer = getDataSourceContainer();
if (oldContainer != null) {
// Update editor actions
oldContainer.getPreferenceStore().addPropertyChangeListener(this);
}
}
// Update controls and actions
updateControls(true);
}
}
if (part != null) {
final IEditorInput editorInput = ((IEditorPart) part).getEditorInput();
activeFile = EditorUtils.getFileFromInput(editorInput);
} else {
activeFile = null;
}
}
private void fillDataSourceList(boolean force) {
if (connectionCombo.isDisposed()) {
return;
}
final List<? extends DBPDataSourceContainer> dataSources = getAvailableDataSources();
boolean update = force;
if (!update) {
// Check if there are any changes
final List<DBPDataSourceContainer> oldDataSources = new ArrayList<>(connectionCombo.getItems());
if (oldDataSources.size() == dataSources.size()) {
for (int i = 0; i < dataSources.size(); i++) {
if (dataSources.get(i) != oldDataSources.get(i)) {
update = true;
break;
}
}
} else {
update = true;
}
}
if (update) {
connectionCombo.setRedraw(false);
}
try {
if (update) {
connectionCombo.removeAll();
connectionCombo.addItem(null);
}
int selectionIndex = 0;
if (activePart != null) {
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (!CommonUtils.isEmpty(dataSources)) {
for (int i = 0; i < dataSources.size(); i++) {
DBPDataSourceContainer ds = dataSources.get(i);
if (ds == null) {
continue;
}
if (update) {
connectionCombo.addItem(ds);
}
if (dataSourceContainer == ds) {
selectionIndex = i + 1;
}
}
}
}
connectionCombo.select(selectionIndex);
} finally {
if (update) {
connectionCombo.setRedraw(true);
}
}
}
@Override
public void handleDataSourceEvent(final DBPEvent event) {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
if (event.getAction() == DBPEvent.Action.OBJECT_ADD ||
event.getAction() == DBPEvent.Action.OBJECT_REMOVE ||
(event.getAction() == DBPEvent.Action.OBJECT_UPDATE && event.getObject() == getDataSourceContainer()) ||
(event.getAction() == DBPEvent.Action.OBJECT_SELECT && Boolean.TRUE.equals(event.getEnabled()) &&
DBUtils.getContainer(event.getObject()) == getDataSourceContainer())
) {
UIUtils.asyncExec(
new Runnable() {
@Override
public void run() {
updateControls(true);
}
}
);
}
// This is a hack. We need to update main toolbar. By design toolbar should be updated along with command state
// but in fact it doesn't. I don't know better way than trigger update explicitly.
// TODO: replace with something smarter
if (event.getAction() == DBPEvent.Action.OBJECT_UPDATE && event.getEnabled() != null) {
DataSourcePropertyTester.firePropertyChange(DataSourcePropertyTester.PROP_CONNECTED);
DataSourcePropertyTester.firePropertyChange(DataSourcePropertyTester.PROP_TRANSACTIONAL);
UIUtils.asyncExec(
new Runnable() {
@Override
public void run() {
IWorkbenchWindow workbenchWindow = UIUtils.getActiveWorkbenchWindow();
if (workbenchWindow instanceof WorkbenchWindow) {
((WorkbenchWindow) workbenchWindow).updateActionBars();
}
}
}
);
}
}
private void updateControls(boolean force) {
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
// Update resultset max size
if (resultSetSize != null && !resultSetSize.isDisposed()) {
if (dataSourceContainer == null) {
resultSetSize.setEnabled(false);
resultSetSize.setText(""); //$NON-NLS-1$
} else {
resultSetSize.setEnabled(true);
resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS)));
}
}
// Update datasources combo
updateDataSourceList(force);
updateDatabaseList(force);
}
private void changeResultSetSize() {
DBPDataSourceContainer dsContainer = getDataSourceContainer();
if (dsContainer != null) {
String rsSize = resultSetSize.getText();
if (rsSize.length() == 0) {
rsSize = "1"; //$NON-NLS-1$
}
DBPPreferenceStore store = dsContainer.getPreferenceStore();
store.setValue(DBeaverPreferences.RESULT_SET_MAX_ROWS, rsSize);
PrefUtils.savePreferenceStore(store);
}
}
private void updateDataSourceList(boolean force) {
if (connectionCombo != null && !connectionCombo.isDisposed()) {
IDataSourceContainerProviderEx containerProvider = getActiveDataSourceUpdater();
if (containerProvider == null) {
connectionCombo.removeAll();
connectionCombo.setEnabled(false);
} else {
connectionCombo.setEnabled(true);
}
fillDataSourceList(force);
}
}
private void updateDatabaseList(boolean force) {
if (!force) {
DBPDataSourceContainer dsContainer = getDataSourceContainer();
if (curDataSourceContainer != null && dsContainer == curDataSourceContainer.get()) {
// The same DS container - nothing to change in DB list
return;
}
}
// Update databases combo
fillDatabaseCombo();
}
private void fillDatabaseCombo() {
if (databaseCombo != null && !databaseCombo.isDisposed()) {
final DBPDataSourceContainer dsContainer = getDataSourceContainer();
databaseCombo.setEnabled(dsContainer != null);
if (dsContainer != null && dsContainer.isConnected()) {
final DBPDataSource dataSource = dsContainer.getDataSource();
if (dataSource != null) {
synchronized (dbListReads) {
for (DatabaseListReader reader : dbListReads) {
if (reader.getExecutionContext().getDataSource() == dataSource) {
return;
}
}
DatabaseListReader databaseReader = new DatabaseListReader(dataSource.getDefaultInstance().getDefaultContext(true));
databaseReader.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(final IJobChangeEvent event) {
UIUtils.syncExec(new Runnable() {
@Override
public void run() {
fillDatabaseList((DatabaseListReader) event.getJob());
}
});
}
});
dbListReads.add(databaseReader);
databaseReader.schedule();
}
}
curDataSourceContainer = new SoftReference<>(dsContainer);
} else {
curDataSourceContainer = null;
databaseCombo.removeAll();
}
}
}
private synchronized void fillDatabaseList(DatabaseListReader reader) {
synchronized (dbListReads) {
dbListReads.remove(reader);
}
if (databaseCombo.isDisposed()) {
return;
}
databaseCombo.setRedraw(false);
try {
databaseCombo.removeAll();
if (reader.active == null) {
databaseCombo.addItem(null);
}
if (!reader.enabled) {
databaseCombo.setEnabled(false);
return;
}
Collection<DBNDatabaseNode> dbList = reader.nodeList;
if (dbList != null && !dbList.isEmpty()) {
for (DBNDatabaseNode node : dbList) {
databaseCombo.addItem(node);
}
}
if (reader.active != null) {
int dbCount = databaseCombo.getItemCount();
for (int i = 0; i < dbCount; i++) {
String dbName = databaseCombo.getItemText(i);
if (dbName.equals(reader.active.getName())) {
databaseCombo.select(i);
break;
}
}
}
databaseCombo.setEnabled(reader.enabled);
} finally {
if (!databaseCombo.isDisposed()) {
databaseCombo.setRedraw(true);
}
}
}
private void changeDataSourceSelection(final DBPDataSourceContainer selectedDataSource) {
if (connectionCombo == null || connectionCombo.isDisposed()) {
return;
}
final IDataSourceContainerProviderEx dataSourceUpdater = getActiveDataSourceUpdater();
if (dataSourceUpdater == null) {
return;
}
final AbstractJob updateJob = new AbstractJob("Change active database") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
dataSourceUpdater.setDataSourceContainer(selectedDataSource);
return Status.OK_STATUS;
}
};
updateJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
UIUtils.asyncExec(new Runnable() {
@Override
public void run() {
updateControls(false);
}
});
}
});
updateJob.schedule();
}
private void changeDataBaseSelection(DBNDatabaseNode node) {
DBPDataSourceContainer dsContainer = getDataSourceContainer();
final String newName = node.getNodeName();
if (dsContainer != null && dsContainer.isConnected()) {
final DBPDataSource dataSource = dsContainer.getDataSource();
new AbstractJob("Change active database") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
DBSObjectContainer oc = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector os = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (os != null) {
final DBSObject defObject = os.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// USe seconds level of active object
DBSObjectSelector os2 = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (os2 != null && os2.supportsDefaultChange()) {
oc = (DBSObjectContainer) defObject;
os = os2;
}
}
}
if (oc != null && os != null && os.supportsDefaultChange()) {
DBSObject newChild = oc.getChild(monitor, newName);
if (newChild != null) {
os.setDefaultObject(monitor, newChild);
} else {
throw new DBException(MessageFormat.format(CoreMessages.toolbar_datasource_selector_error_database_not_found, newName));
}
} else {
throw new DBException(CoreMessages.toolbar_datasource_selector_error_database_change_not_supported);
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
@Override
public void preferenceChange(PreferenceChangeEvent event) {
if (event.getProperty().equals(DBeaverPreferences.RESULT_SET_MAX_ROWS) && !resultSetSize.isDisposed()) {
if (event.getNewValue() != null) {
resultSetSize.setText(event.getNewValue().toString());
}
}
}
Control createControl(Composite parent) {
workbenchWindow.addPageListener(pageListener);
IWorkbenchPage activePage = workbenchWindow.getActivePage();
if (activePage != null) {
pageListener.pageOpened(activePage);
}
// Register as datasource listener in all datasources
// We need it because at this moment there could be come already loaded registries (on startup)
DataSourceProviderRegistry.getInstance().addDataSourceRegistryListener(DataSourceManagementToolbar.this);
for (DataSourceRegistry registry : DataSourceRegistry.getAllRegistries()) {
handleRegistryLoad(registry);
}
Composite comboGroup = new Composite(parent, SWT.NONE);
RowLayout layout = new RowLayout(SWT.HORIZONTAL);
layout.marginTop = 0;
layout.marginBottom = 0;
layout.marginWidth = 5;
layout.marginHeight = 0;
comboGroup.setLayout(layout);
final int fontHeight = UIUtils.getFontHeight(parent);
int comboWidth = fontHeight * 20;
connectionCombo = new SelectDataSourceCombo(comboGroup) {
@Override
protected IProject getActiveProject() {
return DataSourceManagementToolbar.this.getActiveProject();
}
@Override
protected void onDataSourceChange(DBPDataSourceContainer dataSource) {
changeDataSourceSelection(dataSource);
}
};
RowData rd = new RowData();
rd.width = comboWidth;
connectionCombo.setLayoutData(rd);
connectionCombo.setVisibleItemCount(15);
connectionCombo.setWidthHint(comboWidth);
connectionCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_datasource_tooltip);
connectionCombo.addItem(null);
connectionCombo.select(0);
comboWidth = fontHeight * 16;
databaseCombo = new CSmartSelector<DBNDatabaseNode>(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER, new DatabaseLabelProviders.DatabaseLabelProvider()) {
@Override
protected void dropDown(boolean drop) {
if (!drop) {
return;
}
showDatabaseSelector();
}
};
rd = new RowData();
rd.width = comboWidth;
databaseCombo.setLayoutData(rd);
databaseCombo.setVisibleItemCount(15);
databaseCombo.setWidthHint(comboWidth);
databaseCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_database_tooltip);
databaseCombo.addItem(null);
databaseCombo.select(0);
resultSetSize = new Text(comboGroup, SWT.BORDER);
resultSetSize.setTextLimit(10);
rd = new RowData();
rd.width = fontHeight * 4;
resultSetSize.setLayoutData(rd);
resultSetSize.setToolTipText(CoreMessages.toolbar_datasource_selector_resultset_segment_size);
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer != null) {
resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS)));
}
//resultSetSize.setDigits(7);
resultSetSize.addVerifyListener(UIUtils.getIntegerVerifyListener(Locale.getDefault()));
resultSetSize.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
changeResultSetSize();
}
});
comboGroup.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
DataSourceManagementToolbar.this.dispose();
}
});
UIUtils.asyncExec(new Runnable() {
@Override
public void run() {
if (workbenchWindow != null && workbenchWindow.getActivePage() != null) {
setActivePart(workbenchWindow.getActivePage().getActivePart());
}
}
});
return comboGroup;
}
void showDatabaseSelector() {
DBNDatabaseNode selectedDB = databaseCombo.getSelectedItem();
List<DBNDatabaseNode> items = new ArrayList<>(databaseCombo.getItems());
items.removeIf(Objects::isNull);
if (items.isEmpty()) {
return;
}
SelectObjectDialog<DBNDatabaseNode> dialog = new SelectObjectDialog<>(databaseCombo.getShell(),
"Choose catalog/schema",
true,
"SchemaSelector",
items,
selectedDB == null ? null : Collections.singletonList(selectedDB));
dialog.setModeless(true);
if (dialog.open() == IDialogConstants.CANCEL_ID) {
return;
}
DBNDatabaseNode node = dialog.getSelectedObject();
if (node != null) {
databaseCombo.select(node);
}
changeDataBaseSelection(node);
}
@Override
public void nodeChanged(DBNEvent event) {
if (activeFile == null) {
return;
}
final DBNNode node = event.getNode();
if (node instanceof DBNResource && activeFile.equals(((DBNResource) node).getResource())) {
final int selConnection = connectionCombo.getSelectionIndex();
if (selConnection > 0 && activeFile != null) {
DBPDataSourceContainer visibleContainer = connectionCombo.getItem(selConnection);
DBPDataSourceContainer newContainer = EditorUtils.getFileDataSource(activeFile);
if (newContainer != visibleContainer) {
updateControls(true);
}
}
}
}
public static class ToolbarContribution extends WorkbenchWindowControlContribution {
public ToolbarContribution() {
super(IActionConstants.TOOLBAR_DATASOURCE);
}
@Override
protected Control createControl(Composite parent) {
DataSourceManagementToolbar toolbar = new DataSourceManagementToolbar(UIUtils.getActiveWorkbenchWindow());
return toolbar.createControl(parent);
}
}
}
| #3771 Database selector UI improvements
Former-commit-id: 620954eeeab0b60bd833f4aaa14a97e31a7730cc | plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/perspective/DataSourceManagementToolbar.java | #3771 Database selector UI improvements |
|
Java | apache-2.0 | f3a8278ec494e12f6057d245c2d0d84aab0d6e46 | 0 | MathRandomNext/Android | package com.telerikacademy.meetup.view.venue_details;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.telerikacademy.meetup.BaseApplication;
import com.telerikacademy.meetup.R;
import com.telerikacademy.meetup.config.di.module.ControllerModule;
import com.telerikacademy.meetup.model.base.IVenue;
import com.telerikacademy.meetup.provider.base.IIntentFactory;
import com.telerikacademy.meetup.ui.component.dialog.base.IDialog;
import com.telerikacademy.meetup.ui.component.dialog.base.IDialogFactory;
import com.telerikacademy.meetup.ui.fragment.base.IGallery;
import com.telerikacademy.meetup.view.review.ReviewActivity;
import com.telerikacademy.meetup.view.venue_details.base.IVenueDetailsContract;
import com.wang.avi.AVLoadingIndicatorView;
import javax.inject.Inject;
public class VenueDetailsContentFragment extends Fragment
implements IVenueDetailsContract.View {
private static final String EXTRA_VENUE =
VenueDetailsContentFragment.class.getCanonicalName() + ".VENUE";
private static final String PACKAGE_GOOGLE_MAPS = "com.google.android.apps.maps";
@Inject
IDialogFactory dialogFactory;
@Inject
IIntentFactory intentFactory;
@BindView(R.id.venue_details_content_loading_indicator)
AVLoadingIndicatorView contentLoadingIndicator;
@BindView(R.id.tv_venue_details_title)
TextView titleTextView;
@BindView(R.id.tv_venue_details_rating)
TextView ratingTextView;
@BindView(R.id.rb_venue_details_rating)
RatingBar ratingBar;
@BindView(R.id.tv_venue_details_type)
TextView typeTextView;
private IVenueDetailsContract.Presenter presenter;
private IDialog progressDialog;
private IGallery gallery;
private TabLayout galleryIndicator;
private AVLoadingIndicatorView galleryLoadingIndicator;
public VenueDetailsContentFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_venue_details_content, container, false);
BaseApplication.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
injectDependencies();
progressDialog = dialogFactory
.createDialog()
.withContent(R.string.dialog_loading_content)
.withProgress();
startLoading();
presenter.loadData();
presenter.loadPhotos();
}
@Override
public void onStart() {
super.onStart();
if (isNetworkAvailable()) {
presenter.subscribe();
} else {
stopLoading();
showErrorMessage();
getActivity().onBackPressed();
}
}
@Override
public void onStop() {
super.onStop();
presenter.unsubscribe();
}
@Override
public void onResume() {
super.onResume();
if (isNetworkAvailable()) {
presenter.subscribe();
} else {
stopLoading();
showErrorMessage();
getActivity().onBackPressed();
}
}
@Override
public void onPause() {
super.onPause();
presenter.unsubscribe();
}
@Override
public void setPresenter(IVenueDetailsContract.Presenter presenter) {
this.presenter = presenter;
}
@Override
public void setTitle(CharSequence title) {
titleTextView.setText(title);
}
@Override
public void setGallery(IGallery gallery) {
this.gallery = gallery;
}
@Override
public synchronized void addPhoto(final Bitmap photo) {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
gallery.addPhoto(photo);
}
});
}
}
@Override
public void setRating(float rating) {
ratingTextView.setText(Float.toString(rating));
ratingBar.setVisibility(View.VISIBLE);
ratingBar.setRating(rating);
}
@Override
public void setType(String type) {
typeTextView.setText(type);
}
@Override
public void setDefaultPhoto() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap photo = BitmapFactory.decodeResource(getResources(),
R.drawable.no_image_available);
gallery.addPhoto(photo);
}
});
}
@Override
public void startLoading() {
progressDialog.show();
}
@Override
public void stopLoading() {
progressDialog.hide();
}
@Override
public void startGalleryLoadingIndicator() {
galleryLoadingIndicator.smoothToShow();
}
@Override
public void stopGalleryLoadingIndicator() {
galleryLoadingIndicator.smoothToHide();
}
@Override
public void startContentLoadingIndicator() {
contentLoadingIndicator.smoothToShow();
}
@Override
public void stopContentLoadingIndicator() {
contentLoadingIndicator.smoothToHide();
}
@Override
public void showGalleryIndicator() {
galleryIndicator.setVisibility(View.VISIBLE);
if (getContext() != null) {
Animation expandIn = AnimationUtils
.loadAnimation(getContext(), R.anim.expand_in);
galleryIndicator.startAnimation(expandIn);
}
}
@Override
public void startNavigation(Uri uri) {
Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
mapIntent.setPackage(PACKAGE_GOOGLE_MAPS);
startActivity(mapIntent);
}
@Override
public void showErrorMessage() {
if (getContext() != null) {
Toast.makeText(getContext(), "An error has occured", Toast.LENGTH_SHORT).show();
}
}
@Override
public void startDialer(String phoneNumber) {
if (phoneNumber == null || phoneNumber.isEmpty()) {
Toast.makeText(getContext(), "Phone number has not been provided", Toast.LENGTH_SHORT).show();
return;
}
Intent dialerIntent = new Intent(Intent.ACTION_DIAL);
String formattedPhoneNumber = String.format("tel:%s", phoneNumber.trim());
dialerIntent.setData(Uri.parse(formattedPhoneNumber));
startActivity(dialerIntent);
}
@Override
public void startWebsite(Uri websiteUri) {
if (websiteUri == null) {
Toast.makeText(getContext(), "Website has not been provided", Toast.LENGTH_SHORT).show();
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setData(websiteUri);
startActivity(browserIntent);
}
@Override
public void redirectToReview(IVenue venue) {
Intent reviewIntent = intentFactory
.createIntentToFront(ReviewActivity.class)
.putExtra(EXTRA_VENUE, venue);
startActivity(reviewIntent);
}
@OnClick(R.id.btn_venue_details_call)
void onCallButtonClick() {
presenter.onCallButtonClick();
}
@OnClick(R.id.btn_venue_details_save)
void onSaveButtonClick() {
// TODO: Implement
}
@OnClick(R.id.btn_venue_details_review)
void onReviewButtonClick() {
presenter.onReviewButtonClick();
}
@OnClick(R.id.btn_venue_details_website)
void onWebsiteButtonClick() {
presenter.onWebsiteButtonClick();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private void injectDependencies() {
BaseApplication
.from(getContext())
.getComponent()
.getControllerComponent(new ControllerModule(
getActivity(), getFragmentManager()
))
.inject(this);
galleryIndicator = (TabLayout) getActivity()
.findViewById(R.id.gallery_indicator);
galleryLoadingIndicator = (AVLoadingIndicatorView) getActivity()
.findViewById(R.id.gallery_loading_indicator);
}
}
| Meetup/app/src/main/java/com/telerikacademy/meetup/view/venue_details/VenueDetailsContentFragment.java | package com.telerikacademy.meetup.view.venue_details;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.telerikacademy.meetup.BaseApplication;
import com.telerikacademy.meetup.R;
import com.telerikacademy.meetup.config.di.module.ControllerModule;
import com.telerikacademy.meetup.model.base.IVenue;
import com.telerikacademy.meetup.model.base.IVenueDetail;
import com.telerikacademy.meetup.provider.base.IIntentFactory;
import com.telerikacademy.meetup.ui.component.dialog.base.IDialog;
import com.telerikacademy.meetup.ui.component.dialog.base.IDialogFactory;
import com.telerikacademy.meetup.ui.fragment.base.IGallery;
import com.telerikacademy.meetup.view.review.ReviewActivity;
import com.telerikacademy.meetup.view.venue_details.base.IVenueDetailsContract;
import com.wang.avi.AVLoadingIndicatorView;
import javax.inject.Inject;
public class VenueDetailsContentFragment extends Fragment
implements IVenueDetailsContract.View {
private static final String EXTRA_VENUE =
VenueDetailsContentFragment.class.getCanonicalName() + ".VENUE";
private static final String PACKAGE_GOOGLE_MAPS = "com.google.android.apps.maps";
@Inject
IDialogFactory dialogFactory;
@Inject
IIntentFactory intentFactory;
@BindView(R.id.venue_details_content_loading_indicator)
AVLoadingIndicatorView contentLoadingIndicator;
@BindView(R.id.tv_venue_details_title)
TextView titleTextView;
@BindView(R.id.tv_venue_details_rating)
TextView ratingTextView;
@BindView(R.id.rb_venue_details_rating)
RatingBar ratingBar;
@BindView(R.id.tv_venue_details_type)
TextView typeTextView;
private IVenueDetailsContract.Presenter presenter;
private IDialog progressDialog;
private IGallery gallery;
private TabLayout galleryIndicator;
private AVLoadingIndicatorView galleryLoadingIndicator;
public VenueDetailsContentFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_venue_details_content, container, false);
BaseApplication.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
injectDependencies();
progressDialog = dialogFactory
.createDialog()
.withContent(R.string.dialog_loading_content)
.withProgress();
startLoading();
presenter.loadData();
presenter.loadPhotos();
}
@Override
public void onStart() {
super.onStart();
if (isNetworkAvailable()) {
presenter.subscribe();
} else {
stopLoading();
showErrorMessage();
getActivity().onBackPressed();
}
}
@Override
public void onStop() {
super.onStop();
presenter.unsubscribe();
}
@Override
public void onResume() {
super.onResume();
if (isNetworkAvailable()) {
presenter.subscribe();
} else {
stopLoading();
showErrorMessage();
getActivity().onBackPressed();
}
}
@Override
public void onPause() {
super.onPause();
presenter.unsubscribe();
}
@Override
public void setPresenter(IVenueDetailsContract.Presenter presenter) {
this.presenter = presenter;
}
@Override
public void setTitle(CharSequence title) {
titleTextView.setText(title);
}
@Override
public void setGallery(IGallery gallery) {
this.gallery = gallery;
}
@Override
public synchronized void addPhoto(final Bitmap photo) {
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
gallery.addPhoto(photo);
}
});
}
}
@Override
public void setRating(float rating) {
ratingTextView.setText(Float.toString(rating));
ratingBar.setVisibility(View.VISIBLE);
ratingBar.setRating(rating);
}
@Override
public void setType(String type) {
typeTextView.setText(type);
}
@Override
public void setDefaultPhoto() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Bitmap photo = BitmapFactory.decodeResource(getResources(),
R.drawable.no_image_available);
gallery.addPhoto(photo);
}
});
}
@Override
public void startLoading() {
progressDialog.show();
}
@Override
public void stopLoading() {
progressDialog.hide();
}
@Override
public void startGalleryLoadingIndicator() {
galleryLoadingIndicator.smoothToShow();
}
@Override
public void stopGalleryLoadingIndicator() {
galleryLoadingIndicator.smoothToHide();
}
@Override
public void startContentLoadingIndicator() {
contentLoadingIndicator.smoothToShow();
}
@Override
public void stopContentLoadingIndicator() {
contentLoadingIndicator.smoothToHide();
}
@Override
public void showGalleryIndicator() {
galleryIndicator.setVisibility(View.VISIBLE);
if (getContext() != null) {
Animation expandIn = AnimationUtils
.loadAnimation(getContext(), R.anim.expand_in);
galleryIndicator.startAnimation(expandIn);
}
}
@Override
public void startNavigation(Uri uri) {
Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
mapIntent.setPackage(PACKAGE_GOOGLE_MAPS);
startActivity(mapIntent);
}
@Override
public void showErrorMessage() {
if (getContext() != null) {
Toast.makeText(getContext(), "An error has occured", Toast.LENGTH_SHORT).show();
}
}
@Override
public void startDialer(String phoneNumber) {
if (phoneNumber == null || phoneNumber.isEmpty()) {
Toast.makeText(getContext(), "Phone number has not been provided", Toast.LENGTH_SHORT).show();
return;
}
Intent dialerIntent = new Intent(Intent.ACTION_DIAL);
String formattedPhoneNumber = String.format("tel:%s", phoneNumber.trim());
dialerIntent.setData(Uri.parse(formattedPhoneNumber));
startActivity(dialerIntent);
}
@Override
public void startWebsite(Uri websiteUri) {
if (websiteUri == null) {
Toast.makeText(getContext(), "Website has not been provided", Toast.LENGTH_SHORT).show();
return;
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setData(websiteUri);
startActivity(browserIntent);
}
@Override
public void redirectToReview(IVenue venue) {
Intent reviewIntent = intentFactory
.createIntentToFront(ReviewActivity.class)
.putExtra(EXTRA_VENUE, venue);
startActivity(reviewIntent);
}
@OnClick(R.id.btn_venue_details_call)
void onCallButtonClick() {
presenter.onCallButtonClick();
}
@OnClick(R.id.btn_venue_details_save)
void onSaveButtonClick() {
// TODO: Implement
}
@OnClick(R.id.btn_venue_details_review)
void onReviewButtonClick() {
presenter.onReviewButtonClick();
}
@OnClick(R.id.btn_venue_details_website)
void onWebsiteButtonClick() {
presenter.onWebsiteButtonClick();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private void injectDependencies() {
BaseApplication
.from(getContext())
.getComponent()
.getControllerComponent(new ControllerModule(
getActivity(), getFragmentManager()
))
.inject(this);
galleryIndicator = (TabLayout) getActivity()
.findViewById(R.id.gallery_indicator);
galleryLoadingIndicator = (AVLoadingIndicatorView) getActivity()
.findViewById(R.id.gallery_loading_indicator);
}
}
| minor changes
| Meetup/app/src/main/java/com/telerikacademy/meetup/view/venue_details/VenueDetailsContentFragment.java | minor changes |
|
Java | apache-2.0 | 7e9115e04a5ff15f3880feeee428610a517576fc | 0 | telefonicaid/fiware-keypass,telefonicaid/fiware-keypass,telefonicaid/fiware-keypass | package es.tid.fiware.iot.ac.util;
/*
* Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
*
* 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 es.tid.fiware.iot.ac.rs.Tenant;
import es.tid.fiware.iot.ac.rs.Correlator;
import io.dropwizard.hibernate.UnitOfWork;
import java.io.IOException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.Level;
@Path("/admin/log")
@Produces(MediaType.APPLICATION_XML)
public class LogsEndpoint {
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(LogsEndpoint.class);
private static String[] ValidLogLevels = {
"ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL"
};
public LogsEndpoint() {
}
/**
* Change LogLevel
*
* @param logLevel
* @return
*/
@PUT
@UnitOfWork
public Response updateLogLevel(@Tenant String tenant,
@Correlator String correlator,
@QueryParam("logLevel") String logLevel
) {
// Check logLevel proposed
if (logLevel != null) {
if (Arrays.asList(ValidLogLevels).contains(logLevel.toUpperCase())) {
String newLogLevel = logLevel.toUpperCase();
LOGGER.debug("trying to change log level changed to " + newLogLevel);
LOGGER.setLevel(Level.toLevel(newLogLevel));
LOGGER.info("Keypass log level changed to " + newLogLevel);
return Response.status(200).build();
} else {
LOGGER.info("invalid log level " + logLevel);
return Response.status(400).entity("invalid log level").build();
}
} else {
LOGGER.info("log level missing " + logLevel);
return Response.status(400).entity("log level missing").build();
}
}
}
| src/main/java/es/tid/fiware/iot/ac/util/LogsEndpoint.java | package es.tid.fiware.iot.ac.util;
/*
* Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U
*
* 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 es.tid.fiware.iot.ac.rs.Tenant;
import es.tid.fiware.iot.ac.rs.Correlator;
import io.dropwizard.hibernate.UnitOfWork;
import java.io.IOException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Arrays;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.Level;
@Path("/admin/log")
@Produces(MediaType.APPLICATION_XML)
public class LogsEndpoint {
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(LogsEndpoint.class);
private static String[] ValidLogLevels = {
"ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL"
};
public LogsEndpoint() {
}
/**
* Change LogLevel
*
* @param logLevel
* @return
*/
@PUT
@UnitOfWork
<<<<<<< HEAD
public Response updateLogLevel(@Tenant String tenant,
@Correlator String correlator,
@QueryParam("logLevel") String logLevel
) {
// Check logLevel proposed
if (logLevel != null) {
if (Arrays.asList(ValidLogLevels).contains(logLevel.toUpperCase())) {
String newLogLevel = logLevel.toUpperCase();
LOGGER.debug("trying to change log level changed to " + newLogLevel);
LOGGER.setLevel(Level.toLevel(newLogLevel));
LOGGER.info("Keypass log level changed to " + newLogLevel);
return Response.status(200).build();
} else {
LOGGER.info("invalid log level " + logLevel);
return Response.status(400).entity("invalid log level").build();
}
} else {
LOGGER.info("log level missing " + logLevel);
return Response.status(400).entity("log level missing").build();
}
}
}
| remove a typo
| src/main/java/es/tid/fiware/iot/ac/util/LogsEndpoint.java | remove a typo |
|
Java | apache-2.0 | 872b8e007d9e9bfc06ae02d57dd16e8ddbe733fe | 0 | APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,wschaeferB/autopsy,esaunders/autopsy,esaunders/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,narfindustries/autopsy,APriestman/autopsy,millmanorama/autopsy,APriestman/autopsy,dgrove727/autopsy,millmanorama/autopsy,millmanorama/autopsy,wschaeferB/autopsy,millmanorama/autopsy,wschaeferB/autopsy,dgrove727/autopsy,rcordovano/autopsy,APriestman/autopsy,dgrove727/autopsy,narfindustries/autopsy,narfindustries/autopsy,wschaeferB/autopsy,APriestman/autopsy,wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2013 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.report;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.EscapeUtil;
import org.sleuthkit.autopsy.coreutils.ImageUtils;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.report.ReportProgressPanel.ReportStatus;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.SleuthkitCase.CaseDbQuery;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* Instances of this class use GeneralReportModules, TableReportModules and
* FileReportModules to generate a report. If desired, displayProgressPanels()
* can be called to show report generation progress using ReportProgressPanel
* objects displayed using a dialog box.
*/
class ReportGenerator {
private static final Logger logger = Logger.getLogger(ReportGenerator.class.getName());
private Case currentCase = Case.getCurrentCase();
private SleuthkitCase skCase = currentCase.getSleuthkitCase();
private Map<TableReportModule, ReportProgressPanel> tableProgress;
private Map<GeneralReportModule, ReportProgressPanel> generalProgress;
private Map<FileReportModule, ReportProgressPanel> fileProgress;
private String reportPath;
private ReportGenerationPanel panel = new ReportGenerationPanel();
static final String REPORTS_DIR = "Reports"; //NON-NLS
private List<String> errorList;
/**
* Displays the list of errors during report generation in user-friendly
* way. MessageNotifyUtil used to display bubble notification.
*
* @param listOfErrors List of strings explaining the errors.
*/
private void displayReportErrors() {
if (!errorList.isEmpty()) {
String errorString = "";
for (String error : errorList) {
errorString += error + "\n";
}
MessageNotifyUtil.Notify.error(
NbBundle.getMessage(this.getClass(), "ReportGenerator.notifyErr.errsDuringRptGen"), errorString);
return;
}
}
ReportGenerator(Map<TableReportModule, Boolean> tableModuleStates, Map<GeneralReportModule, Boolean> generalModuleStates, Map<FileReportModule, Boolean> fileListModuleStates) {
// Create the root reports directory path of the form: <CASE DIRECTORY>/Reports/<Case fileName> <Timestamp>/
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy-HH-mm-ss");
Date date = new Date();
String dateNoTime = dateFormat.format(date);
this.reportPath = currentCase.getReportDirectory() + File.separator + currentCase.getName() + " " + dateNoTime + File.separator;
this.errorList = new ArrayList<String>();
// Create the root reports directory.
try {
FileUtil.createFolder(new File(this.reportPath));
} catch (IOException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedMakeRptFolder"));
logger.log(Level.SEVERE, "Failed to make report folder, may be unable to generate reports.", ex); //NON-NLS
return;
}
// Initialize the progress panels
generalProgress = new HashMap<>();
tableProgress = new HashMap<>();
fileProgress = new HashMap<>();
setupProgressPanels(tableModuleStates, generalModuleStates, fileListModuleStates);
}
/**
* Create a ReportProgressPanel for each report generation module selected
* by the user.
*
* @param tableModuleStates The enabled/disabled state of each
* TableReportModule
* @param generalModuleStates The enabled/disabled state of each
* GeneralReportModule
* @param fileListModuleStates The enabled/disabled state of each
* FileReportModule
*/
private void setupProgressPanels(Map<TableReportModule, Boolean> tableModuleStates, Map<GeneralReportModule, Boolean> generalModuleStates, Map<FileReportModule, Boolean> fileListModuleStates) {
if (null != tableModuleStates) {
for (Entry<TableReportModule, Boolean> entry : tableModuleStates.entrySet()) {
if (entry.getValue()) {
TableReportModule module = entry.getKey();
String reportFilePath = module.getRelativeFilePath();
if (!reportFilePath.isEmpty()) {
tableProgress.put(module, panel.addReport(module.getName(), reportPath + reportFilePath));
} else {
tableProgress.put(module, panel.addReport(module.getName(), null));
}
}
}
}
if (null != generalModuleStates) {
for (Entry<GeneralReportModule, Boolean> entry : generalModuleStates.entrySet()) {
if (entry.getValue()) {
GeneralReportModule module = entry.getKey();
String reportFilePath = module.getRelativeFilePath();
if (!reportFilePath.isEmpty()) {
generalProgress.put(module, panel.addReport(module.getName(), reportPath + reportFilePath));
} else {
generalProgress.put(module, panel.addReport(module.getName(), null));
}
}
}
}
if (null != fileListModuleStates) {
for (Entry<FileReportModule, Boolean> entry : fileListModuleStates.entrySet()) {
if (entry.getValue()) {
FileReportModule module = entry.getKey();
String reportFilePath = module.getRelativeFilePath();
if (!reportFilePath.isEmpty()) {
fileProgress.put(module, panel.addReport(module.getName(), reportPath + reportFilePath));
} else {
fileProgress.put(module, panel.addReport(module.getName(), null));
}
}
}
}
}
/**
* Display the progress panels to the user, and add actions to close the
* parent dialog.
*/
public void displayProgressPanels() {
final JDialog dialog = new JDialog(new JFrame(), true);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setTitle(NbBundle.getMessage(this.getClass(), "ReportGenerator.displayProgress.title.text"));
dialog.add(this.panel);
dialog.pack();
panel.addCloseAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
panel.close();
}
});
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
int w = dialog.getSize().width;
int h = dialog.getSize().height;
// set the location of the popUp Window on the center of the screen
dialog.setLocation((screenDimension.width - w) / 2, (screenDimension.height - h) / 2);
dialog.setVisible(true);
}
/**
* Run the GeneralReportModules using a SwingWorker.
*/
public void generateGeneralReports() {
GeneralReportsWorker worker = new GeneralReportsWorker();
worker.execute();
}
/**
* Run the TableReportModules using a SwingWorker.
*
* @param artifactTypeSelections the enabled/disabled state of the artifact
* types to be included in the report
* @param tagSelections the enabled/disabled state of the tag names to be
* included in the report
*/
public void generateTableReports(Map<ARTIFACT_TYPE, Boolean> artifactTypeSelections, Map<String, Boolean> tagNameSelections) {
if (!tableProgress.isEmpty() && null != artifactTypeSelections) {
TableReportsWorker worker = new TableReportsWorker(artifactTypeSelections, tagNameSelections);
worker.execute();
}
}
/**
* Run the FileReportModules using a SwingWorker.
*
* @param enabledInfo the Information that should be included about each
* file in the report.
*/
public void generateFileListReports(Map<FileReportDataTypes, Boolean> enabledInfo) {
if (!fileProgress.isEmpty() && null != enabledInfo) {
List<FileReportDataTypes> enabled = new ArrayList<>();
for (Entry<FileReportDataTypes, Boolean> e : enabledInfo.entrySet()) {
if (e.getValue()) {
enabled.add(e.getKey());
}
}
FileReportsWorker worker = new FileReportsWorker(enabled);
worker.execute();
}
}
/**
* SwingWorker to run GeneralReportModules.
*/
private class GeneralReportsWorker extends SwingWorker<Integer, Integer> {
@Override
protected Integer doInBackground() throws Exception {
for (Entry<GeneralReportModule, ReportProgressPanel> entry : generalProgress.entrySet()) {
GeneralReportModule module = entry.getKey();
if (generalProgress.get(module).getStatus() != ReportStatus.CANCELED) {
module.generateReport(reportPath, generalProgress.get(module));
}
}
return 0;
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports", ex); //NON-NLS
} // catch and ignore if we were cancelled
catch (java.util.concurrent.CancellationException ex) {
} finally {
displayReportErrors();
errorList.clear();
}
}
}
/**
* SwingWorker to run FileReportModules.
*/
private class FileReportsWorker extends SwingWorker<Integer, Integer> {
private List<FileReportDataTypes> enabledInfo = Arrays.asList(FileReportDataTypes.values());
private List<FileReportModule> fileModules = new ArrayList<>();
FileReportsWorker(List<FileReportDataTypes> enabled) {
enabledInfo = enabled;
for (Entry<FileReportModule, ReportProgressPanel> entry : fileProgress.entrySet()) {
fileModules.add(entry.getKey());
}
}
@Override
protected Integer doInBackground() throws Exception {
for (FileReportModule module : fileModules) {
ReportProgressPanel progress = fileProgress.get(module);
if (progress.getStatus() != ReportStatus.CANCELED) {
progress.start();
progress.updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.queryingDb.text"));
}
}
List<AbstractFile> files = getFiles();
int numFiles = files.size();
for (FileReportModule module : fileModules) {
module.startReport(reportPath);
module.startTable(enabledInfo);
fileProgress.get(module).setIndeterminate(false);
fileProgress.get(module).setMaximumProgress(numFiles);
}
int i = 0;
// Add files to report.
for (AbstractFile file : files) {
// Check to see if any reports have been cancelled.
if (fileModules.isEmpty()) {
break;
}
// Remove cancelled reports, add files to report otherwise.
Iterator<FileReportModule> iter = fileModules.iterator();
while (iter.hasNext()) {
FileReportModule module = iter.next();
ReportProgressPanel progress = fileProgress.get(module);
if (progress.getStatus() == ReportStatus.CANCELED) {
iter.remove();
} else {
module.addRow(file, enabledInfo);
progress.increment();
}
if ((i % 100) == 0) {
progress.updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processingFile.text",
file.getName()));
}
}
i++;
}
for (FileReportModule module : fileModules) {
module.endTable();
module.endReport();
fileProgress.get(module).complete(ReportStatus.COMPLETE);
}
return 0;
}
/**
* Get all files in the image.
*
* @return
*/
private List<AbstractFile> getFiles() {
List<AbstractFile> absFiles;
try {
SleuthkitCase skCase = Case.getCurrentCase().getSleuthkitCase();
absFiles = skCase.findAllFilesWhere("meta_type != " + TskData.TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()); //NON-NLS
return absFiles;
} catch (TskCoreException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports. Unable to get all files in the image.", ex); //NON-NLS
return Collections.<AbstractFile>emptyList();
}
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports", ex); //NON-NLS
} // catch and ignore if we were cancelled
catch (java.util.concurrent.CancellationException ex) {
} finally {
displayReportErrors();
errorList.clear();
}
}
}
/**
* SwingWorker to run TableReportModules to report on blackboard artifacts,
* content tags, and blackboard artifact tags.
*/
private class TableReportsWorker extends SwingWorker<Integer, Integer> {
private List<TableReportModule> tableModules = new ArrayList<>();
private List<ARTIFACT_TYPE> artifactTypes = new ArrayList<>();
private HashSet<String> tagNamesFilter = new HashSet<>();
private List<Content> images = new ArrayList<>();
TableReportsWorker(Map<ARTIFACT_TYPE, Boolean> artifactTypeSelections, Map<String, Boolean> tagNameSelections) {
// Get the report modules selected by the user.
for (Entry<TableReportModule, ReportProgressPanel> entry : tableProgress.entrySet()) {
tableModules.add(entry.getKey());
}
// Get the artifact types selected by the user.
for (Entry<ARTIFACT_TYPE, Boolean> entry : artifactTypeSelections.entrySet()) {
if (entry.getValue()) {
artifactTypes.add(entry.getKey());
}
}
// Get the tag names selected by the user and make a tag names filter.
if (null != tagNameSelections) {
for (Entry<String, Boolean> entry : tagNameSelections.entrySet()) {
if (entry.getValue() == true) {
tagNamesFilter.add(entry.getKey());
}
}
}
}
@Override
protected Integer doInBackground() throws Exception {
// Start the progress indicators for each active TableReportModule.
for (TableReportModule module : tableModules) {
ReportProgressPanel progress = tableProgress.get(module);
if (progress.getStatus() != ReportStatus.CANCELED) {
module.startReport(reportPath);
progress.start();
progress.setIndeterminate(false);
progress.setMaximumProgress(ARTIFACT_TYPE.values().length + 2); // +2 for content and blackboard artifact tags
}
}
// report on the blackboard results
makeBlackboardArtifactTables();
// report on the tagged files and artifacts
makeContentTagsTables();
makeBlackboardArtifactTagsTables();
// report on the tagged images
makeThumbnailTable();
// finish progress, wrap up
for (TableReportModule module : tableModules) {
tableProgress.get(module).complete(ReportStatus.COMPLETE);
module.endReport();
}
return 0;
}
/**
* Generate the tables for the selected blackboard artifacts
*/
private void makeBlackboardArtifactTables() {
// Make a comment string describing the tag names filter in effect.
StringBuilder comment = new StringBuilder();
if (!tagNamesFilter.isEmpty()) {
comment.append(NbBundle.getMessage(this.getClass(), "ReportGenerator.artifactTable.taggedResults.text"));
comment.append(makeCommaSeparatedList(tagNamesFilter));
}
// Add a table to the report for every enabled blackboard artifact type.
for (ARTIFACT_TYPE type : artifactTypes) {
// Check for cancellaton.
removeCancelledTableReportModules();
if (tableModules.isEmpty()) {
return;
}
for (TableReportModule module : tableModules) {
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
type.getDisplayName()));
}
// Keyword hits and hashset hit artifacts get special handling.
if (type.equals(ARTIFACT_TYPE.TSK_KEYWORD_HIT)) {
writeKeywordHits(tableModules, comment.toString(), tagNamesFilter);
continue;
} else if (type.equals(ARTIFACT_TYPE.TSK_HASHSET_HIT)) {
writeHashsetHits(tableModules, comment.toString(), tagNamesFilter);
continue;
}
List<ArtifactData> unsortedArtifacts = getFilteredArtifacts(type, tagNamesFilter);
if (unsortedArtifacts.isEmpty()) {
continue;
}
// The most efficient way to sort all the Artifacts is to add them to a List, and then
// sort that List based off a Comparator. Adding to a TreeMap/Set/List sorts the list
// each time an element is added, which adds unnecessary overhead if we only need it sorted once.
Collections.sort(unsortedArtifacts);
// Get the column headers appropriate for the artifact type.
/*
* @@@ BC: Seems like a better design here would be to have a
* method that takes in the artifact as an argument and returns
* the attributes. We then use that to make the headers and to
* make each row afterwards so that we don't have
* artifact-specific logic in both getArtifactTableCoumnHeaders
* and ArtifactData.getRow()
*/
List<String> columnHeaders = getArtifactTableColumnHeaders(type.getTypeID());
if (columnHeaders == null) {
// @@@ Hack to prevent system from hanging. Better solution is to merge all attributes into a single column or analyze the artifacts to find out how many are needed.
continue;
}
for (TableReportModule module : tableModules) {
module.startDataType(type.getDisplayName(), comment.toString());
module.startTable(columnHeaders);
}
boolean msgSent = false;
for (ArtifactData artifactData : unsortedArtifacts) {
// Add the row data to all of the reports.
for (TableReportModule module : tableModules) {
// Get the row data for this type of artifact.
List<String> rowData = artifactData.getRow();
if (rowData.isEmpty()) {
if (msgSent == false) {
MessageNotifyUtil.Notify.show(NbBundle.getMessage(this.getClass(),
"ReportGenerator.msgShow.skippingArtRow.title",
type),
NbBundle.getMessage(this.getClass(),
"ReportGenerator.msgShow.skippingArtRow.msg"),
MessageNotifyUtil.MessageType.ERROR);
msgSent = true;
}
continue;
}
module.addRow(rowData);
}
}
// Finish up this data type
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endTable();
module.endDataType();
}
}
}
/**
* Make table for tagged files
*/
@SuppressWarnings("deprecation")
private void makeContentTagsTables() {
// Check for cancellaton.
removeCancelledTableReportModules();
if (tableModules.isEmpty()) {
return;
}
// Get the content tags.
List<ContentTag> tags;
try {
tags = Case.getCurrentCase().getServices().getTagsManager().getAllContentTags();
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetContentTags"));
logger.log(Level.SEVERE, "failed to get content tags", ex); //NON-NLS
return;
}
// Tell the modules reporting on content tags is beginning.
for (TableReportModule module : tableModules) {
// @@@ This casting is a tricky little workaround to allow the HTML report module to slip in a content hyperlink.
// @@@ Alos Using the obsolete ARTIFACT_TYPE.TSK_TAG_FILE is also an expedient hack.
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_TAG_FILE.getDisplayName()));
ArrayList<String> columnHeaders = new ArrayList<>(Arrays.asList(
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.tag"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.file"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.comment"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeModified"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeChanged"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeCreated"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.size"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.hash")));
StringBuilder comment = new StringBuilder();
if (!tagNamesFilter.isEmpty()) {
comment.append(
NbBundle.getMessage(this.getClass(), "ReportGenerator.makeContTagTab.taggedFiles.msg"));
comment.append(makeCommaSeparatedList(tagNamesFilter));
}
if (module instanceof ReportHTML) {
ReportHTML htmlReportModule = (ReportHTML) module;
htmlReportModule.startDataType(ARTIFACT_TYPE.TSK_TAG_FILE.getDisplayName(), comment.toString());
htmlReportModule.startContentTagsTable(columnHeaders);
} else {
module.startDataType(ARTIFACT_TYPE.TSK_TAG_FILE.getDisplayName(), comment.toString());
module.startTable(columnHeaders);
}
}
// Give the modules the rows for the content tags.
for (ContentTag tag : tags) {
// skip tags that we are not reporting on
if (passesTagNamesFilter(tag.getName().getDisplayName()) == false) {
continue;
}
String fileName;
try {
fileName = tag.getContent().getUniquePath();
} catch (TskCoreException ex) {
fileName = tag.getContent().getName();
}
ArrayList<String> rowData = new ArrayList<>(Arrays.asList(tag.getName().getDisplayName(), fileName, tag.getComment()));
for (TableReportModule module : tableModules) {
// @@@ This casting is a tricky little workaround to allow the HTML report module to slip in a content hyperlink.
if (module instanceof ReportHTML) {
ReportHTML htmlReportModule = (ReportHTML) module;
htmlReportModule.addRowWithTaggedContentHyperlink(rowData, tag);
} else {
module.addRow(rowData);
}
}
// see if it is for an image so that we later report on it
checkIfTagHasImage(tag);
}
// The the modules content tags reporting is ended.
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endTable();
module.endDataType();
}
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports", ex); //NON-NLS
} // catch and ignore if we were cancelled
catch (java.util.concurrent.CancellationException ex) {
} finally {
displayReportErrors();
errorList.clear();
}
}
/**
* Generate the tables for the tagged artifacts
*/
@SuppressWarnings("deprecation")
private void makeBlackboardArtifactTagsTables() {
// Check for cancellaton.
removeCancelledTableReportModules();
if (tableModules.isEmpty()) {
return;
}
List<BlackboardArtifactTag> tags;
try {
tags = Case.getCurrentCase().getServices().getTagsManager().getAllBlackboardArtifactTags();
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetBBArtifactTags"));
logger.log(Level.SEVERE, "failed to get blackboard artifact tags", ex); //NON-NLS
return;
}
// Tell the modules reporting on blackboard artifact tags data type is beginning.
// @@@ Using the obsolete ARTIFACT_TYPE.TSK_TAG_ARTIFACT is an expedient hack.
for (TableReportModule module : tableModules) {
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getDisplayName()));
StringBuilder comment = new StringBuilder();
if (!tagNamesFilter.isEmpty()) {
comment.append(
NbBundle.getMessage(this.getClass(), "ReportGenerator.makeBbArtTagTab.taggedRes.msg"));
comment.append(makeCommaSeparatedList(tagNamesFilter));
}
module.startDataType(ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getDisplayName(), comment.toString());
module.startTable(new ArrayList<>(Arrays.asList(
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.resultType"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.tag"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.comment"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.srcFile"))));
}
// Give the modules the rows for the content tags.
for (BlackboardArtifactTag tag : tags) {
if (passesTagNamesFilter(tag.getName().getDisplayName()) == false) {
continue;
}
List<String> row;
for (TableReportModule module : tableModules) {
row = new ArrayList<>(Arrays.asList(tag.getArtifact().getArtifactTypeName(), tag.getName().getDisplayName(), tag.getComment(), tag.getContent().getName()));
module.addRow(row);
}
// check if the tag is an image that we should later make a thumbnail for
checkIfTagHasImage(tag);
}
// The the modules blackboard artifact tags reporting is ended.
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endTable();
module.endDataType();
}
}
/**
* Test if the user requested that this tag be reported on
*
* @param tagName
*
* @return true if it should be reported on
*/
private boolean passesTagNamesFilter(String tagName) {
return tagNamesFilter.isEmpty() || tagNamesFilter.contains(tagName);
}
void removeCancelledTableReportModules() {
Iterator<TableReportModule> iter = tableModules.iterator();
while (iter.hasNext()) {
TableReportModule module = iter.next();
if (tableProgress.get(module).getStatus() == ReportStatus.CANCELED) {
iter.remove();
}
}
}
/**
* Make a report for the files that were previously found to be images.
*/
private void makeThumbnailTable() {
for (TableReportModule module : tableModules) {
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.createdThumb.text"));
if (module instanceof ReportHTML) {
ReportHTML htmlModule = (ReportHTML) module;
htmlModule.startDataType(
NbBundle.getMessage(this.getClass(), "ReportGenerator.thumbnailTable.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.thumbnailTable.desc"));
List<String> emptyHeaders = new ArrayList<>();
for (int i = 0; i < ReportHTML.THUMBNAIL_COLUMNS; i++) {
emptyHeaders.add("");
}
htmlModule.startTable(emptyHeaders);
htmlModule.addThumbnailRows(images);
htmlModule.endTable();
htmlModule.endDataType();
}
}
}
/**
* Analyze artifact associated with tag and add to internal list if it
* is associated with an image.
*
* @param artifactTag
*/
private void checkIfTagHasImage(BlackboardArtifactTag artifactTag) {
AbstractFile file;
try {
file = Case.getCurrentCase().getSleuthkitCase().getAbstractFileById(artifactTag.getArtifact().getObjectID());
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.errGetContentFromBBArtifact"));
logger.log(Level.WARNING, "Error while getting content from a blackboard artifact to report on.", ex); //NON-NLS
return;
}
if (file != null) {
checkIfFileIsImage(file);
}
}
/**
* Analyze file that tag is associated with and determine if it is an
* image and should have a thumbnail reported for it. Images are added
* to internal list.
*
* @param contentTag
*/
private void checkIfTagHasImage(ContentTag contentTag) {
Content c = contentTag.getContent();
if (c instanceof AbstractFile == false) {
return;
}
checkIfFileIsImage((AbstractFile) c);
}
/**
* If file is an image file, add it to the internal 'images' list.
*
* @param file
*/
private void checkIfFileIsImage(AbstractFile file) {
if (file.isDir()
|| file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS
|| file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS) {
return;
}
if (ImageUtils.thumbnailSupported(file)) {
images.add(file);
}
}
}
/// @@@ Should move the methods specific to TableReportsWorker into that scope.
private Boolean failsTagFilter(HashSet<String> tagNames, HashSet<String> tagsNamesFilter) {
if (null == tagsNamesFilter || tagsNamesFilter.isEmpty()) {
return false;
}
HashSet<String> filteredTagNames = new HashSet<>(tagNames);
filteredTagNames.retainAll(tagsNamesFilter);
return filteredTagNames.isEmpty();
}
/**
* Get a List of the artifacts and data of the given type that pass the
* given Tag Filter.
*
* @param type The artifact type to get
* @param tagNamesFilter The tag names that should be included.
*
* @return a list of the filtered tags.
*/
private List<ArtifactData> getFilteredArtifacts(ARTIFACT_TYPE type, HashSet<String> tagNamesFilter) {
List<ArtifactData> artifacts = new ArrayList<>();
try {
for (BlackboardArtifact artifact : skCase.getBlackboardArtifacts(type)) {
List<BlackboardArtifactTag> tags = Case.getCurrentCase().getServices().getTagsManager().getBlackboardArtifactTagsByArtifact(artifact);
HashSet<String> uniqueTagNames = new HashSet<>();
for (BlackboardArtifactTag tag : tags) {
uniqueTagNames.add(tag.getName().getDisplayName());
}
if (failsTagFilter(uniqueTagNames, tagNamesFilter)) {
continue;
}
try {
artifacts.add(new ArtifactData(artifact, skCase.getBlackboardAttributes(artifact), uniqueTagNames));
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetBBAttribs"));
logger.log(Level.SEVERE, "Failed to get Blackboard Attributes when generating report.", ex); //NON-NLS
}
}
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetBBArtifacts"));
logger.log(Level.SEVERE, "Failed to get Blackboard Artifacts when generating report.", ex); //NON-NLS
}
return artifacts;
}
/**
* Write the keyword hits to the provided TableReportModules.
*
* @param tableModules modules to report on
*/
@SuppressWarnings("deprecation")
private void writeKeywordHits(List<TableReportModule> tableModules, String comment, HashSet<String> tagNamesFilter) {
// Query for keyword lists-only so that we can tell modules what lists
// will exist for their index.
// @@@ There is a bug in here. We should use the tags in the below code
// so that we only report the lists that we will later provide with real
// hits. If no keyord hits are tagged, then we make the page for nothing.
String orderByClause;
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att.value_text, 'SQL_ASCII') ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY list ASC"; //NON-NLS
}
String keywordListQuery
= "SELECT att.value_text AS list " + //NON-NLS
"FROM blackboard_attributes AS att, blackboard_artifacts AS art " + //NON-NLS
"WHERE att.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + " " + //NON-NLS
"AND art.artifact_type_id = " + ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID() + " " + //NON-NLS
"AND att.artifact_id = art.artifact_id " + //NON-NLS
"GROUP BY list " + orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(keywordListQuery)) {
ResultSet listsRs = dbQuery.getResultSet();
List<String> lists = new ArrayList<>();
while (listsRs.next()) {
String list = listsRs.getString("list"); //NON-NLS
if (list.isEmpty()) {
list = NbBundle.getMessage(this.getClass(), "ReportGenerator.writeKwHits.userSrchs");
}
lists.add(list);
}
// Make keyword data type and give them set index
for (TableReportModule module : tableModules) {
module.startDataType(ARTIFACT_TYPE.TSK_KEYWORD_HIT.getDisplayName(), comment);
module.addSetIndex(lists);
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_KEYWORD_HIT.getDisplayName()));
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryKWLists"));
logger.log(Level.SEVERE, "Failed to query keyword lists: ", ex); //NON-NLS
return;
}
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att3.value_text, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(att1.value_text, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.parent_path, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.name, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(att2.value_text, 'SQL_ASCII') ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY list ASC, keyword ASC, parent_path ASC, name ASC, preview ASC"; //NON-NLS
}
// Query for keywords, grouped by list
String keywordsQuery
= "SELECT art.artifact_id, art.obj_id, att1.value_text AS keyword, att2.value_text AS preview, att3.value_text AS list, f.name AS name, f.parent_path AS parent_path " + //NON-NLS
"FROM blackboard_artifacts AS art, blackboard_attributes AS att1, blackboard_attributes AS att2, blackboard_attributes AS att3, tsk_files AS f " + //NON-NLS
"WHERE (att1.artifact_id = art.artifact_id) " + //NON-NLS
"AND (att2.artifact_id = art.artifact_id) " + //NON-NLS
"AND (att3.artifact_id = art.artifact_id) " + //NON-NLS
"AND (f.obj_id = art.obj_id) " + //NON-NLS
"AND (att1.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_KEYWORD.getTypeID() + ") " + //NON-NLS
"AND (att2.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW.getTypeID() + ") " + //NON-NLS
"AND (att3.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + ") " + //NON-NLS
"AND (art.artifact_type_id = " + ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID() + ") " + //NON-NLS
orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(keywordsQuery)) {
ResultSet resultSet = dbQuery.getResultSet();
String currentKeyword = "";
String currentList = "";
while (resultSet.next()) {
// Check to see if all the TableReportModules have been canceled
if (tableModules.isEmpty()) {
break;
}
Iterator<TableReportModule> iter = tableModules.iterator();
while (iter.hasNext()) {
TableReportModule module = iter.next();
if (tableProgress.get(module).getStatus() == ReportStatus.CANCELED) {
iter.remove();
}
}
// Get any tags that associated with this artifact and apply the tag filter.
HashSet<String> uniqueTagNames = getUniqueTagNames(resultSet.getLong("artifact_id")); //NON-NLS
if (failsTagFilter(uniqueTagNames, tagNamesFilter)) {
continue;
}
String tagsList = makeCommaSeparatedList(uniqueTagNames);
Long objId = resultSet.getLong("obj_id"); //NON-NLS
String keyword = resultSet.getString("keyword"); //NON-NLS
String preview = resultSet.getString("preview"); //NON-NLS
String list = resultSet.getString("list"); //NON-NLS
String uniquePath = "";
try {
AbstractFile f = skCase.getAbstractFileById(objId);
if (f != null) {
uniquePath = skCase.getAbstractFileById(objId).getUniquePath();
}
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetAbstractFileByID"));
logger.log(Level.WARNING, "Failed to get Abstract File by ID.", ex); //NON-NLS
}
// If the lists aren't the same, we've started a new list
if ((!list.equals(currentList) && !list.isEmpty()) || (list.isEmpty() && !currentList.equals(
NbBundle.getMessage(this.getClass(), "ReportGenerator.writeKwHits.userSrchs")))) {
if (!currentList.isEmpty()) {
for (TableReportModule module : tableModules) {
module.endTable();
module.endSet();
}
}
currentList = list.isEmpty() ? NbBundle
.getMessage(this.getClass(), "ReportGenerator.writeKwHits.userSrchs") : list;
currentKeyword = ""; // reset the current keyword because it's a new list
for (TableReportModule module : tableModules) {
module.startSet(currentList);
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processingList",
ARTIFACT_TYPE.TSK_KEYWORD_HIT.getDisplayName(), currentList));
}
}
if (!keyword.equals(currentKeyword)) {
if (!currentKeyword.equals("")) {
for (TableReportModule module : tableModules) {
module.endTable();
}
}
currentKeyword = keyword;
for (TableReportModule module : tableModules) {
module.addSetElement(currentKeyword);
module.startTable(getArtifactTableColumnHeaders(ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID()));
}
}
String previewreplace = EscapeUtil.escapeHtml(preview);
for (TableReportModule module : tableModules) {
module.addRow(Arrays.asList(new String[]{previewreplace.replaceAll("<!", ""), uniquePath, tagsList}));
}
}
// Finish the current data type
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endDataType();
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryKWs"));
logger.log(Level.SEVERE, "Failed to query keywords: ", ex); //NON-NLS
}
}
/**
* Write the hash set hits to the provided TableReportModules.
*
* @param tableModules modules to report on
*/
@SuppressWarnings("deprecation")
private void writeHashsetHits(List<TableReportModule> tableModules, String comment, HashSet<String> tagNamesFilter) {
String orderByClause;
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att.value_text, 'SQL_ASCII') ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY att.value_text ASC"; //NON-NLS
}
String hashsetsQuery
= "SELECT att.value_text AS list " + //NON-NLS
"FROM blackboard_attributes AS att, blackboard_artifacts AS art " + //NON-NLS
"WHERE att.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + " " + //NON-NLS
"AND art.artifact_type_id = " + ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID() + " " + //NON-NLS
"AND att.artifact_id = art.artifact_id " + //NON-NLS
"GROUP BY list " + orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(hashsetsQuery)) {
// Query for hashsets
ResultSet listsRs = dbQuery.getResultSet();
List<String> lists = new ArrayList<>();
while (listsRs.next()) {
lists.add(listsRs.getString("list")); //NON-NLS
}
for (TableReportModule module : tableModules) {
module.startDataType(ARTIFACT_TYPE.TSK_HASHSET_HIT.getDisplayName(), comment);
module.addSetIndex(lists);
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_HASHSET_HIT.getDisplayName()));
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryHashsetLists"));
logger.log(Level.SEVERE, "Failed to query hashset lists: ", ex); //NON-NLS
return;
}
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att.value_text, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.parent_path, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.name, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "size ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY att.value_text ASC, f.parent_path ASC, f.name ASC, size ASC"; //NON-NLS
}
String hashsetHitsQuery
= "SELECT art.artifact_id, art.obj_id, att.value_text AS setname, f.name AS name, f.size AS size, f.parent_path AS parent_path " + //NON-NLS
"FROM blackboard_artifacts AS art, blackboard_attributes AS att, tsk_files AS f " + //NON-NLS
"WHERE (att.artifact_id = art.artifact_id) " + //NON-NLS
"AND (f.obj_id = art.obj_id) " + //NON-NLS
"AND (att.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + ") " + //NON-NLS
"AND (art.artifact_type_id = " + ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID() + ") " + //NON-NLS
orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(hashsetHitsQuery)) {
// Query for hashset hits
ResultSet resultSet = dbQuery.getResultSet();
String currentSet = "";
while (resultSet.next()) {
// Check to see if all the TableReportModules have been canceled
if (tableModules.isEmpty()) {
break;
}
Iterator<TableReportModule> iter = tableModules.iterator();
while (iter.hasNext()) {
TableReportModule module = iter.next();
if (tableProgress.get(module).getStatus() == ReportStatus.CANCELED) {
iter.remove();
}
}
// Get any tags that associated with this artifact and apply the tag filter.
HashSet<String> uniqueTagNames = getUniqueTagNames(resultSet.getLong("artifact_id")); //NON-NLS
if (failsTagFilter(uniqueTagNames, tagNamesFilter)) {
continue;
}
String tagsList = makeCommaSeparatedList(uniqueTagNames);
Long objId = resultSet.getLong("obj_id"); //NON-NLS
String set = resultSet.getString("setname"); //NON-NLS
String size = resultSet.getString("size"); //NON-NLS
String uniquePath = "";
try {
AbstractFile f = skCase.getAbstractFileById(objId);
if (f != null) {
uniquePath = skCase.getAbstractFileById(objId).getUniquePath();
}
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetAbstractFileFromID"));
logger.log(Level.WARNING, "Failed to get Abstract File from ID.", ex); //NON-NLS
return;
}
// If the sets aren't the same, we've started a new set
if (!set.equals(currentSet)) {
if (!currentSet.isEmpty()) {
for (TableReportModule module : tableModules) {
module.endTable();
module.endSet();
}
}
currentSet = set;
for (TableReportModule module : tableModules) {
module.startSet(currentSet);
module.startTable(getArtifactTableColumnHeaders(ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID()));
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processingList",
ARTIFACT_TYPE.TSK_HASHSET_HIT.getDisplayName(), currentSet));
}
}
// Add a row for this hit to every module
for (TableReportModule module : tableModules) {
module.addRow(Arrays.asList(new String[]{uniquePath, size, tagsList}));
}
}
// Finish the current data type
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endDataType();
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryHashsetHits"));
logger.log(Level.SEVERE, "Failed to query hashsets hits: ", ex); //NON-NLS
}
}
/**
* For a given artifact type ID, return the list of the row titles we're
* reporting on.
*
* @param artifactTypeId artifact type ID
*
* @return List<String> row titles
*/
private List<String> getArtifactTableColumnHeaders(int artifactTypeId) {
ArrayList<String> columnHeaders;
BlackboardArtifact.ARTIFACT_TYPE type = BlackboardArtifact.ARTIFACT_TYPE.fromID(artifactTypeId);
switch (type) {
case TSK_WEB_BOOKMARK:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.title"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateCreated"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_COOKIE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.value"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_HISTORY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.referrer"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.title"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.urlDomainDecoded"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_DOWNLOAD:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dest"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.sourceUrl"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_RECENT_OBJECT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.path"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_INSTALLED_PROG:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.progName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.instDateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_KEYWORD_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.preview"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_HASHSET_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.file"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.size")}));
break;
case TSK_DEVICE_ATTACHED:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devMake"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devModel"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.deviceId"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_SEARCH_QUERY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.domain"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.progName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_METADATA_EXIF:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTaken"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devManufacturer"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devModel"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_CONTACT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumber"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumHome"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumOffice"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumMobile"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.email"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_MESSAGE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.msgType"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.direction"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.readStatus"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.fromPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.fromEmail"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.toPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.toEmail"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.subject"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_CALLLOG:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.fromPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.toPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.direction"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_CALENDAR_ENTRY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.calendarEntryType"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.description"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.startDateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.endDateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.location"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_SPEED_DIAL_ENTRY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.shortCut"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumber"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_BLUETOOTH_PAIRING:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.deviceName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.deviceAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_TRACKPOINT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_BOOKMARK:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.locationAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_LAST_KNOWN_LOCATION:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.locationAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_SEARCH:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.locationAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_SERVICE_ACCOUNT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.category"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.userId"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.password"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.appName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.appPath"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.description"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.replytoAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.mailServer"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_ENCRYPTION_DETECTED:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_EXT_MISMATCH_DETECTED:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.file"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.extension.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.mimeType.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.path")}));
break;
case TSK_OS_INFO:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.processorArchitecture.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.osName.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.osInstallDate.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_EMAIL_MSG:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailTo"), //TSK_EMAIL_TO
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailFrom"), //TSK_EMAIL_FROM
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskSubject"), //TSK_SUBJECT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskDateTimeSent"), //TSK_DATETIME_SENT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskDateTimeRcvd"), //TSK_DATETIME_RCVD
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskPath"), //TSK_PATH
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailCc"), //TSK_EMAIL_CC
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailBcc"), //TSK_EMAIL_BCC
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskMsgId")})); //TSK_MSG_ID
break;
case TSK_INTERESTING_FILE_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskSetName"), //TSK_SET_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskInterestingFilesCategory"), //TSK_CATEGORY
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskPath")})); //TSK_PATH
break;
case TSK_GPS_ROUTE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskGpsRouteCategory"), //TSK_CATEGORY
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"), //TSK_DATETIME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitudeEnd"), //TSK_GEO_LATITUDE_END
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitudeEnd"), //TSK_GEO_LONGITUDE_END
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitudeStart"), //TSK_GEO_LATITUDE_START
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitudeStart"), //TSK_GEO_LONGITUDE_START
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"), //TSK_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.location"), //TSK_LOCATION
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program")}));//TSK_PROG_NAME
break;
case TSK_INTERESTING_ARTIFACT_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskSetName"), //TSK_SET_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.associatedArtifact"), //TSK_ASSOCIATED_ARTIFACT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program")})); //TSK_PROG_NAME
break;
case TSK_PROG_RUN:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"), //TSK_PROG_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.associatedArtifact"), //TSK_ASSOCIATED_ARTIFACT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"), //TSK_DATETIME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.count")})); //TSK_COUNT
break;
case TSK_OS_ACCOUNT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.userName"), //TSK_USER_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.userId")})); //TSK_USER_ID
break;
case TSK_REMOTE_DRIVE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.localPath"), //TSK_LOCAL_PATH
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.remotePath")})); //TSK_REMOTE_PATH
break;
default:
return null;
}
columnHeaders.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tags"));
return columnHeaders;
}
/**
* Map all BlackboardAttributes' values in a list of BlackboardAttributes to
* each attribute's attribute type ID, using module's dateToString method
* for date/time conversions if a module is supplied.
*
* @param attList list of BlackboardAttributes to be mapped
* @param module the TableReportModule the mapping is for
*
* @return Map<Integer, String> of the BlackboardAttributes mapped to their
* attribute type ID
*/
public Map<Integer, String> getMappedAttributes(List<BlackboardAttribute> attList, TableReportModule... module) {
Map<Integer, String> attributes = new HashMap<>();
int size = ATTRIBUTE_TYPE.values().length;
for (int n = 0; n <= size; n++) {
attributes.put(n, "");
}
for (BlackboardAttribute tempatt : attList) {
String value = "";
Integer type = tempatt.getAttributeTypeID();
if (type.equals(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_CREATED.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_MODIFIED.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_SENT.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_RCVD.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_START.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_END.getTypeID())) {
if (module.length > 0) {
value = module[0].dateToString(tempatt.getValueLong());
} else {
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
value = sdf.format(new java.util.Date((tempatt.getValueLong() * 1000)));
}
} else {
value = tempatt.getDisplayString();
}
if (value == null) {
value = "";
}
value = EscapeUtil.escapeHtml(value);
attributes.put(type, value);
}
return attributes;
}
/**
* Converts a collection of strings into a single string of comma-separated
* items
*
* @param items A collection of strings
*
* @return A string of comma-separated items
*/
private String makeCommaSeparatedList(Collection<String> items) {
String list = "";
for (Iterator<String> iterator = items.iterator(); iterator.hasNext();) {
list += iterator.next() + (iterator.hasNext() ? ", " : "");
}
return list;
}
/**
* Given a tsk_file's obj_id, return the unique path of that file.
*
* @param objId tsk_file obj_id
*
* @return String unique path
*/
private String getFileUniquePath(long objId) {
try {
AbstractFile af = skCase.getAbstractFileById(objId);
if (af != null) {
return af.getUniquePath();
} else {
return "";
}
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetAbstractFileByID"));
logger.log(Level.WARNING, "Failed to get Abstract File by ID.", ex); //NON-NLS
}
return "";
}
/**
* Container class that holds data about an Artifact to eliminate duplicate
* calls to the Sleuthkit database.
*/
private class ArtifactData implements Comparable<ArtifactData> {
private BlackboardArtifact artifact;
private List<BlackboardAttribute> attributes;
private HashSet<String> tags;
private List<String> rowData = null;
ArtifactData(BlackboardArtifact artifact, List<BlackboardAttribute> attrs, HashSet<String> tags) {
this.artifact = artifact;
this.attributes = attrs;
this.tags = tags;
}
public BlackboardArtifact getArtifact() {
return artifact;
}
public List<BlackboardAttribute> getAttributes() {
return attributes;
}
public HashSet<String> getTags() {
return tags;
}
public long getArtifactID() {
return artifact.getArtifactID();
}
public long getObjectID() {
return artifact.getObjectID();
}
/**
* Compares ArtifactData objects by the first attribute they have in
* common in their List<BlackboardAttribute>.
*
* If all attributes are the same, they are assumed duplicates and are
* compared by their artifact id. Should only be used with attributes of
* the same type.
*/
@Override
public int compareTo(ArtifactData otherArtifactData) {
List<String> thisRow = getRow();
List<String> otherRow = otherArtifactData.getRow();
for (int i = 0; i < thisRow.size(); i++) {
int compare = thisRow.get(i).compareTo(otherRow.get(i));
if (compare != 0) {
return compare;
}
}
// If all attributes are the same, they're most likely duplicates so sort by artifact ID
return ((Long) this.getArtifactID()).compareTo((Long) otherArtifactData.getArtifactID());
}
/**
* Get the values for each row in the table report.
*/
public List<String> getRow() {
if (rowData == null) {
try {
rowData = getOrderedRowDataAsStrings();
// replace null values if attribute was not defined
for (int i = 0; i < rowData.size(); i++) {
if (rowData.get(i) == null) {
rowData.set(i, "");
}
}
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.coreExceptionWhileGenRptRow"));
logger.log(Level.WARNING, "Core exception while generating row data for artifact report.", ex); //NON-NLS
rowData = Collections.<String>emptyList();
}
}
return rowData;
}
/**
* Get a list of Strings with all the row values for the Artifact in the
* correct order to be written to the report.
*
* @return List<String> row values. Values could be null if attribute is
* not defined in artifact
*
* @throws TskCoreException
*/
private List<String> getOrderedRowDataAsStrings() throws TskCoreException {
Map<Integer, String> mappedAttributes = getMappedAttributes();
List<String> orderedRowData = new ArrayList<>();
BlackboardArtifact.ARTIFACT_TYPE type = BlackboardArtifact.ARTIFACT_TYPE.fromID(getArtifact().getArtifactTypeID());
switch (type) {
case TSK_WEB_BOOKMARK:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TITLE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_CREATED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_COOKIE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_HISTORY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_REFERRER.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TITLE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_DOWNLOAD:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_RECENT_OBJECT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_INSTALLED_PROG:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_DEVICE_ATTACHED:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MAKE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MODEL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_ID.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_SEARCH_QUERY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_METADATA_EXIF:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_CREATED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MAKE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MODEL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_CONTACT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_HOME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_OFFICE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_MOBILE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_MESSAGE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_READ_STATUS.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SUBJECT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_CALLLOG:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_CALENDAR_ENTRY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CALENDAR_ENTRY_TYPE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DESCRIPTION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_END.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_SPEED_DIAL_ENTRY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SHORTCUT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME_PERSON.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_BLUETOOTH_PAIRING:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_ID.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_TRACKPOINT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_BOOKMARK:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_LAST_KNOWN_LOCATION:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_SEARCH:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_SERVICE_ACCOUNT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CATEGORY.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_USER_ID.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PASSWORD.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DESCRIPTION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_REPLYTO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SERVER_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_TOOL_OUTPUT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_ENCRYPTION_DETECTED:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_EXT_MISMATCH_DETECTED:
AbstractFile file = skCase.getAbstractFileById(getObjectID());
if (file != null) {
orderedRowData.add(file.getName());
orderedRowData.add(file.getNameExtension());
String mimeType = file.getMIMEType();
if(mimeType == null) {
orderedRowData.add("");
}
else {
orderedRowData.add(mimeType);
}
orderedRowData.add(file.getUniquePath());
} else {
// Make empty rows to make sure the formatting is correct
orderedRowData.add(null);
orderedRowData.add(null);
orderedRowData.add(null);
orderedRowData.add(null);
}
break;
case TSK_OS_INFO:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROCESSOR_ARCHITECTURE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_EMAIL_MSG:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SUBJECT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_SENT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_RCVD.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_CC.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_BCC.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_MSG_ID.getTypeID()));
break;
case TSK_INTERESTING_FILE_HIT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CATEGORY.getTypeID()));
String pathToShow = mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID());
if (pathToShow.isEmpty()) {
pathToShow = getFileUniquePath(getObjectID());
}
orderedRowData.add(pathToShow);
break;
case TSK_GPS_ROUTE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CATEGORY.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_END.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_END.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
break;
case TSK_INTERESTING_ARTIFACT_HIT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
break;
case TSK_PROG_RUN:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_COUNT.getTypeID()));
break;
case TSK_OS_ACCOUNT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_USER_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_USER_ID.getTypeID()));
break;
case TSK_REMOTE_DRIVE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCAL_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_REMOTE_PATH.getTypeID()));
break;
}
orderedRowData.add(makeCommaSeparatedList(getTags()));
return orderedRowData;
}
/**
* Returns a mapping of Attribute Type ID to the String representation
* of an Attribute Value.
*/
private Map<Integer, String> getMappedAttributes() {
return ReportGenerator.this.getMappedAttributes(attributes);
}
}
/**
* Get any tags associated with an artifact
*
* @param artifactId
*
* @return hash set of tag display names
*
* @throws SQLException
*/
@SuppressWarnings("deprecation")
private HashSet<String> getUniqueTagNames(long artifactId) throws TskCoreException {
HashSet<String> uniqueTagNames = new HashSet<>();
String query = "SELECT display_name, artifact_id FROM tag_names AS tn, blackboard_artifact_tags AS bat " + //NON-NLS
"WHERE tn.tag_name_id = bat.tag_name_id AND bat.artifact_id = " + artifactId; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(query)) {
ResultSet tagNameRows = dbQuery.getResultSet();
while (tagNameRows.next()) {
uniqueTagNames.add(tagNameRows.getString("display_name")); //NON-NLS
}
} catch (TskCoreException | SQLException ex) {
throw new TskCoreException("Error getting tag names for artifact: ", ex);
}
return uniqueTagNames;
}
}
| Core/src/org/sleuthkit/autopsy/report/ReportGenerator.java | /*
* Autopsy Forensic Browser
*
* Copyright 2013 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.report;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.EscapeUtil;
import org.sleuthkit.autopsy.coreutils.ImageUtils;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.report.ReportProgressPanel.ReportStatus;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardArtifactTag;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.SleuthkitCase.CaseDbQuery;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* Instances of this class use GeneralReportModules, TableReportModules and
* FileReportModules to generate a report. If desired, displayProgressPanels()
* can be called to show report generation progress using ReportProgressPanel
* objects displayed using a dialog box.
*/
class ReportGenerator {
private static final Logger logger = Logger.getLogger(ReportGenerator.class.getName());
private Case currentCase = Case.getCurrentCase();
private SleuthkitCase skCase = currentCase.getSleuthkitCase();
private Map<TableReportModule, ReportProgressPanel> tableProgress;
private Map<GeneralReportModule, ReportProgressPanel> generalProgress;
private Map<FileReportModule, ReportProgressPanel> fileProgress;
private String reportPath;
private ReportGenerationPanel panel = new ReportGenerationPanel();
static final String REPORTS_DIR = "Reports"; //NON-NLS
private List<String> errorList;
/**
* Displays the list of errors during report generation in user-friendly
* way. MessageNotifyUtil used to display bubble notification.
*
* @param listOfErrors List of strings explaining the errors.
*/
private void displayReportErrors() {
if (!errorList.isEmpty()) {
String errorString = "";
for (String error : errorList) {
errorString += error + "\n";
}
MessageNotifyUtil.Notify.error(
NbBundle.getMessage(this.getClass(), "ReportGenerator.notifyErr.errsDuringRptGen"), errorString);
return;
}
}
ReportGenerator(Map<TableReportModule, Boolean> tableModuleStates, Map<GeneralReportModule, Boolean> generalModuleStates, Map<FileReportModule, Boolean> fileListModuleStates) {
// Create the root reports directory path of the form: <CASE DIRECTORY>/Reports/<Case fileName> <Timestamp>/
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy-HH-mm-ss");
Date date = new Date();
String dateNoTime = dateFormat.format(date);
this.reportPath = currentCase.getReportDirectory() + File.separator + currentCase.getName() + " " + dateNoTime + File.separator;
this.errorList = new ArrayList<String>();
// Create the root reports directory.
try {
FileUtil.createFolder(new File(this.reportPath));
} catch (IOException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedMakeRptFolder"));
logger.log(Level.SEVERE, "Failed to make report folder, may be unable to generate reports.", ex); //NON-NLS
return;
}
// Initialize the progress panels
generalProgress = new HashMap<>();
tableProgress = new HashMap<>();
fileProgress = new HashMap<>();
setupProgressPanels(tableModuleStates, generalModuleStates, fileListModuleStates);
}
/**
* Create a ReportProgressPanel for each report generation module selected
* by the user.
*
* @param tableModuleStates The enabled/disabled state of each
* TableReportModule
* @param generalModuleStates The enabled/disabled state of each
* GeneralReportModule
* @param fileListModuleStates The enabled/disabled state of each
* FileReportModule
*/
private void setupProgressPanels(Map<TableReportModule, Boolean> tableModuleStates, Map<GeneralReportModule, Boolean> generalModuleStates, Map<FileReportModule, Boolean> fileListModuleStates) {
if (null != tableModuleStates) {
for (Entry<TableReportModule, Boolean> entry : tableModuleStates.entrySet()) {
if (entry.getValue()) {
TableReportModule module = entry.getKey();
String reportFilePath = module.getRelativeFilePath();
if (!reportFilePath.isEmpty()) {
tableProgress.put(module, panel.addReport(module.getName(), reportPath + reportFilePath));
} else {
tableProgress.put(module, panel.addReport(module.getName(), null));
}
}
}
}
if (null != generalModuleStates) {
for (Entry<GeneralReportModule, Boolean> entry : generalModuleStates.entrySet()) {
if (entry.getValue()) {
GeneralReportModule module = entry.getKey();
String reportFilePath = module.getRelativeFilePath();
if (!reportFilePath.isEmpty()) {
generalProgress.put(module, panel.addReport(module.getName(), reportPath + reportFilePath));
} else {
generalProgress.put(module, panel.addReport(module.getName(), null));
}
}
}
}
if (null != fileListModuleStates) {
for (Entry<FileReportModule, Boolean> entry : fileListModuleStates.entrySet()) {
if (entry.getValue()) {
FileReportModule module = entry.getKey();
String reportFilePath = module.getRelativeFilePath();
if (!reportFilePath.isEmpty()) {
fileProgress.put(module, panel.addReport(module.getName(), reportPath + reportFilePath));
} else {
fileProgress.put(module, panel.addReport(module.getName(), null));
}
}
}
}
}
/**
* Display the progress panels to the user, and add actions to close the
* parent dialog.
*/
public void displayProgressPanels() {
final JDialog dialog = new JDialog(new JFrame(), true);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setTitle(NbBundle.getMessage(this.getClass(), "ReportGenerator.displayProgress.title.text"));
dialog.add(this.panel);
dialog.pack();
panel.addCloseAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
panel.close();
}
});
Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
int w = dialog.getSize().width;
int h = dialog.getSize().height;
// set the location of the popUp Window on the center of the screen
dialog.setLocation((screenDimension.width - w) / 2, (screenDimension.height - h) / 2);
dialog.setVisible(true);
}
/**
* Run the GeneralReportModules using a SwingWorker.
*/
public void generateGeneralReports() {
GeneralReportsWorker worker = new GeneralReportsWorker();
worker.execute();
}
/**
* Run the TableReportModules using a SwingWorker.
*
* @param artifactTypeSelections the enabled/disabled state of the artifact
* types to be included in the report
* @param tagSelections the enabled/disabled state of the tag names to be
* included in the report
*/
public void generateTableReports(Map<ARTIFACT_TYPE, Boolean> artifactTypeSelections, Map<String, Boolean> tagNameSelections) {
if (!tableProgress.isEmpty() && null != artifactTypeSelections) {
TableReportsWorker worker = new TableReportsWorker(artifactTypeSelections, tagNameSelections);
worker.execute();
}
}
/**
* Run the FileReportModules using a SwingWorker.
*
* @param enabledInfo the Information that should be included about each
* file in the report.
*/
public void generateFileListReports(Map<FileReportDataTypes, Boolean> enabledInfo) {
if (!fileProgress.isEmpty() && null != enabledInfo) {
List<FileReportDataTypes> enabled = new ArrayList<>();
for (Entry<FileReportDataTypes, Boolean> e : enabledInfo.entrySet()) {
if (e.getValue()) {
enabled.add(e.getKey());
}
}
FileReportsWorker worker = new FileReportsWorker(enabled);
worker.execute();
}
}
/**
* SwingWorker to run GeneralReportModules.
*/
private class GeneralReportsWorker extends SwingWorker<Integer, Integer> {
@Override
protected Integer doInBackground() throws Exception {
for (Entry<GeneralReportModule, ReportProgressPanel> entry : generalProgress.entrySet()) {
GeneralReportModule module = entry.getKey();
if (generalProgress.get(module).getStatus() != ReportStatus.CANCELED) {
module.generateReport(reportPath, generalProgress.get(module));
}
}
return 0;
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports", ex); //NON-NLS
} // catch and ignore if we were cancelled
catch (java.util.concurrent.CancellationException ex) {
} finally {
displayReportErrors();
errorList.clear();
}
}
}
/**
* SwingWorker to run FileReportModules.
*/
private class FileReportsWorker extends SwingWorker<Integer, Integer> {
private List<FileReportDataTypes> enabledInfo = Arrays.asList(FileReportDataTypes.values());
private List<FileReportModule> fileModules = new ArrayList<>();
FileReportsWorker(List<FileReportDataTypes> enabled) {
enabledInfo = enabled;
for (Entry<FileReportModule, ReportProgressPanel> entry : fileProgress.entrySet()) {
fileModules.add(entry.getKey());
}
}
@Override
protected Integer doInBackground() throws Exception {
for (FileReportModule module : fileModules) {
ReportProgressPanel progress = fileProgress.get(module);
if (progress.getStatus() != ReportStatus.CANCELED) {
progress.start();
progress.updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.queryingDb.text"));
}
}
List<AbstractFile> files = getFiles();
int numFiles = files.size();
for (FileReportModule module : fileModules) {
module.startReport(reportPath);
module.startTable(enabledInfo);
fileProgress.get(module).setIndeterminate(false);
fileProgress.get(module).setMaximumProgress(numFiles);
}
int i = 0;
// Add files to report.
for (AbstractFile file : files) {
// Check to see if any reports have been cancelled.
if (fileModules.isEmpty()) {
break;
}
// Remove cancelled reports, add files to report otherwise.
Iterator<FileReportModule> iter = fileModules.iterator();
while (iter.hasNext()) {
FileReportModule module = iter.next();
ReportProgressPanel progress = fileProgress.get(module);
if (progress.getStatus() == ReportStatus.CANCELED) {
iter.remove();
} else {
module.addRow(file, enabledInfo);
progress.increment();
}
if ((i % 100) == 0) {
progress.updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processingFile.text",
file.getName()));
}
}
i++;
}
for (FileReportModule module : fileModules) {
module.endTable();
module.endReport();
fileProgress.get(module).complete(ReportStatus.COMPLETE);
}
return 0;
}
/**
* Get all files in the image.
*
* @return
*/
private List<AbstractFile> getFiles() {
List<AbstractFile> absFiles;
try {
SleuthkitCase skCase = Case.getCurrentCase().getSleuthkitCase();
absFiles = skCase.findAllFilesWhere("meta_type != " + TskData.TSK_FS_META_TYPE_ENUM.TSK_FS_META_TYPE_DIR.getValue()); //NON-NLS
return absFiles;
} catch (TskCoreException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports. Unable to get all files in the image.", ex); //NON-NLS
return Collections.<AbstractFile>emptyList();
}
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports", ex); //NON-NLS
} // catch and ignore if we were cancelled
catch (java.util.concurrent.CancellationException ex) {
} finally {
displayReportErrors();
errorList.clear();
}
}
}
/**
* SwingWorker to run TableReportModules to report on blackboard artifacts,
* content tags, and blackboard artifact tags.
*/
private class TableReportsWorker extends SwingWorker<Integer, Integer> {
private List<TableReportModule> tableModules = new ArrayList<>();
private List<ARTIFACT_TYPE> artifactTypes = new ArrayList<>();
private HashSet<String> tagNamesFilter = new HashSet<>();
private List<Content> images = new ArrayList<>();
TableReportsWorker(Map<ARTIFACT_TYPE, Boolean> artifactTypeSelections, Map<String, Boolean> tagNameSelections) {
// Get the report modules selected by the user.
for (Entry<TableReportModule, ReportProgressPanel> entry : tableProgress.entrySet()) {
tableModules.add(entry.getKey());
}
// Get the artifact types selected by the user.
for (Entry<ARTIFACT_TYPE, Boolean> entry : artifactTypeSelections.entrySet()) {
if (entry.getValue()) {
artifactTypes.add(entry.getKey());
}
}
// Get the tag names selected by the user and make a tag names filter.
if (null != tagNameSelections) {
for (Entry<String, Boolean> entry : tagNameSelections.entrySet()) {
if (entry.getValue() == true) {
tagNamesFilter.add(entry.getKey());
}
}
}
}
@Override
protected Integer doInBackground() throws Exception {
// Start the progress indicators for each active TableReportModule.
for (TableReportModule module : tableModules) {
ReportProgressPanel progress = tableProgress.get(module);
if (progress.getStatus() != ReportStatus.CANCELED) {
module.startReport(reportPath);
progress.start();
progress.setIndeterminate(false);
progress.setMaximumProgress(ARTIFACT_TYPE.values().length + 2); // +2 for content and blackboard artifact tags
}
}
// report on the blackboard results
makeBlackboardArtifactTables();
// report on the tagged files and artifacts
makeContentTagsTables();
makeBlackboardArtifactTagsTables();
// report on the tagged images
makeThumbnailTable();
// finish progress, wrap up
for (TableReportModule module : tableModules) {
tableProgress.get(module).complete(ReportStatus.COMPLETE);
module.endReport();
}
return 0;
}
/**
* Generate the tables for the selected blackboard artifacts
*/
private void makeBlackboardArtifactTables() {
// Make a comment string describing the tag names filter in effect.
StringBuilder comment = new StringBuilder();
if (!tagNamesFilter.isEmpty()) {
comment.append(NbBundle.getMessage(this.getClass(), "ReportGenerator.artifactTable.taggedResults.text"));
comment.append(makeCommaSeparatedList(tagNamesFilter));
}
// Add a table to the report for every enabled blackboard artifact type.
for (ARTIFACT_TYPE type : artifactTypes) {
// Check for cancellaton.
removeCancelledTableReportModules();
if (tableModules.isEmpty()) {
return;
}
for (TableReportModule module : tableModules) {
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
type.getDisplayName()));
}
// Keyword hits and hashset hit artifacts get special handling.
if (type.equals(ARTIFACT_TYPE.TSK_KEYWORD_HIT)) {
writeKeywordHits(tableModules, comment.toString(), tagNamesFilter);
continue;
} else if (type.equals(ARTIFACT_TYPE.TSK_HASHSET_HIT)) {
writeHashsetHits(tableModules, comment.toString(), tagNamesFilter);
continue;
}
List<ArtifactData> unsortedArtifacts = getFilteredArtifacts(type, tagNamesFilter);
if (unsortedArtifacts.isEmpty()) {
continue;
}
// The most efficient way to sort all the Artifacts is to add them to a List, and then
// sort that List based off a Comparator. Adding to a TreeMap/Set/List sorts the list
// each time an element is added, which adds unnecessary overhead if we only need it sorted once.
Collections.sort(unsortedArtifacts);
// Get the column headers appropriate for the artifact type.
/*
* @@@ BC: Seems like a better design here would be to have a
* method that takes in the artifact as an argument and returns
* the attributes. We then use that to make the headers and to
* make each row afterwards so that we don't have
* artifact-specific logic in both getArtifactTableCoumnHeaders
* and ArtifactData.getRow()
*/
List<String> columnHeaders = getArtifactTableColumnHeaders(type.getTypeID());
if (columnHeaders == null) {
// @@@ Hack to prevent system from hanging. Better solution is to merge all attributes into a single column or analyze the artifacts to find out how many are needed.
continue;
}
for (TableReportModule module : tableModules) {
module.startDataType(type.getDisplayName(), comment.toString());
module.startTable(columnHeaders);
}
boolean msgSent = false;
for (ArtifactData artifactData : unsortedArtifacts) {
// Add the row data to all of the reports.
for (TableReportModule module : tableModules) {
// Get the row data for this type of artifact.
List<String> rowData = artifactData.getRow();
if (rowData.isEmpty()) {
if (msgSent == false) {
MessageNotifyUtil.Notify.show(NbBundle.getMessage(this.getClass(),
"ReportGenerator.msgShow.skippingArtRow.title",
type),
NbBundle.getMessage(this.getClass(),
"ReportGenerator.msgShow.skippingArtRow.msg"),
MessageNotifyUtil.MessageType.ERROR);
msgSent = true;
}
continue;
}
module.addRow(rowData);
}
}
// Finish up this data type
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endTable();
module.endDataType();
}
}
}
/**
* Make table for tagged files
*/
@SuppressWarnings("deprecation")
private void makeContentTagsTables() {
// Check for cancellaton.
removeCancelledTableReportModules();
if (tableModules.isEmpty()) {
return;
}
// Get the content tags.
List<ContentTag> tags;
try {
tags = Case.getCurrentCase().getServices().getTagsManager().getAllContentTags();
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetContentTags"));
logger.log(Level.SEVERE, "failed to get content tags", ex); //NON-NLS
return;
}
// Tell the modules reporting on content tags is beginning.
for (TableReportModule module : tableModules) {
// @@@ This casting is a tricky little workaround to allow the HTML report module to slip in a content hyperlink.
// @@@ Alos Using the obsolete ARTIFACT_TYPE.TSK_TAG_FILE is also an expedient hack.
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_TAG_FILE.getDisplayName()));
ArrayList<String> columnHeaders = new ArrayList<>(Arrays.asList(
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.tag"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.file"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.comment"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeModified"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeChanged"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.timeCreated"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.size"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.htmlOutput.header.hash")));
StringBuilder comment = new StringBuilder();
if (!tagNamesFilter.isEmpty()) {
comment.append(
NbBundle.getMessage(this.getClass(), "ReportGenerator.makeContTagTab.taggedFiles.msg"));
comment.append(makeCommaSeparatedList(tagNamesFilter));
}
if (module instanceof ReportHTML) {
ReportHTML htmlReportModule = (ReportHTML) module;
htmlReportModule.startDataType(ARTIFACT_TYPE.TSK_TAG_FILE.getDisplayName(), comment.toString());
htmlReportModule.startContentTagsTable(columnHeaders);
} else {
module.startDataType(ARTIFACT_TYPE.TSK_TAG_FILE.getDisplayName(), comment.toString());
module.startTable(columnHeaders);
}
}
// Give the modules the rows for the content tags.
for (ContentTag tag : tags) {
// skip tags that we are not reporting on
if (passesTagNamesFilter(tag.getName().getDisplayName()) == false) {
continue;
}
String fileName;
try {
fileName = tag.getContent().getUniquePath();
} catch (TskCoreException ex) {
fileName = tag.getContent().getName();
}
ArrayList<String> rowData = new ArrayList<>(Arrays.asList(tag.getName().getDisplayName(), fileName, tag.getComment()));
for (TableReportModule module : tableModules) {
// @@@ This casting is a tricky little workaround to allow the HTML report module to slip in a content hyperlink.
if (module instanceof ReportHTML) {
ReportHTML htmlReportModule = (ReportHTML) module;
htmlReportModule.addRowWithTaggedContentHyperlink(rowData, tag);
} else {
module.addRow(rowData);
}
}
// see if it is for an image so that we later report on it
checkIfTagHasImage(tag);
}
// The the modules content tags reporting is ended.
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endTable();
module.endDataType();
}
}
@Override
protected void done() {
try {
get();
} catch (InterruptedException | ExecutionException ex) {
MessageNotifyUtil.Notify.show(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorTitle"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.errors.reportErrorText") + ex.getLocalizedMessage(),
MessageNotifyUtil.MessageType.ERROR);
logger.log(Level.SEVERE, "failed to generate reports", ex); //NON-NLS
} // catch and ignore if we were cancelled
catch (java.util.concurrent.CancellationException ex) {
} finally {
displayReportErrors();
errorList.clear();
}
}
/**
* Generate the tables for the tagged artifacts
*/
@SuppressWarnings("deprecation")
private void makeBlackboardArtifactTagsTables() {
// Check for cancellaton.
removeCancelledTableReportModules();
if (tableModules.isEmpty()) {
return;
}
List<BlackboardArtifactTag> tags;
try {
tags = Case.getCurrentCase().getServices().getTagsManager().getAllBlackboardArtifactTags();
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetBBArtifactTags"));
logger.log(Level.SEVERE, "failed to get blackboard artifact tags", ex); //NON-NLS
return;
}
// Tell the modules reporting on blackboard artifact tags data type is beginning.
// @@@ Using the obsolete ARTIFACT_TYPE.TSK_TAG_ARTIFACT is an expedient hack.
for (TableReportModule module : tableModules) {
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getDisplayName()));
StringBuilder comment = new StringBuilder();
if (!tagNamesFilter.isEmpty()) {
comment.append(
NbBundle.getMessage(this.getClass(), "ReportGenerator.makeBbArtTagTab.taggedRes.msg"));
comment.append(makeCommaSeparatedList(tagNamesFilter));
}
module.startDataType(ARTIFACT_TYPE.TSK_TAG_ARTIFACT.getDisplayName(), comment.toString());
module.startTable(new ArrayList<>(Arrays.asList(
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.resultType"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.tag"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.comment"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.tagTable.header.srcFile"))));
}
// Give the modules the rows for the content tags.
for (BlackboardArtifactTag tag : tags) {
if (passesTagNamesFilter(tag.getName().getDisplayName()) == false) {
continue;
}
List<String> row;
for (TableReportModule module : tableModules) {
row = new ArrayList<>(Arrays.asList(tag.getArtifact().getArtifactTypeName(), tag.getName().getDisplayName(), tag.getComment(), tag.getContent().getName()));
module.addRow(row);
}
// check if the tag is an image that we should later make a thumbnail for
checkIfTagHasImage(tag);
}
// The the modules blackboard artifact tags reporting is ended.
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endTable();
module.endDataType();
}
}
/**
* Test if the user requested that this tag be reported on
*
* @param tagName
*
* @return true if it should be reported on
*/
private boolean passesTagNamesFilter(String tagName) {
return tagNamesFilter.isEmpty() || tagNamesFilter.contains(tagName);
}
void removeCancelledTableReportModules() {
Iterator<TableReportModule> iter = tableModules.iterator();
while (iter.hasNext()) {
TableReportModule module = iter.next();
if (tableProgress.get(module).getStatus() == ReportStatus.CANCELED) {
iter.remove();
}
}
}
/**
* Make a report for the files that were previously found to be images.
*/
private void makeThumbnailTable() {
for (TableReportModule module : tableModules) {
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.createdThumb.text"));
if (module instanceof ReportHTML) {
ReportHTML htmlModule = (ReportHTML) module;
htmlModule.startDataType(
NbBundle.getMessage(this.getClass(), "ReportGenerator.thumbnailTable.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.thumbnailTable.desc"));
List<String> emptyHeaders = new ArrayList<>();
for (int i = 0; i < ReportHTML.THUMBNAIL_COLUMNS; i++) {
emptyHeaders.add("");
}
htmlModule.startTable(emptyHeaders);
htmlModule.addThumbnailRows(images);
htmlModule.endTable();
htmlModule.endDataType();
}
}
}
/**
* Analyze artifact associated with tag and add to internal list if it
* is associated with an image.
*
* @param artifactTag
*/
private void checkIfTagHasImage(BlackboardArtifactTag artifactTag) {
AbstractFile file;
try {
file = Case.getCurrentCase().getSleuthkitCase().getAbstractFileById(artifactTag.getArtifact().getObjectID());
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.errGetContentFromBBArtifact"));
logger.log(Level.WARNING, "Error while getting content from a blackboard artifact to report on.", ex); //NON-NLS
return;
}
if (file != null) {
checkIfFileIsImage(file);
}
}
/**
* Analyze file that tag is associated with and determine if it is an
* image and should have a thumbnail reported for it. Images are added
* to internal list.
*
* @param contentTag
*/
private void checkIfTagHasImage(ContentTag contentTag) {
Content c = contentTag.getContent();
if (c instanceof AbstractFile == false) {
return;
}
checkIfFileIsImage((AbstractFile) c);
}
/**
* If file is an image file, add it to the internal 'images' list.
*
* @param file
*/
private void checkIfFileIsImage(AbstractFile file) {
if (file.isDir()
|| file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS
|| file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS) {
return;
}
if (ImageUtils.thumbnailSupported(file)) {
images.add(file);
}
}
}
/// @@@ Should move the methods specific to TableReportsWorker into that scope.
private Boolean failsTagFilter(HashSet<String> tagNames, HashSet<String> tagsNamesFilter) {
if (null == tagsNamesFilter || tagsNamesFilter.isEmpty()) {
return false;
}
HashSet<String> filteredTagNames = new HashSet<>(tagNames);
filteredTagNames.retainAll(tagsNamesFilter);
return filteredTagNames.isEmpty();
}
/**
* Get a List of the artifacts and data of the given type that pass the
* given Tag Filter.
*
* @param type The artifact type to get
* @param tagNamesFilter The tag names that should be included.
*
* @return a list of the filtered tags.
*/
private List<ArtifactData> getFilteredArtifacts(ARTIFACT_TYPE type, HashSet<String> tagNamesFilter) {
List<ArtifactData> artifacts = new ArrayList<>();
try {
for (BlackboardArtifact artifact : skCase.getBlackboardArtifacts(type)) {
List<BlackboardArtifactTag> tags = Case.getCurrentCase().getServices().getTagsManager().getBlackboardArtifactTagsByArtifact(artifact);
HashSet<String> uniqueTagNames = new HashSet<>();
for (BlackboardArtifactTag tag : tags) {
uniqueTagNames.add(tag.getName().getDisplayName());
}
if (failsTagFilter(uniqueTagNames, tagNamesFilter)) {
continue;
}
try {
artifacts.add(new ArtifactData(artifact, skCase.getBlackboardAttributes(artifact), uniqueTagNames));
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetBBAttribs"));
logger.log(Level.SEVERE, "Failed to get Blackboard Attributes when generating report.", ex); //NON-NLS
}
}
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetBBArtifacts"));
logger.log(Level.SEVERE, "Failed to get Blackboard Artifacts when generating report.", ex); //NON-NLS
}
return artifacts;
}
/**
* Write the keyword hits to the provided TableReportModules.
*
* @param tableModules modules to report on
*/
@SuppressWarnings("deprecation")
private void writeKeywordHits(List<TableReportModule> tableModules, String comment, HashSet<String> tagNamesFilter) {
// Query for keyword lists-only so that we can tell modules what lists
// will exist for their index.
// @@@ There is a bug in here. We should use the tags in the below code
// so that we only report the lists that we will later provide with real
// hits. If no keyord hits are tagged, then we make the page for nothing.
String orderByClause;
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att.value_text, 'SQL_ASCII') ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY list ASC"; //NON-NLS
}
String keywordListQuery
= "SELECT att.value_text AS list " + //NON-NLS
"FROM blackboard_attributes AS att, blackboard_artifacts AS art " + //NON-NLS
"WHERE att.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + " " + //NON-NLS
"AND art.artifact_type_id = " + ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID() + " " + //NON-NLS
"AND att.artifact_id = art.artifact_id " + //NON-NLS
"GROUP BY list " + orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(keywordListQuery)) {
ResultSet listsRs = dbQuery.getResultSet();
List<String> lists = new ArrayList<>();
while (listsRs.next()) {
String list = listsRs.getString("list"); //NON-NLS
if (list.isEmpty()) {
list = NbBundle.getMessage(this.getClass(), "ReportGenerator.writeKwHits.userSrchs");
}
lists.add(list);
}
// Make keyword data type and give them set index
for (TableReportModule module : tableModules) {
module.startDataType(ARTIFACT_TYPE.TSK_KEYWORD_HIT.getDisplayName(), comment);
module.addSetIndex(lists);
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_KEYWORD_HIT.getDisplayName()));
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryKWLists"));
logger.log(Level.SEVERE, "Failed to query keyword lists: ", ex); //NON-NLS
return;
}
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att3.value_text, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(att1.value_text, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.parent_path, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.name, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(att2.value_text, 'SQL_ASCII') ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY list ASC, keyword ASC, parent_path ASC, name ASC, preview ASC"; //NON-NLS
}
// Query for keywords, grouped by list
String keywordsQuery
= "SELECT art.artifact_id, art.obj_id, att1.value_text AS keyword, att2.value_text AS preview, att3.value_text AS list, f.name AS name, f.parent_path AS parent_path " + //NON-NLS
"FROM blackboard_artifacts AS art, blackboard_attributes AS att1, blackboard_attributes AS att2, blackboard_attributes AS att3, tsk_files AS f " + //NON-NLS
"WHERE (att1.artifact_id = art.artifact_id) " + //NON-NLS
"AND (att2.artifact_id = art.artifact_id) " + //NON-NLS
"AND (att3.artifact_id = art.artifact_id) " + //NON-NLS
"AND (f.obj_id = art.obj_id) " + //NON-NLS
"AND (att1.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_KEYWORD.getTypeID() + ") " + //NON-NLS
"AND (att2.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW.getTypeID() + ") " + //NON-NLS
"AND (att3.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + ") " + //NON-NLS
"AND (art.artifact_type_id = " + ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID() + ") " + //NON-NLS
orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(keywordsQuery)) {
ResultSet resultSet = dbQuery.getResultSet();
String currentKeyword = "";
String currentList = "";
while (resultSet.next()) {
// Check to see if all the TableReportModules have been canceled
if (tableModules.isEmpty()) {
break;
}
Iterator<TableReportModule> iter = tableModules.iterator();
while (iter.hasNext()) {
TableReportModule module = iter.next();
if (tableProgress.get(module).getStatus() == ReportStatus.CANCELED) {
iter.remove();
}
}
// Get any tags that associated with this artifact and apply the tag filter.
HashSet<String> uniqueTagNames = getUniqueTagNames(resultSet.getLong("artifact_id")); //NON-NLS
if (failsTagFilter(uniqueTagNames, tagNamesFilter)) {
continue;
}
String tagsList = makeCommaSeparatedList(uniqueTagNames);
Long objId = resultSet.getLong("obj_id"); //NON-NLS
String keyword = resultSet.getString("keyword"); //NON-NLS
String preview = resultSet.getString("preview"); //NON-NLS
String list = resultSet.getString("list"); //NON-NLS
String uniquePath = "";
try {
AbstractFile f = skCase.getAbstractFileById(objId);
if (f != null) {
uniquePath = skCase.getAbstractFileById(objId).getUniquePath();
}
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetAbstractFileByID"));
logger.log(Level.WARNING, "Failed to get Abstract File by ID.", ex); //NON-NLS
}
// If the lists aren't the same, we've started a new list
if ((!list.equals(currentList) && !list.isEmpty()) || (list.isEmpty() && !currentList.equals(
NbBundle.getMessage(this.getClass(), "ReportGenerator.writeKwHits.userSrchs")))) {
if (!currentList.isEmpty()) {
for (TableReportModule module : tableModules) {
module.endTable();
module.endSet();
}
}
currentList = list.isEmpty() ? NbBundle
.getMessage(this.getClass(), "ReportGenerator.writeKwHits.userSrchs") : list;
currentKeyword = ""; // reset the current keyword because it's a new list
for (TableReportModule module : tableModules) {
module.startSet(currentList);
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processingList",
ARTIFACT_TYPE.TSK_KEYWORD_HIT.getDisplayName(), currentList));
}
}
if (!keyword.equals(currentKeyword)) {
if (!currentKeyword.equals("")) {
for (TableReportModule module : tableModules) {
module.endTable();
}
}
currentKeyword = keyword;
for (TableReportModule module : tableModules) {
module.addSetElement(currentKeyword);
module.startTable(getArtifactTableColumnHeaders(ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID()));
}
}
String previewreplace = EscapeUtil.escapeHtml(preview);
for (TableReportModule module : tableModules) {
module.addRow(Arrays.asList(new String[]{previewreplace.replaceAll("<!", ""), uniquePath, tagsList}));
}
}
// Finish the current data type
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endDataType();
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryKWs"));
logger.log(Level.SEVERE, "Failed to query keywords: ", ex); //NON-NLS
}
}
/**
* Write the hash set hits to the provided TableReportModules.
*
* @param tableModules modules to report on
*/
@SuppressWarnings("deprecation")
private void writeHashsetHits(List<TableReportModule> tableModules, String comment, HashSet<String> tagNamesFilter) {
String orderByClause;
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att.value_text, 'SQL_ASCII') ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY att.value_text ASC"; //NON-NLS
}
String hashsetsQuery
= "SELECT att.value_text AS list " + //NON-NLS
"FROM blackboard_attributes AS att, blackboard_artifacts AS art " + //NON-NLS
"WHERE att.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + " " + //NON-NLS
"AND art.artifact_type_id = " + ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID() + " " + //NON-NLS
"AND att.artifact_id = art.artifact_id " + //NON-NLS
"GROUP BY list " + orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(hashsetsQuery)) {
// Query for hashsets
ResultSet listsRs = dbQuery.getResultSet();
List<String> lists = new ArrayList<>();
while (listsRs.next()) {
lists.add(listsRs.getString("list")); //NON-NLS
}
for (TableReportModule module : tableModules) {
module.startDataType(ARTIFACT_TYPE.TSK_HASHSET_HIT.getDisplayName(), comment);
module.addSetIndex(lists);
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processing",
ARTIFACT_TYPE.TSK_HASHSET_HIT.getDisplayName()));
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryHashsetLists"));
logger.log(Level.SEVERE, "Failed to query hashset lists: ", ex); //NON-NLS
return;
}
if (currentCase.getCaseType() == Case.CaseType.MULTI_USER_CASE) {
orderByClause = "ORDER BY convert_to(att.value_text, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.parent_path, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "convert_to(f.name, 'SQL_ASCII') ASC NULLS FIRST, " //NON-NLS
+ "size ASC NULLS FIRST"; //NON-NLS
} else {
orderByClause = "ORDER BY att.value_text ASC, f.parent_path ASC, f.name ASC, size ASC"; //NON-NLS
}
String hashsetHitsQuery
= "SELECT art.artifact_id, art.obj_id, att.value_text AS setname, f.name AS name, f.size AS size, f.parent_path AS parent_path " + //NON-NLS
"FROM blackboard_artifacts AS art, blackboard_attributes AS att, tsk_files AS f " + //NON-NLS
"WHERE (att.artifact_id = art.artifact_id) " + //NON-NLS
"AND (f.obj_id = art.obj_id) " + //NON-NLS
"AND (att.attribute_type_id = " + ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() + ") " + //NON-NLS
"AND (art.artifact_type_id = " + ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID() + ") " + //NON-NLS
orderByClause; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(hashsetHitsQuery)) {
// Query for hashset hits
ResultSet resultSet = dbQuery.getResultSet();
String currentSet = "";
while (resultSet.next()) {
// Check to see if all the TableReportModules have been canceled
if (tableModules.isEmpty()) {
break;
}
Iterator<TableReportModule> iter = tableModules.iterator();
while (iter.hasNext()) {
TableReportModule module = iter.next();
if (tableProgress.get(module).getStatus() == ReportStatus.CANCELED) {
iter.remove();
}
}
// Get any tags that associated with this artifact and apply the tag filter.
HashSet<String> uniqueTagNames = getUniqueTagNames(resultSet.getLong("artifact_id")); //NON-NLS
if (failsTagFilter(uniqueTagNames, tagNamesFilter)) {
continue;
}
String tagsList = makeCommaSeparatedList(uniqueTagNames);
Long objId = resultSet.getLong("obj_id"); //NON-NLS
String set = resultSet.getString("setname"); //NON-NLS
String size = resultSet.getString("size"); //NON-NLS
String uniquePath = "";
try {
AbstractFile f = skCase.getAbstractFileById(objId);
if (f != null) {
uniquePath = skCase.getAbstractFileById(objId).getUniquePath();
}
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetAbstractFileFromID"));
logger.log(Level.WARNING, "Failed to get Abstract File from ID.", ex); //NON-NLS
return;
}
// If the sets aren't the same, we've started a new set
if (!set.equals(currentSet)) {
if (!currentSet.isEmpty()) {
for (TableReportModule module : tableModules) {
module.endTable();
module.endSet();
}
}
currentSet = set;
for (TableReportModule module : tableModules) {
module.startSet(currentSet);
module.startTable(getArtifactTableColumnHeaders(ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID()));
tableProgress.get(module).updateStatusLabel(
NbBundle.getMessage(this.getClass(), "ReportGenerator.progress.processingList",
ARTIFACT_TYPE.TSK_HASHSET_HIT.getDisplayName(), currentSet));
}
}
// Add a row for this hit to every module
for (TableReportModule module : tableModules) {
module.addRow(Arrays.asList(new String[]{uniquePath, size, tagsList}));
}
}
// Finish the current data type
for (TableReportModule module : tableModules) {
tableProgress.get(module).increment();
module.endDataType();
}
} catch (TskCoreException | SQLException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedQueryHashsetHits"));
logger.log(Level.SEVERE, "Failed to query hashsets hits: ", ex); //NON-NLS
}
}
/**
* For a given artifact type ID, return the list of the row titles we're
* reporting on.
*
* @param artifactTypeId artifact type ID
*
* @return List<String> row titles
*/
private List<String> getArtifactTableColumnHeaders(int artifactTypeId) {
ArrayList<String> columnHeaders;
BlackboardArtifact.ARTIFACT_TYPE type = BlackboardArtifact.ARTIFACT_TYPE.fromID(artifactTypeId);
switch (type) {
case TSK_WEB_BOOKMARK:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.title"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateCreated"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_COOKIE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.value"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_HISTORY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.referrer"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.title"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.urlDomainDecoded"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_DOWNLOAD:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dest"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.sourceUrl"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_RECENT_OBJECT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.path"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_INSTALLED_PROG:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.progName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.instDateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_KEYWORD_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.preview"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_HASHSET_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.file"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.size")}));
break;
case TSK_DEVICE_ATTACHED:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devMake"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devModel"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.deviceId"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_WEB_SEARCH_QUERY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.domain"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateAccessed"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.progName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_METADATA_EXIF:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTaken"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devManufacturer"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.devModel"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_CONTACT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumber"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumHome"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumOffice"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumMobile"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.email"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_MESSAGE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.msgType"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.direction"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.readStatus"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.fromPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.fromEmail"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.toPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.toEmail"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.subject"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_CALLLOG:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.fromPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.toPhoneNum"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.direction"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_CALENDAR_ENTRY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.calendarEntryType"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.description"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.startDateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.endDateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.location"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_SPEED_DIAL_ENTRY:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.shortCut"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.phoneNumber"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_BLUETOOTH_PAIRING:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.deviceName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.deviceAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_TRACKPOINT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_BOOKMARK:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.locationAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_LAST_KNOWN_LOCATION:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.locationAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_GPS_SEARCH:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.altitude"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.locationAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_SERVICE_ACCOUNT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.category"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.userId"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.password"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.personName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.appName"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.url"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.appPath"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.description"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.replytoAddress"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.mailServer"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_ENCRYPTION_DETECTED:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_EXT_MISMATCH_DETECTED:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.file"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.extension.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.mimeType.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.path")}));
break;
case TSK_OS_INFO:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.processorArchitecture.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.osName.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.osInstallDate.text"),
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.srcFile")}));
break;
case TSK_EMAIL_MSG:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailTo"), //TSK_EMAIL_TO
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailFrom"), //TSK_EMAIL_FROM
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskSubject"), //TSK_SUBJECT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskDateTimeSent"), //TSK_DATETIME_SENT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskDateTimeRcvd"), //TSK_DATETIME_RCVD
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskPath"), //TSK_PATH
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailCc"), //TSK_EMAIL_CC
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskEmailBcc"), //TSK_EMAIL_BCC
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskMsgId")})); //TSK_MSG_ID
break;
case TSK_INTERESTING_FILE_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskSetName"), //TSK_SET_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskInterestingFilesCategory"), //TSK_CATEGORY
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskPath")})); //TSK_PATH
break;
case TSK_GPS_ROUTE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskGpsRouteCategory"), //TSK_CATEGORY
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"), //TSK_DATETIME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitudeEnd"), //TSK_GEO_LATITUDE_END
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitudeEnd"), //TSK_GEO_LONGITUDE_END
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.latitudeStart"), //TSK_GEO_LATITUDE_START
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.longitudeStart"), //TSK_GEO_LONGITUDE_START
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.name"), //TSK_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.location"), //TSK_LOCATION
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program")}));//TSK_PROG_NAME
break;
case TSK_INTERESTING_ARTIFACT_HIT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tskSetName"), //TSK_SET_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.associatedArtifact"), //TSK_ASSOCIATED_ARTIFACT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program")})); //TSK_PROG_NAME
break;
case TSK_PROG_RUN:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.program"), //TSK_PROG_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.associatedArtifact"), //TSK_ASSOCIATED_ARTIFACT
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.dateTime"), //TSK_DATETIME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.count")})); //TSK_COUNT
break;
case TSK_OS_ACCOUNT:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.userName"), //TSK_USER_NAME
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.userId")})); //TSK_USER_ID
break;
case TSK_REMOTE_DRIVE:
columnHeaders = new ArrayList<>(Arrays.asList(new String[]{
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.localPath"), //TSK_LOCAL_PATH
NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.remotePath")})); //TSK_REMOTE_PATH
break;
default:
return null;
}
columnHeaders.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.artTableColHdr.tags"));
return columnHeaders;
}
/**
* Map all BlackboardAttributes' values in a list of BlackboardAttributes to
* each attribute's attribute type ID, using module's dateToString method
* for date/time conversions if a module is supplied.
*
* @param attList list of BlackboardAttributes to be mapped
* @param module the TableReportModule the mapping is for
*
* @return Map<Integer, String> of the BlackboardAttributes mapped to their
* attribute type ID
*/
public Map<Integer, String> getMappedAttributes(List<BlackboardAttribute> attList, TableReportModule... module) {
Map<Integer, String> attributes = new HashMap<>();
int size = ATTRIBUTE_TYPE.values().length;
for (int n = 0; n <= size; n++) {
attributes.put(n, "");
}
for (BlackboardAttribute tempatt : attList) {
String value = "";
Integer type = tempatt.getAttributeTypeID();
if (type.equals(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_CREATED.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_MODIFIED.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_SENT.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_RCVD.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_START.getTypeID())
|| type.equals(ATTRIBUTE_TYPE.TSK_DATETIME_END.getTypeID())) {
if (module.length > 0) {
value = module[0].dateToString(tempatt.getValueLong());
} else {
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
value = sdf.format(new java.util.Date((tempatt.getValueLong() * 1000)));
}
} else {
value = tempatt.getDisplayString();
}
if (value == null) {
value = "";
}
value = EscapeUtil.escapeHtml(value);
attributes.put(type, value);
}
return attributes;
}
/**
* Converts a collection of strings into a single string of comma-separated
* items
*
* @param items A collection of strings
*
* @return A string of comma-separated items
*/
private String makeCommaSeparatedList(Collection<String> items) {
String list = "";
for (Iterator<String> iterator = items.iterator(); iterator.hasNext();) {
list += iterator.next() + (iterator.hasNext() ? ", " : "");
}
return list;
}
/**
* Given a tsk_file's obj_id, return the unique path of that file.
*
* @param objId tsk_file obj_id
*
* @return String unique path
*/
private String getFileUniquePath(long objId) {
try {
AbstractFile af = skCase.getAbstractFileById(objId);
if (af != null) {
return af.getUniquePath();
} else {
return "";
}
} catch (TskCoreException ex) {
errorList.add(NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.failedGetAbstractFileByID"));
logger.log(Level.WARNING, "Failed to get Abstract File by ID.", ex); //NON-NLS
}
return "";
}
/**
* Container class that holds data about an Artifact to eliminate duplicate
* calls to the Sleuthkit database.
*/
private class ArtifactData implements Comparable<ArtifactData> {
private BlackboardArtifact artifact;
private List<BlackboardAttribute> attributes;
private HashSet<String> tags;
private List<String> rowData = null;
ArtifactData(BlackboardArtifact artifact, List<BlackboardAttribute> attrs, HashSet<String> tags) {
this.artifact = artifact;
this.attributes = attrs;
this.tags = tags;
}
public BlackboardArtifact getArtifact() {
return artifact;
}
public List<BlackboardAttribute> getAttributes() {
return attributes;
}
public HashSet<String> getTags() {
return tags;
}
public long getArtifactID() {
return artifact.getArtifactID();
}
public long getObjectID() {
return artifact.getObjectID();
}
/**
* Compares ArtifactData objects by the first attribute they have in
* common in their List<BlackboardAttribute>.
*
* If all attributes are the same, they are assumed duplicates and are
* compared by their artifact id. Should only be used with attributes of
* the same type.
*/
@Override
public int compareTo(ArtifactData otherArtifactData) {
List<String> thisRow = getRow();
List<String> otherRow = otherArtifactData.getRow();
for (int i = 0; i < thisRow.size(); i++) {
int compare = thisRow.get(i).compareTo(otherRow.get(i));
if (compare != 0) {
return compare;
}
}
// If all attributes are the same, they're most likely duplicates so sort by artifact ID
return ((Long) this.getArtifactID()).compareTo((Long) otherArtifactData.getArtifactID());
}
/**
* Get the values for each row in the table report.
*/
public List<String> getRow() {
if (rowData == null) {
try {
rowData = getOrderedRowDataAsStrings();
// replace null values if attribute was not defined
for (int i = 0; i < rowData.size(); i++) {
if (rowData.get(i) == null) {
rowData.set(i, "");
}
}
} catch (TskCoreException ex) {
errorList.add(
NbBundle.getMessage(this.getClass(), "ReportGenerator.errList.coreExceptionWhileGenRptRow"));
logger.log(Level.WARNING, "Core exception while generating row data for artifact report.", ex); //NON-NLS
rowData = Collections.<String>emptyList();
}
}
return rowData;
}
/**
* Get a list of Strings with all the row values for the Artifact in the
* correct order to be written to the report.
*
* @return List<String> row values. Values could be null if attribute is
* not defined in artifact
*
* @throws TskCoreException
*/
private List<String> getOrderedRowDataAsStrings() throws TskCoreException {
Map<Integer, String> mappedAttributes = getMappedAttributes();
List<String> orderedRowData = new ArrayList<>();
BlackboardArtifact.ARTIFACT_TYPE type = BlackboardArtifact.ARTIFACT_TYPE.fromID(getArtifact().getArtifactTypeID());
switch (type) {
case TSK_WEB_BOOKMARK:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TITLE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_CREATED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_COOKIE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_HISTORY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_REFERRER.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TITLE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_DOWNLOAD:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_RECENT_OBJECT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_INSTALLED_PROG:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_DEVICE_ATTACHED:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MAKE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MODEL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_ID.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_WEB_SEARCH_QUERY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_METADATA_EXIF:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_CREATED.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MAKE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_MODEL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_CONTACT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_HOME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_OFFICE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_MOBILE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_MESSAGE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_READ_STATUS.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SUBJECT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_CALLLOG:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_CALENDAR_ENTRY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CALENDAR_ENTRY_TYPE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DESCRIPTION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_END.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_SPEED_DIAL_ENTRY:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SHORTCUT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME_PERSON.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_BLUETOOTH_PAIRING:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DEVICE_ID.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_TRACKPOINT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_BOOKMARK:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_LAST_KNOWN_LOCATION:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_GPS_SEARCH:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_ALTITUDE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_SERVICE_ACCOUNT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CATEGORY.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_USER_ID.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PASSWORD.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_URL.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DESCRIPTION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_REPLYTO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SERVER_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_TOOL_OUTPUT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_ENCRYPTION_DETECTED:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_EXT_MISMATCH_DETECTED:
AbstractFile file = skCase.getAbstractFileById(getObjectID());
if (file != null) {
orderedRowData.add(file.getName());
String mimeType = file.getMIMEType();
if(mimeType == null) {
orderedRowData.add("");
}
else {
orderedRowData.add(mimeType);
}
orderedRowData.add(file.getUniquePath());
} else {
// Make empty rows to make sure the formatting is correct
orderedRowData.add(null);
orderedRowData.add(null);
orderedRowData.add(null);
orderedRowData.add(null);
}
break;
case TSK_OS_INFO:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROCESSOR_ARCHITECTURE.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(getFileUniquePath(getObjectID()));
break;
case TSK_EMAIL_MSG:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_TO.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_FROM.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SUBJECT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_SENT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME_RCVD.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_CC.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_EMAIL_BCC.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_MSG_ID.getTypeID()));
break;
case TSK_INTERESTING_FILE_HIT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CATEGORY.getTypeID()));
String pathToShow = mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PATH.getTypeID());
if (pathToShow.isEmpty()) {
pathToShow = getFileUniquePath(getObjectID());
}
orderedRowData.add(pathToShow);
break;
case TSK_GPS_ROUTE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_CATEGORY.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_END.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_END.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_START.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCATION.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
break;
case TSK_INTERESTING_ARTIFACT_HIT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
break;
case TSK_PROG_RUN:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_COUNT.getTypeID()));
break;
case TSK_OS_ACCOUNT:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_USER_NAME.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_USER_ID.getTypeID()));
break;
case TSK_REMOTE_DRIVE:
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_LOCAL_PATH.getTypeID()));
orderedRowData.add(mappedAttributes.get(ATTRIBUTE_TYPE.TSK_REMOTE_PATH.getTypeID()));
break;
}
orderedRowData.add(makeCommaSeparatedList(getTags()));
return orderedRowData;
}
/**
* Returns a mapping of Attribute Type ID to the String representation
* of an Attribute Value.
*/
private Map<Integer, String> getMappedAttributes() {
return ReportGenerator.this.getMappedAttributes(attributes);
}
}
/**
* Get any tags associated with an artifact
*
* @param artifactId
*
* @return hash set of tag display names
*
* @throws SQLException
*/
@SuppressWarnings("deprecation")
private HashSet<String> getUniqueTagNames(long artifactId) throws TskCoreException {
HashSet<String> uniqueTagNames = new HashSet<>();
String query = "SELECT display_name, artifact_id FROM tag_names AS tn, blackboard_artifact_tags AS bat " + //NON-NLS
"WHERE tn.tag_name_id = bat.tag_name_id AND bat.artifact_id = " + artifactId; //NON-NLS
try (CaseDbQuery dbQuery = skCase.executeQuery(query)) {
ResultSet tagNameRows = dbQuery.getResultSet();
while (tagNameRows.next()) {
uniqueTagNames.add(tagNameRows.getString("display_name")); //NON-NLS
}
} catch (TskCoreException | SQLException ex) {
throw new TskCoreException("Error getting tag names for artifact: ", ex);
}
return uniqueTagNames;
}
}
| Fixed bug in reports
| Core/src/org/sleuthkit/autopsy/report/ReportGenerator.java | Fixed bug in reports |
|
Java | apache-2.0 | 85f26bb899cba58b52288f6d5df84f265e135757 | 0 | sidheshenator/autopsy,APriestman/autopsy,dgrove727/autopsy,sidheshenator/autopsy,narfindustries/autopsy,maxrp/autopsy,mhmdfy/autopsy,karlmortensen/autopsy,raman-bt/autopsy,raman-bt/autopsy,APriestman/autopsy,esaunders/autopsy,raman-bt/autopsy,narfindustries/autopsy,eXcomm/autopsy,APriestman/autopsy,esaunders/autopsy,dgrove727/autopsy,maxrp/autopsy,wschaeferB/autopsy,APriestman/autopsy,raman-bt/autopsy,esaunders/autopsy,eXcomm/autopsy,mhmdfy/autopsy,raman-bt/autopsy,raman-bt/autopsy,rcordovano/autopsy,millmanorama/autopsy,raman-bt/autopsy,karlmortensen/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy,karlmortensen/autopsy,rcordovano/autopsy,rcordovano/autopsy,millmanorama/autopsy,sidheshenator/autopsy,sidheshenator/autopsy,rcordovano/autopsy,rcordovano/autopsy,APriestman/autopsy,mhmdfy/autopsy,maxrp/autopsy,mhmdfy/autopsy,eXcomm/autopsy,millmanorama/autopsy,narfindustries/autopsy,eXcomm/autopsy,dgrove727/autopsy,wschaeferB/autopsy,karlmortensen/autopsy,millmanorama/autopsy,APriestman/autopsy,wschaeferB/autopsy,esaunders/autopsy,maxrp/autopsy,APriestman/autopsy,wschaeferB/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.ingest;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.util.Cancellable;
import org.openide.util.Lookup;
import org.sleuthkit.autopsy.ingest.IngestMessage.MessageType;
import org.sleuthkit.datamodel.FsContent;
import org.sleuthkit.datamodel.Image;
import org.sleuthkit.datamodel.TskData;
/**
* IngestManager sets up and manages ingest services
* runs them in a background thread
* notifies services when work is complete or should be interrupted
* processes messages from services via messenger proxy and posts them to GUI
*
*/
public class IngestManager {
enum UpdateFrequency {
FAST(20),
AVG(10),
SLOW(5);
private final int time;
UpdateFrequency(int time) {
this.time = time;
}
int getTime() {
return time;
}
};
private static final Logger logger = Logger.getLogger(IngestManager.class.getName());
private IngestManagerStats stats;
private volatile UpdateFrequency updateFrequency = UpdateFrequency.AVG;
//queues
private final ImageQueue imageQueue = new ImageQueue(); // list of services and images to analyze
private final FsContentQueue fsContentQueue = new FsContentQueue();
private final Object queuesLock = new Object();
//workers
private IngestFsContentThread fsContentIngester;
private List<IngestImageThread> imageIngesters;
private SwingWorker queueWorker;
//services
final List<IngestServiceImage> imageServices = enumerateImageServices();
final List<IngestServiceFsContent> fsContentServices = enumerateFsContentServices();
// service return values
private final Map<String, IngestServiceFsContent.ProcessResult> fsContentServiceResults = new HashMap<String, IngestServiceFsContent.ProcessResult>();
//manager proxy
final IngestManagerProxy managerProxy = new IngestManagerProxy(this);
//notifications
private final static PropertyChangeSupport pcs = new PropertyChangeSupport(IngestManager.class);
//monitor
private final IngestMonitor ingestMonitor = new IngestMonitor();
private enum IngestManagerEvents {
SERVICE_STARTED, SERVICE_COMPLETED, SERVICE_STOPPED, SERVICE_HAS_DATA
};
public final static String SERVICE_STARTED_EVT = IngestManagerEvents.SERVICE_STARTED.name();
public final static String SERVICE_COMPLETED_EVT = IngestManagerEvents.SERVICE_COMPLETED.name();
public final static String SERVICE_STOPPED_EVT = IngestManagerEvents.SERVICE_STOPPED.name();
public final static String SERVICE_HAS_DATA_EVT = IngestManagerEvents.SERVICE_HAS_DATA.name();
//ui
private IngestUI ui = null;
//singleton
private static IngestManager instance;
private IngestManager() {
imageIngesters = new ArrayList<IngestImageThread>();
}
public static synchronized IngestManager getDefault() {
if (instance == null) {
logger.log(Level.INFO, "creating manager instance");
instance = new IngestManager();
}
return instance;
}
void initUI() {
ui = IngestMessageTopComponent.findInstance();
}
/**
* Add property change listener to listen to ingest events
* @param l PropertyChangeListener to add
*/
public static synchronized void addPropertyChangeListener(final PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public static synchronized void fireServiceEvent(String eventType, String serviceName) {
pcs.firePropertyChange(eventType, serviceName, null);
}
public static synchronized void fireServiceDataEvent(ServiceDataEvent serviceDataEvent) {
pcs.firePropertyChange(SERVICE_HAS_DATA_EVT, serviceDataEvent, null);
}
IngestServiceFsContent.ProcessResult getFsContentServiceResult(String serviceName) {
synchronized (fsContentServiceResults) {
if (fsContentServiceResults.containsKey(serviceName)) {
return fsContentServiceResults.get(serviceName);
} else {
return IngestServiceFsContent.ProcessResult.UNKNOWN;
}
}
}
/**
* Multiple image version of execute, enqueues multiple images and associated services at once
* @param services services to execute on every image
* @param images images to execute services on
*/
void execute(final List<IngestServiceAbstract> services, final List<Image> images) {
logger.log(Level.INFO, "Will enqueue number of images: " + images.size() + " to " + services.size() + " services.");
if (!isIngestRunning()) {
ui.clearMessages();
}
queueWorker = new EnqueueWorker(services, images);
queueWorker.execute();
ui.restoreMessages();
//logger.log(Level.INFO, "Queues: " + imageQueue.toString() + " " + fsContentQueue.toString());
}
/**
* IngestManager entry point, enqueues image to be processed.
* Spawns background thread which enumerates all sorted files and executes chosen services per file in a pre-determined order.
* Notifies services when work is complete or should be interrupted using complete() and stop() calls.
* Does not block and can be called multiple times to enqueue more work to already running background process.
* @param services services to execute on the image
* @param image image to execute services on
*/
void execute(final List<IngestServiceAbstract> services, final Image image) {
List<Image> images = new ArrayList<Image>();
images.add(image);
logger.log(Level.INFO, "Will enqueue image: " + image.getName());
execute(services, images);
}
/**
* Starts the needed worker threads.
*
* if fsContent service is still running, do nothing and allow it to consume queue
* otherwise start /restart fsContent worker
*
* image workers run per (service,image). Check if one for the (service,image) is already running
* otherwise start/restart the worker
*/
private synchronized void startAll() {
logger.log(Level.INFO, "Image queue: " + this.imageQueue.toString());
logger.log(Level.INFO, "File queue: " + this.fsContentQueue.toString());
if (!ingestMonitor.isRunning()) {
ingestMonitor.start();
}
//image ingesters
// cycle through each image in the queue
while (hasNextImage()) {
//dequeue
// get next image and set of services
final Map.Entry<Image, List<IngestServiceImage>> qu =
this.getNextImage();
// check if each service for this image is already running
//synchronized (this) {
for (IngestServiceImage quService : qu.getValue()) {
boolean alreadyRunning = false;
for (IngestImageThread worker : imageIngesters) {
// ignore threads that are on different images
if (!worker.getImage().equals(qu.getKey())) {
continue; //check next worker
}
//same image, check service (by name, not id, since different instances)
if (worker.getService().getName().equals(quService.getName())) {
alreadyRunning = true;
logger.log(Level.INFO, "Image Ingester <" + qu.getKey() + ", " + quService.getName() + "> is already running");
break;
}
}
//checked all workers
if (alreadyRunning == false) {
logger.log(Level.INFO, "Starting new image Ingester <" + qu.getKey() + ", " + quService.getName() + ">");
IngestImageThread newImageWorker = new IngestImageThread(this, qu.getKey(), quService);
imageIngesters.add(newImageWorker);
//image services are now initialized per instance
quService.init(managerProxy);
newImageWorker.execute();
IngestManager.fireServiceEvent(SERVICE_STARTED_EVT, quService.getName());
}
}
}
//}
//fsContent ingester
boolean startFsContentIngester = false;
if (hasNextFsContent()) {
if (fsContentIngester
== null) {
startFsContentIngester = true;
logger.log(Level.INFO, "Starting initial FsContent ingester");
} //if worker had completed, restart it in case data is still enqueued
else if (fsContentIngester.isDone()) {
startFsContentIngester = true;
logger.log(Level.INFO, "Restarting fsContent ingester");
}
} else {
logger.log(Level.INFO, "no new FsContent enqueued, no ingester needed");
}
if (startFsContentIngester) {
stats = new IngestManagerStats();
fsContentIngester = new IngestFsContentThread();
//init all fs services, everytime new worker starts
for (IngestServiceFsContent s : fsContentServices) {
s.init(managerProxy);
}
fsContentIngester.execute();
}
}
/**
* stop currently running threads if any (e.g. when changing a case)
*/
synchronized void stopAll() {
//stop queue worker
if (queueWorker != null) {
queueWorker.cancel(true);
queueWorker = null;
}
//empty queues
emptyFsContents();
emptyImages();
//stop service workers
if (fsContentIngester != null) {
//send signals to all file services
for (IngestServiceFsContent s : this.fsContentServices) {
if (isServiceRunning(s))
s.stop();
}
//stop fs ingester thread
boolean cancelled = fsContentIngester.cancel(true);
if (!cancelled) {
logger.log(Level.WARNING, "Unable to cancel file ingest worker");
} else {
fsContentIngester = null;
}
}
List<IngestImageThread> toStop = new ArrayList<IngestImageThread>();
toStop.addAll(imageIngesters);
for (IngestImageThread imageWorker : toStop) {
IngestServiceImage s = imageWorker.getService();
if (isServiceRunning(s))
imageWorker.getService().stop();
boolean cancelled = imageWorker.cancel(true);
if (!cancelled) {
logger.log(Level.WARNING, "Unable to cancel image ingest worker for service: " + imageWorker.getService().getName() + " img: " + imageWorker.getImage().getName());
}
}
logger.log(Level.INFO, "stopped all");
}
/**
* test if any of image of fscontent ingesters are running
* @return true if any service is running, false otherwise
*/
public synchronized boolean isIngestRunning() {
if (isEnqueueRunning()) {
return true;
} else if (isFileIngestRunning()) {
return true;
} else if (isImageIngestRunning()) {
return true;
} else {
return false;
}
}
public synchronized boolean isEnqueueRunning() {
if (queueWorker != null && !queueWorker.isDone()) {
return true;
}
return false;
}
public synchronized boolean isFileIngestRunning() {
if (fsContentIngester != null && !fsContentIngester.isDone()) {
return true;
}
return false;
}
public synchronized boolean isImageIngestRunning() {
if (imageIngesters.isEmpty()) {
return false;
}
//in case there are still image ingesters in the queue but already done
boolean allDone = true;
for (IngestImageThread ii : imageIngesters) {
if (ii.isDone() == false) {
allDone = false;
break;
}
}
if (allDone) {
return false;
} else {
return true;
}
}
/**
* check if the service is running (was started and not yet complete/stopped)
* give a complete answer, i.e. it's already consumed all files
* but it might have background threads running
*
*/
public boolean isServiceRunning(final IngestServiceAbstract service) {
if (service.getType() == IngestServiceAbstract.ServiceType.FsContent) {
synchronized (queuesLock) {
if (fsContentQueue.hasServiceEnqueued((IngestServiceFsContent) service)) {
//has work enqueued, so running
return true;
} else {
//not in the queue, but could still have bkg work running
return service.hasBackgroundJobsRunning();
}
}
} else {
//image service
synchronized (this) {
if (imageIngesters.isEmpty()) {
return false;
}
IngestImageThread imt = null;
for (IngestImageThread ii : imageIngesters) {
if (ii.getService().equals(service)) {
imt = ii;
break;
}
}
if (imt == null) {
return false;
}
if (imt.isDone() == false) {
return true;
} else {
return false;
}
}
}
}
/**
* returns the current minimal update frequency setting in minutes
* Services should call this at init() to get current setting
* and use the setting to change notification and data refresh intervals
*/
UpdateFrequency getUpdateFrequency() {
return updateFrequency;
}
/**
* set new minimal update frequency services should use
* @param frequency to use in minutes
*/
void setUpdateFrequency(UpdateFrequency frequency) {
this.updateFrequency = frequency;
}
/**
* returns ingest summary report (how many files ingested, any errors, etc)
*/
String getReport() {
return stats.toString();
}
/**
* Service publishes message using InegestManager handle
* Does not block.
* The message gets enqueued in the GUI thread and displayed in a widget
* IngestService should make an attempt not to publish the same message multiple times.
* Viewer will attempt to identify duplicate messages and filter them out (slower)
*/
synchronized void postMessage(final IngestMessage message) {
if (stats != null) {
//record the error for stats, if stats are running
if (message.getMessageType() == MessageType.ERROR) {
stats.addError(message.getSource());
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ui.displayMessage(message);
}
});
}
/**
* helper to return all image services managed (using Lookup API) sorted in Lookup position order
*/
public static List<IngestServiceImage> enumerateImageServices() {
List<IngestServiceImage> ret = new ArrayList<IngestServiceImage>();
for (IngestServiceImage list : Lookup.getDefault().lookupAll(IngestServiceImage.class)) {
ret.add(list);
}
return ret;
}
/**
* helper to return all file/dir services managed (using Lookup API) sorted in Lookup position order
*/
public static List<IngestServiceFsContent> enumerateFsContentServices() {
List<IngestServiceFsContent> ret = new ArrayList<IngestServiceFsContent>();
for (IngestServiceFsContent list : Lookup.getDefault().lookupAll(IngestServiceFsContent.class)) {
ret.add(list);
}
return ret;
}
/**
* Queue up an image to be processed by a given service.
* @param service Service to analyze image
* @param image Image to analyze
*/
private void addImage(IngestServiceImage service, Image image) {
synchronized (queuesLock) {
imageQueue.enqueue(image, service);
}
}
/**
* Queue up an image to be processed by a given File service.
* @param service
* @param image
*/
private void addFsContent(IngestServiceFsContent service, Collection<FsContent> fsContents) {
synchronized (queuesLock) {
for (FsContent fsContent : fsContents) {
fsContentQueue.enqueue(fsContent, service);
}
}
}
/**
* get next file/dir and associated list of services to process
* the queue of FsContent to process is maintained internally
* and could be dynamically sorted as data comes in
*/
private Map.Entry<FsContent, List<IngestServiceFsContent>> getNextFsContent() {
Map.Entry<FsContent, List<IngestServiceFsContent>> ret = null;
synchronized (queuesLock) {
ret = fsContentQueue.dequeue();
}
return ret;
}
private boolean hasNextFsContent() {
boolean ret = false;
synchronized (queuesLock) {
ret = fsContentQueue.hasNext();
}
return ret;
}
private int getNumFsContents() {
int ret = 0;
synchronized (queuesLock) {
ret = fsContentQueue.getCount();
}
return ret;
}
private void emptyFsContents() {
synchronized (queuesLock) {
fsContentQueue.empty();
}
}
private void emptyImages() {
synchronized (queuesLock) {
imageQueue.empty();
}
}
/**
* get next Image/Service pair to process
* the queue of Images to process is maintained internally
* and could be dynamically sorted as data comes in
*/
private Map.Entry<Image, List<IngestServiceImage>> getNextImage() {
Map.Entry<Image, List<IngestServiceImage>> ret = null;
synchronized (queuesLock) {
ret = imageQueue.dequeue();
}
return ret;
}
private boolean hasNextImage() {
boolean ret = false;
synchronized (queuesLock) {
ret = imageQueue.hasNext();
}
return ret;
}
private int getNumImages() {
int ret = 0;
synchronized (queuesLock) {
ret = imageQueue.getCount();
}
return ret;
}
//image worker to remove itself when complete or interrupted
void removeImageIngestWorker(IngestImageThread worker) {
//remove worker
synchronized (this) {
imageIngesters.remove(worker);
}
}
/**
* Priority determination for FsContent
*/
private static class FsContentPriotity {
enum Priority {
LOW, MEDIUM, HIGH
};
static final List<Pattern> lowPriorityPaths = new ArrayList<Pattern>();
static final List<Pattern> mediumPriorityPaths = new ArrayList<Pattern>();
static final List<Pattern> highPriorityPaths = new ArrayList<Pattern>();
static {
lowPriorityPaths.add(Pattern.compile("^\\/Windows", Pattern.CASE_INSENSITIVE));
mediumPriorityPaths.add(Pattern.compile("^\\/Program Files", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/Users", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/Documents and Settings", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/home", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/ProgramData", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/Windows\\/Temp", Pattern.CASE_INSENSITIVE));
}
static Priority getPriority(final FsContent fsContent) {
final String path = fsContent.getParentPath();
for (Pattern p : highPriorityPaths) {
Matcher m = p.matcher(path);
if (m.find()) {
return Priority.HIGH;
}
}
for (Pattern p : mediumPriorityPaths) {
Matcher m = p.matcher(path);
if (m.find()) {
return Priority.MEDIUM;
}
}
for (Pattern p : lowPriorityPaths) {
Matcher m = p.matcher(path);
if (m.find()) {
return Priority.LOW;
}
}
//default is medium
return Priority.MEDIUM;
}
}
/**
* manages queue of pending FsContent and list of associated IngestServiceFsContent to use on that content
* sorted based on FsContentPriotity
*/
private class FsContentQueue {
final Comparator<FsContent> sorter = new Comparator<FsContent>() {
@Override
public int compare(FsContent q1, FsContent q2) {
FsContentPriotity.Priority p1 = FsContentPriotity.getPriority(q1);
FsContentPriotity.Priority p2 = FsContentPriotity.getPriority(q2);
if (p1 == p2) {
return (int) (q2.getId() - q1.getId());
} else {
return p2.ordinal() - p1.ordinal();
}
}
};
final TreeMap<FsContent, List<IngestServiceFsContent>> fsContentUnits = new TreeMap<FsContent, List<IngestServiceFsContent>>(sorter);
void enqueue(FsContent fsContent, IngestServiceFsContent service) {
//fsContentUnits.put(fsContent, Collections.singletonList(service));
List<IngestServiceFsContent> services = fsContentUnits.get(fsContent);
if (services == null) {
services = new ArrayList<IngestServiceFsContent>();
fsContentUnits.put(fsContent, services);
}
services.add(service);
}
void enqueue(FsContent fsContent, List<IngestServiceFsContent> services) {
List<IngestServiceFsContent> oldServices = fsContentUnits.get(fsContent);
if (oldServices == null) {
oldServices = new ArrayList<IngestServiceFsContent>();
fsContentUnits.put(fsContent, oldServices);
}
oldServices.addAll(services);
}
boolean hasNext() {
return !fsContentUnits.isEmpty();
}
int getCount() {
return fsContentUnits.size();
}
void empty() {
fsContentUnits.clear();
}
/**
* Returns next FsContent and list of associated services
* @return
*/
Map.Entry<FsContent, List<IngestServiceFsContent>> dequeue() {
if (!hasNext()) {
throw new UnsupportedOperationException("FsContent processing queue is empty");
}
//logger.log(Level.INFO, "DEQUE: " + remove.content.getParentPath() + " SIZE: " + toString());
return (fsContentUnits.pollFirstEntry());
}
/**
* checks if the service has any work enqueued
* @param service to check for
* @return true if the service is enqueued to do work
*/
boolean hasServiceEnqueued(IngestServiceFsContent service) {
for (List<IngestServiceFsContent> list : fsContentUnits.values()) {
if (list.contains(service)) {
return true;
}
}
return false;
}
@Override
public synchronized String toString() {
return "FsContentQueue, size: " + Integer.toString(fsContentUnits.size());
}
public String printQueue() {
StringBuilder sb = new StringBuilder();
/*for (QueueUnit<FsContent, IngestServiceFsContent> u : fsContentUnits) {
sb.append(u.toString());
sb.append("\n");
}*/
return sb.toString();
}
}
/**
* manages queue of pending Images and IngestServiceImage to use on that image.
* image / service pairs are added one at a time and internally, it keeps track of all
* services for a given image.
*/
private class ImageQueue {
final Comparator<Image> sorter = new Comparator<Image>() {
@Override
public int compare(Image q1, Image q2) {
return (int) (q2.getId() - q1.getId());
}
};
private TreeMap<Image, List<IngestServiceImage>> imageUnits = new TreeMap<Image, List<IngestServiceImage>>(sorter);
void enqueue(Image image, IngestServiceImage service) {
List<IngestServiceImage> services = imageUnits.get(image);
if (services == null) {
services = new ArrayList<IngestServiceImage>();
imageUnits.put(image, services);
}
services.add(service);
}
void enqueue(Image image, List<IngestServiceImage> services) {
List<IngestServiceImage> oldServices = imageUnits.get(image);
if (oldServices == null) {
oldServices = new ArrayList<IngestServiceImage>();
imageUnits.put(image, oldServices);
}
oldServices.addAll(services);
}
boolean hasNext() {
return !imageUnits.isEmpty();
}
int getCount() {
return imageUnits.size();
}
void empty() {
imageUnits.clear();
}
/**
* Return a QueueUnit that contains an image and set of services to run on it.
* @return
*/
Map.Entry<Image, List<IngestServiceImage>> dequeue() {
if (!hasNext()) {
throw new UnsupportedOperationException("Image processing queue is empty");
}
return imageUnits.pollFirstEntry();
}
@Override
public synchronized String toString() {
return "ImageQueue, size: " + Integer.toString(imageUnits.size());
}
}
/**
* collects IngestManager statistics during runtime
*/
private static class IngestManagerStats {
Date startTime;
Date endTime;
int errorsTotal;
Map<IngestServiceAbstract, Integer> errors;
private static DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
IngestManagerStats() {
errors = new HashMap<IngestServiceAbstract, Integer>();
}
@Override
public String toString() {
final String EOL = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
if (startTime != null) {
sb.append("Start time: ").append(dateFormatter.format(startTime)).append(EOL);
}
if (endTime != null) {
sb.append("End time: ").append(dateFormatter.format(endTime)).append(EOL);
}
sb.append("Total ingest time: ").append(getTotalTimeString()).append(EOL);
sb.append("Total errors: ").append(errorsTotal).append(EOL);
if (errorsTotal > 0) {
sb.append("Errors per service:");
for (IngestServiceAbstract service : errors.keySet()) {
final int errorsService = errors.get(service);
sb.append("\t").append(service.getName()).append(": ").append(errorsService).append(EOL);
}
}
return sb.toString();
}
public String toHtmlString() {
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("Ingest time: ").append(getTotalTimeString()).append("<br />");
sb.append("Total errors: ").append(errorsTotal).append("<br />");
/*
if (errorsTotal > 0) {
sb.append("Errors per service:");
for (IngestServiceAbstract service : errors.keySet()) {
final int errorsService = errors.get(service);
sb.append("\t").append(service.getName()).append(": ").append(errorsService).append("<br />");
}
}
* */
sb.append("</html>");
return sb.toString();
}
void start() {
startTime = new Date();
}
void end() {
endTime = new Date();
}
long getTotalTime() {
if (startTime == null || endTime == null) {
return 0;
}
return endTime.getTime() - startTime.getTime();
}
String getStartTimeString() {
return dateFormatter.format(startTime);
}
String getEndTimeString() {
return dateFormatter.format(endTime);
}
String getTotalTimeString() {
long ms = getTotalTime();
long hours = TimeUnit.MILLISECONDS.toHours(ms);
ms -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(ms);
ms -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(ms);
final StringBuilder sb = new StringBuilder();
sb.append(hours < 10 ? "0" : "").append(hours).append(':').append(minutes < 10 ? "0" : "").append(minutes).append(':').append(seconds < 10 ? "0" : "").append(seconds);
return sb.toString();
}
synchronized void addError(IngestServiceAbstract source) {
++errorsTotal;
Integer curServiceErrorI = errors.get(source);
if (curServiceErrorI == null) {
errors.put(source, 1);
} else {
errors.put(source, curServiceErrorI + 1);
}
}
}
//ingester worker for fsContent queue
//worker runs until fsContent queue is consumed
//and if needed, new instance is created and started when data arrives
private class IngestFsContentThread extends SwingWorker {
private Logger logger = Logger.getLogger(IngestFsContentThread.class.getName());
private ProgressHandle progress;
@Override
protected Object doInBackground() throws Exception {
logger.log(Level.INFO, "Starting background processing");
stats.start();
//notify main thread services started
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
for (IngestServiceFsContent s : fsContentServices) {
IngestManager.fireServiceEvent(SERVICE_STARTED_EVT, s.getName());
}
}
});
progress = ProgressHandleFactory.createHandle("File Ingest", new Cancellable() {
@Override
public boolean cancel() {
return IngestFsContentThread.this.cancel(true);
}
});
progress.start();
progress.switchToIndeterminate();
int numFsContents = getNumFsContents();
progress.switchToDeterminate(numFsContents);
int processedFiles = 0;
//process fscontents queue
while (hasNextFsContent()) {
Map.Entry<FsContent, List<IngestServiceFsContent>> unit = getNextFsContent();
//clear return values from services for last file
synchronized (fsContentServiceResults) {
fsContentServiceResults.clear();
}
final FsContent fileToProcess = unit.getKey();
progress.progress(fileToProcess.getName(), processedFiles);
for (IngestServiceFsContent service : unit.getValue()) {
if (isCancelled()) {
return null;
}
try {
IngestServiceFsContent.ProcessResult result = service.process(fileToProcess);
//handle unconditional stop
if (result == IngestServiceFsContent.ProcessResult.STOP) {
break;
//will skip other services and start to process next file
}
//store the result for subsequent services for this file
synchronized (fsContentServiceResults) {
fsContentServiceResults.put(service.getName(), result);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception from service: " + service.getName(), e);
stats.addError(service);
}
}
int newFsContents = getNumFsContents();
if (newFsContents > numFsContents) {
//update progress bar if new enqueued
numFsContents = newFsContents + processedFiles + 1;
progress.switchToIndeterminate();
progress.switchToDeterminate(numFsContents);
}
++processedFiles;
--numFsContents;
} //end of this fsContent
logger.log(Level.INFO, "Done background processing");
return null;
}
@Override
protected void done() {
try {
super.get(); //block and get all exceptions thrown while doInBackground()
//notify services of completion
if (!this.isCancelled()) {
for (IngestServiceFsContent s : fsContentServices) {
s.complete();
IngestManager.fireServiceEvent(SERVICE_COMPLETED_EVT, s.getName());
}
}
} catch (CancellationException e) {
//task was cancelled
handleInterruption();
} catch (InterruptedException ex) {
handleInterruption();
} catch (ExecutionException ex) {
handleInterruption();
logger.log(Level.SEVERE, "Fatal error during ingest.", ex);
} catch (Exception ex) {
handleInterruption();
logger.log(Level.SEVERE, "Fatal error during ingest.", ex);
} finally {
stats.end();
progress.finish();
if (!this.isCancelled()) {
//logger.log(Level.INFO, "Summary Report: " + stats.toString());
//ui.displayReport(stats.toHtmlString());
IngestManager.this.postMessage(IngestMessage.createManagerMessage("File Ingest Complete", stats.toHtmlString()));
}
}
}
private void handleInterruption() {
for (IngestServiceFsContent s : fsContentServices) {
s.stop();
IngestManager.fireServiceEvent(SERVICE_STOPPED_EVT, s.getName());
}
//empty queues
emptyFsContents();
}
}
/* Thread that adds image/file and service pairs to queues */
private class EnqueueWorker extends SwingWorker {
List<IngestServiceAbstract> services;
final List<Image> images;
int total;
EnqueueWorker(final List<IngestServiceAbstract> services, final List<Image> images) {
this.services = services;
this.images = images;
}
private ProgressHandle progress;
@Override
protected Object doInBackground() throws Exception {
progress = ProgressHandleFactory.createHandle("Queueing Ingest", new Cancellable() {
@Override
public boolean cancel() {
return EnqueueWorker.this.cancel(true);
}
});
total = services.size() * images.size();
progress.start(total);
//progress.switchToIndeterminate();
queueAll(services, images);
return null;
}
/* clean up or start the worker threads */
@Override
protected void done() {
try {
super.get(); //block and get all exceptions thrown while doInBackground()
} catch (CancellationException e) {
//task was cancelled
handleInterruption();
} catch (InterruptedException ex) {
handleInterruption();
} catch (ExecutionException ex) {
handleInterruption();
} catch (Exception ex) {
handleInterruption();
} finally {
//queing end
if (this.isCancelled()) {
//empty queues
handleInterruption();
} else {
//start ingest workers
startAll();
}
progress.finish();
}
}
private void queueAll(List<IngestServiceAbstract> services, final List<Image> images) {
int processed = 0;
for (Image image : images) {
final String imageName = image.getName();
Collection<FsContent> fsContents = null;
for (IngestServiceAbstract service : services) {
if (isCancelled()) {
return;
}
final String serviceName = service.getName();
progress.progress(serviceName + " " + imageName, processed);
switch (service.getType()) {
case Image:
//enqueue a new instance of image service
try {
final IngestServiceImage newServiceInstance = (IngestServiceImage) (service.getClass()).newInstance();
addImage(newServiceInstance, image);
logger.log(Level.INFO, "Added image " + image.getName() + " with service " + service.getName());
} catch (InstantiationException e) {
logger.log(Level.SEVERE, "Cannot instantiate service: " + service.getName(), e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Cannot instantiate service: " + service.getName(), e);
}
//addImage((IngestServiceImage) service, image);
break;
case FsContent:
if (fsContents == null) {
long start = System.currentTimeMillis();
fsContents = new GetAllFilesContentVisitor().visit(image);
logger.info("Get all files took " + (System.currentTimeMillis() - start) + "ms");
}
//enqueue the same singleton fscontent service
logger.log(Level.INFO, "Adding image " + image.getName() + " with " + fsContents.size() + " number of fsContent to service " + service.getName());
addFsContent((IngestServiceFsContent) service, fsContents);
break;
default:
logger.log(Level.SEVERE, "Unexpected service type: " + service.getType().name());
}
progress.progress(serviceName + " " + imageName, ++processed);
}
if (fsContents != null) {
fsContents.clear();
}
}
//logger.log(Level.INFO, fsContentQueue.printQueue());
progress.progress("Sorting files", processed);
}
private void handleInterruption() {
//empty queues
emptyFsContents();
emptyImages();
}
}
}
| Ingest/src/org/sleuthkit/autopsy/ingest/IngestManager.java | /*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.ingest;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.util.Cancellable;
import org.openide.util.Lookup;
import org.sleuthkit.autopsy.ingest.IngestMessage.MessageType;
import org.sleuthkit.datamodel.FsContent;
import org.sleuthkit.datamodel.Image;
import org.sleuthkit.datamodel.TskData;
/**
* IngestManager sets up and manages ingest services
* runs them in a background thread
* notifies services when work is complete or should be interrupted
* processes messages from services via messenger proxy and posts them to GUI
*
*/
public class IngestManager {
enum UpdateFrequency {
FAST(20),
AVG(10),
SLOW(5);
private final int time;
UpdateFrequency(int time) {
this.time = time;
}
int getTime(){ return time;}
};
private static final Logger logger = Logger.getLogger(IngestManager.class.getName());
private IngestManagerStats stats;
private volatile UpdateFrequency updateFrequency = UpdateFrequency.AVG;
//queues
private final ImageQueue imageQueue = new ImageQueue(); // list of services and images to analyze
private final FsContentQueue fsContentQueue = new FsContentQueue();
private final Object queuesLock = new Object();
//workers
private IngestFsContentThread fsContentIngester;
private List<IngestImageThread> imageIngesters;
private SwingWorker queueWorker;
//services
final List<IngestServiceImage> imageServices = enumerateImageServices();
final List<IngestServiceFsContent> fsContentServices = enumerateFsContentServices();
// service return values
private final Map<String, IngestServiceFsContent.ProcessResult> fsContentServiceResults = new HashMap<String, IngestServiceFsContent.ProcessResult>();
//manager proxy
final IngestManagerProxy managerProxy = new IngestManagerProxy(this);
//notifications
private final static PropertyChangeSupport pcs = new PropertyChangeSupport(IngestManager.class);
//monitor
private final IngestMonitor ingestMonitor = new IngestMonitor();
private enum IngestManagerEvents {
SERVICE_STARTED, SERVICE_COMPLETED, SERVICE_STOPPED, SERVICE_HAS_DATA
};
public final static String SERVICE_STARTED_EVT = IngestManagerEvents.SERVICE_STARTED.name();
public final static String SERVICE_COMPLETED_EVT = IngestManagerEvents.SERVICE_COMPLETED.name();
public final static String SERVICE_STOPPED_EVT = IngestManagerEvents.SERVICE_STOPPED.name();
public final static String SERVICE_HAS_DATA_EVT = IngestManagerEvents.SERVICE_HAS_DATA.name();
//ui
private IngestUI ui = null;
//singleton
private static IngestManager instance;
private IngestManager() {
imageIngesters = new ArrayList<IngestImageThread>();
}
public static synchronized IngestManager getDefault() {
if (instance == null) {
logger.log(Level.INFO, "creating manager instance");
instance = new IngestManager();
}
return instance;
}
void initUI() {
ui = IngestMessageTopComponent.findInstance();
}
/**
* Add property change listener to listen to ingest events
* @param l PropertyChangeListener to add
*/
public static synchronized void addPropertyChangeListener(final PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public static synchronized void fireServiceEvent(String eventType, String serviceName) {
pcs.firePropertyChange(eventType, serviceName, null);
}
public static synchronized void fireServiceDataEvent(ServiceDataEvent serviceDataEvent) {
pcs.firePropertyChange(SERVICE_HAS_DATA_EVT, serviceDataEvent, null);
}
IngestServiceFsContent.ProcessResult getFsContentServiceResult(String serviceName) {
synchronized (fsContentServiceResults) {
if (fsContentServiceResults.containsKey(serviceName)) {
return fsContentServiceResults.get(serviceName);
} else {
return IngestServiceFsContent.ProcessResult.UNKNOWN;
}
}
}
/**
* Multiple image version of execute, enqueues multiple images and associated services at once
* @param services services to execute on every image
* @param images images to execute services on
*/
void execute(final List<IngestServiceAbstract> services, final List<Image> images) {
logger.log(Level.INFO, "Will enqueue number of images: " + images.size() + " to " + services.size() + " services.");
if (!isIngestRunning()) {
ui.clearMessages();
}
queueWorker = new EnqueueWorker(services, images);
queueWorker.execute();
ui.restoreMessages();
//logger.log(Level.INFO, "Queues: " + imageQueue.toString() + " " + fsContentQueue.toString());
}
/**
* IngestManager entry point, enqueues image to be processed.
* Spawns background thread which enumerates all sorted files and executes chosen services per file in a pre-determined order.
* Notifies services when work is complete or should be interrupted using complete() and stop() calls.
* Does not block and can be called multiple times to enqueue more work to already running background process.
* @param services services to execute on the image
* @param image image to execute services on
*/
void execute(final List<IngestServiceAbstract> services, final Image image) {
List<Image> images = new ArrayList<Image>();
images.add(image);
logger.log(Level.INFO, "Will enqueue image: " + image.getName());
execute(services, images);
}
/**
* Starts the needed worker threads.
*
* if fsContent service is still running, do nothing and allow it to consume queue
* otherwise start /restart fsContent worker
*
* image workers run per (service,image). Check if one for the (service,image) is already running
* otherwise start/restart the worker
*/
private synchronized void startAll() {
logger.log(Level.INFO, "Image queue: " + this.imageQueue.toString());
logger.log(Level.INFO, "File queue: " + this.fsContentQueue.toString());
if (! ingestMonitor.isRunning())
ingestMonitor.start();
//image ingesters
// cycle through each image in the queue
while (hasNextImage()) {
//dequeue
// get next image and set of services
final Map.Entry<Image, List<IngestServiceImage>> qu =
this.getNextImage();
// check if each service for this image is already running
//synchronized (this) {
for (IngestServiceImage quService : qu.getValue()) {
boolean alreadyRunning = false;
for (IngestImageThread worker : imageIngesters) {
// ignore threads that are on different images
if (!worker.getImage().equals(qu.getKey())) {
continue; //check next worker
}
//same image, check service (by name, not id, since different instances)
if (worker.getService().getName().equals(quService.getName())) {
alreadyRunning = true;
logger.log(Level.INFO, "Image Ingester <" + qu.getKey() + ", " + quService.getName() + "> is already running");
break;
}
}
//checked all workers
if (alreadyRunning == false) {
logger.log(Level.INFO, "Starting new image Ingester <" + qu.getKey() + ", " + quService.getName() + ">");
IngestImageThread newImageWorker = new IngestImageThread(this, qu.getKey(), quService);
imageIngesters.add(newImageWorker);
//image services are now initialized per instance
quService.init(managerProxy);
newImageWorker.execute();
IngestManager.fireServiceEvent(SERVICE_STARTED_EVT, quService.getName());
}
}
}
//}
//fsContent ingester
boolean startFsContentIngester = false;
if (hasNextFsContent()) {
if (fsContentIngester
== null) {
startFsContentIngester = true;
logger.log(Level.INFO, "Starting initial FsContent ingester");
} //if worker had completed, restart it in case data is still enqueued
else if (fsContentIngester.isDone()) {
startFsContentIngester = true;
logger.log(Level.INFO, "Restarting fsContent ingester");
}
} else {
logger.log(Level.INFO, "no new FsContent enqueued, no ingester needed");
}
if (startFsContentIngester) {
stats = new IngestManagerStats();
fsContentIngester = new IngestFsContentThread();
//init all fs services, everytime new worker starts
for (IngestServiceFsContent s : fsContentServices) {
s.init(managerProxy);
}
fsContentIngester.execute();
}
}
/**
* stop currently running threads if any (e.g. when changing a case)
*/
void stopAll() {
//stop queue worker
if (queueWorker != null) {
queueWorker.cancel(true);
queueWorker = null;
}
//empty queues
emptyFsContents();
emptyImages();
//stop service workers
if (fsContentIngester != null) {
boolean cancelled = fsContentIngester.cancel(true);
if (!cancelled) {
logger.log(Level.WARNING, "Unable to cancel file ingest worker");
} else {
fsContentIngester = null;
}
}
List<IngestImageThread> toStop = new ArrayList<IngestImageThread>();
synchronized (this) {
toStop.addAll(imageIngesters);
}
for (IngestImageThread imageWorker : toStop) {
boolean cancelled = imageWorker.cancel(true);
if (!cancelled) {
logger.log(Level.WARNING, "Unable to cancel image ingest worker for service: " + imageWorker.getService().getName() + " img: " + imageWorker.getImage().getName());
}
}
logger.log(Level.INFO, "stopped all");
}
/**
* test if any of image of fscontent ingesters are running
* @return true if any service is running, false otherwise
*/
public synchronized boolean isIngestRunning() {
if (isEnqueueRunning()) {
return true;
} else if (isFileIngestRunning()) {
return true;
} else if (isImageIngestRunning()) {
return true;
} else {
return false;
}
}
public synchronized boolean isEnqueueRunning() {
if (queueWorker != null && !queueWorker.isDone()) {
return true;
}
return false;
}
public synchronized boolean isFileIngestRunning() {
if (fsContentIngester != null && !fsContentIngester.isDone()) {
return true;
}
return false;
}
public synchronized boolean isImageIngestRunning() {
if (imageIngesters.isEmpty()) {
return false;
}
//in case there are still image ingesters in the queue but already done
boolean allDone = true;
for (IngestImageThread ii : imageIngesters) {
if (ii.isDone() == false) {
allDone = false;
break;
}
}
if (allDone) {
return false;
} else {
return true;
}
}
/**
* check if the service is running (was started and not yet complete/stopped)
* give a complete answer, i.e. it's already consumed all files
* but it might have background threads running
*
*/
public boolean isServiceRunning(final IngestServiceAbstract service) {
if (service.getType() == IngestServiceAbstract.ServiceType.FsContent) {
synchronized (queuesLock) {
if (fsContentQueue.hasServiceEnqueued((IngestServiceFsContent) service)) {
//has work enqueued, so running
return true;
} else {
//not in the queue, but could still have bkg work running
return service.hasBackgroundJobsRunning();
}
}
} else {
//image service
synchronized (this) {
if (imageIngesters.isEmpty()) {
return false;
}
IngestImageThread imt = null;
for (IngestImageThread ii : imageIngesters) {
if (ii.getService().equals(service)) {
imt = ii;
break;
}
}
if (imt == null) {
return false;
}
if (imt.isDone() == false) {
return true;
} else {
return false;
}
}
}
}
/**
* returns the current minimal update frequency setting in minutes
* Services should call this at init() to get current setting
* and use the setting to change notification and data refresh intervals
*/
UpdateFrequency getUpdateFrequency() {
return updateFrequency;
}
/**
* set new minimal update frequency services should use
* @param frequency to use in minutes
*/
void setUpdateFrequency(UpdateFrequency frequency) {
this.updateFrequency = frequency;
}
/**
* returns ingest summary report (how many files ingested, any errors, etc)
*/
String getReport() {
return stats.toString();
}
/**
* Service publishes message using InegestManager handle
* Does not block.
* The message gets enqueued in the GUI thread and displayed in a widget
* IngestService should make an attempt not to publish the same message multiple times.
* Viewer will attempt to identify duplicate messages and filter them out (slower)
*/
synchronized void postMessage(final IngestMessage message) {
if (stats != null) {
//record the error for stats, if stats are running
if (message.getMessageType() == MessageType.ERROR) {
stats.addError(message.getSource());
}
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ui.displayMessage(message);
}
});
}
/**
* helper to return all image services managed (using Lookup API) sorted in Lookup position order
*/
public static List<IngestServiceImage> enumerateImageServices() {
List<IngestServiceImage> ret = new ArrayList<IngestServiceImage>();
for (IngestServiceImage list : Lookup.getDefault().lookupAll(IngestServiceImage.class)) {
ret.add(list);
}
return ret;
}
/**
* helper to return all file/dir services managed (using Lookup API) sorted in Lookup position order
*/
public static List<IngestServiceFsContent> enumerateFsContentServices() {
List<IngestServiceFsContent> ret = new ArrayList<IngestServiceFsContent>();
for (IngestServiceFsContent list : Lookup.getDefault().lookupAll(IngestServiceFsContent.class)) {
ret.add(list);
}
return ret;
}
/**
* Queue up an image to be processed by a given service.
* @param service Service to analyze image
* @param image Image to analyze
*/
private void addImage(IngestServiceImage service, Image image) {
synchronized (queuesLock) {
imageQueue.enqueue(image, service);
}
}
/**
* Queue up an image to be processed by a given File service.
* @param service
* @param image
*/
private void addFsContent(IngestServiceFsContent service, Collection<FsContent> fsContents) {
synchronized (queuesLock) {
for (FsContent fsContent : fsContents) {
fsContentQueue.enqueue(fsContent, service);
}
}
}
/**
* get next file/dir and associated list of services to process
* the queue of FsContent to process is maintained internally
* and could be dynamically sorted as data comes in
*/
private Map.Entry<FsContent, List<IngestServiceFsContent>> getNextFsContent() {
Map.Entry<FsContent, List<IngestServiceFsContent>> ret = null;
synchronized (queuesLock) {
ret = fsContentQueue.dequeue();
}
return ret;
}
private boolean hasNextFsContent() {
boolean ret = false;
synchronized (queuesLock) {
ret = fsContentQueue.hasNext();
}
return ret;
}
private int getNumFsContents() {
int ret = 0;
synchronized (queuesLock) {
ret = fsContentQueue.getCount();
}
return ret;
}
private void emptyFsContents() {
synchronized (queuesLock) {
fsContentQueue.empty();
}
}
private void emptyImages() {
synchronized (queuesLock) {
imageQueue.empty();
}
}
/**
* get next Image/Service pair to process
* the queue of Images to process is maintained internally
* and could be dynamically sorted as data comes in
*/
private Map.Entry<Image, List<IngestServiceImage>> getNextImage() {
Map.Entry<Image, List<IngestServiceImage>> ret = null;
synchronized (queuesLock) {
ret = imageQueue.dequeue();
}
return ret;
}
private boolean hasNextImage() {
boolean ret = false;
synchronized (queuesLock) {
ret = imageQueue.hasNext();
}
return ret;
}
private int getNumImages() {
int ret = 0;
synchronized (queuesLock) {
ret = imageQueue.getCount();
}
return ret;
}
//image worker to remove itself when complete or interrupted
void removeImageIngestWorker(IngestImageThread worker) {
//remove worker
synchronized (this) {
imageIngesters.remove(worker);
}
}
/**
* Priority determination for FsContent
*/
private static class FsContentPriotity {
enum Priority {
LOW, MEDIUM, HIGH
};
static final List<Pattern> lowPriorityPaths = new ArrayList<Pattern>();
static final List<Pattern> mediumPriorityPaths = new ArrayList<Pattern>();
static final List<Pattern> highPriorityPaths = new ArrayList<Pattern>();
static {
lowPriorityPaths.add(Pattern.compile("^\\/Windows", Pattern.CASE_INSENSITIVE));
mediumPriorityPaths.add(Pattern.compile("^\\/Program Files", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/Users", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/Documents and Settings", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/home", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/ProgramData", Pattern.CASE_INSENSITIVE));
highPriorityPaths.add(Pattern.compile("^\\/Windows\\/Temp", Pattern.CASE_INSENSITIVE));
}
static Priority getPriority(final FsContent fsContent) {
final String path = fsContent.getParentPath();
for (Pattern p : highPriorityPaths) {
Matcher m = p.matcher(path);
if (m.find()) {
return Priority.HIGH;
}
}
for (Pattern p : mediumPriorityPaths) {
Matcher m = p.matcher(path);
if (m.find()) {
return Priority.MEDIUM;
}
}
for (Pattern p : lowPriorityPaths) {
Matcher m = p.matcher(path);
if (m.find()) {
return Priority.LOW;
}
}
//default is medium
return Priority.MEDIUM;
}
}
/**
* manages queue of pending FsContent and list of associated IngestServiceFsContent to use on that content
* sorted based on FsContentPriotity
*/
private class FsContentQueue {
final Comparator<FsContent> sorter = new Comparator<FsContent>() {
@Override
public int compare(FsContent q1, FsContent q2) {
FsContentPriotity.Priority p1 = FsContentPriotity.getPriority(q1);
FsContentPriotity.Priority p2 = FsContentPriotity.getPriority(q2);
if (p1 == p2) {
return (int) (q2.getId() - q1.getId());
} else {
return p2.ordinal() - p1.ordinal();
}
}
};
final TreeMap<FsContent, List<IngestServiceFsContent>> fsContentUnits = new TreeMap<FsContent, List<IngestServiceFsContent>>(sorter);
void enqueue(FsContent fsContent, IngestServiceFsContent service) {
//fsContentUnits.put(fsContent, Collections.singletonList(service));
List<IngestServiceFsContent> services = fsContentUnits.get(fsContent);
if (services == null) {
services = new ArrayList<IngestServiceFsContent>();
fsContentUnits.put(fsContent, services);
}
services.add(service);
}
void enqueue(FsContent fsContent, List<IngestServiceFsContent> services) {
List<IngestServiceFsContent> oldServices = fsContentUnits.get(fsContent);
if (oldServices == null) {
oldServices = new ArrayList<IngestServiceFsContent>();
fsContentUnits.put(fsContent, oldServices);
}
oldServices.addAll(services);
}
boolean hasNext() {
return !fsContentUnits.isEmpty();
}
int getCount() {
return fsContentUnits.size();
}
void empty() {
fsContentUnits.clear();
}
/**
* Returns next FsContent and list of associated services
* @return
*/
Map.Entry<FsContent, List<IngestServiceFsContent>> dequeue() {
if (!hasNext()) {
throw new UnsupportedOperationException("FsContent processing queue is empty");
}
//logger.log(Level.INFO, "DEQUE: " + remove.content.getParentPath() + " SIZE: " + toString());
return (fsContentUnits.pollFirstEntry());
}
/**
* checks if the service has any work enqueued
* @param service to check for
* @return true if the service is enqueued to do work
*/
boolean hasServiceEnqueued(IngestServiceFsContent service) {
for (List<IngestServiceFsContent> list : fsContentUnits.values()) {
if (list.contains(service)) {
return true;
}
}
return false;
}
@Override
public synchronized String toString() {
return "FsContentQueue, size: " + Integer.toString(fsContentUnits.size());
}
public String printQueue() {
StringBuilder sb = new StringBuilder();
/*for (QueueUnit<FsContent, IngestServiceFsContent> u : fsContentUnits) {
sb.append(u.toString());
sb.append("\n");
}*/
return sb.toString();
}
}
/**
* manages queue of pending Images and IngestServiceImage to use on that image.
* image / service pairs are added one at a time and internally, it keeps track of all
* services for a given image.
*/
private class ImageQueue {
final Comparator<Image> sorter = new Comparator<Image>() {
@Override
public int compare(Image q1, Image q2) {
return (int) (q2.getId() - q1.getId());
}
};
private TreeMap<Image, List<IngestServiceImage>> imageUnits = new TreeMap<Image, List<IngestServiceImage>>(sorter);
void enqueue(Image image, IngestServiceImage service) {
List<IngestServiceImage> services = imageUnits.get(image);
if (services == null) {
services = new ArrayList<IngestServiceImage>();
imageUnits.put(image, services);
}
services.add(service);
}
void enqueue(Image image, List<IngestServiceImage> services) {
List<IngestServiceImage> oldServices = imageUnits.get(image);
if (oldServices == null) {
oldServices = new ArrayList<IngestServiceImage>();
imageUnits.put(image, oldServices);
}
oldServices.addAll(services);
}
boolean hasNext() {
return !imageUnits.isEmpty();
}
int getCount() {
return imageUnits.size();
}
void empty() {
imageUnits.clear();
}
/**
* Return a QueueUnit that contains an image and set of services to run on it.
* @return
*/
Map.Entry<Image, List<IngestServiceImage>> dequeue() {
if (!hasNext()) {
throw new UnsupportedOperationException("Image processing queue is empty");
}
return imageUnits.pollFirstEntry();
}
@Override
public synchronized String toString() {
return "ImageQueue, size: " + Integer.toString(imageUnits.size());
}
}
/**
* collects IngestManager statistics during runtime
*/
private static class IngestManagerStats {
Date startTime;
Date endTime;
int errorsTotal;
Map<IngestServiceAbstract, Integer> errors;
private static DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
IngestManagerStats() {
errors = new HashMap<IngestServiceAbstract, Integer>();
}
@Override
public String toString() {
final String EOL = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder();
if (startTime != null) {
sb.append("Start time: ").append(dateFormatter.format(startTime)).append(EOL);
}
if (endTime != null) {
sb.append("End time: ").append(dateFormatter.format(endTime)).append(EOL);
}
sb.append("Total ingest time: ").append(getTotalTimeString()).append(EOL);
sb.append("Total errors: ").append(errorsTotal).append(EOL);
if (errorsTotal > 0) {
sb.append("Errors per service:");
for (IngestServiceAbstract service : errors.keySet()) {
final int errorsService = errors.get(service);
sb.append("\t").append(service.getName()).append(": ").append(errorsService).append(EOL);
}
}
return sb.toString();
}
public String toHtmlString() {
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("Ingest time: ").append(getTotalTimeString()).append("<br />");
sb.append("Total errors: ").append(errorsTotal).append("<br />");
/*
if (errorsTotal > 0) {
sb.append("Errors per service:");
for (IngestServiceAbstract service : errors.keySet()) {
final int errorsService = errors.get(service);
sb.append("\t").append(service.getName()).append(": ").append(errorsService).append("<br />");
}
}
* */
sb.append("</html>");
return sb.toString();
}
void start() {
startTime = new Date();
}
void end() {
endTime = new Date();
}
long getTotalTime() {
if (startTime == null || endTime == null) {
return 0;
}
return endTime.getTime() - startTime.getTime();
}
String getStartTimeString() {
return dateFormatter.format(startTime);
}
String getEndTimeString() {
return dateFormatter.format(endTime);
}
String getTotalTimeString() {
long ms = getTotalTime();
long hours = TimeUnit.MILLISECONDS.toHours(ms);
ms -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(ms);
ms -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(ms);
final StringBuilder sb = new StringBuilder();
sb.append(hours < 10 ? "0" : "").append(hours).append(':').append(minutes < 10 ? "0" : "").append(minutes).append(':').append(seconds < 10 ? "0" : "").append(seconds);
return sb.toString();
}
synchronized void addError(IngestServiceAbstract source) {
++errorsTotal;
Integer curServiceErrorI = errors.get(source);
if (curServiceErrorI == null) {
errors.put(source, 1);
} else {
errors.put(source, curServiceErrorI + 1);
}
}
}
//ingester worker for fsContent queue
//worker runs until fsContent queue is consumed
//and if needed, new instance is created and started when data arrives
private class IngestFsContentThread extends SwingWorker {
private Logger logger = Logger.getLogger(IngestFsContentThread.class.getName());
private ProgressHandle progress;
@Override
protected Object doInBackground() throws Exception {
logger.log(Level.INFO, "Starting background processing");
stats.start();
//notify main thread services started
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
for (IngestServiceFsContent s : fsContentServices) {
IngestManager.fireServiceEvent(SERVICE_STARTED_EVT, s.getName());
}
}
});
progress = ProgressHandleFactory.createHandle("File Ingest", new Cancellable() {
@Override
public boolean cancel() {
return IngestFsContentThread.this.cancel(true);
}
});
progress.start();
progress.switchToIndeterminate();
int numFsContents = getNumFsContents();
progress.switchToDeterminate(numFsContents);
int processedFiles = 0;
//process fscontents queue
while (hasNextFsContent()) {
Map.Entry<FsContent, List<IngestServiceFsContent>> unit = getNextFsContent();
//clear return values from services for last file
synchronized (fsContentServiceResults) {
fsContentServiceResults.clear();
}
final FsContent fileToProcess = unit.getKey();
progress.progress(fileToProcess.getName(), processedFiles);
for (IngestServiceFsContent service : unit.getValue()) {
if (isCancelled()) {
return null;
}
try {
IngestServiceFsContent.ProcessResult result = service.process(fileToProcess);
//handle unconditional stop
if (result == IngestServiceFsContent.ProcessResult.STOP) {
break;
//will skip other services and start to process next file
}
//store the result for subsequent services for this file
synchronized (fsContentServiceResults) {
fsContentServiceResults.put(service.getName(), result);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception from service: " + service.getName(), e);
stats.addError(service);
}
}
int newFsContents = getNumFsContents();
if (newFsContents > numFsContents) {
//update progress bar if new enqueued
numFsContents = newFsContents + processedFiles + 1;
progress.switchToIndeterminate();
progress.switchToDeterminate(numFsContents);
}
++processedFiles;
--numFsContents;
} //end of this fsContent
logger.log(Level.INFO, "Done background processing");
return null;
}
@Override
protected void done() {
try {
super.get(); //block and get all exceptions thrown while doInBackground()
//notify services of completion
if (!this.isCancelled()) {
for (IngestServiceFsContent s : fsContentServices) {
s.complete();
IngestManager.fireServiceEvent(SERVICE_COMPLETED_EVT, s.getName());
}
}
} catch (CancellationException e) {
//task was cancelled
handleInterruption();
} catch (InterruptedException ex) {
handleInterruption();
} catch (ExecutionException ex) {
handleInterruption();
logger.log(Level.SEVERE, "Fatal error during ingest.", ex);
} catch (Exception ex) {
handleInterruption();
logger.log(Level.SEVERE, "Fatal error during ingest.", ex);
} finally {
stats.end();
progress.finish();
if (!this.isCancelled()) {
//logger.log(Level.INFO, "Summary Report: " + stats.toString());
//ui.displayReport(stats.toHtmlString());
IngestManager.this.postMessage(IngestMessage.createManagerMessage("File Ingest Complete", stats.toHtmlString()));
}
}
}
private void handleInterruption() {
for (IngestServiceFsContent s : fsContentServices) {
s.stop();
IngestManager.fireServiceEvent(SERVICE_STOPPED_EVT, s.getName());
}
//empty queues
emptyFsContents();
}
}
/* Thread that adds image/file and service pairs to queues */
private class EnqueueWorker extends SwingWorker {
List<IngestServiceAbstract> services;
final List<Image> images;
int total;
EnqueueWorker(final List<IngestServiceAbstract> services, final List<Image> images) {
this.services = services;
this.images = images;
}
private ProgressHandle progress;
@Override
protected Object doInBackground() throws Exception {
progress = ProgressHandleFactory.createHandle("Queueing Ingest", new Cancellable() {
@Override
public boolean cancel() {
return EnqueueWorker.this.cancel(true);
}
});
total = services.size() * images.size();
progress.start(total);
//progress.switchToIndeterminate();
queueAll(services, images);
return null;
}
/* clean up or start the worker threads */
@Override
protected void done() {
try {
super.get(); //block and get all exceptions thrown while doInBackground()
} catch (CancellationException e) {
//task was cancelled
handleInterruption();
} catch (InterruptedException ex) {
handleInterruption();
} catch (ExecutionException ex) {
handleInterruption();
} catch (Exception ex) {
handleInterruption();
} finally {
//queing end
if (this.isCancelled()) {
//empty queues
handleInterruption();
} else {
//start ingest workers
startAll();
}
progress.finish();
}
}
private void queueAll(List<IngestServiceAbstract> services, final List<Image> images) {
int processed = 0;
for (Image image : images) {
final String imageName = image.getName();
Collection<FsContent> fsContents = null;
for (IngestServiceAbstract service : services) {
if (isCancelled()) {
return;
}
final String serviceName = service.getName();
progress.progress(serviceName + " " + imageName, processed);
switch (service.getType()) {
case Image:
//enqueue a new instance of image service
try {
final IngestServiceImage newServiceInstance = (IngestServiceImage) (service.getClass()).newInstance();
addImage(newServiceInstance, image);
logger.log(Level.INFO, "Added image " + image.getName() + " with service " + service.getName());
} catch (InstantiationException e) {
logger.log(Level.SEVERE, "Cannot instantiate service: " + service.getName(), e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Cannot instantiate service: " + service.getName(), e);
}
//addImage((IngestServiceImage) service, image);
break;
case FsContent:
if (fsContents == null) {
long start = System.currentTimeMillis();
fsContents = new GetAllFilesContentVisitor().visit(image);
logger.info("Get all files took " + (System.currentTimeMillis() - start) + "ms");
}
//enqueue the same singleton fscontent service
logger.log(Level.INFO, "Adding image " + image.getName() + " with " + fsContents.size() + " number of fsContent to service " + service.getName());
addFsContent((IngestServiceFsContent) service, fsContents);
break;
default:
logger.log(Level.SEVERE, "Unexpected service type: " + service.getType().name());
}
progress.progress(serviceName + " " + imageName, ++processed);
}
if (fsContents != null) {
fsContents.clear();
}
}
//logger.log(Level.INFO, fsContentQueue.printQueue());
progress.progress("Sorting files", processed);
}
private void handleInterruption() {
//empty queues
emptyFsContents();
emptyImages();
}
}
}
| Ensure any individual service managed background threads are shutdown first, before the ingester thread.
| Ingest/src/org/sleuthkit/autopsy/ingest/IngestManager.java | Ensure any individual service managed background threads are shutdown first, before the ingester thread. |
|
Java | apache-2.0 | 2d6c5bfb01713671cccc0c9543a4c0844f11bddb | 0 | oaugustus/phonegap-diagnostic-plugin,oaugustus/phonegap-diagnostic-plugin | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.neton.cordova.diagnostic;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.location.LocationManager;
import android.location.LocationListener;
public class Diagnostic extends CordovaPlugin {
public static final String TAG = "Diagnostic";
/**
* Constructor.
*/
public Diagnostic() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
JSONObject r = new JSONObject();
if (action.equals("switchToLocationSettings")){
switchToLocationSettings();
callbackContext.success();
} else
if (action.equals("isGpsEnabled")) {
r.put("success", isGpsEnabled());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
/**
* Check device settings for GPS.
*
* @returns {boolean} The status of GPS in device settings.
*/
public boolean isGpsEnabled() {
boolean result = isLocationProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d(TAG, "GPS enabled: " + result);
return result;
}
/**
* Requests that the user enable the location in device settings.
*/
public void switchToLocationSettings() {
Context ctx = this.cordova.getActivity().getApplicationContext();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
private boolean isLocationProviderEnabled(String provider) {
Context ctx = this.cordova.getActivity().getApplicationContext();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(provider);
}
}
| src/android/Diagnostic.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 com.neton.cordova.diagnostic;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.location.LocationManager;
import android.location.LocationListener;
public class Diagnostic extends CordovaPlugin {
public static final String TAG = "Diagnostic";
/**
* Constructor.
*/
public Diagnostic() {
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback id used when calling back into JavaScript.
* @return True if the action was valid, false if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
JSONObject r = new JSONObject();
if (action.equals("switchToLocationSettings")){
switchToLocationSettings();
callbackContext.success();
} else
if (action.equals("isGpsEnabled")) {
r.put("success", isGpsEnabled());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
/**
* Check device settings for GPS.
*
* @returns {boolean} The status of GPS in device settings.
*/
public boolean isGpsEnabled() {
boolean result = isLocationProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d(TAG, "GPS enabled: " + result);
return result;
}
/**
* Requests that the user enable the location in device settings.
*/
public void switchToLocationSettings() {
Context ctx = this.cordova.getActivity().getApplicationContext();
LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
private boolean isLocationProviderEnabled(String provider) {
Context ctx = this.cordova.getActivity().getApplicationContext();
LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(provider);
}
}
| Fixes
| src/android/Diagnostic.java | Fixes |
|
Java | apache-2.0 | 673e8581ae82e4c0a7a2704a944457aa09b5bf2c | 0 | aika-algorithm/aika,aika-algorithm/aika | /*
* 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 network.aika.neuron.phase;
/**
*
* @author Lukas Molzberger
*/
public class RankedImpl implements Ranked {
private Integer rank;
private Ranked previousRank;
public RankedImpl() {}
public RankedImpl(Ranked previousPhase) {
this.previousRank = previousPhase;
}
@Override
public Ranked getPreviousRank() {
return previousRank;
}
@Override
public int getRank() {
if(rank == null)
rank = getPreviousRank() != null ?
getPreviousRank().getRank() + 1 :
0;
return rank;
}
public String toString() {
return "Placeholder";
}
@Override
public String dumpPreviousRanks() {
return (getPreviousRank() != null ? getPreviousRank().dumpPreviousRanks() + "\n" : "") + getRank() + " : " + toString();
}
}
| src/main/java/network/aika/neuron/phase/RankedImpl.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 network.aika.neuron.phase;
/**
*
* @author Lukas Molzberger
*/
public class RankedImpl implements Ranked {
private Integer rank;
private Ranked previousRank;
public RankedImpl() {}
public RankedImpl(Ranked previousPhase) {
this.previousRank = previousPhase;
}
@Override
public Ranked getPreviousRank() {
return previousRank;
}
@Override
public int getRank() {
if(rank != null)
return rank;
if(getPreviousRank() == null) {
rank = 0;
} else {
rank = getPreviousRank().getRank() + 1;
}
return rank;
}
public String toString() {
return "";
}
@Override
public String dumpPreviousRanks() {
return (getPreviousRank() != null ? getPreviousRank().dumpPreviousRanks() + "\n" : "") + getRank() + " : " + toString();
}
}
| refactored phase ranking
| src/main/java/network/aika/neuron/phase/RankedImpl.java | refactored phase ranking |
|
Java | apache-2.0 | d592e1e161ec67929421d4beeb6216eba833c402 | 0 | DBCG/cql_measure_processor,DBCG/cqf-ruler,DBCG/cqf-ruler,DBCG/cqf-ruler,DBCG/cql_measure_processor | package org.opencds.cqf.r4.providers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.cqframework.cql.cql2elm.CqlTranslator;
import org.cqframework.cql.cql2elm.CqlTranslatorException;
import org.cqframework.cql.cql2elm.LibraryManager;
import org.cqframework.cql.cql2elm.ModelManager;
import org.cqframework.cql.elm.execution.VersionedIdentifier;
import org.cqframework.cql.elm.tracking.TrackBack;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Endpoint;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.Library;
import org.hl7.fhir.r4.model.Narrative;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.Resource;
import org.hl7.fhir.r4.model.StringType;
import org.opencds.cqf.common.evaluation.LibraryLoader;
import org.opencds.cqf.common.helpers.ClientHelperDos;
import org.opencds.cqf.common.helpers.DateHelper;
import org.opencds.cqf.common.helpers.TranslatorHelper;
import org.opencds.cqf.common.helpers.UsingHelper;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.common.providers.LibrarySourceProvider;
import org.opencds.cqf.common.providers.R4ApelonFhirTerminologyProvider;
import org.opencds.cqf.common.retrieve.JpaFhirRetrieveProvider;
import org.opencds.cqf.cql.engine.data.DataProvider;
import org.opencds.cqf.cql.engine.data.CompositeDataProvider;
import org.opencds.cqf.cql.engine.execution.Context;
import org.opencds.cqf.cql.engine.execution.CqlEngine;
import org.opencds.cqf.cql.engine.execution.EvaluationResult;
import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver;
import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver;
import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider;
import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver;
import org.opencds.cqf.cql.engine.fhir.terminology.R4FhirTerminologyProvider;
import org.opencds.cqf.cql.engine.retrieve.RetrieveProvider;
import org.opencds.cqf.cql.engine.runtime.DateTime;
import org.opencds.cqf.cql.engine.runtime.Interval;
import org.opencds.cqf.cql.engine.terminology.TerminologyProvider;
import org.opencds.cqf.library.r4.NarrativeProvider;
import org.opencds.cqf.r4.helpers.FhirMeasureBundler;
import org.opencds.cqf.r4.helpers.LibraryHelper;
import ca.uhn.fhir.jpa.dao.DaoRegistry;
import ca.uhn.fhir.jpa.rp.r4.LibraryResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.UriParam;
public class LibraryOperationsProvider implements LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> {
private NarrativeProvider narrativeProvider;
private DataRequirementsProvider dataRequirementsProvider;
private LibraryResourceProvider libraryResourceProvider;
DaoRegistry registry;
TerminologyProvider defaultTerminologyProvider;
public LibraryOperationsProvider(LibraryResourceProvider libraryResourceProvider,
NarrativeProvider narrativeProvider, DaoRegistry registry, TerminologyProvider defaultTerminologyProvider) {
this.narrativeProvider = narrativeProvider;
this.dataRequirementsProvider = new DataRequirementsProvider();
this.libraryResourceProvider = libraryResourceProvider;
this.registry = registry;
this.defaultTerminologyProvider = defaultTerminologyProvider;
}
private ModelManager getModelManager() {
return new ModelManager();
}
private LibraryManager getLibraryManager(ModelManager modelManager) {
LibraryManager libraryManager = new LibraryManager(modelManager);
libraryManager.getLibrarySourceLoader().clearProviders();
libraryManager.getLibrarySourceLoader().registerProvider(getLibrarySourceProvider());
return libraryManager;
}
private LibrarySourceProvider<org.hl7.fhir.r4.model.Library, org.hl7.fhir.r4.model.Attachment> librarySourceProvider;
private LibrarySourceProvider<org.hl7.fhir.r4.model.Library, org.hl7.fhir.r4.model.Attachment> getLibrarySourceProvider() {
if (librarySourceProvider == null) {
librarySourceProvider = new LibrarySourceProvider<org.hl7.fhir.r4.model.Library, org.hl7.fhir.r4.model.Attachment>(
getLibraryResourceProvider(), x -> x.getContent(), x -> x.getContentType(), x -> x.getData());
}
return librarySourceProvider;
}
private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> getLibraryResourceProvider() {
return this;
}
@Operation(name = "$refresh-generated-content", type = Library.class)
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
@IdParam IdType theId) {
Library theResource = this.libraryResourceProvider.getDao().read(theId);
// this.formatCql(theResource);
ModelManager modelManager = this.getModelManager();
LibraryManager libraryManager = this.getLibraryManager(modelManager);
CqlTranslator translator = this.dataRequirementsProvider.getTranslator(theResource, libraryManager,
modelManager);
if (translator.getErrors().size() > 0) {
throw new RuntimeException("Errors during library compilation.");
}
this.dataRequirementsProvider.ensureElm(theResource, translator);
this.dataRequirementsProvider.ensureRelatedArtifacts(theResource, translator, this);
this.dataRequirementsProvider.ensureDataRequirements(theResource, translator);
try {
Narrative n = this.narrativeProvider.getNarrative(this.libraryResourceProvider.getContext(), theResource);
theResource.setText(n);
} catch (Exception e) {
// Ignore the exception so the resource still gets updated
}
return this.libraryResourceProvider.update(theRequest, theResource, theId,
theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name = "$get-elm", idempotent = true, type = Library.class)
public Parameters getElm(@IdParam IdType theId, @OperationParam(name = "format") String format) {
Library theResource = this.libraryResourceProvider.getDao().read(theId);
// this.formatCql(theResource);
ModelManager modelManager = this.getModelManager();
LibraryManager libraryManager = this.getLibraryManager(modelManager);
String elm = "";
CqlTranslator translator = this.dataRequirementsProvider.getTranslator(theResource, libraryManager,
modelManager);
if (translator != null) {
if (format.equals("json")) {
elm = translator.toJson();
} else {
elm = translator.toXml();
}
}
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(elm));
return p;
}
@Operation(name = "$get-narrative", idempotent = true, type = Library.class)
public Parameters getNarrative(@IdParam IdType theId) {
Library theResource = this.libraryResourceProvider.getDao().read(theId);
Narrative n = this.narrativeProvider.getNarrative(this.libraryResourceProvider.getContext(), theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
// NOTICE: This is trash code that needs to be removed. Don't fix this. It's for
// a one-off
@Operation(name = "$evaluate", idempotent = true, type = Library.class)
public Bundle evaluate(@IdParam IdType theId, @OperationParam(name = "patientId") String patientId,
@OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd,
@OperationParam(name = "productLine") String productLine,
@OperationParam(name = "terminologyEndpoint") Endpoint terminologyEndpoint,
@OperationParam(name = "dataEndpoint") Endpoint dataEndpoint,
@OperationParam(name = "context") String contextParam,
@OperationParam(name = "executionResults") String executionResults,
@OperationParam(name = "parameters") Parameters parameters) {
if (patientId == null && contextParam != null && contextParam.equals("Patient")) {
throw new IllegalArgumentException("Must specify a patientId when executing in Patient context.");
}
Library theResource = this.libraryResourceProvider.getDao().read(theId);
VersionedIdentifier libraryIdentifier = new VersionedIdentifier().withId(theResource.getName())
.withVersion(theResource.getVersion());
FhirModelResolver resolver = new R4FhirModelResolver();
TerminologyProvider terminologyProvider;
if (terminologyEndpoint != null) {
IGenericClient client = ClientHelperDos.getClient(resolver.getFhirContext(), terminologyEndpoint);
if (terminologyEndpoint.getAddress().contains("apelon")) {
terminologyProvider = new R4ApelonFhirTerminologyProvider(client);
} else {
terminologyProvider = new R4FhirTerminologyProvider(client);
}
} else {
terminologyProvider = this.defaultTerminologyProvider;
}
DataProvider dataProvider;
if (dataEndpoint != null) {
IGenericClient client = ClientHelperDos.getClient(resolver.getFhirContext(), dataEndpoint);
RestFhirRetrieveProvider retriever = new RestFhirRetrieveProvider(new SearchParameterResolver(resolver.getFhirContext()), client);
retriever.setTerminologyProvider(terminologyProvider);
if (terminologyEndpoint == null ||(terminologyEndpoint != null && !terminologyEndpoint.getAddress().equals(dataEndpoint.getAddress()))) {
retriever.setExpandValueSets(true);
}
dataProvider = new CompositeDataProvider(resolver, retriever);
} else {
JpaFhirRetrieveProvider retriever = new JpaFhirRetrieveProvider(this.registry,
new SearchParameterResolver(resolver.getFhirContext()));
retriever.setTerminologyProvider(terminologyProvider);
// Assume it's a different server, therefore need to expand.
if (terminologyEndpoint != null) {
retriever.setExpandValueSets(true);
}
dataProvider = new CompositeDataProvider(resolver, retriever);
}
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.getLibraryResourceProvider());
CqlEngine engine = new CqlEngine(libraryLoader, Collections.singletonMap("http://hl7.org/fhir", dataProvider), terminologyProvider);
Map<String, Object> resolvedParameters = new HashMap<>();
if (parameters != null) {
for (Parameters.ParametersParameterComponent pc : parameters.getParameter()) {
resolvedParameters.put(pc.getName(), pc.getValue());
}
}
if (periodStart != null && periodEnd != null) {
// resolve the measurement period
Interval measurementPeriod = new Interval(DateHelper.resolveRequestDate(periodStart, true), true,
DateHelper.resolveRequestDate(periodEnd, false), true);
resolvedParameters.put("Measurement Period",
new Interval(DateTime.fromJavaDate((Date) measurementPeriod.getStart()), true,
DateTime.fromJavaDate((Date) measurementPeriod.getEnd()), true));
}
if (productLine != null) {
resolvedParameters.put("Product Line", productLine);
}
EvaluationResult evalResult = engine.evaluate(libraryIdentifier,
Pair.of(contextParam != null ? contextParam : "Unspecified", patientId == null ? "null" : patientId),
resolvedParameters);
List<Resource> results = new ArrayList<>();
FhirMeasureBundler bundler = new FhirMeasureBundler();
if (evalResult != null && evalResult.expressionResults != null) {
for (Map.Entry<String, Object> def : evalResult.expressionResults.entrySet()) {
Parameters result = new Parameters();
try {
result.setId(def.getKey());
Object res = def.getValue();
// String location = String.format("[%d:%d]",
// locations.get(def.getName()).get(0),
// locations.get(def.getName()).get(1));
// result.addParameter().setName("location").setValue(new StringType(location));
// Object res = def instanceof org.cqframework.cql.elm.execution.FunctionDef
// ? "Definition successfully validated"
// : def.getExpression().evaluate(context);
if (res == null) {
result.addParameter().setName("value").setValue(new StringType("null"));
} else if (res instanceof List<?>) {
if (((List<?>) res).size() > 0 && ((List<?>) res).get(0) instanceof Resource) {
if (executionResults != null && executionResults.equals("Summary")) {
result.addParameter().setName("value")
.setValue(new StringType(((Resource) ((List<?>) res).get(0)).getIdElement()
.getResourceType() + "/"
+ ((Resource) ((List<?>) res).get(0)).getIdElement().getIdPart()));
} else {
result.addParameter().setName("value").setResource(bundler.bundle((Iterable) res));
}
} else {
result.addParameter().setName("value").setValue(new StringType(res.toString()));
}
} else if (res instanceof Iterable) {
result.addParameter().setName("value").setResource(bundler.bundle((Iterable) res));
} else if (res instanceof Resource) {
if (executionResults != null && executionResults.equals("Summary")) {
result.addParameter().setName("value")
.setValue(new StringType(((Resource) res).getIdElement().getResourceType() + "/"
+ ((Resource) res).getIdElement().getIdPart()));
} else {
result.addParameter().setName("value").setResource((Resource) res);
}
} else {
result.addParameter().setName("value").setValue(new StringType(res.toString()));
}
result.addParameter().setName("resultType").setValue(new StringType(resolveType(res)));
} catch (RuntimeException re) {
re.printStackTrace();
String message = re.getMessage() != null ? re.getMessage() : re.getClass().getName();
result.addParameter().setName("error").setValue(new StringType(message));
}
results.add(result);
}
}
return bundler.bundle(results);
}
// TODO: Figure out if we should throw an exception or something here.
@Override
public void update(Library library) {
this.libraryResourceProvider.getDao().update(library);
}
@Override
public Library resolveLibraryById(String libraryId) {
try {
return this.libraryResourceProvider.getDao().read(new IdType(libraryId));
} catch (Exception e) {
throw new IllegalArgumentException(String.format("Could not resolve library id %s", libraryId));
}
}
@Override
public Library resolveLibraryByName(String libraryName, String libraryVersion) {
Iterable<org.hl7.fhir.r4.model.Library> libraries = getLibrariesByName(libraryName);
org.hl7.fhir.r4.model.Library library = LibraryResolutionProvider.selectFromList(libraries, libraryVersion,
x -> x.getVersion());
if (library == null) {
throw new IllegalArgumentException(String.format("Could not resolve library name %s", libraryName));
}
return library;
}
@Override
public Library resolveLibraryByCanonicalUrl(String url) {
Objects.requireNonNull(url, "url must not be null");
String[] parts = url.split("\\|");
String resourceUrl = parts[0];
String version = null;
if (parts.length > 1) {
version = parts[1];
}
SearchParameterMap map = new SearchParameterMap();
map.add("url", new UriParam(resourceUrl));
if (version != null) {
map.add("version", new TokenParam(version));
}
ca.uhn.fhir.rest.api.server.IBundleProvider bundleProvider = this.libraryResourceProvider.getDao().search(map);
if (bundleProvider.size() == 0) {
return null;
}
List<IBaseResource> resourceList = bundleProvider.getResources(0, bundleProvider.size());
return LibraryResolutionProvider.selectFromList(resolveLibraries(resourceList), version, x -> x.getVersion());
}
private Iterable<org.hl7.fhir.r4.model.Library> getLibrariesByName(String name) {
// Search for libraries by name
SearchParameterMap map = new SearchParameterMap();
map.add("name", new StringParam(name, true));
ca.uhn.fhir.rest.api.server.IBundleProvider bundleProvider = this.libraryResourceProvider.getDao().search(map);
if (bundleProvider.size() == 0) {
return new ArrayList<>();
}
List<IBaseResource> resourceList = bundleProvider.getResources(0, bundleProvider.size());
return resolveLibraries(resourceList);
}
private Iterable<org.hl7.fhir.r4.model.Library> resolveLibraries(List<IBaseResource> resourceList) {
List<org.hl7.fhir.r4.model.Library> ret = new ArrayList<>();
for (IBaseResource res : resourceList) {
Class<?> clazz = res.getClass();
ret.add((org.hl7.fhir.r4.model.Library) clazz.cast(res));
}
return ret;
}
private Map<String, List<Integer>> getLocations(org.hl7.elm.r1.Library library) {
Map<String, List<Integer>> locations = new HashMap<>();
if (library.getStatements() == null)
return locations;
for (org.hl7.elm.r1.ExpressionDef def : library.getStatements().getDef()) {
int startLine = def.getTrackbacks().isEmpty() ? 0 : def.getTrackbacks().get(0).getStartLine();
int startChar = def.getTrackbacks().isEmpty() ? 0 : def.getTrackbacks().get(0).getStartChar();
List<Integer> loc = Arrays.asList(startLine, startChar);
locations.put(def.getName(), loc);
}
return locations;
}
private String resolveType(Object result) {
String type = result == null ? "Null" : result.getClass().getSimpleName();
switch (type) {
case "BigDecimal":
return "Decimal";
case "ArrayList":
return "List";
case "FhirBundleCursor":
return "Retrieve";
}
return type;
}
} | r4/src/main/java/org/opencds/cqf/r4/providers/LibraryOperationsProvider.java | package org.opencds.cqf.r4.providers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.cqframework.cql.cql2elm.CqlTranslator;
import org.cqframework.cql.cql2elm.CqlTranslatorException;
import org.cqframework.cql.cql2elm.LibraryManager;
import org.cqframework.cql.cql2elm.ModelManager;
import org.cqframework.cql.elm.execution.VersionedIdentifier;
import org.cqframework.cql.elm.tracking.TrackBack;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Endpoint;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.Library;
import org.hl7.fhir.r4.model.Narrative;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.Resource;
import org.hl7.fhir.r4.model.StringType;
import org.opencds.cqf.common.evaluation.LibraryLoader;
import org.opencds.cqf.common.helpers.ClientHelperDos;
import org.opencds.cqf.common.helpers.DateHelper;
import org.opencds.cqf.common.helpers.TranslatorHelper;
import org.opencds.cqf.common.helpers.UsingHelper;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.common.providers.LibrarySourceProvider;
import org.opencds.cqf.common.providers.R4ApelonFhirTerminologyProvider;
import org.opencds.cqf.common.retrieve.JpaFhirRetrieveProvider;
import org.opencds.cqf.cql.engine.data.DataProvider;
import org.opencds.cqf.cql.engine.data.CompositeDataProvider;
import org.opencds.cqf.cql.engine.execution.Context;
import org.opencds.cqf.cql.engine.execution.CqlEngine;
import org.opencds.cqf.cql.engine.execution.EvaluationResult;
import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver;
import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver;
import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider;
import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver;
import org.opencds.cqf.cql.engine.fhir.terminology.R4FhirTerminologyProvider;
import org.opencds.cqf.cql.engine.retrieve.RetrieveProvider;
import org.opencds.cqf.cql.engine.runtime.DateTime;
import org.opencds.cqf.cql.engine.runtime.Interval;
import org.opencds.cqf.cql.engine.terminology.TerminologyProvider;
import org.opencds.cqf.library.r4.NarrativeProvider;
import org.opencds.cqf.r4.helpers.FhirMeasureBundler;
import org.opencds.cqf.r4.helpers.LibraryHelper;
import ca.uhn.fhir.jpa.dao.DaoRegistry;
import ca.uhn.fhir.jpa.rp.r4.LibraryResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.param.UriParam;
public class LibraryOperationsProvider implements LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> {
private NarrativeProvider narrativeProvider;
private DataRequirementsProvider dataRequirementsProvider;
private LibraryResourceProvider libraryResourceProvider;
DaoRegistry registry;
TerminologyProvider defaultTerminologyProvider;
public LibraryOperationsProvider(LibraryResourceProvider libraryResourceProvider,
NarrativeProvider narrativeProvider, DaoRegistry registry, TerminologyProvider defaultTerminologyProvider) {
this.narrativeProvider = narrativeProvider;
this.dataRequirementsProvider = new DataRequirementsProvider();
this.libraryResourceProvider = libraryResourceProvider;
this.registry = registry;
this.defaultTerminologyProvider = defaultTerminologyProvider;
}
private ModelManager getModelManager() {
return new ModelManager();
}
private LibraryManager getLibraryManager(ModelManager modelManager) {
LibraryManager libraryManager = new LibraryManager(modelManager);
libraryManager.getLibrarySourceLoader().clearProviders();
libraryManager.getLibrarySourceLoader().registerProvider(getLibrarySourceProvider());
return libraryManager;
}
private LibrarySourceProvider<org.hl7.fhir.r4.model.Library, org.hl7.fhir.r4.model.Attachment> librarySourceProvider;
private LibrarySourceProvider<org.hl7.fhir.r4.model.Library, org.hl7.fhir.r4.model.Attachment> getLibrarySourceProvider() {
if (librarySourceProvider == null) {
librarySourceProvider = new LibrarySourceProvider<org.hl7.fhir.r4.model.Library, org.hl7.fhir.r4.model.Attachment>(
getLibraryResourceProvider(), x -> x.getContent(), x -> x.getContentType(), x -> x.getData());
}
return librarySourceProvider;
}
private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> getLibraryResourceProvider() {
return this;
}
@Operation(name = "$refresh-generated-content", type = Library.class)
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
@IdParam IdType theId) {
Library theResource = this.libraryResourceProvider.getDao().read(theId);
// this.formatCql(theResource);
ModelManager modelManager = this.getModelManager();
LibraryManager libraryManager = this.getLibraryManager(modelManager);
CqlTranslator translator = this.dataRequirementsProvider.getTranslator(theResource, libraryManager,
modelManager);
if (translator.getErrors().size() > 0) {
throw new RuntimeException("Errors during library compilation.");
}
this.dataRequirementsProvider.ensureElm(theResource, translator);
this.dataRequirementsProvider.ensureRelatedArtifacts(theResource, translator, this);
this.dataRequirementsProvider.ensureDataRequirements(theResource, translator);
try {
Narrative n = this.narrativeProvider.getNarrative(this.libraryResourceProvider.getContext(), theResource);
theResource.setText(n);
} catch (Exception e) {
// Ignore the exception so the resource still gets updated
}
return this.libraryResourceProvider.update(theRequest, theResource, theId,
theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name = "$get-elm", idempotent = true, type = Library.class)
public Parameters getElm(@IdParam IdType theId, @OperationParam(name = "format") String format) {
Library theResource = this.libraryResourceProvider.getDao().read(theId);
// this.formatCql(theResource);
ModelManager modelManager = this.getModelManager();
LibraryManager libraryManager = this.getLibraryManager(modelManager);
String elm = "";
CqlTranslator translator = this.dataRequirementsProvider.getTranslator(theResource, libraryManager,
modelManager);
if (translator != null) {
if (format.equals("json")) {
elm = translator.toJson();
} else {
elm = translator.toXml();
}
}
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(elm));
return p;
}
@Operation(name = "$get-narrative", idempotent = true, type = Library.class)
public Parameters getNarrative(@IdParam IdType theId) {
Library theResource = this.libraryResourceProvider.getDao().read(theId);
Narrative n = this.narrativeProvider.getNarrative(this.libraryResourceProvider.getContext(), theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
// NOTICE: This is trash code that needs to be removed. Don't fix this. It's for
// a one-off
@Operation(name = "$evaluate", idempotent = true, type = Library.class)
public Bundle evaluate(@IdParam IdType theId, @OperationParam(name = "patientId") String patientId,
@OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd,
@OperationParam(name = "productLine") String productLine,
@OperationParam(name = "terminologyEndpoint") Endpoint terminologyEndpoint,
@OperationParam(name = "dataEndpoint") Endpoint dataEndpoint,
@OperationParam(name = "context") String contextParam,
@OperationParam(name = "executionResults") String executionResults,
@OperationParam(name = "parameters") Parameters parameters) {
if (patientId == null && contextParam != null && contextParam.equals("Patient")) {
throw new IllegalArgumentException("Must specify a patientId when executing in Patient context.");
}
Library theResource = this.libraryResourceProvider.getDao().read(theId);
VersionedIdentifier libraryIdentifier = new VersionedIdentifier().withId(theResource.getName())
.withVersion(theResource.getVersion());
FhirModelResolver resolver = new R4FhirModelResolver();
TerminologyProvider terminologyProvider;
if (terminologyEndpoint != null) {
IGenericClient client = ClientHelperDos.getClient(resolver.getFhirContext(), terminologyEndpoint);
if (terminologyEndpoint.getAddress().contains("apelon")) {
terminologyProvider = new R4ApelonFhirTerminologyProvider(client);
} else {
terminologyProvider = new R4FhirTerminologyProvider(client);
}
} else {
terminologyProvider = this.defaultTerminologyProvider;
}
DataProvider dataProvider;
if (dataEndpoint != null) {
IGenericClient client = ClientHelperDos.getClient(resolver.getFhirContext(), dataEndpoint);
RestFhirRetrieveProvider retriever = new RestFhirRetrieveProvider(new SearchParameterResolver(resolver.getFhirContext()), client);
retriever.setTerminologyProvider(terminologyProvider);
if (terminologyEndpoint != null && !terminologyEndpoint.getAddress().equals(dataEndpoint.getAddress())) {
retriever.setExpandValueSets(true);
}
dataProvider = new CompositeDataProvider(resolver, retriever);
} else {
JpaFhirRetrieveProvider retriever = new JpaFhirRetrieveProvider(this.registry,
new SearchParameterResolver(resolver.getFhirContext()));
retriever.setTerminologyProvider(terminologyProvider);
// Assume it's a different server, therefore need to expand.
if (terminologyEndpoint != null) {
retriever.setExpandValueSets(true);
}
dataProvider = new CompositeDataProvider(resolver, retriever);
}
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.getLibraryResourceProvider());
CqlEngine engine = new CqlEngine(libraryLoader, Collections.singletonMap("http://hl7.org/fhir", dataProvider), terminologyProvider);
Map<String, Object> resolvedParameters = new HashMap<>();
if (parameters != null) {
for (Parameters.ParametersParameterComponent pc : parameters.getParameter()) {
resolvedParameters.put(pc.getName(), pc.getValue());
}
}
if (periodStart != null && periodEnd != null) {
// resolve the measurement period
Interval measurementPeriod = new Interval(DateHelper.resolveRequestDate(periodStart, true), true,
DateHelper.resolveRequestDate(periodEnd, false), true);
resolvedParameters.put("Measurement Period",
new Interval(DateTime.fromJavaDate((Date) measurementPeriod.getStart()), true,
DateTime.fromJavaDate((Date) measurementPeriod.getEnd()), true));
}
if (productLine != null) {
resolvedParameters.put("Product Line", productLine);
}
EvaluationResult evalResult = engine.evaluate(libraryIdentifier,
Pair.of(contextParam != null ? contextParam : "Unspecified", patientId == null ? "null" : patientId),
resolvedParameters);
List<Resource> results = new ArrayList<>();
FhirMeasureBundler bundler = new FhirMeasureBundler();
if (evalResult != null && evalResult.expressionResults != null) {
for (Map.Entry<String, Object> def : evalResult.expressionResults.entrySet()) {
Parameters result = new Parameters();
try {
result.setId(def.getKey());
Object res = def.getValue();
// String location = String.format("[%d:%d]",
// locations.get(def.getName()).get(0),
// locations.get(def.getName()).get(1));
// result.addParameter().setName("location").setValue(new StringType(location));
// Object res = def instanceof org.cqframework.cql.elm.execution.FunctionDef
// ? "Definition successfully validated"
// : def.getExpression().evaluate(context);
if (res == null) {
result.addParameter().setName("value").setValue(new StringType("null"));
} else if (res instanceof List<?>) {
if (((List<?>) res).size() > 0 && ((List<?>) res).get(0) instanceof Resource) {
if (executionResults != null && executionResults.equals("Summary")) {
result.addParameter().setName("value")
.setValue(new StringType(((Resource) ((List<?>) res).get(0)).getIdElement()
.getResourceType() + "/"
+ ((Resource) ((List<?>) res).get(0)).getIdElement().getIdPart()));
} else {
result.addParameter().setName("value").setResource(bundler.bundle((Iterable) res));
}
} else {
result.addParameter().setName("value").setValue(new StringType(res.toString()));
}
} else if (res instanceof Iterable) {
result.addParameter().setName("value").setResource(bundler.bundle((Iterable) res));
} else if (res instanceof Resource) {
if (executionResults != null && executionResults.equals("Summary")) {
result.addParameter().setName("value")
.setValue(new StringType(((Resource) res).getIdElement().getResourceType() + "/"
+ ((Resource) res).getIdElement().getIdPart()));
} else {
result.addParameter().setName("value").setResource((Resource) res);
}
} else {
result.addParameter().setName("value").setValue(new StringType(res.toString()));
}
result.addParameter().setName("resultType").setValue(new StringType(resolveType(res)));
} catch (RuntimeException re) {
re.printStackTrace();
String message = re.getMessage() != null ? re.getMessage() : re.getClass().getName();
result.addParameter().setName("error").setValue(new StringType(message));
}
results.add(result);
}
}
return bundler.bundle(results);
}
// TODO: Figure out if we should throw an exception or something here.
@Override
public void update(Library library) {
this.libraryResourceProvider.getDao().update(library);
}
@Override
public Library resolveLibraryById(String libraryId) {
try {
return this.libraryResourceProvider.getDao().read(new IdType(libraryId));
} catch (Exception e) {
throw new IllegalArgumentException(String.format("Could not resolve library id %s", libraryId));
}
}
@Override
public Library resolveLibraryByName(String libraryName, String libraryVersion) {
Iterable<org.hl7.fhir.r4.model.Library> libraries = getLibrariesByName(libraryName);
org.hl7.fhir.r4.model.Library library = LibraryResolutionProvider.selectFromList(libraries, libraryVersion,
x -> x.getVersion());
if (library == null) {
throw new IllegalArgumentException(String.format("Could not resolve library name %s", libraryName));
}
return library;
}
@Override
public Library resolveLibraryByCanonicalUrl(String url) {
Objects.requireNonNull(url, "url must not be null");
String[] parts = url.split("\\|");
String resourceUrl = parts[0];
String version = null;
if (parts.length > 1) {
version = parts[1];
}
SearchParameterMap map = new SearchParameterMap();
map.add("url", new UriParam(resourceUrl));
if (version != null) {
map.add("version", new TokenParam(version));
}
ca.uhn.fhir.rest.api.server.IBundleProvider bundleProvider = this.libraryResourceProvider.getDao().search(map);
if (bundleProvider.size() == 0) {
return null;
}
List<IBaseResource> resourceList = bundleProvider.getResources(0, bundleProvider.size());
return LibraryResolutionProvider.selectFromList(resolveLibraries(resourceList), version, x -> x.getVersion());
}
private Iterable<org.hl7.fhir.r4.model.Library> getLibrariesByName(String name) {
// Search for libraries by name
SearchParameterMap map = new SearchParameterMap();
map.add("name", new StringParam(name, true));
ca.uhn.fhir.rest.api.server.IBundleProvider bundleProvider = this.libraryResourceProvider.getDao().search(map);
if (bundleProvider.size() == 0) {
return new ArrayList<>();
}
List<IBaseResource> resourceList = bundleProvider.getResources(0, bundleProvider.size());
return resolveLibraries(resourceList);
}
private Iterable<org.hl7.fhir.r4.model.Library> resolveLibraries(List<IBaseResource> resourceList) {
List<org.hl7.fhir.r4.model.Library> ret = new ArrayList<>();
for (IBaseResource res : resourceList) {
Class<?> clazz = res.getClass();
ret.add((org.hl7.fhir.r4.model.Library) clazz.cast(res));
}
return ret;
}
private Map<String, List<Integer>> getLocations(org.hl7.elm.r1.Library library) {
Map<String, List<Integer>> locations = new HashMap<>();
if (library.getStatements() == null)
return locations;
for (org.hl7.elm.r1.ExpressionDef def : library.getStatements().getDef()) {
int startLine = def.getTrackbacks().isEmpty() ? 0 : def.getTrackbacks().get(0).getStartLine();
int startChar = def.getTrackbacks().isEmpty() ? 0 : def.getTrackbacks().get(0).getStartChar();
List<Integer> loc = Arrays.asList(startLine, startChar);
locations.put(def.getName(), loc);
}
return locations;
}
private String resolveType(Object result) {
String type = result == null ? "Null" : result.getClass().getSimpleName();
switch (type) {
case "BigDecimal":
return "Decimal";
case "ArrayList":
return "List";
case "FhirBundleCursor":
return "Retrieve";
}
return type;
}
} | Fix not using local terminology provider
| r4/src/main/java/org/opencds/cqf/r4/providers/LibraryOperationsProvider.java | Fix not using local terminology provider |
|
Java | apache-2.0 | 0e86bcaaed699db925e42dbb6f9b45530129bd5a | 0 | IHTSDO/snomed-release-service,IHTSDO/snomed-release-service | package org.ihtsdo.buildcloud.config;
import org.ihtsdo.sso.integration.RequestHeaderAuthenticationDecorator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityContextConfiguration extends WebSecurityConfigurerAdapter {
@Value("${srs.basicAuth.username}")
private String username;
@Value("${srs.basicAuth.password}")
private String password;
/*
This configuration is required for basic authentication to work with this version of Spring Security (3.2.5.RELEASE).
In later versions default user credentials are read from the following properties in the application.properties file:
spring.security.user.name
spring.security.user.password
spring.security.user.roles
This functionality is implemented in class InitializeUserDetailsBeanManagerConfigurer.java since 4.1.x
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
.password(password)
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers("/snomed-release-service-websocket/**/*",
"/swagger-ui.html",
"/swagger-resources/**",
"/v2/api-docs",
"/webjars/springfox-swagger-ui/**").permitAll()
.anyRequest().authenticated()
.and().httpBasic();
http.csrf().disable();
http.addFilterAfter(new RequestHeaderAuthenticationDecorator(), BasicAuthenticationFilter.class);
}
// Does not seem to be used anywhere
@Bean
public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint() {
return new Http403ForbiddenEntryPoint();
}
} | src/main/java/org/ihtsdo/buildcloud/config/SecurityContextConfiguration.java | package org.ihtsdo.buildcloud.config;
import org.ihtsdo.sso.integration.RequestHeaderAuthenticationDecorator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityContextConfiguration extends WebSecurityConfigurerAdapter {
@Value("${srs.basicAuth.username}")
private String username;
@Value("${srs.basicAuth.password}")
private String password;
/*
This configuration is required for basic authentication to work with this version of Spring Security (3.2.5.RELEASE).
In later versions default user credentials are read from the following properties in the application.properties file:
spring.security.user.name
spring.security.user.password
spring.security.user.roles
This functionality is implemented in class InitializeUserDetailsBeanManagerConfigurer.java since 4.1.x
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser(username)
.password(password)
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers("/snomed-release-service-websocket",
"/swagger-ui.html",
"/swagger-resources/**",
"/v2/api-docs",
"/webjars/springfox-swagger-ui/**").permitAll()
.anyRequest().authenticated()
.and().httpBasic();
http.csrf().disable();
http.addFilterAfter(new RequestHeaderAuthenticationDecorator(), BasicAuthenticationFilter.class);
}
// Does not seem to be used anywhere
@Bean
public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint() {
return new Http403ForbiddenEntryPoint();
}
} | FRI-225 - Updated security configuration
| src/main/java/org/ihtsdo/buildcloud/config/SecurityContextConfiguration.java | FRI-225 - Updated security configuration |
|
Java | apache-2.0 | 257ca00b2f6d0e6e8a6d66b8513d9c7210217698 | 0 | meikaiyipian/solo,ZacharyChang/solo,istarvip/solo,taolong001/solo,lfyuan13/solo,meikaiyipian/solo,kanjianhaian/solo,AndiHappy/solo,sshiting/solo,EasonYi/solo,WilliamRen/solo,fengshao0907/solo,446541492/solo,b3log/b3log-solo,wziyong/solo,leontius/solo,xuzizzz/solo,lfyuan13/solo,fengjx/solo,oamzn/solo,b3log/b3log-solo,ZacharyChang/solo,cgm1521/b3log-solo,b3log/b3log-solo,RayWang8888/solo,xiongba-me/solo,446541492/solo,fengjx/solo,meikaiyipian/solo,istarvip/solo,VIRGIL-YAN/solo,oamzn/solo,leontius/solo,iceelor/solo,kanjianhaian/solo,lfyuan13/solo,ippxie/solo,RayWang8888/solo,sshiting/solo,iceelor/solo,iceelor/solo,fengshao0907/solo,oamzn/solo,xiongba-me/solo,taolong001/solo,gefangshuai/solo,fengshao0907/solo,wziyong/solo,ippxie/solo,VIRGIL-YAN/solo,EasonYi/solo,xuzizzz/solo,ZacharyChang/solo,leontius/solo,suclogger/solo,xiongba-me/solo,fengjx/solo,suclogger/solo,sitexa/solo,gefangshuai/solo,sitexa/solo,sshiting/solo,wziyong/solo,istarvip/solo,WilliamRen/solo,kanjianhaian/solo,RayWang8888/solo,xuzizzz/solo,ippxie/solo,xiongba-me/solo,AndiHappy/solo,sitexa/solo,suclogger/solo,EasonYi/solo,gefangshuai/solo,WilliamRen/solo,VIRGIL-YAN/solo,taolong001/solo,cgm1521/b3log-solo,446541492/solo,AndiHappy/solo | /*
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import org.b3log.latke.Keys;
import org.b3log.latke.event.EventManager;
import org.b3log.latke.plugin.PluginManager;
import org.b3log.latke.repository.Transaction;
import org.b3log.latke.servlet.AbstractServletListener;
import org.b3log.solo.event.comment.ArticleCommentReplyNotifier;
import org.b3log.solo.event.comment.PageCommentReplyNotifier;
import org.b3log.solo.event.ping.AddArticleGoogleBlogSearchPinger;
import org.b3log.solo.event.ping.UpdateArticleGoogleBlogSearchPinger;
import org.b3log.solo.event.rhythm.ArticleSender;
import org.b3log.solo.model.Preference;
import org.b3log.latke.plugin.ViewLoadEventHandler;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.util.Stopwatchs;
import org.b3log.latke.util.Strings;
import org.b3log.solo.event.plugin.PluginRefresher;
import org.b3log.solo.model.Skin;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.freemarker.Templates;
import org.b3log.solo.repository.PreferenceRepository;
import org.b3log.solo.repository.impl.PreferenceRepositoryImpl;
import org.b3log.solo.repository.impl.UserRepositoryImpl;
import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Statistics;
import org.json.JSONObject;
/**
* B3log Solo servlet listener.
*
* @author <a href="mailto:[email protected]">Liang Ding</a>
* @version 1.0.7.4, Jun 2, 2011
* @since 0.3.1
*/
public final class SoloServletListener extends AbstractServletListener {
/**
* B3log Solo version.
*/
public static final String VERSION = "0.4.6";
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(SoloServletListener.class.getName());
/**
* JSONO print indent factor.
*/
public static final int JSON_PRINT_INDENT_FACTOR = 4;
/**
* B3log Rhythm address.
*/
public static final String B3LOG_RHYTHM_ADDRESS = "http://rhythm.b3log.org:80";
/**
* Enter escape.
*/
public static final String ENTER_ESC = "_esc_enter_88250_";
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
Stopwatchs.start("Context Initialized");
super.contextInitialized(servletContextEvent);
// Default to skin "ease", loads from preference later
Skins.setDirectoryForTemplateLoading("ease");
final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance();
final Transaction transaction = preferenceRepository.beginTransaction();
// Cache will be cleared manaully if necessary, see loadPreference.
transaction.clearQueryCache(false);
try {
loadPreference();
if (transaction.isActive()) {
transaction.commit();
}
} catch (final Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
}
PluginManager.getInstance().load();
registerEventProcessor();
LOGGER.info("Initialized the context");
Stopwatchs.end();
LOGGER.log(Level.FINE, "Stopwatch: {0}{1}", new Object[]{Strings.LINE_SEPARATOR, Stopwatchs.getTimingStat()});
}
@Override
public void contextDestroyed(final ServletContextEvent servletContextEvent) {
super.contextDestroyed(servletContextEvent);
LOGGER.info("Destroyed the context");
}
@Override
public void sessionCreated(final HttpSessionEvent httpSessionEvent) {
}
// Note: This method will never invoked on GAE production environment
@Override
public void sessionDestroyed(final HttpSessionEvent httpSessionEvent) {
}
@Override
public void requestInitialized(final ServletRequestEvent servletRequestEvent) {
final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
final String requestURI = httpServletRequest.getRequestURI();
Stopwatchs.start("Request Initialized[requestURI=" + requestURI + "]");
if (Requests.searchEngineBotRequest(httpServletRequest)) {
LOGGER.log(Level.FINER, "Request made from a search engine[User-Agent={0}]", httpServletRequest.getHeader("User-Agent"));
httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, true);
} else {
// Gets the session of this request
final HttpSession session = httpServletRequest.getSession();
LOGGER.log(Level.FINE, "Gets a session[id={0}, remoteAddr={1}, User-Agent={2}, isNew={3}]",
new Object[]{session.getId(), httpServletRequest.getRemoteAddr(), httpServletRequest.getHeader("User-Agent"),
session.isNew()});
// Online visitor count
Statistics.onlineVisitorCount(httpServletRequest);
}
resolveSkinDir(httpServletRequest);
}
@Override
public void requestDestroyed(final ServletRequestEvent servletRequestEvent) {
Stopwatchs.end();
LOGGER.log(Level.FINE, "Stopwatch: {0}{1}", new Object[]{Strings.LINE_SEPARATOR, Stopwatchs.getTimingStat()});
Stopwatchs.release();
super.requestDestroyed(servletRequestEvent);
}
/**
* Loads preference.
*
* <p>
* Loads preference from repository, loads skins from skin directory then
* sets it into preference if the skins changed. Puts preference into
* cache and persists it to repository finally.
* </p>
*
* <p>
* <b>Note</b>: Do NOT use method
* {@linkplain org.b3log.solo.util.Preferences#getPreference()}
* to load it, caused by the method may retrieve it from cache.
* </p>
*/
private void loadPreference() {
Stopwatchs.start("Load Preference");
LOGGER.info("Loading preference....");
final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance();
JSONObject preference;
try {
preference = preferenceRepository.get(Preference.PREFERENCE);
if (null == preference) {
LOGGER.log(Level.WARNING, "Can't not init default skin, please init B3log Solo first");
return;
}
Skins.loadSkins(preference);
final boolean pageCacheEnabled = preference.getBoolean(Preference.PAGE_CACHE_ENABLED);
Templates.enableCache(pageCacheEnabled);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new IllegalStateException(e);
}
Stopwatchs.end();
}
/**
* Determines Solo had been initialized.
*
* @return {@code true} if it had been initialized, {@code false} otherwise
*/
// XXX: to find a better way (isInited)?
public static boolean isInited() {
try {
final JSONObject admin = UserRepositoryImpl.getInstance().getAdmin();
return null != admin;
} catch (final RepositoryException e) {
LOGGER.log(Level.WARNING, "B3log Solo has not been initialized");
return false;
}
}
/**
* Register event processors.
*/
private void registerEventProcessor() {
Stopwatchs.start("Register Event Processors");
LOGGER.log(Level.INFO, "Registering event processors....");
try {
final EventManager eventManager = EventManager.getInstance();
eventManager.registerListener(new ArticleCommentReplyNotifier());
eventManager.registerListener(new PageCommentReplyNotifier());
eventManager.registerListener(new AddArticleGoogleBlogSearchPinger());
eventManager.registerListener(new UpdateArticleGoogleBlogSearchPinger());
eventManager.registerListener(new ArticleSender());
eventManager.registerListener(new PluginRefresher());
eventManager.registerListener(new ViewLoadEventHandler());
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Register event processors error", e);
throw new IllegalStateException(e);
}
LOGGER.log(Level.INFO, "Registering event processors....");
Stopwatchs.end();
}
/**
* Resolve skin (template) for the specified HTTP servlet request.
*
* @param httpServletRequest the specified HTTP servlet request
*/
private void resolveSkinDir(final HttpServletRequest httpServletRequest) {
try {
final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance();
final JSONObject preference = preferenceRepository.get(Preference.PREFERENCE);
if (null == preference) { // Did not initialize yet
return;
}
final String requestURI = httpServletRequest.getRequestURI();
String desiredView = Requests.mobileSwitchToggle(httpServletRequest);
if (desiredView == null && !Requests.mobileRequest(httpServletRequest)
|| desiredView != null && desiredView.equals("normal")) {
desiredView = preference.getString(Skin.SKIN_DIR_NAME);
} else {
desiredView = "mobile";
LOGGER.log(Level.FINER, "The request [URI={0}] comes frome mobile device", requestURI);
}
httpServletRequest.setAttribute(Keys.TEMAPLTE_DIR_NAME, desiredView);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Resolves skin failed", e);
}
}
}
| core/src/main/java/org/b3log/solo/SoloServletListener.java | /*
* Copyright (c) 2009, 2010, 2011, 2012, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.solo;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import org.b3log.latke.Keys;
import org.b3log.latke.event.EventManager;
import org.b3log.latke.plugin.PluginManager;
import org.b3log.latke.repository.Transaction;
import org.b3log.latke.servlet.AbstractServletListener;
import org.b3log.solo.event.comment.ArticleCommentReplyNotifier;
import org.b3log.solo.event.comment.PageCommentReplyNotifier;
import org.b3log.solo.event.ping.AddArticleGoogleBlogSearchPinger;
import org.b3log.solo.event.ping.UpdateArticleGoogleBlogSearchPinger;
import org.b3log.solo.event.rhythm.ArticleSender;
import org.b3log.solo.model.Preference;
import org.b3log.latke.plugin.ViewLoadEventHandler;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.util.Stopwatchs;
import org.b3log.latke.util.Strings;
import org.b3log.solo.event.plugin.PluginRefresher;
import org.b3log.solo.model.Skin;
import org.b3log.latke.util.Requests;
import org.b3log.latke.util.freemarker.Templates;
import org.b3log.solo.repository.PreferenceRepository;
import org.b3log.solo.repository.impl.PreferenceRepositoryImpl;
import org.b3log.solo.repository.impl.UserRepositoryImpl;
import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Statistics;
import org.json.JSONObject;
/**
* B3log Solo servlet listener.
*
* @author <a href="mailto:[email protected]">Liang Ding</a>
* @version 1.0.7.3, Jun 19, 2011
* @since 0.3.1
*/
public final class SoloServletListener extends AbstractServletListener {
/**
* B3log Solo version.
*/
public static final String VERSION = "0.4.6";
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(SoloServletListener.class.getName());
/**
* JSONO print indent factor.
*/
public static final int JSON_PRINT_INDENT_FACTOR = 4;
/**
* B3log Rhythm address.
*/
public static final String B3LOG_RHYTHM_ADDRESS = "http://b3log-rhythm.appspot.com:80";
/**
* Enter escape.
*/
public static final String ENTER_ESC = "_esc_enter_88250_";
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
Stopwatchs.start("Context Initialized");
super.contextInitialized(servletContextEvent);
// Default to skin "ease", loads from preference later
Skins.setDirectoryForTemplateLoading("ease");
final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance();
final Transaction transaction = preferenceRepository.beginTransaction();
// Cache will be cleared manaully if necessary, see loadPreference.
transaction.clearQueryCache(false);
try {
loadPreference();
if (transaction.isActive()) {
transaction.commit();
}
} catch (final Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
}
PluginManager.getInstance().load();
registerEventProcessor();
LOGGER.info("Initialized the context");
Stopwatchs.end();
LOGGER.log(Level.FINE, "Stopwatch: {0}{1}", new Object[]{Strings.LINE_SEPARATOR, Stopwatchs.getTimingStat()});
}
@Override
public void contextDestroyed(final ServletContextEvent servletContextEvent) {
super.contextDestroyed(servletContextEvent);
LOGGER.info("Destroyed the context");
}
@Override
public void sessionCreated(final HttpSessionEvent httpSessionEvent) {
}
// Note: This method will never invoked on GAE production environment
@Override
public void sessionDestroyed(final HttpSessionEvent httpSessionEvent) {
}
@Override
public void requestInitialized(final ServletRequestEvent servletRequestEvent) {
final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequestEvent.getServletRequest();
final String requestURI = httpServletRequest.getRequestURI();
Stopwatchs.start("Request Initialized[requestURI=" + requestURI + "]");
if (Requests.searchEngineBotRequest(httpServletRequest)) {
LOGGER.log(Level.FINER, "Request made from a search engine[User-Agent={0}]", httpServletRequest.getHeader("User-Agent"));
httpServletRequest.setAttribute(Keys.HttpRequest.IS_SEARCH_ENGINE_BOT, true);
} else {
// Gets the session of this request
final HttpSession session = httpServletRequest.getSession();
LOGGER.log(Level.FINE, "Gets a session[id={0}, remoteAddr={1}, User-Agent={2}, isNew={3}]",
new Object[]{session.getId(), httpServletRequest.getRemoteAddr(), httpServletRequest.getHeader("User-Agent"),
session.isNew()});
// Online visitor count
Statistics.onlineVisitorCount(httpServletRequest);
}
resolveSkinDir(httpServletRequest);
}
@Override
public void requestDestroyed(final ServletRequestEvent servletRequestEvent) {
Stopwatchs.end();
LOGGER.log(Level.FINE, "Stopwatch: {0}{1}", new Object[]{Strings.LINE_SEPARATOR, Stopwatchs.getTimingStat()});
Stopwatchs.release();
super.requestDestroyed(servletRequestEvent);
}
/**
* Loads preference.
*
* <p>
* Loads preference from repository, loads skins from skin directory then
* sets it into preference if the skins changed. Puts preference into
* cache and persists it to repository finally.
* </p>
*
* <p>
* <b>Note</b>: Do NOT use method
* {@linkplain org.b3log.solo.util.Preferences#getPreference()}
* to load it, caused by the method may retrieve it from cache.
* </p>
*/
private void loadPreference() {
Stopwatchs.start("Load Preference");
LOGGER.info("Loading preference....");
final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance();
JSONObject preference;
try {
preference = preferenceRepository.get(Preference.PREFERENCE);
if (null == preference) {
LOGGER.log(Level.WARNING, "Can't not init default skin, please init B3log Solo first");
return;
}
Skins.loadSkins(preference);
final boolean pageCacheEnabled = preference.getBoolean(Preference.PAGE_CACHE_ENABLED);
Templates.enableCache(pageCacheEnabled);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
throw new IllegalStateException(e);
}
Stopwatchs.end();
}
/**
* Determines Solo had been initialized.
*
* @return {@code true} if it had been initialized, {@code false} otherwise
*/
// XXX: to find a better way (isInited)?
public static boolean isInited() {
try {
final JSONObject admin = UserRepositoryImpl.getInstance().getAdmin();
return null != admin;
} catch (final RepositoryException e) {
LOGGER.log(Level.WARNING, "B3log Solo has not been initialized");
return false;
}
}
/**
* Register event processors.
*/
private void registerEventProcessor() {
Stopwatchs.start("Register Event Processors");
LOGGER.log(Level.INFO, "Registering event processors....");
try {
final EventManager eventManager = EventManager.getInstance();
eventManager.registerListener(new ArticleCommentReplyNotifier());
eventManager.registerListener(new PageCommentReplyNotifier());
eventManager.registerListener(new AddArticleGoogleBlogSearchPinger());
eventManager.registerListener(new UpdateArticleGoogleBlogSearchPinger());
eventManager.registerListener(new ArticleSender());
eventManager.registerListener(new PluginRefresher());
eventManager.registerListener(new ViewLoadEventHandler());
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Register event processors error", e);
throw new IllegalStateException(e);
}
LOGGER.log(Level.INFO, "Registering event processors....");
Stopwatchs.end();
}
/**
* Resolve skin (template) for the specified HTTP servlet request.
*
* @param httpServletRequest the specified HTTP servlet request
*/
private void resolveSkinDir(final HttpServletRequest httpServletRequest) {
try {
final PreferenceRepository preferenceRepository = PreferenceRepositoryImpl.getInstance();
final JSONObject preference = preferenceRepository.get(Preference.PREFERENCE);
if (null == preference) { // Did not initialize yet
return;
}
final String requestURI = httpServletRequest.getRequestURI();
String desiredView = Requests.mobileSwitchToggle(httpServletRequest);
if (desiredView == null && !Requests.mobileRequest(httpServletRequest)
|| desiredView != null && desiredView.equals("normal")) {
desiredView = preference.getString(Skin.SKIN_DIR_NAME);
} else {
desiredView = "mobile";
LOGGER.log(Level.FINER, "The request [URI={0}] comes frome mobile device", requestURI);
}
httpServletRequest.setAttribute(Keys.TEMAPLTE_DIR_NAME, desiredView);
} catch (final Exception e) {
LOGGER.log(Level.SEVERE, "Resolves skin failed", e);
}
}
}
| 修改 Rhythm 调用地址
从 b3log-rhythm.appspot.com 改成 rhythm.b3log.org
| core/src/main/java/org/b3log/solo/SoloServletListener.java | 修改 Rhythm 调用地址 |
|
Java | apache-2.0 | 2f08d4aaa4ea7f0c6f5467b08ece344dffe2cec5 | 0 | pupnewfster/Lavasurvival,pupnewfster/Lavasurvival | package me.eddiep.minecraft.ls.system;
import me.eddiep.handles.ClassicPhysicsEvent;
import me.eddiep.minecraft.ls.Lavasurvival;
import me.eddiep.minecraft.ls.game.Gamemode;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.HashMap;
public class PhysicsListener implements Listener {
private static final long DEFAULT_SPEED = 5 * 20;
private static final HashMap<MaterialData, Integer> ticksToMelt = new HashMap<>();
private ArrayList<Integer> tasks = new ArrayList<>();
public PhysicsListener() {
setup();
}
private static void setup() {
if (ticksToMelt.size() > 0)
return;
//Default blocks
ticksToMelt.put(new MaterialData(Material.TORCH), 20);
ticksToMelt.put(new MaterialData(Material.WOOD), 55 * 20);
ticksToMelt.put(new MaterialData(Material.DIRT), 100 * 20);
ticksToMelt.put(new MaterialData(Material.GRASS), 100 * 20);
ticksToMelt.put(new MaterialData(Material.SAND), 70 * 20);
ticksToMelt.put(new MaterialData(Material.COBBLESTONE), 130 * 20);
//Basic blocks
ticksToMelt.put(new MaterialData(Material.GRAVEL), 140 * 20);
ticksToMelt.put(new MaterialData(Material.STONE), 190 * 20);
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 0), 80 * 20);//Oak log
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 1), 80 * 20);//Spruce log
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 2), 80 * 20);//Birch log
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 3), 80 * 20);//Jungle log
ticksToMelt.put(new MaterialData(Material.LOG_2, (byte) 0), 80 * 20);//Acacia log
ticksToMelt.put(new MaterialData(Material.LOG_2, (byte) 1), 80 * 20);//Dark oak log
ticksToMelt.put(new MaterialData(Material.SANDSTONE), 160 * 20);
ticksToMelt.put(new MaterialData(Material.HARD_CLAY), 130 * 20);
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 0), 115 * 20);//White clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 1), 115 * 20);//Orange clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 2), 115 * 20);//Magenta clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 3), 115 * 20);//Light blue clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 4), 115 * 20);//Yellow clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 5), 115 * 20);//Lime clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 6), 115 * 20);//Pink clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 7), 115 * 20);//Gray clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 8), 115 * 20);//Light gray clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 9), 115 * 20);//Cyan clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 10), 115 * 20);//Purple clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 11), 115 * 20);//Blue clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 12), 115 * 20);//Brown clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 13), 115 * 20);//Green clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 14), 115 * 20);//Red clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 15), 115 * 20);//Black clay
//Advanced blocks
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 0), 170 * 20);//Stone slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 1), 170 * 20);//Sandstone slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 3), 155 * 20);//Cobble slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 4), 170 * 20);//Brick slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 5), 175 * 20);//Stone brick slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 7), 178 * 20);//Quartz slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 0), 50 * 20);//Oak slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 1), 50 * 20);//Spruce slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 2), 50 * 20);//Birch slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 3), 50 * 20);//Jungle slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 4), 50 * 20);//Acacia slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 5), 50 * 20);//Dark oak slab
ticksToMelt.put(new MaterialData(Material.MOSSY_COBBLESTONE), 165 * 20);
ticksToMelt.put(new MaterialData(Material.SMOOTH_BRICK, (byte) 2), 164 * 20);//Cracked stone brick
ticksToMelt.put(new MaterialData(Material.GLASS), 168 * 20);
//Survivor blocks
ticksToMelt.put(new MaterialData(Material.PACKED_ICE), 10 * 20);
ticksToMelt.put(new MaterialData(Material.BRICK), 180 * 20);
ticksToMelt.put(new MaterialData(Material.SMOOTH_BRICK, (byte) 0), 184 * 20);//Stone brick
ticksToMelt.put(new MaterialData(Material.THIN_GLASS), 168 * 20);
ticksToMelt.put(new MaterialData(Material.IRON_FENCE), 195 * 20);//Iron bars
ticksToMelt.put(new MaterialData(Material.IRON_BLOCK), 200 * 20);
//Trusted blocks
ticksToMelt.put(new MaterialData(Material.FLOWER_POT_ITEM), 3 * 20);
ticksToMelt.put(new MaterialData(Material.FLOWER_POT), 3 * 20);
//ticksToMelt.put(new MaterialData(Material.YELLOW_FLOWER), ()) Flowers don't melt :3
//ticksToMelt.put(new MaterialData(Material.RED_ROSE), ()); Flowers don't melt :3
ticksToMelt.put(new MaterialData(Material.WOOD_DOOR), 55 * 20);
ticksToMelt.put(new MaterialData(Material.WOODEN_DOOR), 55 * 20);
ticksToMelt.put(new MaterialData(Material.BOOKSHELF), 100 * 20);
ticksToMelt.put(new MaterialData(Material.FENCE), 53 * 20);
ticksToMelt.put(new MaterialData(Material.WOOD_STAIRS), 65 * 20);//Oak stairs
ticksToMelt.put(new MaterialData(Material.COBBLESTONE_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.BRICK_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.SMOOTH_STAIRS), 65 * 20);//Stone brick stairs
ticksToMelt.put(new MaterialData(Material.SANDSTONE_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.SPRUCE_WOOD_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.BIRCH_WOOD_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.JUNGLE_WOOD_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.QUARTZ_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.ACACIA_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.DARK_OAK_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.COBBLE_WALL, (byte) 0), 130 * 20);//Cobblestone wall
ticksToMelt.put(new MaterialData(Material.COBBLE_WALL, (byte) 1), 130 * 20);//Mossy cobblestone wall
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 0), 168 * 20);//White glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 1), 168 * 20);//Orange glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 2), 168 * 20);//Magenta glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 3), 168 * 20);//Light blue glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 4), 168 * 20);//Yellow glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 5), 168 * 20);//Lime glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 6), 168 * 20);//Pink glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 7), 168 * 20);//Gray glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 8), 168 * 20);//Light gray glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 9), 168 * 20);//Cyan glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 10), 168 * 20);//Purple glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 11), 168 * 20);//Blue glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 12), 168 * 20);//Brown glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 13), 168 * 20);//Green glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 14), 168 * 20);//Red glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 15), 168 * 20);//Black glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 0), 168 * 20);//White glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 1), 168 * 20);//Orange glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 2), 168 * 20);//Magenta glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 3), 168 * 20);//Light blue glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 4), 168 * 20);//Yellow glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 5), 168 * 20);//Lime glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 6), 168 * 20);//Pink glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 7), 168 * 20);//Gray glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 8), 168 * 20);//Light gray glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 9), 168 * 20);//Cyan glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 10), 168 * 20);//Purple glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 11), 168 * 20);//Blue glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 12), 168 * 20);//Brown glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 13), 168 * 20);//Green glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 14), 168 * 20);//Red glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 15), 168 * 20);//Black glass pane
//Elder blocks
ticksToMelt.put(new MaterialData(Material.GLOWSTONE), 100 * 20);
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 6), 165 * 20);//Nether brick slab
ticksToMelt.put(new MaterialData(Material.NETHER_FENCE), 300 * 20);
ticksToMelt.put(new MaterialData(Material.NETHERRACK), 330 * 20);
ticksToMelt.put(new MaterialData(Material.NETHER_BRICK), 370 * 20);
ticksToMelt.put(new MaterialData(Material.NETHER_BRICK_STAIRS), 250 * 20);
ticksToMelt.put(new MaterialData(Material.ENDER_STONE), 400 * 20);
//Unburnable
ticksToMelt.put(new MaterialData(Material.YELLOW_FLOWER), -1);
ticksToMelt.put(new MaterialData(Material.RED_ROSE), -1);
ticksToMelt.put(new MaterialData(Material.IRON_DOOR_BLOCK), -1);
ticksToMelt.put(new MaterialData(Material.BEDROCK), -1);
ticksToMelt.put(new MaterialData(Material.OBSIDIAN), -1);
ticksToMelt.put(new MaterialData(Material.BARRIER), -1);
for (Material m : Material.values())
if (!m.equals(Material.LAVA) && !m.equals(Material.STATIONARY_LAVA) && !m.equals(Material.WATER) && !m.equals(Material.STATIONARY_WATER) && !m.equals(Material.AIR) &&
!ticksToMelt.containsKey(new MaterialData(m)))
ticksToMelt.put(new MaterialData(m), 30 * 20);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onClassicPhysics(final ClassicPhysicsEvent event) {
if (!event.isClassicEvent() || Gamemode.getCurrentGame().hasEnded())
return;
final Block blockChecking = event.getOldBlock();
if (blockChecking.getType().equals(Material.AIR))
return;
MaterialData dat = new MaterialData(blockChecking.getType(), blockChecking.getData());
if (!ticksToMelt.containsKey(dat))
dat = new MaterialData(blockChecking.getType());
if (ticksToMelt.containsKey(dat)) {
event.setCancelled(true);
long tickCount = ticksToMelt.get(dat);
if (tickCount == -1) //It's unburnable
return;
if (!blockChecking.hasMetadata("player_placed"))
tickCount /= 2;
int task = Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() {
@Override
public void run() {
Lavasurvival.INSTANCE.getPhysicsHandler().placeClassicBlockAt(event.getLocation(), event.getLogicContainer().logicFor());
}
}, tickCount);
tasks.add(task);
}
}
public static String getMeltTimeAsString(MaterialData data) {
int seconds = ticksToMelt.containsKey(data) ? ticksToMelt.get(data) / 20 : 0;
if (seconds == 0) {
return "Immediately";
} else if (seconds < 0) {
return "Never";
} else {
return seconds + " Second" + (seconds == 1 ? "" : "s");
}
}
public static int getMeltTime(MaterialData data) {//seconds
return ticksToMelt.containsKey(data) ? ticksToMelt.get(data) / 20 : 0;
}
public void cancelAllTasks() {
tasks.clear();
}
public void cleanup() {
cancelAllTasks();
HandlerList.unregisterAll(this);
}
} | Lavasurvival/src/main/java/me/eddiep/minecraft/ls/system/PhysicsListener.java | package me.eddiep.minecraft.ls.system;
import me.eddiep.handles.ClassicPhysicsEvent;
import me.eddiep.minecraft.ls.Lavasurvival;
import me.eddiep.minecraft.ls.game.Gamemode;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.HashMap;
public class PhysicsListener implements Listener {
private static final long DEFAULT_SPEED = 5 * 20;
private static final HashMap<MaterialData, Integer> ticksToMelt = new HashMap<>();
private ArrayList<Integer> tasks = new ArrayList<>();
public PhysicsListener() {
setup();
}
private static void setup() {
if (ticksToMelt.size() > 0)
return;
//Default blocks
ticksToMelt.put(new MaterialData(Material.TORCH), 20);
ticksToMelt.put(new MaterialData(Material.WOOD), 55 * 20);
ticksToMelt.put(new MaterialData(Material.DIRT), 100 * 20);
ticksToMelt.put(new MaterialData(Material.GRASS), 100 * 20);
ticksToMelt.put(new MaterialData(Material.SAND), 70 * 20);
ticksToMelt.put(new MaterialData(Material.COBBLESTONE), 130 * 20);
//Basic blocks
ticksToMelt.put(new MaterialData(Material.GRAVEL), 140 * 20);
ticksToMelt.put(new MaterialData(Material.STONE), 190 * 20);
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 0), 80 * 20);//Oak log
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 1), 80 * 20);//Spruce log
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 2), 80 * 20);//Birch log
ticksToMelt.put(new MaterialData(Material.LOG, (byte) 3), 80 * 20);//Jungle log
ticksToMelt.put(new MaterialData(Material.LOG_2, (byte) 0), 80 * 20);//Acacia log
ticksToMelt.put(new MaterialData(Material.LOG_2, (byte) 1), 80 * 20);//Dark oak log
ticksToMelt.put(new MaterialData(Material.SANDSTONE), 160 * 20);
ticksToMelt.put(new MaterialData(Material.HARD_CLAY), 130 * 20);
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 0), 115 * 20);//White clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 1), 115 * 20);//Orange clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 2), 115 * 20);//Magenta clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 3), 115 * 20);//Light blue clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 4), 115 * 20);//Yellow clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 5), 115 * 20);//Lime clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 6), 115 * 20);//Pink clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 7), 115 * 20);//Gray clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 8), 115 * 20);//Light gray clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 9), 115 * 20);//Cyan clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 10), 115 * 20);//Purple clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 11), 115 * 20);//Blue clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 12), 115 * 20);//Brown clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 13), 115 * 20);//Green clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 14), 115 * 20);//Red clay
ticksToMelt.put(new MaterialData(Material.STAINED_CLAY, (byte) 15), 115 * 20);//Black clay
//Advanced blocks
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 0), 170 * 20);//Stone slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 1), 170 * 20);//Sandstone slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 3), 155 * 20);//Cobble slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 4), 170 * 20);//Brick slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 5), 175 * 20);//Stone brick slab
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 7), 178 * 20);//Quartz slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 0), 50 * 20);//Oak slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 1), 50 * 20);//Spruce slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 2), 50 * 20);//Birch slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 3), 50 * 20);//Jungle slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 4), 50 * 20);//Acacia slab
ticksToMelt.put(new MaterialData(Material.WOOD_STEP, (byte) 5), 50 * 20);//Dark oak slab
ticksToMelt.put(new MaterialData(Material.MOSSY_COBBLESTONE), 165 * 20);
ticksToMelt.put(new MaterialData(Material.SMOOTH_BRICK, (byte) 2), 164 * 20);//Cracked stone brick
ticksToMelt.put(new MaterialData(Material.GLASS), 168 * 20);
//Survivor blocks
ticksToMelt.put(new MaterialData(Material.PACKED_ICE), 10 * 20);
ticksToMelt.put(new MaterialData(Material.BRICK), 180 * 20);
ticksToMelt.put(new MaterialData(Material.SMOOTH_BRICK, (byte) 0), 184 * 20);//Stone brick
ticksToMelt.put(new MaterialData(Material.THIN_GLASS), 168 * 20);
ticksToMelt.put(new MaterialData(Material.IRON_FENCE), 195 * 20);//Iron bars
ticksToMelt.put(new MaterialData(Material.IRON_BLOCK), 200 * 20);
//Trusted blocks
ticksToMelt.put(new MaterialData(Material.FLOWER_POT_ITEM), 3 * 20);
ticksToMelt.put(new MaterialData(Material.FLOWER_POT), 3 * 20);
//ticksToMelt.put(new MaterialData(Material.YELLOW_FLOWER), ()) Flowers don't melt :3
//ticksToMelt.put(new MaterialData(Material.RED_ROSE), ()); Flowers don't melt :3
ticksToMelt.put(new MaterialData(Material.WOOD_DOOR), 55 * 20);
ticksToMelt.put(new MaterialData(Material.WOODEN_DOOR), 55 * 20);
ticksToMelt.put(new MaterialData(Material.BOOKSHELF), 100 * 20);
ticksToMelt.put(new MaterialData(Material.FENCE), 53 * 20);
ticksToMelt.put(new MaterialData(Material.WOOD_STAIRS), 65 * 20);//Oak stairs
ticksToMelt.put(new MaterialData(Material.COBBLESTONE_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.BRICK_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.SMOOTH_STAIRS), 65 * 20);//Stone brick stairs
ticksToMelt.put(new MaterialData(Material.SANDSTONE_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.SPRUCE_WOOD_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.BIRCH_WOOD_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.JUNGLE_WOOD_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.QUARTZ_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.ACACIA_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.DARK_OAK_STAIRS), 65 * 20);
ticksToMelt.put(new MaterialData(Material.COBBLE_WALL, (byte) 0), 130 * 20);//Cobblestone wall
ticksToMelt.put(new MaterialData(Material.COBBLE_WALL, (byte) 1), 130 * 20);//Mossy cobblestone wall
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 0), 168 * 20);//White glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 1), 168 * 20);//Orange glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 2), 168 * 20);//Magenta glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 3), 168 * 20);//Light blue glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 4), 168 * 20);//Yellow glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 5), 168 * 20);//Lime glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 6), 168 * 20);//Pink glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 7), 168 * 20);//Gray glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 8), 168 * 20);//Light gray glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 9), 168 * 20);//Cyan glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 10), 168 * 20);//Purple glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 11), 168 * 20);//Blue glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 12), 168 * 20);//Brown glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 13), 168 * 20);//Green glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 14), 168 * 20);//Red glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS, (byte) 15), 168 * 20);//Black glass
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 0), 168 * 20);//White glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 1), 168 * 20);//Orange glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 2), 168 * 20);//Magenta glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 3), 168 * 20);//Light blue glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 4), 168 * 20);//Yellow glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 5), 168 * 20);//Lime glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 6), 168 * 20);//Pink glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 7), 168 * 20);//Gray glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 8), 168 * 20);//Light gray glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 9), 168 * 20);//Cyan glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 10), 168 * 20);//Purple glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 11), 168 * 20);//Blue glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 12), 168 * 20);//Brown glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 13), 168 * 20);//Green glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 14), 168 * 20);//Red glass pane
ticksToMelt.put(new MaterialData(Material.STAINED_GLASS_PANE, (byte) 15), 168 * 20);//Black glass pane
//Elder blocks
ticksToMelt.put(new MaterialData(Material.GLOWSTONE), 100 * 20);
ticksToMelt.put(new MaterialData(Material.STEP, (byte) 6), 165 * 20);//Nether brick slab
ticksToMelt.put(new MaterialData(Material.NETHER_FENCE), 300 * 20);
ticksToMelt.put(new MaterialData(Material.NETHERRACK), 330 * 20);
ticksToMelt.put(new MaterialData(Material.NETHER_BRICK), 370 * 20);
ticksToMelt.put(new MaterialData(Material.NETHER_BRICK_STAIRS), 250 * 20);
ticksToMelt.put(new MaterialData(Material.ENDER_STONE), 400 * 20);
//Unburnable
ticksToMelt.put(new MaterialData(Material.YELLOW_FLOWER), -1);
ticksToMelt.put(new MaterialData(Material.RED_ROSE), -1);
ticksToMelt.put(new MaterialData(Material.IRON_DOOR_BLOCK), -1);
ticksToMelt.put(new MaterialData(Material.BEDROCK), -1);
ticksToMelt.put(new MaterialData(Material.OBSIDIAN), -1);
ticksToMelt.put(new MaterialData(Material.BARRIER), -1);
for (Material m : Material.values())
if (!m.equals(Material.LAVA) && !m.equals(Material.STATIONARY_LAVA) && !m.equals(Material.WATER) && !m.equals(Material.STATIONARY_WATER) && !m.equals(Material.AIR) &&
!ticksToMelt.containsKey(new MaterialData(m)))
ticksToMelt.put(new MaterialData(m), 30 * 20);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onClassicPhysics(final ClassicPhysicsEvent event) {
if (!event.isClassicEvent() || Gamemode.getCurrentGame().hasEnded())
return;
final Block blockChecking = event.getOldBlock();
if (blockChecking.getType().equals(Material.AIR))
return;
MaterialData dat = new MaterialData(blockChecking.getType(), blockChecking.getData());
if (!ticksToMelt.containsKey(dat))
dat = new MaterialData(blockChecking.getType());
if (ticksToMelt.containsKey(dat)) {
event.setCancelled(true);
long tickCount = ticksToMelt.get(dat);
if (tickCount == -1) //It's unburnable
return;
if (!blockChecking.hasMetadata("player_placed"))
tickCount /= 2;
int task = Bukkit.getScheduler().scheduleSyncDelayedTask(Lavasurvival.INSTANCE, new Runnable() {
@Override
public void run() {
Lavasurvival.INSTANCE.getPhysicsHandler().placeClassicBlockAt(event.getLocation(), event.getLogicContainer().logicFor());
}
}, tickCount);
tasks.add(task);
}
}
public static String getMeltTimeAsString(MaterialData data) {
int seconds = ticksToMelt.containsKey(data) ? ticksToMelt.get(data) / 20 : 0;
if (seconds == 0) {
return "Immediately";
} else if (seconds == -1) {
return "Never";
} else {
return seconds + " Second" + (seconds == 1 ? "" : "s");
}
}
public static int getMeltTime(MaterialData data) {//seconds
return ticksToMelt.containsKey(data) ? ticksToMelt.get(data) / 20 : 0;
}
public void cancelAllTasks() {
tasks.clear();
}
public void cleanup() {
cancelAllTasks();
HandlerList.unregisterAll(this);
}
} | Check if negative instead of just -1 because of when we divide by 20
| Lavasurvival/src/main/java/me/eddiep/minecraft/ls/system/PhysicsListener.java | Check if negative instead of just -1 because of when we divide by 20 |
|
Java | apache-2.0 | 8400beec35549a3c79efe7f944fd114fc9ed831b | 0 | Legioth/vaadin,fireflyc/vaadin,Peppe/vaadin,travisfw/vaadin,shahrzadmn/vaadin,cbmeeks/vaadin,magi42/vaadin,bmitc/vaadin,oalles/vaadin,cbmeeks/vaadin,Legioth/vaadin,travisfw/vaadin,Peppe/vaadin,synes/vaadin,synes/vaadin,peterl1084/framework,carrchang/vaadin,Darsstar/framework,oalles/vaadin,shahrzadmn/vaadin,sitexa/vaadin,jdahlstrom/vaadin.react,shahrzadmn/vaadin,Flamenco/vaadin,carrchang/vaadin,bmitc/vaadin,udayinfy/vaadin,Flamenco/vaadin,udayinfy/vaadin,magi42/vaadin,kironapublic/vaadin,travisfw/vaadin,cbmeeks/vaadin,bmitc/vaadin,Darsstar/framework,jdahlstrom/vaadin.react,Scarlethue/vaadin,udayinfy/vaadin,kironapublic/vaadin,oalles/vaadin,mittop/vaadin,Peppe/vaadin,shahrzadmn/vaadin,carrchang/vaadin,peterl1084/framework,kironapublic/vaadin,oalles/vaadin,Scarlethue/vaadin,Legioth/vaadin,synes/vaadin,shahrzadmn/vaadin,kironapublic/vaadin,kironapublic/vaadin,Peppe/vaadin,mstahv/framework,sitexa/vaadin,Darsstar/framework,Legioth/vaadin,oalles/vaadin,peterl1084/framework,Flamenco/vaadin,jdahlstrom/vaadin.react,udayinfy/vaadin,sitexa/vaadin,carrchang/vaadin,Darsstar/framework,magi42/vaadin,mstahv/framework,jdahlstrom/vaadin.react,jdahlstrom/vaadin.react,bmitc/vaadin,mstahv/framework,mittop/vaadin,synes/vaadin,asashour/framework,sitexa/vaadin,udayinfy/vaadin,asashour/framework,mstahv/framework,mstahv/framework,travisfw/vaadin,fireflyc/vaadin,fireflyc/vaadin,fireflyc/vaadin,fireflyc/vaadin,magi42/vaadin,Scarlethue/vaadin,travisfw/vaadin,cbmeeks/vaadin,sitexa/vaadin,asashour/framework,Scarlethue/vaadin,Legioth/vaadin,peterl1084/framework,Scarlethue/vaadin,Peppe/vaadin,asashour/framework,peterl1084/framework,mittop/vaadin,synes/vaadin,Flamenco/vaadin,asashour/framework,Darsstar/framework,mittop/vaadin,magi42/vaadin | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IUpload extends FormPanel implements Paintable, ClickListener,
FormHandler {
public static final String CLASSNAME = "i-upload";
/**
* FileUpload component that opens native OS dialog to select file.
*/
FileUpload fu = new FileUpload();
Panel panel = new FlowPanel();
ApplicationConnection client;
private String paintableId;
/**
* Button that initiates uploading
*/
private final Button submitButton;
/**
* When expecting big files, programmer may initiate some UI changes when
* uploading the file starts. Bit after submitting file we'll visit the
* server to check possible changes.
*/
private Timer t;
/**
* some browsers tries to send form twice if submit is called in button
* click handler, some don't submit at all without it, so we need to track
* if form is already being submitted
*/
private boolean submitted = false;
private boolean enabled = true;
public IUpload() {
super();
setEncoding(FormPanel.ENCODING_MULTIPART);
setMethod(FormPanel.METHOD_POST);
setWidget(panel);
panel.add(fu);
submitButton = new Button();
submitButton.addClickListener(this);
panel.add(submitButton);
addFormHandler(this);
setStyleName(CLASSNAME);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if (client.updateComponent(this, uidl, true)) {
return;
}
this.client = client;
paintableId = uidl.getId();
setAction(client.getAppUri());
submitButton.setText(uidl.getStringAttribute("buttoncaption"));
fu.setName(paintableId + "_file");
if (uidl.hasAttribute("disabled")) {
disableUpload();
} else if (uidl.getBooleanAttribute("state")) {
enableUploaod();
}
}
public void onClick(Widget sender) {
submit();
}
public void onSubmit(FormSubmitEvent event) {
if (fu.getFilename().length() == 0 || submitted || !enabled) {
event.setCancelled(true);
ApplicationConnection
.getConsole()
.log(
"Submit cancelled (disabled, no file or already submitted)");
return;
}
submitted = true;
ApplicationConnection.getConsole().log("Submitted form");
disableUpload();
/*
* visit server after upload to see possible changes from UploadStarted
* event
*/
t = new Timer() {
public void run() {
client.sendPendingVariableChanges();
}
};
t.schedule(800);
}
protected void disableUpload() {
submitButton.setEnabled(false);
fu.setVisible(false);
enabled = false;
}
protected void enableUploaod() {
submitButton.setEnabled(true);
fu.setVisible(true);
enabled = true;
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
if (client != null) {
if (t != null) {
t.cancel();
}
ApplicationConnection.getConsole().log("Submit complete");
client.sendPendingVariableChanges();
}
submitted = false;
enableUploaod();
}
}
| src/com/itmill/toolkit/terminal/gwt/client/ui/IUpload.java | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IUpload extends FormPanel implements Paintable, ClickListener,
FormHandler {
public static final String CLASSNAME = "i-upload";
/**
* FileUpload component that opens native OS dialog to select file.
*/
FileUpload fu = new FileUpload();
Panel panel = new FlowPanel();
ApplicationConnection client;
private String paintableId;
/**
* Button that initiates uploading
*/
private final Button submitButton;
/**
* When expecting big files, programmer may initiate some UI changes when
* uploading the file starts. Bit after submitting file we'll visit the
* server to check possible changes.
*/
private Timer t;
/**
* some browsers tries to send form twice if submit is called in button
* click handler, some don't submit at all without it, so we need to track
* if form is already being submitted
*/
private boolean submitted = false;
private boolean enabled;
public IUpload() {
super();
setEncoding(FormPanel.ENCODING_MULTIPART);
setMethod(FormPanel.METHOD_POST);
setWidget(panel);
panel.add(fu);
submitButton = new Button();
submitButton.addClickListener(this);
panel.add(submitButton);
addFormHandler(this);
setStyleName(CLASSNAME);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
if (client.updateComponent(this, uidl, true)) {
return;
}
this.client = client;
paintableId = uidl.getId();
setAction(client.getAppUri());
submitButton.setText(uidl.getStringAttribute("buttoncaption"));
fu.setName(paintableId + "_file");
if (uidl.hasAttribute("disabled")) {
disableUpload();
} else if (uidl.getBooleanAttribute("state")) {
enableUploaod();
}
}
public void onClick(Widget sender) {
submit();
}
public void onSubmit(FormSubmitEvent event) {
if (fu.getFilename().length() == 0 || submitted || !enabled) {
event.setCancelled(true);
ApplicationConnection
.getConsole()
.log(
"Submit cancelled (disabled, no file or already submitted)");
return;
}
submitted = true;
ApplicationConnection.getConsole().log("Submitted form");
disableUpload();
/*
* visit server after upload to see possible changes from UploadStarted
* event
*/
t = new Timer() {
public void run() {
client.sendPendingVariableChanges();
}
};
t.schedule(800);
}
protected void disableUpload() {
submitButton.setEnabled(false);
fu.setVisible(false);
enabled = false;
}
protected void enableUploaod() {
submitButton.setEnabled(true);
fu.setVisible(true);
enabled = true;
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
if (client != null) {
if (t != null) {
t.cancel();
}
ApplicationConnection.getConsole().log("Submit complete");
client.sendPendingVariableChanges();
}
submitted = false;
enableUploaod();
}
}
| proper default value
svn changeset:3261/svn branch:trunk
| src/com/itmill/toolkit/terminal/gwt/client/ui/IUpload.java | proper default value |
|
Java | apache-2.0 | a0c5a75ab5cc3fcb2958f18898234bdf42a92e42 | 0 | gavanx/pdflearn,ZhenyaM/veraPDF-pdfbox,BezrukovM/veraPDF-pdfbox,BezrukovM/veraPDF-pdfbox,mdamt/pdfbox,ChunghwaTelecom/pdfbox,benmccann/pdfbox,ChunghwaTelecom/pdfbox,mathieufortin01/pdfbox,joansmith/pdfbox,mathieufortin01/pdfbox,veraPDF/veraPDF-pdfbox,mdamt/pdfbox,ZhenyaM/veraPDF-pdfbox,gavanx/pdflearn,veraPDF/veraPDF-pdfbox,joansmith/pdfbox,benmccann/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.pdmodel.interactive.form;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.common.COSArrayList;
import org.apache.pdfbox.pdmodel.interactive.form.FieldUtils.KeyValue;
/**
* A choice field contains several text items, one or more of which shall be selected as the field
* value.
*
* @author sug
* @author John Hewson
*/
public abstract class PDChoice extends PDVariableText
{
static final int FLAG_COMBO = 1 << 17;
private static final int FLAG_SORT = 1 << 19;
private static final int FLAG_MULTI_SELECT = 1 << 21;
private static final int FLAG_DO_NOT_SPELL_CHECK = 1 << 22;
private static final int FLAG_COMMIT_ON_SEL_CHANGE = 1 << 26;
/**
* @see PDField#PDField(PDAcroForm)
*
* @param acroForm The acroform.
*/
public PDChoice(PDAcroForm acroForm)
{
super(acroForm);
dictionary.setItem(COSName.FT, COSName.CH);
}
/**
* Constructor.
*
* @param acroForm The form that this field is part of.
* @param field the PDF object to represent as a field.
* @param parent the parent node of the node
*/
PDChoice(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent)
{
super(acroForm, field, parent);
}
/**
* This will get the option values "Opt".
*
* <p>
* For a choice field the options array can either be an array
* of text strings or an array of a two-element arrays.<br/>
* The method always only returns either the text strings or,
* in case of two-element arrays, an array of the first element of
* the two-element arrays
* </p>
* <p>
* Use {@link #getOptionsExportValues()} and {@link #getOptionsDisplayValues()}
* to get the entries of two-element arrays.
* </p>
*
* @return List containing the export values.
*/
public List<String> getOptions()
{
COSBase values = dictionary.getDictionaryObject(COSName.OPT);
return FieldUtils.getPairableItems(values, 0);
}
/**
* This will set the display values - the 'Opt' key.
*
* <p>
* The Opt array specifies the list of options in the choice field either
* as an array of text strings representing the display value
* or as an array of a two-element array where the
* first element is the export value and the second the display value.
* </p>
* <p>
* To set both the export and the display value use {@link #setOptions(List, List)}
* </p>
*
* @param displayValues List containing all possible options.
*/
public void setOptions(List<String> displayValues)
{
if (displayValues != null && !displayValues.isEmpty())
{
if (isSort())
{
Collections.sort(displayValues);
}
dictionary.setItem(COSName.OPT, COSArrayList.convertStringListToCOSStringCOSArray(displayValues));
}
else
{
dictionary.removeItem(COSName.OPT);
}
}
/**
* This will set the display and export values - the 'Opt' key.
*
* <p>
* This will set both, the export value and the display value
* of the choice field. If either one of the parameters is null or an
* empty list is supplied the options will
* be removed.
* </p>
* <p>
* An {@link IllegalArgumentException} will be thrown if the
* number of items in the list differ.
* </p>
*
* @see #setOptions(List)
* @param exportValues List containing all possible export values.
* @param displayValues List containing all possible display values.
*/
public void setOptions(List<String> exportValues, List<String> displayValues)
{
if (exportValues != null && displayValues != null && !exportValues.isEmpty() && !displayValues.isEmpty())
{
if (exportValues.size() != displayValues.size())
{
throw new IllegalArgumentException(
"The number of entries for exportValue and displayValue shall be the same.");
}
else
{
List<KeyValue> keyValuePairs = FieldUtils.toKeyValueList(exportValues, displayValues);
if (isSort())
{
FieldUtils.sortByValue(keyValuePairs);
}
COSArray options = new COSArray();
for (int i = 0; i<exportValues.size(); i++)
{
COSArray entry = new COSArray();
entry.add(new COSString(keyValuePairs.get(i).getKey()));
entry.add(new COSString(keyValuePairs.get(i).getValue()));
options.add(entry);
}
dictionary.setItem(COSName.OPT, options);
}
}
else
{
dictionary.removeItem(COSName.OPT);
}
}
/**
* This will get the display values from the options.
*
* <p>
* For options with an array of text strings the display value and export value
* are the same.<br/>
* For options with an array of two-element arrays the display value is the
* second entry in the two-element array.
* </p>
*
* @return List containing all the display values.
*/
public List<String> getOptionsDisplayValues()
{
COSBase values = dictionary.getDictionaryObject(COSName.OPT);
return FieldUtils.getPairableItems(values, 1);
}
/**
* This will get the export values from the options.
*
* <p>
* For options with an array of text strings the display value and export value
* are the same.<br/>
* For options with an array of two-element arrays the export value is the
* first entry in the two-element array.
* </p>
*
* @return List containing all export values.
*/
public List<String> getOptionsExportValues()
{
return getOptions();
}
/**
* This will get the indices of the selected options - the 'I' key.
* <p>
* This is only needed if a choice field allows multiple selections and
* two different items have the same export value or more than one values
* is selected.
* </p>
* <p>The indices are zero-based</p>
*
* @return List containing the indices of all selected options.
*/
public List<Integer> getSelectedOptionsIndex()
{
COSBase value = dictionary.getDictionaryObject(COSName.I);
if (value != null)
{
return COSArrayList.convertIntegerCOSArrayToList((COSArray) value);
}
return Collections.<Integer>emptyList();
}
/**
* This will set the indices of the selected options - the 'I' key.
* <p>
* This method is preferred over {@link #setValue(List)} for choice fields which
* <ul>
* <li>do support multiple selections</li>
* <li>have export values with the same value</li>
* </ul>
* </p>
* <p>
* Setting the index will set the value too.
* </p>
*
* @param values List containing the indices of all selected options.
*/
public void setSelectedOptionsIndex(List<Integer> values)
{
if (values != null && !values.isEmpty())
{
if (!isMultiSelect())
{
throw new IllegalArgumentException(
"Setting the indices is not allowed for choice fields not allowing multiple selections.");
}
dictionary.setItem(COSName.I, COSArrayList.converterToCOSArray(values));
}
else
{
dictionary.removeItem(COSName.I);
}
}
/**
* Determines if Sort is set.
*
* <p>
* If set, the field’s option items shall be sorted alphabetically.
* The sorting has to be done when writing the PDF. PDF Readers are supposed to
* display the options in the order in which they occur in the Opt array.
* </p>
*
* @return true if the options are sorted.
*/
public boolean isSort()
{
return dictionary.getFlag(COSName.FF, FLAG_SORT);
}
/**
* Set the Sort bit.
*
* @see #isSort()
* @param sort The value for Sort.
*/
public void setSort(boolean sort)
{
dictionary.setFlag(COSName.FF, FLAG_SORT, sort);
}
/**
* Determines if MultiSelect is set.
*
* @return true if multi select is allowed.
*/
public boolean isMultiSelect()
{
return dictionary.getFlag(COSName.FF, FLAG_MULTI_SELECT);
}
/**
* Set the MultiSelect bit.
*
* @param multiSelect The value for MultiSelect.
*/
public void setMultiSelect(boolean multiSelect)
{
dictionary.setFlag(COSName.FF, FLAG_MULTI_SELECT, multiSelect);
}
/**
* Determines if DoNotSpellCheck is set.
*
* @return true if spell checker is disabled.
*/
public boolean isDoNotSpellCheck()
{
return dictionary.getFlag(COSName.FF, FLAG_DO_NOT_SPELL_CHECK);
}
/**
* Set the DoNotSpellCheck bit.
*
* @param doNotSpellCheck The value for DoNotSpellCheck.
*/
public void setDoNotSpellCheck(boolean doNotSpellCheck)
{
dictionary.setFlag(COSName.FF, FLAG_DO_NOT_SPELL_CHECK, doNotSpellCheck);
}
/**
* Determines if CommitOnSelChange is set.
*
* @return true if value shall be committed as soon as a selection is made.
*/
public boolean isCommitOnSelChange()
{
return dictionary.getFlag(COSName.FF, FLAG_COMMIT_ON_SEL_CHANGE);
}
/**
* Set the CommitOnSelChange bit.
*
* @param commitOnSelChange The value for CommitOnSelChange.
*/
public void setCommitOnSelChange(boolean commitOnSelChange)
{
dictionary.setFlag(COSName.FF, FLAG_COMMIT_ON_SEL_CHANGE, commitOnSelChange);
}
/**
* Determines if Combo is set.
*
* @return true if value the choice is a combo box..
*/
public boolean isCombo()
{
return dictionary.getFlag(COSName.FF, FLAG_COMBO);
}
/**
* Set the Combo bit.
*
* @param combo The value for Combo.
*/
public void setCombo(boolean combo)
{
dictionary.setFlag(COSName.FF, FLAG_COMBO, combo);
}
/**
* Sets the selected value of this field.
*
* @param value The name of the selected item.
* @throws IOException if the value could not be set
*/
public void setValue(String value) throws IOException
{
dictionary.setString(COSName.V, value);
// remove I key for single valued choice field
setSelectedOptionsIndex(null);
applyChange();
}
/**
* Sets the default value of this field.
*
* @param value The name of the selected item.
* @throws IOException if the value could not be set
*/
public void setDefaultValue(String value) throws IOException
{
dictionary.setString(COSName.DV, value);
}
/**
* Sets the entry "V" to the given values. Requires {@link #isMultiSelect()} to be true.
*
* @param values the list of values
*/
public void setValue(List<String> values) throws IOException
{
if (values != null && !values.isEmpty())
{
if (!isMultiSelect())
{
throw new IllegalArgumentException("The list box does not allow multiple selections.");
}
if (!getOptions().containsAll(values))
{
throw new IllegalArgumentException("The values are not contained in the selectable options.");
}
dictionary.setItem(COSName.V, COSArrayList.convertStringListToCOSStringCOSArray(values));
updateSelectedOptionsIndex(values);
}
else
{
dictionary.removeItem(COSName.V);
}
applyChange();
}
/**
* Returns the selected values, or an empty List. This list always contains a single item
* unless {@link #isMultiSelect()} is true.
*
* @return A non-null string.
*/
public List<String> getValue()
{
return getValueFor(COSName.V);
}
/**
* Returns the default values, or an empty List. This list always contains a single item
* unless {@link #isMultiSelect()} is true.
*
* @return A non-null string.
*/
public List<String> getDefaultValue()
{
return getValueFor(COSName.DV);
}
/**
* Returns the selected values, or an empty List, for the given key.
*/
private List<String> getValueFor(COSName name)
{
COSBase value = dictionary.getDictionaryObject(name);
if (value instanceof COSString)
{
List<String> array = new ArrayList<String>();
array.add(((COSString) value).getString());
return array;
}
else if (value instanceof COSArray)
{
return COSArrayList.convertCOSStringCOSArrayToList((COSArray)value);
}
return Collections.emptyList();
}
@Override
public String getValueAsString()
{
return Arrays.toString(getValue().toArray());
}
/**
* Update the 'I' key based on values set.
*/
private void updateSelectedOptionsIndex(List<String> values)
{
List<String> options = getOptions();
List<Integer> indices = new ArrayList<Integer>();
for (String value : values)
{
indices.add(options.indexOf(value));
}
// Indices have to be "... array of integers, sorted in ascending order ..."
Collections.sort(indices);
setSelectedOptionsIndex(indices);
}
@Override
void constructAppearances() throws IOException
{
// TODO: implement appearance generation for choices
throw new UnsupportedOperationException("not implemented");
}
}
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDChoice.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.pdmodel.interactive.form;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.common.COSArrayList;
import org.apache.pdfbox.pdmodel.interactive.form.FieldUtils.KeyValue;
/**
* A choice field contains several text items, one or more of which shall be selected as the field
* value.
*
* @author sug
* @author John Hewson
*/
public abstract class PDChoice extends PDVariableText
{
static final int FLAG_COMBO = 1 << 17;
private static final int FLAG_SORT = 1 << 19;
private static final int FLAG_MULTI_SELECT = 1 << 21;
private static final int FLAG_DO_NOT_SPELL_CHECK = 1 << 22;
private static final int FLAG_COMMIT_ON_SEL_CHANGE = 1 << 26;
/**
* @see PDField#PDField(PDAcroForm)
*
* @param acroForm The acroform.
*/
public PDChoice(PDAcroForm acroForm)
{
super(acroForm);
dictionary.setItem(COSName.FT, COSName.CH);
}
/**
* Constructor.
*
* @param acroForm The form that this field is part of.
* @param field the PDF object to represent as a field.
* @param parent the parent node of the node
*/
PDChoice(PDAcroForm acroForm, COSDictionary field, PDNonTerminalField parent)
{
super(acroForm, field, parent);
}
/**
* This will get the option values "Opt".
*
* <p>
* For a choice field the options array can either be an array
* of text strings or an array of a two-element arrays.<br/>
* The method always only returns either the text strings or,
* in case of two-element arrays, an array of the first element of
* the two-element arrays
* </p>
* <p>
* Use {@link #getOptionsExportValues()} and {@link #getOptionsDisplayValues()}
* to get the entries of two-element arrays.
* </p>
*
* @return List containing the export values.
*/
public List<String> getOptions()
{
COSBase values = dictionary.getDictionaryObject(COSName.OPT);
return FieldUtils.getPairableItems(values, 0);
}
/**
* This will set the display values - the 'Opt' key.
*
* <p>
* The Opt array specifies the list of options in the choice field either
* as an array of text strings representing the display value
* or as an array of a two-element array where the
* first element is the export value and the second the display value.
* </p>
* <p>
* To set both the export and the display value use {@link #setOptions(List, List)}
* </p>
*
* @param displayValues List containing all possible options.
*/
public void setOptions(List<String> displayValues)
{
if (displayValues != null && !displayValues.isEmpty())
{
if (isSort())
{
Collections.sort(displayValues);
}
dictionary.setItem(COSName.OPT, COSArrayList.convertStringListToCOSStringCOSArray(displayValues));
}
else
{
dictionary.removeItem(COSName.OPT);
}
}
/**
* This will set the display and export values - the 'Opt' key.
*
* <p>
* This will set both, the export value and the display value
* of the choice field. If either one of the parameters is null or an
* empty list is supplied the options will
* be removed.
* </p>
* <p>
* An {@link IllegalArgumentException} will be thrown if the
* number of items in the list differ.
* </p>
*
* @see #setOptions(List)
* @param exportValues List containing all possible export values.
* @param displayValues List containing all possible display values.
*/
public void setOptions(List<String> exportValues, List<String> displayValues)
{
if (exportValues != null && displayValues != null && !exportValues.isEmpty() && !displayValues.isEmpty())
{
if (exportValues.size() != displayValues.size())
{
throw new IllegalArgumentException(
"The number of entries for exportValue and displayValue shall be the same.");
}
else
{
List<KeyValue> keyValuePairs = FieldUtils.toKeyValueList(exportValues, displayValues);
if (isSort())
{
FieldUtils.sortByValue(keyValuePairs);
}
COSArray options = new COSArray();
for (int i = 0; i<exportValues.size(); i++)
{
COSArray entry = new COSArray();
entry.add(new COSString(keyValuePairs.get(i).getKey()));
entry.add(new COSString(keyValuePairs.get(i).getValue()));
options.add(entry);
}
dictionary.setItem(COSName.OPT, options);
}
}
else
{
dictionary.removeItem(COSName.OPT);
}
}
/**
* This will get the display values from the options.
*
* <p>
* For options with an array of text strings the display value and export value
* are the same.<br/>
* For options with an array of two-element arrays the display value is the
* second entry in the two-element array.
* </p>
*
* @return List containing all the display values.
*/
public List<String> getOptionsDisplayValues()
{
COSBase values = dictionary.getDictionaryObject(COSName.OPT);
return FieldUtils.getPairableItems(values, 1);
}
/**
* This will get the export values from the options.
*
* <p>
* For options with an array of text strings the display value and export value
* are the same.<br/>
* For options with an array of two-element arrays the export value is the
* first entry in the two-element array.
* </p>
*
* @return List containing all export values.
*/
public List<String> getOptionsExportValues()
{
return getOptions();
}
/**
* This will get the indices of the selected options - the 'I' key.
* <p>
* This is only needed if a choice field allows multiple selections and
* two different items have the same export value or more than one values
* is selected.
* </p>
* <p>The indices are zero-based</p>
*
* @return List containing the indices of all selected options.
*/
public List<Integer> getSelectedOptionsIndex()
{
COSBase value = dictionary.getDictionaryObject(COSName.I);
if (value != null)
{
return COSArrayList.convertIntegerCOSArrayToList((COSArray) value);
}
return Collections.<Integer>emptyList();
}
/**
* This will set the indices of the selected options - the 'I' key.
* <p>
* This method is preferred over {@link #setValue(List)} for choice fields which
* <ul>
* <li>do support multiple selections</li>
* <li>have export values with the same value</li>
* </ul>
* </p>
* <p>
* Setting the index will set the value too.
* </p>
*
* @param values List containing the indices of all selected options.
*/
public void setSelectedOptionsIndex(List<Integer> values)
{
if (values != null && !values.isEmpty())
{
if (!isMultiSelect())
{
throw new IllegalArgumentException(
"Setting the indices is not allowed for choice fields not allowing multiple selections.");
}
dictionary.setItem(COSName.I, COSArrayList.converterToCOSArray(values));
}
else
{
dictionary.removeItem(COSName.I);
}
}
/**
* Determines if Sort is set.
*
* <p>
* If set, the field’s option items shall be sorted alphabetically.
* The sorting has to be done when writing the PDF. PDF Readers are supposed to
* display the options in the order in which they occur in the Opt array.
* </p>
*
* @return true if the options are sorted.
*/
public boolean isSort()
{
return dictionary.getFlag(COSName.FF, FLAG_SORT);
}
/**
* Set the Sort bit.
*
* @see #isSort()
* @param sort The value for Sort.
*/
public void setSort(boolean sort)
{
dictionary.setFlag(COSName.FF, FLAG_SORT, sort);
}
/**
* Determines if MultiSelect is set.
*
* @return true if multi select is allowed.
*/
public boolean isMultiSelect()
{
return dictionary.getFlag(COSName.FF, FLAG_MULTI_SELECT);
}
/**
* Set the MultiSelect bit.
*
* @param multiSelect The value for MultiSelect.
*/
public void setMultiSelect(boolean multiSelect)
{
dictionary.setFlag(COSName.FF, FLAG_MULTI_SELECT, multiSelect);
}
/**
* Determines if DoNotSpellCheck is set.
*
* @return true if spell checker is disabled.
*/
public boolean isDoNotSpellCheck()
{
return dictionary.getFlag(COSName.FF, FLAG_DO_NOT_SPELL_CHECK);
}
/**
* Set the DoNotSpellCheck bit.
*
* @param doNotSpellCheck The value for DoNotSpellCheck.
*/
public void setDoNotSpellCheck(boolean doNotSpellCheck)
{
dictionary.setFlag(COSName.FF, FLAG_DO_NOT_SPELL_CHECK, doNotSpellCheck);
}
/**
* Determines if CommitOnSelChange is set.
*
* @return true if value shall be committed as soon as a selection is made.
*/
public boolean isCommitOnSelChange()
{
return dictionary.getFlag(COSName.FF, FLAG_COMMIT_ON_SEL_CHANGE);
}
/**
* Set the CommitOnSelChange bit.
*
* @param commitOnSelChange The value for CommitOnSelChange.
*/
public void setCommitOnSelChange(boolean commitOnSelChange)
{
dictionary.setFlag(COSName.FF, FLAG_COMMIT_ON_SEL_CHANGE, commitOnSelChange);
}
/**
* Determines if Combo is set.
*
* @return true if value the choice is a combo box..
*/
public boolean isCombo()
{
return dictionary.getFlag(COSName.FF, FLAG_COMBO);
}
/**
* Set the Combo bit.
*
* @param combo The value for Combo.
*/
public void setCombo(boolean combo)
{
dictionary.setFlag(COSName.FF, FLAG_COMBO, combo);
}
/**
* Sets the selected value of this field.
*
* @param value The name of the selected item.
* @throws IOException if the value could not be set
*/
public void setValue(String value) throws IOException
{
dictionary.setString(COSName.V, value);
// remove I key for single valued choice field
setSelectedOptionsIndex(null);
applyChange();
}
/**
* Sets the default value of this field.
*
* @param value The name of the selected item.
* @throws IOException if the value could not be set
*/
public void setDefaultValue(String value) throws IOException
{
dictionary.setString(COSName.DV, value);
}
/**
* Sets the entry "V" to the given values. Requires {@link #isMultiSelect()} to be true.
*
* @param values the list of values
*/
public void setValue(List<String> values) throws IOException
{
if (values != null && !values.isEmpty())
{
if (!isMultiSelect())
{
throw new IllegalArgumentException("The list box does not allow multiple selections.");
}
if (!getOptions().containsAll(values))
{
throw new IllegalArgumentException("The values are not contained in the selectable options.");
}
dictionary.setItem(COSName.V, COSArrayList.convertStringListToCOSStringCOSArray(values));
updateSelectedOptionsIndex(values);
}
else
{
dictionary.removeItem(COSName.V);
}
applyChange();
}
/**
* Returns the selected values, or an empty string. This list always contains a single item
* unless {@link #isMultiSelect()} is true.
*
* @return A non-null string.
*/
public List<String> getValue()
{
return getValueFor(COSName.V);
}
/**
* Returns the default values, or an empty string. This list always contains a single item
* unless {@link #isMultiSelect()} is true.
*
* @return A non-null string.
*/
public List<String> getDefaultValue()
{
return getValueFor(COSName.DV);
}
/**
* Returns the selected values, or an empty string, for the given key.
*/
private List<String> getValueFor(COSName name)
{
COSBase value = dictionary.getDictionaryObject(name);
if (value instanceof COSString)
{
List<String> array = new ArrayList<String>();
array.add(((COSString) value).getString());
return array;
}
else if (value instanceof COSArray)
{
return COSArrayList.convertCOSStringCOSArrayToList((COSArray)value);
}
return Collections.emptyList();
}
@Override
public String getValueAsString()
{
return Arrays.toString(getValue().toArray());
}
/**
* Update the 'I' key based on values set.
*/
private void updateSelectedOptionsIndex(List<String> values)
{
List<String> options = getOptions();
List<Integer> indices = new ArrayList<Integer>();
for (String value : values)
{
indices.add(options.indexOf(value));
}
// Indices have to be "... array of integers, sorted in ascending order ..."
Collections.sort(indices);
setSelectedOptionsIndex(indices);
}
@Override
void constructAppearances() throws IOException
{
// TODO: implement appearance generation for choices
throw new UnsupportedOperationException("not implemented");
}
}
| PDFBOX-2576: correct javadoc
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1687747 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDChoice.java | PDFBOX-2576: correct javadoc |
|
Java | bsd-3-clause | 692fe1e8215c7ad2919ac810e64ccc2853ac985d | 0 | vkscool/xstream,emopers/xstream,Groostav/xstream,tenghuihua/xstream,emopers/xstream,tenghuihua/xstream,Groostav/xstream,vkscool/xstream | package com.thoughtworks.xstream;
import java.awt.font.TextAttribute;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringBufferConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.PropertiesConverter;
import com.thoughtworks.xstream.converters.collections.TreeMapConverter;
import com.thoughtworks.xstream.converters.collections.TreeSetConverter;
import com.thoughtworks.xstream.converters.extended.ColorConverter;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.FontConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.extended.SqlDateConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimeConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter;
import com.thoughtworks.xstream.converters.extended.TextAttributeConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.core.BaseException;
import com.thoughtworks.xstream.core.DefaultConverterLookup;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.core.MapBackedDataHolder;
import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy;
import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy;
import com.thoughtworks.xstream.core.TreeMarshallingStrategy;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StatefulWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.ArrayMapper;
import com.thoughtworks.xstream.mapper.AttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.AttributeMapper;
import com.thoughtworks.xstream.mapper.CachingMapper;
import com.thoughtworks.xstream.mapper.ClassAliasingMapper;
import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
import com.thoughtworks.xstream.mapper.DefaultMapper;
import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
import com.thoughtworks.xstream.mapper.EnumMapper;
import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.mapper.OuterClassMapper;
import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;
/**
* Simple facade to XStream library, a Java-XML serialization tool. <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* XStream xstream = new XStream();
* String xml = xstream.toXML(myObject); // serialize to XML
* Object myObject2 = xstream.fromXML(xml); // deserialize from XML
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Aliasing classes</h3>
* <p/>
* <p>
* To create shorter XML, you can specify aliases for classes using the <code>alias()</code>
* method. For example, you can shorten all occurences of element
* <code><com.blah.MyThing></code> to <code><my-thing></code> by registering an
* alias for the class.
* <p>
* <hr>
* <blockquote>
*
* <pre>
* xstream.alias("my-thing", MyThing.class);
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Converters</h3>
* <p/>
* <p>
* XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each
* of which acts as a strategy for converting a particular type of class to XML and back again. Out
* of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc)
* and collections (Map, List, Set, Properties, etc). For other objects reflection is used to
* serialize each field recursively.
* </p>
* <p/>
* <p>
* Extra converters can be registered using the <code>registerConverter()</code> method. Some
* non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended}
* package and you can create your own by implementing the
* {@link com.thoughtworks.xstream.converters.Converter} interface.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.registerConverter(new SqlTimestampConverter());
* xstream.registerConverter(new DynamicProxyConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p>
* The default converter, ie the converter which will be used if no other registered converter is
* suitable, can be configured by either one of the constructors or can be changed using the
* <code>changeDefaultConverter()</code> method. If not set, XStream uses
* {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the initial default
* converter.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.changeDefaultConverter(new ACustomDefaultConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Object graphs</h3>
* <p/>
* <p>
* XStream has support for object graphs; a deserialized object graph will keep references intact,
* including circular references.
* </p>
* <p/>
* <p>
* XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using
* <code>setMode()</code>:
* </p>
* <p/> <table border="1">
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td>
* <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML
* with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td>
* <td>Uses XPath absolute references to signify duplicate
* references. This produces XML with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td>
* <td>Uses ID references to signify duplicate references. In some scenarios, such as when using
* hand-written XML, this is easier to work with.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td>
* <td>This disables object graph support and treats the object structure like a tree. Duplicate
* references are treated as two seperate objects and circular references cause an exception. This
* is slightly faster and uses less memory than the other two modes.</td>
* </tr>
* </table>
* <h3>Thread safety</h3>
* <p>
* The XStream instance is thread-safe. That is, once the XStream instance has been created and
* configured, it may be shared across multiple threads allowing objects to be
* serialized/deserialized concurrently.
* <h3>Implicit collections</h3>
* <p/>
* <p>
* To avoid the need for special tags for collections, you can define implicit collections using one
* of the <code>addImplicitCollection</code> methods.
* </p>
*
* @author Joe Walnes
* @author Jörg Schaible
* @author Mauro Talevi
*/
public class XStream {
// CAUTION: The sequence of the fields is intentional for an optimal XML output of a
// self-serializaion!
private ReflectionProvider reflectionProvider;
private HierarchicalStreamDriver hierarchicalStreamDriver;
private ClassLoaderReference classLoaderReference;
private MarshallingStrategy marshallingStrategy;
private Mapper mapper;
private DefaultConverterLookup converterLookup;
private ClassAliasingMapper classAliasingMapper;
private FieldAliasingMapper fieldAliasingMapper;
private AttributeAliasingMapper attributeAliasingMapper;
private AttributeMapper attributeMapper;
private DefaultImplementationsMapper defaultImplementationsMapper;
private ImmutableTypesMapper immutableTypesMapper;
private ImplicitCollectionMapper implicitCollectionMapper;
private transient JVM jvm = new JVM();
public static final int NO_REFERENCES = 1001;
public static final int ID_REFERENCES = 1002;
public static final int XPATH_RELATIVE_REFERENCES = 1003;
public static final int XPATH_ABSOLUTE_REFERENCES = 1004;
/**
* @deprecated since 1.2, use {@value #XPATH_RELATIVE_REFERENCES} or
* {@value #XPATH_ABSOLUTE_REFERENCES} instead.
*/
public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES;
public static final int PRIORITY_VERY_HIGH = 10000;
public static final int PRIORITY_NORMAL = 0;
public static final int PRIORITY_LOW = -10;
public static final int PRIORITY_VERY_LOW = -20;
/**
* Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream() {
this(null, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(ReflectionProvider reflectionProvider) {
this(reflectionProvider, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) {
this(null, (Mapper)null, hierarchicalStreamDriver);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) {
this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)}
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver) {
this(reflectionProvider, (Mapper)classMapper, driver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and
* register classAttributeIdentifier as alias
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver, String classAttributeIdentifier) {
this(reflectionProvider, (Mapper)classMapper, driver);
aliasAttribute(classAttributeIdentifier, "class");
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) {
jvm = new JVM();
if (reflectionProvider == null) {
reflectionProvider = jvm.bestReflectionProvider();
}
this.reflectionProvider = reflectionProvider;
this.hierarchicalStreamDriver = driver;
this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader());
this.mapper = mapper == null ? buildMapper() : mapper;
this.converterLookup = new DefaultConverterLookup(this.mapper);
setupMappers();
setupAliases();
setupDefaultImplementations();
setupConverters();
setupImmutableTypes();
setMode(XPATH_RELATIVE_REFERENCES);
}
private Mapper buildMapper() {
Mapper mapper = new DefaultMapper(classLoaderReference);
if ( useXStream11XmlFriendlyMapper() ){
mapper = new XStream11XmlFriendlyMapper(mapper);
}
mapper = new ClassAliasingMapper(mapper);
mapper = new FieldAliasingMapper(mapper);
mapper = new AttributeAliasingMapper(mapper);
mapper = new AttributeMapper(mapper);
mapper = new ImplicitCollectionMapper(mapper);
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
mapper = buildMapperDynamically(
"com.thoughtworks.xstream.mapper.CGLIBMapper",
new Class[]{Mapper.class}, new Object[]{mapper});
}
mapper = new DynamicProxyMapper(mapper);
if (JVM.is15()) {
mapper = new EnumMapper(mapper);
}
mapper = new OuterClassMapper(mapper);
mapper = new ArrayMapper(mapper);
mapper = new DefaultImplementationsMapper(mapper);
mapper = new ImmutableTypesMapper(mapper);
mapper = wrapMapper((MapperWrapper)mapper);
mapper = new CachingMapper(mapper);
return mapper;
}
private Mapper buildMapperDynamically(
String className, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
return (Mapper)constructor.newInstance(constructorParamValues);
} catch (Exception e) {
throw new InitializationException("Could not instatiate mapper : " + className, e);
}
}
protected MapperWrapper wrapMapper(MapperWrapper next) {
return next;
}
protected boolean useXStream11XmlFriendlyMapper() {
return false;
}
private void setupMappers() {
classAliasingMapper = (ClassAliasingMapper)this.mapper
.lookupMapperOfType(ClassAliasingMapper.class);
fieldAliasingMapper = (FieldAliasingMapper)this.mapper
.lookupMapperOfType(FieldAliasingMapper.class);
attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class);
attributeAliasingMapper = (AttributeAliasingMapper)this.mapper
.lookupMapperOfType(AttributeAliasingMapper.class);
implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper
.lookupMapperOfType(ImplicitCollectionMapper.class);
defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper
.lookupMapperOfType(DefaultImplementationsMapper.class);
immutableTypesMapper = (ImmutableTypesMapper)this.mapper
.lookupMapperOfType(ImmutableTypesMapper.class);
// should use ctor, but converterLookup is not yet initialized instantiating this mapper
if (attributeMapper != null) {
attributeMapper.setConverterLookup(converterLookup);
}
}
protected void setupAliases() {
if (classAliasingMapper == null) {
return;
}
alias("null", Mapper.Null.class);
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("big-int", BigInteger.class);
alias("big-decimal", BigDecimal.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("method", Method.class);
alias("constructor", Constructor.class);
alias("date", Date.class);
alias("url", URL.class);
alias("bit-set", BitSet.class);
alias("map", Map.class);
alias("entry", Map.Entry.class);
alias("properties", Properties.class);
alias("list", List.class);
alias("set", Set.class);
alias("linked-list", LinkedList.class);
alias("vector", Vector.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
alias("hashtable", Hashtable.class);
// Instantiating these two classes starts the AWT system, which is undesirable. Calling
// loadClass ensures a reference to the class is found but they are not instantiated.
alias("awt-color", jvm.loadClass("java.awt.Color"));
alias("awt-font", jvm.loadClass("java.awt.Font"));
alias("awt-text-attribute", TextAttribute.class);
alias("sql-timestamp", Timestamp.class);
alias("sql-time", Time.class);
alias("sql-date", java.sql.Date.class);
alias("file", File.class);
alias("locale", Locale.class);
alias("gregorian-calendar", Calendar.class);
// since jdk 1.4 included, but previously available as separate package ...
Class type = jvm.loadClass("javax.security.auth.Subject");
if (type != null) {
alias("auth-subject", type);
}
if (JVM.is14()) {
alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap"));
alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet"));
alias("trace", jvm.loadClass("java.lang.StackTraceElement"));
alias("currency", jvm.loadClass("java.util.Currency"));
aliasType("charset", jvm.loadClass("java.nio.charset.Charset"));
}
if (JVM.is15()) {
alias("enum-set", jvm.loadClass("java.util.EnumSet"));
alias("enum-map", jvm.loadClass("java.util.EnumMap"));
}
}
protected void setupDefaultImplementations() {
if (defaultImplementationsMapper == null) {
return;
}
addDefaultImplementation(HashMap.class, Map.class);
addDefaultImplementation(ArrayList.class, List.class);
addDefaultImplementation(HashSet.class, Set.class);
addDefaultImplementation(GregorianCalendar.class, Calendar.class);
}
protected void setupConverters() {
// use different ReflectionProvider depending on JDK
final ReflectionConverter reflectionConverter;
if (JVM.is15()) {
Class annotationProvider = jvm
.loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider");
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.annotations.AnnotationReflectionConverter",
PRIORITY_VERY_LOW, new Class[]{
Mapper.class, ReflectionProvider.class, annotationProvider},
new Object[]{
mapper, reflectionProvider,
reflectionProvider.newInstance(annotationProvider)});
reflectionConverter = (ReflectionConverter)converterLookup
.lookupConverterForType(Object.class);
} else {
reflectionConverter = new ReflectionConverter(mapper, reflectionProvider);
registerConverter(reflectionConverter, PRIORITY_VERY_LOW);
}
registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new StringBufferConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL);
registerConverter(new MapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL);
registerConverter(new PropertiesConverter(), PRIORITY_NORMAL);
registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new FontConverter(), PRIORITY_NORMAL);
registerConverter(new ColorConverter(), PRIORITY_NORMAL);
registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL);
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
// since jdk 1.4 included, but previously available as separate package ...
if (jvm.loadClass("javax.security.auth.Subject") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.SubjectConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
}
if (JVM.is14()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.ThrowableConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.StackTraceElementConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CurrencyConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.RegexPatternConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CharsetConverter",
PRIORITY_NORMAL, null, null);
}
if (JVM.is15()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
}
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.reflection.CGLIBEnhancedConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class},
new Object[]{mapper, reflectionProvider});
}
registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL);
}
private void dynamicallyRegisterConverter(
String className, int priority, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
Object instance = constructor.newInstance(constructorParamValues);
if (instance instanceof Converter) {
registerConverter((Converter)instance, priority);
} else if (instance instanceof SingleValueConverter) {
registerConverter((SingleValueConverter)instance, priority);
}
} catch (Exception e) {
throw new InitializationException("Could not instatiate converter : " + className, e);
}
}
protected void setupImmutableTypes() {
if (immutableTypesMapper == null) {
return;
}
// primitives are always immutable
addImmutableType(boolean.class);
addImmutableType(Boolean.class);
addImmutableType(byte.class);
addImmutableType(Byte.class);
addImmutableType(char.class);
addImmutableType(Character.class);
addImmutableType(double.class);
addImmutableType(Double.class);
addImmutableType(float.class);
addImmutableType(Float.class);
addImmutableType(int.class);
addImmutableType(Integer.class);
addImmutableType(long.class);
addImmutableType(Long.class);
addImmutableType(short.class);
addImmutableType(Short.class);
// additional types
addImmutableType(Mapper.Null.class);
addImmutableType(BigDecimal.class);
addImmutableType(BigInteger.class);
addImmutableType(String.class);
addImmutableType(URL.class);
addImmutableType(File.class);
addImmutableType(Class.class);
addImmutableType(TextAttribute.class);
if (JVM.is14()) {
// late bound types - allows XStream to be compiled on earlier JDKs
Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter");
addImmutableType(type);
}
}
public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {
this.marshallingStrategy = marshallingStrategy;
}
/**
* Serialize an object to a pretty-printed XML String.
* @throws BaseException if the object cannot be serialized
*/
public String toXML(Object obj) {
Writer writer = new StringWriter();
toXML(obj, writer);
return writer.toString();
}
/**
* Serialize an object to the given Writer as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, Writer out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize an object to the given OutputStream as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, OutputStream out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer) {
marshal(obj, writer, null);
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) {
marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder);
}
/**
* Deserialize an object from an XML String.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml) {
return fromXML(new StringReader(xml));
}
/**
* Deserialize an object from an XML Reader.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), null);
}
/**
* Deserialize an object from an XML InputStream.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream input) {
return unmarshal(hierarchicalStreamDriver.createReader(input), null);
}
/**
* Deserialize an object from an XML String, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml, Object root) {
return fromXML(new StringReader(xml), root);
}
/**
* Deserialize an object from an XML Reader, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from an XML InputStream, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader) {
return unmarshal(reader, null, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML), populating the fields
* of the given root object instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root) {
return unmarshal(reader, root, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*
* @param root If present, the passed in object will have its fields populated, as opposed to
* XStream creating a new instance.
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addClassAlias(name, type);
}
/**
* Alias a type to a shorter name to be used in XML elements.
* Any class that is assignable to this type will be aliased to the same name.
*
* @param name Short name
* @param type Type to be aliased
* @since 1.2
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void aliasType(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addTypeAlias(name, type);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @param defaultImplementation Default implementation of type to use if no other specified.
* @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type, Class defaultImplementation) {
alias(name, type);
addDefaultImplementation(defaultImplementation, type);
}
/**
* Create an alias for a field name.
*
* @param alias the alias itself
* @param type the type that declares the field
* @param fieldName the name of the field
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void aliasField(String alias, Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.addFieldAlias(alias, type, fieldName);
}
/**
* Create an alias for an attribute
*
* @param alias the alias itself
* @param attributeName the name of the attribute
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(String alias, String attributeName) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName()
+ " available");
}
attributeAliasingMapper.addAliasFor(attributeName, alias);
}
/**
* Use an XML attribute for a field or a specific type.
*
* @param fieldName the name of the field
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(String fieldName, Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(fieldName, type);
}
/**
* Use an XML attribute for an arbotrary type.
*
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(type);
}
/**
* Associate a default implementation of a class with an object. Whenever XStream encounters an
* instance of this type, it will use the default implementation instead. For example,
* java.util.ArrayList is the default implementation of java.util.List.
*
* @param defaultImplementation
* @param ofType
* @throws InitializationException if no {@link DefaultImplementationsMapper} is available
*/
public void addDefaultImplementation(Class defaultImplementation, Class ofType) {
if (defaultImplementationsMapper == null) {
throw new InitializationException("No "
+ DefaultImplementationsMapper.class.getName()
+ " available");
}
defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType);
}
/**
* Add immutable types. The value of the instances of these types will always be written into
* the stream even if they appear multiple times.
* @throws InitializationException if no {@link ImmutableTypesMapper} is available
*/
public void addImmutableType(Class type) {
if (immutableTypesMapper == null) {
throw new InitializationException("No "
+ ImmutableTypesMapper.class.getName()
+ " available");
}
immutableTypesMapper.addImmutableType(type);
}
public void registerConverter(Converter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(Converter converter, int priority) {
converterLookup.registerConverter(converter, priority);
}
public void registerConverter(SingleValueConverter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(SingleValueConverter converter, int priority) {
converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority);
}
/**
* @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance
* @deprecated As of 1.2, use {@link #getMapper}
*/
public ClassMapper getClassMapper() {
if (mapper instanceof ClassMapper) {
return (ClassMapper)mapper;
} else {
return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(mapper, args);
}
});
}
}
/**
* Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}.
*
* @return the mapper
* @since 1.2
*/
public Mapper getMapper() {
return mapper;
}
/**
* Retrieve the {@link ReflectionProvider} in use.
*
* @return the mapper
* @since upcoming
*/
public ReflectionProvider getReflectionProvider() {
return reflectionProvider;
}
public ConverterLookup getConverterLookup() {
return converterLookup;
}
/**
* Change mode for dealing with duplicate references. Valid valuse are
* <code>XPATH_ABSOLUTE_REFERENCES</code>, <code>XPATH_RELATIVE_REFERENCES</code>,
* <code>XStream.ID_REFERENCES</code> and <code>XStream.NO_REFERENCES</code>.
*
* @throws IllegalArgumentException if the mode is not one of the declared types
* @see #XPATH_ABSOLUTE_REFERENCES
* @see #XPATH_RELATIVE_REFERENCES
* @see #ID_REFERENCES
* @see #NO_REFERENCES
*/
public void setMode(int mode) {
switch (mode) {
case NO_REFERENCES:
setMarshallingStrategy(new TreeMarshallingStrategy());
break;
case ID_REFERENCES:
setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
break;
case XPATH_RELATIVE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.RELATIVE));
break;
case XPATH_ABSOLUTE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.ABSOLUTE));
break;
default:
throw new IllegalArgumentException("Unknown mode : " + mode);
}
}
/**
* Adds a default implicit collection which is used for any unmapped xml tag.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
*/
public void addImplicitCollection(Class ownerType, String fieldName) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, Object.class);
}
/**
* Adds implicit collection which is used for all items of the given itemType.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemType type of the items to be part of this collection.
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, itemType);
}
/**
* Adds implicit collection which is used for all items of the given element name defined by
* itemFieldName.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemFieldName element name of the implicit collection
* @param itemType item type to be aliases be the itemFieldName
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(
Class ownerType, String fieldName, String itemFieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType);
}
public DataHolder newDataHolder() {
return new MapBackedDataHolder();
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer)
throws IOException {
return createObjectOutputStream(writer, "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName)
throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* Because an ObjectOutputStream can contain multiple items and XML only allows a single root
* node, the stream must be written inside an enclosing node.
* </p>
* <p>
* It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be
* incomplete.
* </p>
* <h3>Example</h3>
*
* <pre>
* ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
* out.writeInt(123);
* out.writeObject("Hello");
* out.writeObject(someObject)
* out.close();
* </pre>
*
* @param writer The writer to serialize the objects to.
* @param rootNodeName The name of the root node enclosing the stream of objects.
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(
final HierarchicalStreamWriter writer, String rootNodeName) throws IOException {
final StatefulWriter statefulWriter = new StatefulWriter(writer);
statefulWriter.startNode(rootNodeName, null);
return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
marshal(object, statefulWriter);
}
public void writeFieldsToStream(Map fields) throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void defaultWriteObject() throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void flush() {
statefulWriter.flush();
}
public void close() {
if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) {
statefulWriter.endNode();
statefulWriter.close();
}
}
});
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
* <h3>Example</h3>
*
* <pre>
* ObjectInputStream in = xstream.createObjectOutputStream(aReader);
* int a = out.readInt();
* Object b = out.readObject();
* Object c = out.readObject();
* </pre>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader)
throws IOException {
return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
public Object readFromStream() throws EOFException {
if (!reader.hasMoreChildren()) {
throw new EOFException();
}
reader.moveDown();
Object result = unmarshal(reader);
reader.moveUp();
return result;
}
public Map readFieldsFromStream() throws IOException {
throw new NotActiveException("not in call to readObject");
}
public void defaultReadObject() throws NotActiveException {
throw new NotActiveException("not in call to readObject");
}
public void registerValidation(ObjectInputValidation validation, int priority)
throws NotActiveException {
throw new NotActiveException("stream inactive");
}
public void close() {
reader.close();
}
});
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public void setClassLoader(ClassLoader classLoader) {
classLoaderReference.setReference(classLoader);
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public ClassLoader getClassLoader() {
return classLoaderReference.getReference();
}
/**
* Prevents a field from being serialized. To omit a field you must always provide the declaring
* type and not necessarily the type that is converted.
*
* @since 1.1.3
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void omitField(Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.omitField(type, fieldName);
}
public static class InitializationException extends BaseException {
public InitializationException(String message, Throwable cause) {
super(message, cause);
}
public InitializationException(String message) {
super(message);
}
}
private Object readResolve() {
jvm = new JVM();
return this;
}
}
| xstream/src/java/com/thoughtworks/xstream/XStream.java | package com.thoughtworks.xstream;
import java.awt.font.TextAttribute;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringBufferConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.PropertiesConverter;
import com.thoughtworks.xstream.converters.collections.TreeMapConverter;
import com.thoughtworks.xstream.converters.collections.TreeSetConverter;
import com.thoughtworks.xstream.converters.extended.ColorConverter;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.FontConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.extended.SqlDateConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimeConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter;
import com.thoughtworks.xstream.converters.extended.TextAttributeConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.core.BaseException;
import com.thoughtworks.xstream.core.DefaultConverterLookup;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.core.MapBackedDataHolder;
import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy;
import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy;
import com.thoughtworks.xstream.core.TreeMarshallingStrategy;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StatefulWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.ArrayMapper;
import com.thoughtworks.xstream.mapper.AttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.AttributeMapper;
import com.thoughtworks.xstream.mapper.CachingMapper;
import com.thoughtworks.xstream.mapper.ClassAliasingMapper;
import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
import com.thoughtworks.xstream.mapper.DefaultMapper;
import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
import com.thoughtworks.xstream.mapper.EnumMapper;
import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.mapper.OuterClassMapper;
import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;
/**
* Simple facade to XStream library, a Java-XML serialization tool. <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* XStream xstream = new XStream();
* String xml = xstream.toXML(myObject); // serialize to XML
* Object myObject2 = xstream.fromXML(xml); // deserialize from XML
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Aliasing classes</h3>
* <p/>
* <p>
* To create shorter XML, you can specify aliases for classes using the <code>alias()</code>
* method. For example, you can shorten all occurences of element
* <code><com.blah.MyThing></code> to <code><my-thing></code> by registering an
* alias for the class.
* <p>
* <hr>
* <blockquote>
*
* <pre>
* xstream.alias("my-thing", MyThing.class);
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Converters</h3>
* <p/>
* <p>
* XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each
* of which acts as a strategy for converting a particular type of class to XML and back again. Out
* of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc)
* and collections (Map, List, Set, Properties, etc). For other objects reflection is used to
* serialize each field recursively.
* </p>
* <p/>
* <p>
* Extra converters can be registered using the <code>registerConverter()</code> method. Some
* non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended}
* package and you can create your own by implementing the
* {@link com.thoughtworks.xstream.converters.Converter} interface.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.registerConverter(new SqlTimestampConverter());
* xstream.registerConverter(new DynamicProxyConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p>
* The default converter, ie the converter which will be used if no other registered converter is
* suitable, can be configured by either one of the constructors or can be changed using the
* <code>changeDefaultConverter()</code> method. If not set, XStream uses
* {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the initial default
* converter.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.changeDefaultConverter(new ACustomDefaultConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Object graphs</h3>
* <p/>
* <p>
* XStream has support for object graphs; a deserialized object graph will keep references intact,
* including circular references.
* </p>
* <p/>
* <p>
* XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using
* <code>setMode()</code>:
* </p>
* <p/> <table border="1">
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td>
* <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML
* with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td>
* <td>Uses XPath absolute references to signify duplicate
* references. This produces XML with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td>
* <td>Uses ID references to signify duplicate references. In some scenarios, such as when using
* hand-written XML, this is easier to work with.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td>
* <td>This disables object graph support and treats the object structure like a tree. Duplicate
* references are treated as two seperate objects and circular references cause an exception. This
* is slightly faster and uses less memory than the other two modes.</td>
* </tr>
* </table>
* <h3>Thread safety</h3>
* <p>
* The XStream instance is thread-safe. That is, once the XStream instance has been created and
* configured, it may be shared across multiple threads allowing objects to be
* serialized/deserialized concurrently.
* <h3>Implicit collections</h3>
* <p/>
* <p>
* To avoid the need for special tags for collections, you can define implicit collections using one
* of the <code>addImplicitCollection</code> methods.
* </p>
*
* @author Joe Walnes
* @author Jörg Schaible
* @author Mauro Talevi
*/
public class XStream {
// CAUTION: The sequence of the fields is intentional for an optimal XML output of a
// self-serializaion!
private ReflectionProvider reflectionProvider;
private HierarchicalStreamDriver hierarchicalStreamDriver;
private ClassLoaderReference classLoaderReference;
private MarshallingStrategy marshallingStrategy;
private Mapper mapper;
private DefaultConverterLookup converterLookup;
private ClassAliasingMapper classAliasingMapper;
private FieldAliasingMapper fieldAliasingMapper;
private AttributeAliasingMapper attributeAliasingMapper;
private AttributeMapper attributeMapper;
private DefaultImplementationsMapper defaultImplementationsMapper;
private ImmutableTypesMapper immutableTypesMapper;
private ImplicitCollectionMapper implicitCollectionMapper;
private transient JVM jvm = new JVM();
public static final int NO_REFERENCES = 1001;
public static final int ID_REFERENCES = 1002;
public static final int XPATH_RELATIVE_REFERENCES = 1003;
public static final int XPATH_ABSOLUTE_REFERENCES = 1004;
/**
* @deprecated since 1.2, use {@value #XPATH_RELATIVE_REFERENCES} or
* {@value #XPATH_ABSOLUTE_REFERENCES} instead.
*/
public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES;
public static final int PRIORITY_VERY_HIGH = 10000;
public static final int PRIORITY_NORMAL = 0;
public static final int PRIORITY_LOW = -10;
public static final int PRIORITY_VERY_LOW = -20;
/**
* Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream() {
this(null, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(ReflectionProvider reflectionProvider) {
this(reflectionProvider, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) {
this(null, (Mapper)null, hierarchicalStreamDriver);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) {
this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)}
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver) {
this(reflectionProvider, (Mapper)classMapper, driver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and
* register classAttributeIdentifier as alias
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver, String classAttributeIdentifier) {
this(reflectionProvider, (Mapper)classMapper, driver);
aliasAttribute(classAttributeIdentifier, "class");
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) {
jvm = new JVM();
if (reflectionProvider == null) {
reflectionProvider = jvm.bestReflectionProvider();
}
this.reflectionProvider = reflectionProvider;
this.hierarchicalStreamDriver = driver;
this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader());
this.mapper = mapper == null ? buildMapper() : mapper;
this.converterLookup = new DefaultConverterLookup(this.mapper);
setupMappers();
setupAliases();
setupDefaultImplementations();
setupConverters();
setupImmutableTypes();
setMode(XPATH_RELATIVE_REFERENCES);
}
private Mapper buildMapper() {
Mapper mapper = new DefaultMapper(classLoaderReference);
if ( useXStream11XmlFriendlyMapper() ){
mapper = new XStream11XmlFriendlyMapper(mapper);
}
mapper = new ClassAliasingMapper(mapper);
mapper = new FieldAliasingMapper(mapper);
mapper = new AttributeAliasingMapper(mapper);
mapper = new AttributeMapper(mapper);
mapper = new ImplicitCollectionMapper(mapper);
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
mapper = buildMapperDynamically(
"com.thoughtworks.xstream.mapper.CGLIBMapper",
new Class[]{Mapper.class}, new Object[]{mapper});
}
mapper = new DynamicProxyMapper(mapper);
if (JVM.is15()) {
mapper = new EnumMapper(mapper);
}
mapper = new OuterClassMapper(mapper);
mapper = new ArrayMapper(mapper);
mapper = new DefaultImplementationsMapper(mapper);
mapper = new ImmutableTypesMapper(mapper);
mapper = wrapMapper((MapperWrapper)mapper);
mapper = new CachingMapper(mapper);
return mapper;
}
private Mapper buildMapperDynamically(
String className, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
return (Mapper)constructor.newInstance(constructorParamValues);
} catch (Exception e) {
throw new InitializationException("Could not instatiate mapper : " + className, e);
}
}
protected MapperWrapper wrapMapper(MapperWrapper next) {
return next;
}
protected boolean useXStream11XmlFriendlyMapper() {
return false;
}
private void setupMappers() {
classAliasingMapper = (ClassAliasingMapper)this.mapper
.lookupMapperOfType(ClassAliasingMapper.class);
fieldAliasingMapper = (FieldAliasingMapper)this.mapper
.lookupMapperOfType(FieldAliasingMapper.class);
attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class);
attributeAliasingMapper = (AttributeAliasingMapper)this.mapper
.lookupMapperOfType(AttributeAliasingMapper.class);
implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper
.lookupMapperOfType(ImplicitCollectionMapper.class);
defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper
.lookupMapperOfType(DefaultImplementationsMapper.class);
immutableTypesMapper = (ImmutableTypesMapper)this.mapper
.lookupMapperOfType(ImmutableTypesMapper.class);
// should use ctor, but converterLookup is not yet initialized instantiating this mapper
if (attributeMapper != null) {
attributeMapper.setConverterLookup(converterLookup);
}
}
protected void setupAliases() {
if (classAliasingMapper == null) {
return;
}
alias("null", Mapper.Null.class);
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("big-int", BigInteger.class);
alias("big-decimal", BigDecimal.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("method", Method.class);
alias("constructor", Constructor.class);
alias("date", Date.class);
alias("url", URL.class);
alias("bit-set", BitSet.class);
alias("map", Map.class);
alias("entry", Map.Entry.class);
alias("properties", Properties.class);
alias("list", List.class);
alias("set", Set.class);
alias("linked-list", LinkedList.class);
alias("vector", Vector.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
alias("hashtable", Hashtable.class);
// Instantiating these two classes starts the AWT system, which is undesirable. Calling
// loadClass ensures a reference to the class is found but they are not instantiated.
alias("awt-color", jvm.loadClass("java.awt.Color"));
alias("awt-font", jvm.loadClass("java.awt.Font"));
alias("awt-text-attribute", TextAttribute.class);
alias("sql-timestamp", Timestamp.class);
alias("sql-time", Time.class);
alias("sql-date", java.sql.Date.class);
alias("file", File.class);
alias("locale", Locale.class);
alias("gregorian-calendar", Calendar.class);
// since jdk 1.4 included, but previously available as separate package ...
Class type = jvm.loadClass("javax.security.auth.Subject");
if (type != null) {
alias("auth-subject", type);
}
if (JVM.is14()) {
alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap"));
alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet"));
alias("trace", jvm.loadClass("java.lang.StackTraceElement"));
alias("currency", jvm.loadClass("java.util.Currency"));
aliasType("charset", jvm.loadClass("java.nio.charset.Charset"));
}
if (JVM.is15()) {
alias("enum-set", jvm.loadClass("java.util.EnumSet"));
alias("enum-map", jvm.loadClass("java.util.EnumMap"));
}
}
protected void setupDefaultImplementations() {
if (defaultImplementationsMapper == null) {
return;
}
addDefaultImplementation(HashMap.class, Map.class);
addDefaultImplementation(ArrayList.class, List.class);
addDefaultImplementation(HashSet.class, Set.class);
addDefaultImplementation(GregorianCalendar.class, Calendar.class);
}
protected void setupConverters() {
// use different ReflectionProvider depending on JDK
final ReflectionConverter reflectionConverter;
if (JVM.is15()) {
Class annotationProvider = jvm
.loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider");
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.annotations.AnnotationReflectionConverter",
PRIORITY_VERY_LOW, new Class[]{
Mapper.class, ReflectionProvider.class, annotationProvider},
new Object[]{
mapper, reflectionProvider,
reflectionProvider.newInstance(annotationProvider)});
reflectionConverter = (ReflectionConverter)converterLookup
.lookupConverterForType(Object.class);
} else {
reflectionConverter = new ReflectionConverter(mapper, reflectionProvider);
registerConverter(reflectionConverter, PRIORITY_VERY_LOW);
}
registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new StringBufferConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL);
registerConverter(new MapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL);
registerConverter(new PropertiesConverter(), PRIORITY_NORMAL);
registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new FontConverter(), PRIORITY_NORMAL);
registerConverter(new ColorConverter(), PRIORITY_NORMAL);
registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL);
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
// since jdk 1.4 included, but previously available as separate package ...
if (jvm.loadClass("javax.security.auth.Subject") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.SubjectConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
}
if (JVM.is14()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.ThrowableConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.StackTraceElementConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CurrencyConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.RegexPatternConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CharsetConverter",
PRIORITY_NORMAL, null, null);
}
if (JVM.is15()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
}
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.reflection.CGLIBEnhancedConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class},
new Object[]{mapper, reflectionProvider});
}
registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL);
}
private void dynamicallyRegisterConverter(
String className, int priority, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
Object instance = constructor.newInstance(constructorParamValues);
if (instance instanceof Converter) {
registerConverter((Converter)instance, priority);
} else if (instance instanceof SingleValueConverter) {
registerConverter((SingleValueConverter)instance, priority);
}
} catch (Exception e) {
throw new InitializationException("Could not instatiate converter : " + className, e);
}
}
protected void setupImmutableTypes() {
if (immutableTypesMapper == null) {
return;
}
// primitives are always immutable
addImmutableType(boolean.class);
addImmutableType(Boolean.class);
addImmutableType(byte.class);
addImmutableType(Byte.class);
addImmutableType(char.class);
addImmutableType(Character.class);
addImmutableType(double.class);
addImmutableType(Double.class);
addImmutableType(float.class);
addImmutableType(Float.class);
addImmutableType(int.class);
addImmutableType(Integer.class);
addImmutableType(long.class);
addImmutableType(Long.class);
addImmutableType(short.class);
addImmutableType(Short.class);
// additional types
addImmutableType(Mapper.Null.class);
addImmutableType(BigDecimal.class);
addImmutableType(BigInteger.class);
addImmutableType(String.class);
addImmutableType(URL.class);
addImmutableType(File.class);
addImmutableType(Class.class);
addImmutableType(TextAttribute.class);
if (JVM.is14()) {
// late bound types - allows XStream to be compiled on earlier JDKs
Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter");
addImmutableType(type);
}
}
public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {
this.marshallingStrategy = marshallingStrategy;
}
/**
* Serialize an object to a pretty-printed XML String.
* @throws BaseException if the object cannot be serialized
*/
public String toXML(Object obj) {
Writer writer = new StringWriter();
toXML(obj, writer);
return writer.toString();
}
/**
* Serialize an object to the given Writer as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, Writer out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize an object to the given OutputStream as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, OutputStream out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer) {
marshal(obj, writer, null);
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) {
marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder);
}
/**
* Deserialize an object from an XML String.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml) {
return fromXML(new StringReader(xml));
}
/**
* Deserialize an object from an XML Reader.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), null);
}
/**
* Deserialize an object from an XML InputStream.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream input) {
return unmarshal(hierarchicalStreamDriver.createReader(input), null);
}
/**
* Deserialize an object from an XML String, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml, Object root) {
return fromXML(new StringReader(xml), root);
}
/**
* Deserialize an object from an XML Reader, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from an XML InputStream, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader) {
return unmarshal(reader, null, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML), populating the fields
* of the given root object instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root) {
return unmarshal(reader, root, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*
* @param root If present, the passed in object will have its fields populated, as opposed to
* XStream creating a new instance.
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addClassAlias(name, type);
}
/**
* Alias a type to a shorter name to be used in XML elements.
* Any class that is assignable to this type will be aliased to the same name.
*
* @param name Short name
* @param type Type to be aliased
* @since 1.2
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void aliasType(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addTypeAlias(name, type);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @param defaultImplementation Default implementation of type to use if no other specified.
* @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type, Class defaultImplementation) {
alias(name, type);
addDefaultImplementation(defaultImplementation, type);
}
/**
* Create an alias for a field name.
*
* @param alias the alias itself
* @param type the type that declares the field
* @param fieldName the name of the field
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void aliasField(String alias, Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.addFieldAlias(alias, type, fieldName);
}
/**
* Create an alias for an attribute
*
* @param alias the alias itself
* @param attributeName the name of the attribute
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(String alias, String attributeName) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName()
+ " available");
}
attributeAliasingMapper.addAliasFor(attributeName, alias);
}
/**
* Use an XML attribute for a field or a specific type.
*
* @param fieldName the name of the field
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(String fieldName, Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(fieldName, type);
}
/**
* Use an XML attribute for an arbotrary type.
*
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(type);
}
/**
* Associate a default implementation of a class with an object. Whenever XStream encounters an
* instance of this type, it will use the default implementation instead. For example,
* java.util.ArrayList is the default implementation of java.util.List.
*
* @param defaultImplementation
* @param ofType
* @throws InitializationException if no {@link DefaultImplementationsMapper} is available
*/
public void addDefaultImplementation(Class defaultImplementation, Class ofType) {
if (defaultImplementationsMapper == null) {
throw new InitializationException("No "
+ DefaultImplementationsMapper.class.getName()
+ " available");
}
defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType);
}
/**
* Add immutable types. The value of the instances of these types will always be written into
* the stream even if they appear multiple times.
* @throws InitializationException if no {@link ImmutableTypesMapper} is available
*/
public void addImmutableType(Class type) {
if (immutableTypesMapper == null) {
throw new InitializationException("No "
+ ImmutableTypesMapper.class.getName()
+ " available");
}
immutableTypesMapper.addImmutableType(type);
}
public void registerConverter(Converter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(Converter converter, int priority) {
converterLookup.registerConverter(converter, priority);
}
public void registerConverter(SingleValueConverter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(SingleValueConverter converter, int priority) {
converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority);
}
/**
* @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance
* @deprecated As of 1.2, use {@link #getMapper}
*/
public ClassMapper getClassMapper() {
if (mapper instanceof ClassMapper) {
return (ClassMapper)mapper;
} else {
return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(mapper, args);
}
});
}
}
/**
* Retrieve the mapper. This is by default a chain of {@link MapperWrapper MapperWrappers}.
*
* @return the mapper
* @since 1.2
*/
public Mapper getMapper() {
return mapper;
}
public ConverterLookup getConverterLookup() {
return converterLookup;
}
/**
* Change mode for dealing with duplicate references. Valid valuse are
* <code>XPATH_ABSOLUTE_REFERENCES</code>, <code>XPATH_RELATIVE_REFERENCES</code>,
* <code>XStream.ID_REFERENCES</code> and <code>XStream.NO_REFERENCES</code>.
*
* @throws IllegalArgumentException if the mode is not one of the declared types
* @see #XPATH_ABSOLUTE_REFERENCES
* @see #XPATH_RELATIVE_REFERENCES
* @see #ID_REFERENCES
* @see #NO_REFERENCES
*/
public void setMode(int mode) {
switch (mode) {
case NO_REFERENCES:
setMarshallingStrategy(new TreeMarshallingStrategy());
break;
case ID_REFERENCES:
setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
break;
case XPATH_RELATIVE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.RELATIVE));
break;
case XPATH_ABSOLUTE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.ABSOLUTE));
break;
default:
throw new IllegalArgumentException("Unknown mode : " + mode);
}
}
/**
* Adds a default implicit collection which is used for any unmapped xml tag.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
*/
public void addImplicitCollection(Class ownerType, String fieldName) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, Object.class);
}
/**
* Adds implicit collection which is used for all items of the given itemType.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemType type of the items to be part of this collection.
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, itemType);
}
/**
* Adds implicit collection which is used for all items of the given element name defined by
* itemFieldName.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemFieldName element name of the implicit collection
* @param itemType item type to be aliases be the itemFieldName
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(
Class ownerType, String fieldName, String itemFieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType);
}
public DataHolder newDataHolder() {
return new MapBackedDataHolder();
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer)
throws IOException {
return createObjectOutputStream(writer, "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName)
throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* Because an ObjectOutputStream can contain multiple items and XML only allows a single root
* node, the stream must be written inside an enclosing node.
* </p>
* <p>
* It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be
* incomplete.
* </p>
* <h3>Example</h3>
*
* <pre>
* ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
* out.writeInt(123);
* out.writeObject("Hello");
* out.writeObject(someObject)
* out.close();
* </pre>
*
* @param writer The writer to serialize the objects to.
* @param rootNodeName The name of the root node enclosing the stream of objects.
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(
final HierarchicalStreamWriter writer, String rootNodeName) throws IOException {
final StatefulWriter statefulWriter = new StatefulWriter(writer);
statefulWriter.startNode(rootNodeName, null);
return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
marshal(object, statefulWriter);
}
public void writeFieldsToStream(Map fields) throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void defaultWriteObject() throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void flush() {
statefulWriter.flush();
}
public void close() {
if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) {
statefulWriter.endNode();
statefulWriter.close();
}
}
});
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
* <h3>Example</h3>
*
* <pre>
* ObjectInputStream in = xstream.createObjectOutputStream(aReader);
* int a = out.readInt();
* Object b = out.readObject();
* Object c = out.readObject();
* </pre>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader)
throws IOException {
return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
public Object readFromStream() throws EOFException {
if (!reader.hasMoreChildren()) {
throw new EOFException();
}
reader.moveDown();
Object result = unmarshal(reader);
reader.moveUp();
return result;
}
public Map readFieldsFromStream() throws IOException {
throw new NotActiveException("not in call to readObject");
}
public void defaultReadObject() throws NotActiveException {
throw new NotActiveException("not in call to readObject");
}
public void registerValidation(ObjectInputValidation validation, int priority)
throws NotActiveException {
throw new NotActiveException("stream inactive");
}
public void close() {
reader.close();
}
});
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public void setClassLoader(ClassLoader classLoader) {
classLoaderReference.setReference(classLoader);
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public ClassLoader getClassLoader() {
return classLoaderReference.getReference();
}
/**
* Prevents a field from being serialized. To omit a field you must always provide the declaring
* type and not necessarily the type that is converted.
*
* @since 1.1.3
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void omitField(Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.omitField(type, fieldName);
}
public static class InitializationException extends BaseException {
public InitializationException(String message, Throwable cause) {
super(message, cause);
}
public InitializationException(String message) {
super(message);
}
}
private Object readResolve() {
jvm = new JVM();
return this;
}
}
| Add getReflectionProvider().
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1043 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e
| xstream/src/java/com/thoughtworks/xstream/XStream.java | Add getReflectionProvider(). |
|
Java | bsd-3-clause | e62edb1b579cb35371b6f86e900adcf3e68c3dbc | 0 | sammymax/nullpomino,sammymax/nullpomino | /*
Copyright (c) 2010, NullNoname
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 NullNoname nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.game_host.hebo.nullpomino.game.subsystem.mode;
import java.util.Random;
import org.game_host.hebo.nullpomino.game.component.BGMStatus;
import org.game_host.hebo.nullpomino.game.component.Block;
import org.game_host.hebo.nullpomino.game.component.Controller;
import org.game_host.hebo.nullpomino.game.component.Field;
import org.game_host.hebo.nullpomino.game.component.Piece;
import org.game_host.hebo.nullpomino.game.event.EventReceiver;
import org.game_host.hebo.nullpomino.game.play.GameEngine;
import org.game_host.hebo.nullpomino.game.play.GameManager;
import org.game_host.hebo.nullpomino.util.CustomProperties;
import org.game_host.hebo.nullpomino.util.GeneralUtil;
/**
* AVALANCHE VS-BATTLE mode (beta)
*/
public class AvalancheVSMode extends DummyMode {
/** 現在のバージョン */
private static final int CURRENT_VERSION = 0;
/** Enabled piece types */
private static final int[] PIECE_ENABLE = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0};
/** Block colors */
private static final int[] BLOCK_COLORS =
{
Block.BLOCK_COLOR_RED,
Block.BLOCK_COLOR_GREEN,
Block.BLOCK_COLOR_BLUE,
Block.BLOCK_COLOR_YELLOW,
Block.BLOCK_COLOR_PURPLE
};
/** プレイヤーの数 */
private static final int MAX_PLAYERS = 2;
/** Names of ojama counter setting constants */
private final int OJAMA_COUNTER_OFF = 0, OJAMA_COUNTER_ON = 1, OJAMA_COUNTER_FEVER = 2;
/** 邪魔ブロックタイプの表示名 */
//private final String[] OJAMA_TYPE_STRING = {"NORMAL", "ONE RISE", "1-ATTACK"};
/** Names of ojama counter settings */
private final String[] OJAMA_COUNTER_STRING = {"OFF", "ON", "FEVER"};
/** 各プレイヤーの枠の色 */
private final int[] PLAYER_COLOR_FRAME = {GameEngine.FRAME_COLOR_RED, GameEngine.FRAME_COLOR_BLUE};
/** このモードを所有するGameManager */
private GameManager owner;
/** 描画などのイベント処理 */
private EventReceiver receiver;
/** Rule settings for countering ojama not yet dropped */
private int[] ojamaCounterMode;
/** 溜まっている邪魔ブロックの数 */
private int[] ojama;
/** 送った邪魔ブロックの数 */
private int[] ojamaSent;
/** 最後にスコア獲得してから経過した時間 */
private int[] scgettime;
/** 使用するBGM */
private int bgmno;
/** ビッグ */
private boolean[] big;
/** 効果音ON/OFF */
private boolean[] enableSE;
/** マップ使用フラグ */
private boolean[] useMap;
/** 使用するマップセット番号 */
private int[] mapSet;
/** マップ番号(-1でランダム) */
private int[] mapNumber;
/** 最後に使ったプリセット番号 */
private int[] presetNumber;
/** 勝者 */
private int winnerID;
/** マップセットのプロパティファイル */
private CustomProperties[] propMap;
/** 最大マップ番号 */
private int[] mapMaxNo;
/** バックアップ用フィールド(マップをリプレイに保存するときに使用) */
private Field[] fldBackup;
/** マップ選択用乱数 */
private Random randMap;
/** バージョン */
private int version;
/** Flag for all clear */
private boolean[] zenKeshi;
/** Amount of points earned from most recent clear */
private int[] lastscore, lastmultiplier;
/** Amount of ojama added in current chain */
private int[] ojamaAdd;
/** Score */
private int[] score;
/** Max amount of ojama dropped at once */
private int[] maxAttack;
/** Number of colors to use */
private int[] numColors;
/** Minimum chain count needed to send ojama */
private int[] rensaShibari;
/** Denominator for score-to-ojama conversion */
private int[] ojamaRate;
/** Settings for hard ojama blocks */
private int[] ojamaHard;
/** Hurryup開始までの秒数(0でHurryupなし) */
private int[] hurryupSeconds;
/** Fever points needed to enter Fever Mode */
private int[] feverThreshold;
/** Fever points */
private int[] feverPoints;
/** Fever time */
private int[] feverTime;
/** Minimum and maximum fever time */
private int[] feverTimeMin, feverTimeMax;
/** Flag set to true when player is in Fever Mode */
private boolean[] inFever;
/** Backup fields for Fever Mode */
private Field[] feverBackupField;
/** Second ojama counter for Fever Mode */
private int[] ojamaFever;
/** Set to true when opponent starts chain while in Fever Mode */
private boolean[] ojamaAddToFever;
/** Set to true when last drop resulted in a clear */
private boolean[] cleared;
/** Set to true when dropping ojama blocks */
private boolean[] ojamaDrop;
/*
* モード名
*/
@Override
public String getName() {
return "AVALANCHE VS-BATTLE (BETA)";
}
/*
* プレイヤー数
*/
@Override
public int getPlayers() {
return MAX_PLAYERS;
}
/*
* モードの初期化
*/
@Override
public void modeInit(GameManager manager) {
owner = manager;
receiver = owner.receiver;
ojamaCounterMode = new int[MAX_PLAYERS];
ojama = new int[MAX_PLAYERS];
ojamaSent = new int[MAX_PLAYERS];
scgettime = new int[MAX_PLAYERS];
bgmno = 0;
big = new boolean[MAX_PLAYERS];
enableSE = new boolean[MAX_PLAYERS];
hurryupSeconds = new int[MAX_PLAYERS];
useMap = new boolean[MAX_PLAYERS];
mapSet = new int[MAX_PLAYERS];
mapNumber = new int[MAX_PLAYERS];
presetNumber = new int[MAX_PLAYERS];
propMap = new CustomProperties[MAX_PLAYERS];
mapMaxNo = new int[MAX_PLAYERS];
fldBackup = new Field[MAX_PLAYERS];
randMap = new Random();
zenKeshi = new boolean[MAX_PLAYERS];
lastscore = new int[MAX_PLAYERS];
lastmultiplier = new int[MAX_PLAYERS];
ojamaAdd = new int[MAX_PLAYERS];
score = new int[MAX_PLAYERS];
numColors = new int[MAX_PLAYERS];
maxAttack = new int[MAX_PLAYERS];
rensaShibari = new int[MAX_PLAYERS];
ojamaRate = new int[MAX_PLAYERS];
ojamaHard = new int[MAX_PLAYERS];
feverThreshold = new int[MAX_PLAYERS];
feverPoints = new int[MAX_PLAYERS];
feverTime = new int[MAX_PLAYERS];
feverTimeMin = new int[MAX_PLAYERS];
feverTimeMax = new int[MAX_PLAYERS];
inFever = new boolean[MAX_PLAYERS];
feverBackupField = new Field[MAX_PLAYERS];
ojamaFever = new int[MAX_PLAYERS];
ojamaAddToFever = new boolean[MAX_PLAYERS];
cleared = new boolean[MAX_PLAYERS];
ojamaDrop = new boolean[MAX_PLAYERS];
winnerID = -1;
}
/**
* スピードプリセットを読み込み
* @param engine GameEngine
* @param prop 読み込み元のプロパティファイル
* @param preset プリセット番号
*/
private void loadPreset(GameEngine engine, CustomProperties prop, int preset) {
engine.speed.gravity = prop.getProperty("avalanchevs.gravity." + preset, 4);
engine.speed.denominator = prop.getProperty("avalanchevs.denominator." + preset, 256);
engine.speed.are = prop.getProperty("avalanchevs.are." + preset, 24);
engine.speed.areLine = prop.getProperty("avalanchevs.areLine." + preset, 24);
engine.speed.lineDelay = prop.getProperty("avalanchevs.lineDelay." + preset, 10);
engine.speed.lockDelay = prop.getProperty("avalanchevs.lockDelay." + preset, 30);
engine.speed.das = prop.getProperty("avalanchevs.das." + preset, 14);
}
/**
* スピードプリセットを保存
* @param engine GameEngine
* @param prop 保存先のプロパティファイル
* @param preset プリセット番号
*/
private void savePreset(GameEngine engine, CustomProperties prop, int preset) {
prop.setProperty("avalanchevs.gravity." + preset, engine.speed.gravity);
prop.setProperty("avalanchevs.denominator." + preset, engine.speed.denominator);
prop.setProperty("avalanchevs.are." + preset, engine.speed.are);
prop.setProperty("avalanchevs.areLine." + preset, engine.speed.areLine);
prop.setProperty("avalanchevs.lineDelay." + preset, engine.speed.lineDelay);
prop.setProperty("avalanchevs.lockDelay." + preset, engine.speed.lockDelay);
prop.setProperty("avalanchevs.das." + preset, engine.speed.das);
}
/**
* スピード以外の設定を読み込み
* @param engine GameEngine
* @param prop 読み込み元のプロパティファイル
*/
private void loadOtherSetting(GameEngine engine, CustomProperties prop) {
int playerID = engine.playerID;
bgmno = prop.getProperty("avalanchevs.bgmno", 0);
ojamaCounterMode[playerID] = prop.getProperty("avalanchevs.ojamaCounterMode", OJAMA_COUNTER_ON);
big[playerID] = prop.getProperty("avalanchevs.big.p" + playerID, false);
enableSE[playerID] = prop.getProperty("avalanchevs.enableSE.p" + playerID, true);
hurryupSeconds[playerID] = prop.getProperty("vsbattle.hurryupSeconds.p" + playerID, 192);
useMap[playerID] = prop.getProperty("avalanchevs.useMap.p" + playerID, false);
mapSet[playerID] = prop.getProperty("avalanchevs.mapSet.p" + playerID, 0);
mapNumber[playerID] = prop.getProperty("avalanchevs.mapNumber.p" + playerID, -1);
presetNumber[playerID] = prop.getProperty("avalanchevs.presetNumber.p" + playerID, 0);
maxAttack[playerID] = prop.getProperty("avalanchevs.maxAttack.p" + playerID, 30);
numColors[playerID] = prop.getProperty("avalanchevs.numColors.p" + playerID, 5);
rensaShibari[playerID] = prop.getProperty("avalanchevs.rensaShibari.p" + playerID, 1);
ojamaRate[playerID] = prop.getProperty("avalanchevs.ojamaRate.p" + playerID, 120);
ojamaHard[playerID] = prop.getProperty("avalanchevs.ojamaHard.p" + playerID, 0);
feverThreshold[playerID] = prop.getProperty("avalanchevs.feverThreshold.p" + playerID, 0);
feverTimeMin[playerID] = prop.getProperty("avalanchevs.feverTimeMin.p" + playerID, 15);
feverTimeMax[playerID] = prop.getProperty("avalanchevs.feverTimeMax.p" + playerID, 30);
}
/**
* スピード以外の設定を保存
* @param engine GameEngine
* @param prop 保存先のプロパティファイル
*/
private void saveOtherSetting(GameEngine engine, CustomProperties prop) {
int playerID = engine.playerID;
prop.setProperty("avalanchevs.bgmno", bgmno);
prop.setProperty("avalanchevs.ojamaCounterMode", ojamaCounterMode[playerID]);
prop.setProperty("avalanchevs.big.p" + playerID, big[playerID]);
prop.setProperty("avalanchevs.enableSE.p" + playerID, enableSE[playerID]);
prop.setProperty("vsbattle.hurryupSeconds.p" + playerID, hurryupSeconds[playerID]);
prop.setProperty("avalanchevs.useMap.p" + playerID, useMap[playerID]);
prop.setProperty("avalanchevs.mapSet.p" + playerID, mapSet[playerID]);
prop.setProperty("avalanchevs.mapNumber.p" + playerID, mapNumber[playerID]);
prop.setProperty("avalanchevs.presetNumber.p" + playerID, presetNumber[playerID]);
prop.setProperty("avalanchevs.maxAttack.p" + playerID, maxAttack[playerID]);
prop.setProperty("avalanchevs.numColors.p" + playerID, numColors[playerID]);
prop.setProperty("avalanchevs.rensaShibari.p" + playerID, rensaShibari[playerID]);
prop.setProperty("avalanchevs.ojamaRate.p" + playerID, ojamaRate[playerID]);
prop.setProperty("avalanchevs.ojamaHard.p" + playerID, ojamaHard[playerID]);
prop.setProperty("avalanchevs.feverThreshold.p" + playerID, feverThreshold[playerID]);
}
/**
* マップ読み込み
* @param field フィールド
* @param prop 読み込み元のプロパティファイル
* @param preset 任意のID
*/
private void loadMap(Field field, CustomProperties prop, int id) {
field.reset();
//field.readProperty(prop, id);
field.stringToField(prop.getProperty("map." + id, ""));
field.setAllAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true);
field.setAllAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true);
field.setAllAttribute(Block.BLOCK_ATTRIBUTE_SELFPLACED, false);
}
/**
* マップ保存
* @param field フィールド
* @param prop 保存先のプロパティファイル
* @param id 任意のID
*/
private void saveMap(Field field, CustomProperties prop, int id) {
//field.writeProperty(prop, id);
prop.setProperty("map." + id, field.fieldToString());
}
/**
* プレビュー用にマップを読み込み
* @param engine GameEngine
* @param playerID プレイヤー番号
* @param id マップID
* @param forceReload trueにするとマップファイルを強制再読み込み
*/
private void loadMapPreview(GameEngine engine, int playerID, int id, boolean forceReload) {
if((propMap[playerID] == null) || (forceReload)) {
mapMaxNo[playerID] = 0;
propMap[playerID] = receiver.loadProperties("config/map/vsbattle/" + mapSet[playerID] + ".map");
}
if((propMap[playerID] == null) && (engine.field != null)) {
engine.field.reset();
} else if(propMap[playerID] != null) {
mapMaxNo[playerID] = propMap[playerID].getProperty("map.maxMapNumber", 0);
engine.createFieldIfNeeded();
loadMap(engine.field, propMap[playerID], id);
engine.field.setAllSkin(engine.getSkin());
}
}
/*
* 各プレイヤーの初期化
*/
@Override
public void playerInit(GameEngine engine, int playerID) {
if(playerID == 1) {
engine.randSeed = owner.engine[0].randSeed;
engine.random = new Random(owner.engine[0].randSeed);
}
engine.framecolor = PLAYER_COLOR_FRAME[playerID];
engine.clearMode = GameEngine.CLEAR_COLOR;
engine.garbageColorClear = true;
engine.lineGravityType = GameEngine.LINE_GRAVITY_CASCADE;
for(int i = 0; i < Piece.PIECE_COUNT; i++)
engine.nextPieceEnable[i] = (PIECE_ENABLE[i] == 1);
engine.blockColors = BLOCK_COLORS;
engine.randomBlockColor = true;
engine.connectBlocks = false;
ojama[playerID] = 0;
ojamaSent[playerID] = 0;
score[playerID] = 0;
zenKeshi[playerID] = false;
scgettime[playerID] = 0;
feverPoints[playerID] = 0;
feverTime[playerID] = feverTimeMin[playerID] * 60;
inFever[playerID] = false;
feverBackupField[playerID] = null;
cleared[playerID] = false;
ojamaDrop[playerID] = false;
if(engine.owner.replayMode == false) {
loadOtherSetting(engine, engine.owner.modeConfig);
loadPreset(engine, engine.owner.modeConfig, -1 - playerID);
version = CURRENT_VERSION;
} else {
loadOtherSetting(engine, engine.owner.replayProp);
loadPreset(engine, engine.owner.replayProp, -1 - playerID);
version = owner.replayProp.getProperty("avalanchevs.version", 0);
}
}
/*
* 設定画面の処理
*/
@Override
public boolean onSetting(GameEngine engine, int playerID) {
// メニュー
if((engine.owner.replayMode == false) && (engine.statc[4] == 0)) {
// 上
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_UP)) {
engine.statc[2]--;
if(engine.statc[2] < 0) engine.statc[2] = 24;
engine.playSE("cursor");
}
// 下
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN)) {
engine.statc[2]++;
if(engine.statc[2] > 24) engine.statc[2] = 0;
engine.playSE("cursor");
}
// 設定変更
int change = 0;
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT)) change = -1;
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) change = 1;
if(change != 0) {
engine.playSE("change");
int m = 1;
if(engine.ctrl.isPress(Controller.BUTTON_E)) m = 100;
if(engine.ctrl.isPress(Controller.BUTTON_F)) m = 1000;
switch(engine.statc[2]) {
case 0:
engine.speed.gravity += change * m;
if(engine.speed.gravity < -1) engine.speed.gravity = 99999;
if(engine.speed.gravity > 99999) engine.speed.gravity = -1;
break;
case 1:
engine.speed.denominator += change * m;
if(engine.speed.denominator < -1) engine.speed.denominator = 99999;
if(engine.speed.denominator > 99999) engine.speed.denominator = -1;
break;
case 2:
engine.speed.are += change;
if(engine.speed.are < 0) engine.speed.are = 99;
if(engine.speed.are > 99) engine.speed.are = 0;
break;
case 3:
engine.speed.areLine += change;
if(engine.speed.areLine < 0) engine.speed.areLine = 99;
if(engine.speed.areLine > 99) engine.speed.areLine = 0;
break;
case 4:
engine.speed.lineDelay += change;
if(engine.speed.lineDelay < 0) engine.speed.lineDelay = 99;
if(engine.speed.lineDelay > 99) engine.speed.lineDelay = 0;
break;
case 5:
engine.speed.lockDelay += change;
if(engine.speed.lockDelay < 0) engine.speed.lockDelay = 99;
if(engine.speed.lockDelay > 99) engine.speed.lockDelay = 0;
break;
case 6:
engine.speed.das += change;
if(engine.speed.das < 0) engine.speed.das = 99;
if(engine.speed.das > 99) engine.speed.das = 0;
break;
case 7:
case 8:
presetNumber[playerID] += change;
if(presetNumber[playerID] < 0) presetNumber[playerID] = 99;
if(presetNumber[playerID] > 99) presetNumber[playerID] = 0;
break;
case 9:
ojamaCounterMode[playerID] += change;
if(ojamaCounterMode[playerID] < 0) ojamaCounterMode[playerID] = 2;
if(ojamaCounterMode[playerID] > 2) ojamaCounterMode[playerID] = 0;
break;
case 10:
maxAttack[playerID] += change;
if(maxAttack[playerID] < 0) maxAttack[playerID] = 99;
if(maxAttack[playerID] > 99) maxAttack[playerID] = 0;
break;
case 11:
numColors[playerID] += change;
if(numColors[playerID] < 3) numColors[playerID] = 5;
if(numColors[playerID] > 5) numColors[playerID] = 3;
break;
case 12:
rensaShibari[playerID] += change;
if(rensaShibari[playerID] < 1) rensaShibari[playerID] = 20;
if(rensaShibari[playerID] > 20) rensaShibari[playerID] = 1;
break;
case 13:
ojamaRate[playerID] += change*10;
if(ojamaRate[playerID] < 10) ojamaRate[playerID] = 1000;
if(ojamaRate[playerID] > 1000) ojamaRate[playerID] = 10;
break;
case 14:
big[playerID] = !big[playerID];
break;
case 15:
enableSE[playerID] = !enableSE[playerID];
break;
case 16:
hurryupSeconds[playerID] += change;
if(hurryupSeconds[playerID] < 0) hurryupSeconds[playerID] = 300;
if(hurryupSeconds[playerID] > 300) hurryupSeconds[playerID] = 0;
break;
case 17:
ojamaHard[playerID] += change;
if(ojamaHard[playerID] < 0) ojamaHard[playerID] = 9;
if(ojamaHard[playerID] > 9) ojamaHard[playerID] = 0;
break;
case 18:
bgmno += change;
if(bgmno < 0) bgmno = BGMStatus.BGM_COUNT - 1;
if(bgmno > BGMStatus.BGM_COUNT - 1) bgmno = 0;
break;
case 19:
useMap[playerID] = !useMap[playerID];
if(!useMap[playerID]) {
if(engine.field != null) engine.field.reset();
} else {
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
}
break;
case 20:
mapSet[playerID] += change;
if(mapSet[playerID] < 0) mapSet[playerID] = 99;
if(mapSet[playerID] > 99) mapSet[playerID] = 0;
if(useMap[playerID]) {
mapNumber[playerID] = -1;
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
}
break;
case 21:
if(useMap[playerID]) {
mapNumber[playerID] += change;
if(mapNumber[playerID] < -1) mapNumber[playerID] = mapMaxNo[playerID] - 1;
if(mapNumber[playerID] > mapMaxNo[playerID] - 1) mapNumber[playerID] = -1;
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
} else {
mapNumber[playerID] = -1;
}
break;
case 22:
feverThreshold[playerID] += change;
if(feverThreshold[playerID] < 0) feverThreshold[playerID] = 9;
if(feverThreshold[playerID] > 9) feverThreshold[playerID] = 0;
break;
case 23:
feverTimeMin[playerID] += change;
if(feverTimeMin[playerID] < 1) feverTimeMin[playerID] = feverTimeMax[playerID];
if(feverTimeMin[playerID] > feverTimeMax[playerID]) feverTimeMin[playerID] = 1;
break;
case 24:
feverTimeMax[playerID] += change;
if(feverTimeMax[playerID] < feverTimeMin[playerID]) feverTimeMax[playerID] = 99;
if(feverTimeMax[playerID] > 99) feverTimeMax[playerID] = feverTimeMin[playerID];
break;
}
}
// 決定
if(engine.ctrl.isPush(Controller.BUTTON_A) && (engine.statc[3] >= 5)) {
engine.playSE("decide");
if(engine.statc[2] == 7) {
loadPreset(engine, owner.modeConfig, presetNumber[playerID]);
} else if(engine.statc[2] == 8) {
savePreset(engine, owner.modeConfig, presetNumber[playerID]);
receiver.saveModeConfig(owner.modeConfig);
} else {
saveOtherSetting(engine, owner.modeConfig);
savePreset(engine, owner.modeConfig, -1 - playerID);
receiver.saveModeConfig(owner.modeConfig);
engine.statc[4] = 1;
}
}
// キャンセル
if(engine.ctrl.isPush(Controller.BUTTON_B)) {
engine.quitflag = true;
}
// プレビュー用マップ読み込み
if(useMap[playerID] && (engine.statc[3] == 0)) {
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
}
// ランダムマッププレビュー
if(useMap[playerID] && (propMap[playerID] != null) && (mapNumber[playerID] < 0)) {
if(engine.statc[3] % 30 == 0) {
engine.statc[5]++;
if(engine.statc[5] >= mapMaxNo[playerID]) engine.statc[5] = 0;
loadMapPreview(engine, playerID, engine.statc[5], false);
}
}
engine.statc[3]++;
} else if(engine.statc[4] == 0) {
engine.statc[3]++;
engine.statc[2] = 0;
if(engine.statc[3] >= 60) {
engine.statc[2] = 9;
}
if(engine.statc[3] >= 120) {
engine.statc[4] = 1;
}
} else {
// 開始
if((owner.engine[0].statc[4] == 1) && (owner.engine[1].statc[4] == 1) && (playerID == 1)) {
owner.engine[0].stat = GameEngine.STAT_READY;
owner.engine[1].stat = GameEngine.STAT_READY;
owner.engine[0].resetStatc();
owner.engine[1].resetStatc();
}
// キャンセル
else if(engine.ctrl.isPush(Controller.BUTTON_B)) {
engine.statc[4] = 0;
}
}
return true;
}
/*
* 設定画面の描画
*/
@Override
public void renderSetting(GameEngine engine, int playerID) {
if(engine.statc[4] == 0) {
if(engine.statc[2] < 9) {
if(owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, (engine.statc[2] * 2) + 1, "b",
(playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "GRAVITY", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 1, String.valueOf(engine.speed.gravity), (engine.statc[2] == 0));
receiver.drawMenuFont(engine, playerID, 0, 2, "G-MAX", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(engine.speed.denominator), (engine.statc[2] == 1));
receiver.drawMenuFont(engine, playerID, 0, 4, "ARE", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(engine.speed.are), (engine.statc[2] == 2));
receiver.drawMenuFont(engine, playerID, 0, 6, "ARE LINE", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 7, String.valueOf(engine.speed.areLine), (engine.statc[2] == 3));
receiver.drawMenuFont(engine, playerID, 0, 8, "LINE DELAY", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 9, String.valueOf(engine.speed.lineDelay), (engine.statc[2] == 4));
receiver.drawMenuFont(engine, playerID, 0, 10, "LOCK DELAY", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 11, String.valueOf(engine.speed.lockDelay), (engine.statc[2] == 5));
receiver.drawMenuFont(engine, playerID, 0, 12, "DAS", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 13, String.valueOf(engine.speed.das), (engine.statc[2] == 6));
receiver.drawMenuFont(engine, playerID, 0, 14, "LOAD", EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 1, 15, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 7));
receiver.drawMenuFont(engine, playerID, 0, 16, "SAVE", EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 1, 17, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 8));
} else if(engine.statc[2] < 19) {
if(owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 9) * 2) + 1, "b",
(playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "COUNTER", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 1, OJAMA_COUNTER_STRING[ojamaCounterMode[playerID]], (engine.statc[2] == 9));
receiver.drawMenuFont(engine, playerID, 0, 2, "MAX ATTACK", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(maxAttack[playerID]), (engine.statc[2] == 10));
receiver.drawMenuFont(engine, playerID, 0, 4, "COLORS", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(numColors[playerID]), (engine.statc[2] == 11));
receiver.drawMenuFont(engine, playerID, 0, 6, "MIN CHAIN", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 7, String.valueOf(rensaShibari[playerID]), (engine.statc[2] == 12));
receiver.drawMenuFont(engine, playerID, 0, 8, "OJAMA RATE", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 9, String.valueOf(ojamaRate[playerID]), (engine.statc[2] == 13));
receiver.drawMenuFont(engine, playerID, 0, 10, "BIG", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 11, GeneralUtil.getONorOFF(big[playerID]), (engine.statc[2] == 14));
receiver.drawMenuFont(engine, playerID, 0, 12, "SE", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 13, GeneralUtil.getONorOFF(enableSE[playerID]), (engine.statc[2] == 15));
receiver.drawMenuFont(engine, playerID, 0, 14, "HURRYUP", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 15, (hurryupSeconds[playerID] == 0) ? "NONE" : hurryupSeconds[playerID]+"SEC",
(engine.statc[2] == 16));
receiver.drawMenuFont(engine, playerID, 0, 16, "HARD OJAMA", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 17, String.valueOf(ojamaHard[playerID]), (engine.statc[2] == 17));
receiver.drawMenuFont(engine, playerID, 0, 18, "BGM", EventReceiver.COLOR_PINK);
receiver.drawMenuFont(engine, playerID, 1, 19, String.valueOf(bgmno), (engine.statc[2] == 18));
} else {
if(owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 19) * 2) + 1, "b",
(playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "USE MAP", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 1, GeneralUtil.getONorOFF(useMap[playerID]), (engine.statc[2] == 19));
receiver.drawMenuFont(engine, playerID, 0, 2, "MAP SET", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(mapSet[playerID]), (engine.statc[2] == 20));
receiver.drawMenuFont(engine, playerID, 0, 4, "MAP NO.", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 5, (mapNumber[playerID] < 0) ? "RANDOM" : mapNumber[playerID]+"/"+(mapMaxNo[playerID]-1),
(engine.statc[2] == 21));
receiver.drawMenuFont(engine, playerID, 0, 6, "FEVER", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 7, (feverThreshold[playerID] == 0) ? "NONE" : feverThreshold[playerID]+" PTS",
(engine.statc[2] == 22));
receiver.drawMenuFont(engine, playerID, 0, 8, "F-MIN TIME", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 9, feverTimeMin[playerID] + "SEC", (engine.statc[2] == 23));
receiver.drawMenuFont(engine, playerID, 0, 10, "F-MAX TIME", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 11, feverTimeMax[playerID] + "SEC", (engine.statc[2] == 24));
}
} else {
receiver.drawMenuFont(engine, playerID, 3, 10, "WAIT", EventReceiver.COLOR_YELLOW);
}
}
/*
* Readyの時の初期化処理(初期化前)
*/
@Override
public boolean onReady(GameEngine engine, int playerID) {
if(engine.statc[0] == 0) {
engine.numColors = numColors[playerID];
feverTime[playerID] = feverTimeMin[playerID] * 60;
// マップ読み込み・リプレイ保存用にバックアップ
if(useMap[playerID]) {
if(owner.replayMode) {
engine.createFieldIfNeeded();
loadMap(engine.field, owner.replayProp, playerID);
engine.field.setAllSkin(engine.getSkin());
} else {
if(propMap[playerID] == null) {
propMap[playerID] = receiver.loadProperties("config/map/vsbattle/" + mapSet[playerID] + ".map");
}
if(propMap[playerID] != null) {
engine.createFieldIfNeeded();
if(mapNumber[playerID] < 0) {
if((playerID == 1) && (useMap[0]) && (mapNumber[0] < 0)) {
engine.field.copy(owner.engine[0].field);
} else {
int no = (mapMaxNo[playerID] < 1) ? 0 : randMap.nextInt(mapMaxNo[playerID]);
loadMap(engine.field, propMap[playerID], no);
}
} else {
loadMap(engine.field, propMap[playerID], mapNumber[playerID]);
}
engine.field.setAllSkin(engine.getSkin());
fldBackup[playerID] = new Field(engine.field);
}
}
} else if(engine.field != null) {
engine.field.reset();
}
}
return false;
}
/*
* ゲーム開始時の処理
*/
@Override
public void startGame(GameEngine engine, int playerID) {
engine.b2bEnable = false;
engine.comboType = GameEngine.COMBO_TYPE_DISABLE;
engine.big = big[playerID];
engine.enableSE = enableSE[playerID];
if(playerID == 1) owner.bgmStatus.bgm = bgmno;
engine.colorClearSize = big[playerID] ? 12 : 4;
engine.tspinAllowKick = false;
engine.tspinEnable = false;
engine.useAllSpinBonus = false;
}
/*
* スコア表示
*/
@Override
public void renderLast(GameEngine engine, int playerID) {
// ステータス表示
if(playerID == 0) {
receiver.drawScoreFont(engine, playerID, -1, 0, "AVALANCHE VS", EventReceiver.COLOR_GREEN);
receiver.drawScoreFont(engine, playerID, -1, 2, "OJAMA", EventReceiver.COLOR_PURPLE);
String ojamaStr1P = String.valueOf(ojama[0]);
if (ojamaAdd[0] > 0 && !(inFever[0] && ojamaAddToFever[0]))
ojamaStr1P = ojamaStr1P + "(+" + String.valueOf(ojamaAdd[0]) + ")";
String ojamaStr2P = String.valueOf(ojama[1]);
if (ojamaAdd[1] > 0 && !(inFever[1] && ojamaAddToFever[1]))
ojamaStr2P = ojamaStr2P + "(+" + String.valueOf(ojamaAdd[1]) + ")";
receiver.drawScoreFont(engine, playerID, -1, 3, "1P:", EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, 3, 3, ojamaStr1P, (ojama[0] > 0));
receiver.drawScoreFont(engine, playerID, -1, 4, "2P:", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 3, 4, ojamaStr2P, (ojama[1] > 0));
receiver.drawScoreFont(engine, playerID, -1, 6, "ATTACK", EventReceiver.COLOR_GREEN);
receiver.drawScoreFont(engine, playerID, -1, 7, "1P: " + String.valueOf(ojamaSent[0]), EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, -1, 8, "2P: " + String.valueOf(ojamaSent[1]), EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, -1, 10, "SCORE", EventReceiver.COLOR_PURPLE);
receiver.drawScoreFont(engine, playerID, -1, 11, "1P: " + String.valueOf(score[0]), EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, -1, 12, "2P: " + String.valueOf(score[1]), EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, -1, 14, "TIME", EventReceiver.COLOR_GREEN);
receiver.drawScoreFont(engine, playerID, -1, 15, GeneralUtil.getTime(engine.statistics.time));
if (inFever[0] || inFever[1])
{
receiver.drawScoreFont(engine, playerID, -1, 17, "FEVER OJAMA", EventReceiver.COLOR_PURPLE);
String ojamaFeverStr1P = String.valueOf(ojamaFever[0]);
if (ojamaAdd[0] > 0 && inFever[0] && ojamaAddToFever[0])
ojamaFeverStr1P = ojamaFeverStr1P + "(+" + String.valueOf(ojamaAdd[0]) + ")";
String ojamaFeverStr2P = String.valueOf(ojamaFever[1]);
if (ojamaAdd[1] > 0 && inFever[1] && ojamaAddToFever[1])
ojamaFeverStr2P = ojamaFeverStr2P + "(+" + String.valueOf(ojamaAdd[1]) + ")";
receiver.drawScoreFont(engine, playerID, -1, 18, "1P:", EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, 3, 18, ojamaFeverStr1P, (ojamaFever[0] > 0));
receiver.drawScoreFont(engine, playerID, -1, 19, "2P:", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 3, 19, ojamaFeverStr2P, (ojamaFever[1] > 0));
}
}
if (!owner.engine[playerID].gameActive)
return;
int playerColor = (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE;
if (feverThreshold[playerID] > 0)
{
receiver.drawMenuFont(engine, playerID, 0, 17, "FEVER POINT", playerColor);
receiver.drawMenuFont(engine, playerID, 0, 18, feverPoints[playerID] + " / " + feverThreshold[playerID], inFever[playerID]);
receiver.drawMenuFont(engine, playerID, 0, 19, "FEVER TIME", playerColor);
receiver.drawMenuFont(engine, playerID, 0, 20, GeneralUtil.getTime(feverTime[playerID]), inFever[playerID]);
}
if(zenKeshi[playerID])
receiver.drawMenuFont(engine, playerID, 1, 21, "ZENKESHI!", EventReceiver.COLOR_YELLOW);
if (ojamaHard[playerID] > 0 && engine.field != null)
for (int x = 0; x < engine.field.getWidth(); x++)
for (int y = 0; y < engine.field.getHeight(); y++)
{
int hard = engine.field.getBlock(x, y).hard;
if (hard > 0)
receiver.drawMenuFont(engine, playerID, x, y, String.valueOf(hard), EventReceiver.COLOR_YELLOW);
}
}
/*
* スコア計算
*/
@Override
public void calcScore(GameEngine engine, int playerID, int avalanche) {
int enemyID = 0;
if(playerID == 0) enemyID = 1;
if (big[playerID])
avalanche >>= 2;
// ラインクリアボーナス
int pts = avalanche*10;
int ojamaNew = 0;
if (avalanche > 0) {
cleared[playerID] = true;
if (zenKeshi[playerID])
ojamaNew += 30;
if (engine.field.isEmpty()) {
engine.playSE("bravo");
zenKeshi[playerID] = true;
engine.statistics.score += 2100;
}
else
zenKeshi[playerID] = false;
int chain = engine.chain;
engine.playSE("combo" + Math.min(chain, 20));
if (chain == 1)
ojamaAddToFever[enemyID] = inFever[enemyID];
int multiplier = engine.field.colorClearExtraCount;
if (big[playerID])
multiplier >>= 2;
if (engine.field.colorsCleared > 1)
multiplier += (engine.field.colorsCleared-1)*2;
/*
if (multiplier < 0)
multiplier = 0;
if (chain == 0)
firstExtra = avalanche > engine.colorClearSize;
*/
if (chain == 2)
multiplier += 8;
else if (chain == 3)
multiplier += 16;
else if (chain >= 4)
multiplier += 32*(chain-3);
/*
if (firstExtra)
multiplier++;
*/
if (multiplier > 999)
multiplier = 999;
if (multiplier < 1)
multiplier = 1;
lastscore[playerID] = pts;
lastmultiplier[playerID] = multiplier;
scgettime[playerID] = 120;
int ptsTotal = pts*multiplier;
score[playerID] += ptsTotal;
if (hurryupSeconds[playerID] > 0 && engine.statistics.time > hurryupSeconds[playerID])
ptsTotal <<= engine.statistics.time / (hurryupSeconds[playerID] * 60);
ojamaNew += (ptsTotal+ojamaRate[playerID]-1)/ojamaRate[playerID];
if (chain >= rensaShibari[playerID])
{
ojamaSent[playerID] += ojamaNew;
if (ojamaCounterMode[playerID] != OJAMA_COUNTER_OFF)
{
boolean countered = false;
if (inFever[playerID])
{
if (ojamaFever[playerID] > 0 && ojamaNew > 0)
{
int delta = Math.min(ojamaFever[playerID], ojamaNew);
ojamaFever[playerID] -= delta;
ojamaNew -= delta;
countered = true;
}
if (ojamaAdd[playerID] > 0 && ojamaNew > 0)
{
int delta = Math.min(ojamaAdd[playerID], ojamaNew);
ojamaAdd[playerID] -= delta;
ojamaNew -= delta;
countered = true;
}
}
if (ojama[playerID] > 0 && ojamaNew > 0)
{
int delta = Math.min(ojama[playerID], ojamaNew);
ojama[playerID] -= delta;
ojamaNew -= delta;
countered = true;
}
if (ojamaAdd[playerID] > 0 && ojamaNew > 0)
{
int delta = Math.min(ojamaAdd[playerID], ojamaNew);
ojamaAdd[playerID] -= delta;
ojamaNew -= delta;
countered = true;
}
if (countered)
{
if (feverThreshold[playerID] > 0 && feverThreshold[playerID] > feverPoints[playerID])
feverPoints[playerID]++;
if (feverThreshold[enemyID] > 0)
feverTime[enemyID] = Math.min(feverTime[enemyID]+60,feverTimeMax[enemyID]*60);
}
}
if (ojamaNew > 0)
ojamaAdd[enemyID] += ojamaNew;
}
}
else if (!engine.field.canCascade())
cleared[playerID] = false;
}
public boolean lineClearEnd(GameEngine engine, int playerID) {
int enemyID = 0;
if(playerID == 0) enemyID = 1;
if (ojamaAdd[enemyID] > 0)
{
if (ojamaAddToFever[enemyID] && inFever[enemyID])
ojamaFever[enemyID] += ojamaAdd[enemyID];
else
ojama[enemyID] += ojamaAdd[enemyID];
ojamaAdd[enemyID] = 0;
}
checkFeverEnd(engine, playerID);
int ojamaNow = inFever[playerID] ? ojamaFever[playerID] : ojama[playerID];
if (ojamaNow > 0 && !ojamaDrop[playerID] &&
(!cleared[playerID] || ojamaCounterMode[playerID] != OJAMA_COUNTER_FEVER))
{
ojamaDrop[playerID] = true;
int drop = Math.min(ojamaNow, maxAttack[playerID]);
if (inFever[playerID])
ojamaFever[playerID] -= drop;
else
ojama[playerID] -= drop;
engine.field.garbageDrop(engine, drop, big[playerID], ojamaHard[playerID]);
return true;
}
checkFeverStart(engine, playerID);
return false;
}
private void checkFeverStart(GameEngine engine, int playerID)
{
if (!inFever[playerID] && feverPoints[playerID] == feverThreshold[playerID])
{
inFever[playerID] = true;
feverBackupField[playerID] = engine.field;
engine.field = null;
engine.createFieldIfNeeded();
//TODO: Add preset chain.
}
}
private void checkFeverEnd(GameEngine engine, int playerID)
{
if (inFever[playerID] && feverTime[playerID] == 0)
{
inFever[playerID] = false;
feverTime[playerID] = feverTimeMin[playerID] * 60;
feverPoints[playerID] = 0;
engine.field = feverBackupField[playerID];
ojama[playerID] += ojamaFever[playerID];
ojamaFever[playerID] = 0;
ojamaAddToFever[playerID] = false;
}
}
/*
* 各フレームの最後の処理
*/
@Override
public void onLast(GameEngine engine, int playerID) {
scgettime[playerID]++;
if (inFever[playerID] && feverTime[playerID] > 0)
{
if (feverTime[playerID] == 1)
engine.playSE("levelstop");
feverTime[playerID]--;
}
if (engine.stat == GameEngine.STAT_MOVE)
ojamaDrop[playerID] = false;
int width = 1;
if (engine.field != null)
width = engine.field.getWidth();
int blockHeight = receiver.getBlockGraphicsHeight(engine, playerID);
// せり上がりメーター
if(ojama[playerID] * blockHeight / width > engine.meterValue) {
engine.meterValue++;
} else if(ojama[playerID] * blockHeight / width < engine.meterValue) {
engine.meterValue--;
}
if(ojama[playerID] >= 5*width) engine.meterColor = GameEngine.METER_COLOR_RED;
else if(ojama[playerID] >= width) engine.meterColor = GameEngine.METER_COLOR_ORANGE;
else if(ojama[playerID] >= 1) engine.meterColor = GameEngine.METER_COLOR_YELLOW;
else engine.meterColor = GameEngine.METER_COLOR_GREEN;
// 決着
if((playerID == 1) && (owner.engine[0].gameActive)) {
if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) {
// 引き分け
winnerID = -1;
owner.engine[0].gameActive = false;
owner.engine[1].gameActive = false;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
} else if((owner.engine[0].stat != GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) {
// 1P勝利
winnerID = 0;
owner.engine[0].gameActive = false;
owner.engine[1].gameActive = false;
owner.engine[0].stat = GameEngine.STAT_EXCELLENT;
owner.engine[0].resetStatc();
owner.engine[0].statc[1] = 1;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
} else if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat != GameEngine.STAT_GAMEOVER)) {
// 2P勝利
winnerID = 1;
owner.engine[0].gameActive = false;
owner.engine[1].gameActive = false;
owner.engine[1].stat = GameEngine.STAT_EXCELLENT;
owner.engine[1].resetStatc();
owner.engine[1].statc[1] = 1;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
}
}
}
/*
* 結果画面の描画
*/
@Override
public void renderResult(GameEngine engine, int playerID) {
receiver.drawMenuFont(engine, playerID, 0, 1, "RESULT", EventReceiver.COLOR_ORANGE);
if(winnerID == -1) {
receiver.drawMenuFont(engine, playerID, 6, 2, "DRAW", EventReceiver.COLOR_GREEN);
} else if(winnerID == playerID) {
receiver.drawMenuFont(engine, playerID, 6, 2, "WIN!", EventReceiver.COLOR_YELLOW);
} else {
receiver.drawMenuFont(engine, playerID, 6, 2, "LOSE", EventReceiver.COLOR_WHITE);
}
receiver.drawMenuFont(engine, playerID, 0, 3, "ATTACK", EventReceiver.COLOR_ORANGE);
String strScore = String.format("%10d", ojamaSent[playerID]);
receiver.drawMenuFont(engine, playerID, 0, 4, strScore);
receiver.drawMenuFont(engine, playerID, 0, 5, "LINE", EventReceiver.COLOR_ORANGE);
String strLines = String.format("%10d", engine.statistics.lines);
receiver.drawMenuFont(engine, playerID, 0, 6, strLines);
receiver.drawMenuFont(engine, playerID, 0, 7, "PIECE", EventReceiver.COLOR_ORANGE);
String strPiece = String.format("%10d", engine.statistics.totalPieceLocked);
receiver.drawMenuFont(engine, playerID, 0, 8, strPiece);
receiver.drawMenuFont(engine, playerID, 0, 9, "ATTACK/MIN", EventReceiver.COLOR_ORANGE);
float apm = (float)(ojamaSent[playerID] * 3600) / (float)(engine.statistics.time);
String strAPM = String.format("%10g", apm);
receiver.drawMenuFont(engine, playerID, 0, 10, strAPM);
receiver.drawMenuFont(engine, playerID, 0, 11, "LINE/MIN", EventReceiver.COLOR_ORANGE);
String strLPM = String.format("%10g", engine.statistics.lpm);
receiver.drawMenuFont(engine, playerID, 0, 12, strLPM);
receiver.drawMenuFont(engine, playerID, 0, 13, "PIECE/SEC", EventReceiver.COLOR_ORANGE);
String strPPS = String.format("%10g", engine.statistics.pps);
receiver.drawMenuFont(engine, playerID, 0, 14, strPPS);
receiver.drawMenuFont(engine, playerID, 0, 15, "TIME", EventReceiver.COLOR_ORANGE);
String strTime = String.format("%10s", GeneralUtil.getTime(owner.engine[0].statistics.time));
receiver.drawMenuFont(engine, playerID, 0, 16, strTime);
}
/*
* リプレイ保存時の処理
*/
@Override
public void saveReplay(GameEngine engine, int playerID, CustomProperties prop) {
saveOtherSetting(engine, owner.replayProp);
savePreset(engine, owner.replayProp, -1 - playerID);
if(useMap[playerID] && (fldBackup[playerID] != null)) {
saveMap(fldBackup[playerID], owner.replayProp, playerID);
}
owner.replayProp.setProperty("avalanchevs.version", version);
}
}
| src/org/game_host/hebo/nullpomino/game/subsystem/mode/AvalancheVSMode.java | /*
Copyright (c) 2010, NullNoname
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 NullNoname nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.game_host.hebo.nullpomino.game.subsystem.mode;
import java.util.Random;
import org.game_host.hebo.nullpomino.game.component.BGMStatus;
import org.game_host.hebo.nullpomino.game.component.Block;
import org.game_host.hebo.nullpomino.game.component.Controller;
import org.game_host.hebo.nullpomino.game.component.Field;
import org.game_host.hebo.nullpomino.game.component.Piece;
import org.game_host.hebo.nullpomino.game.event.EventReceiver;
import org.game_host.hebo.nullpomino.game.play.GameEngine;
import org.game_host.hebo.nullpomino.game.play.GameManager;
import org.game_host.hebo.nullpomino.util.CustomProperties;
import org.game_host.hebo.nullpomino.util.GeneralUtil;
/**
* AVALANCHE VS-BATTLE mode (beta)
*/
public class AvalancheVSMode extends DummyMode {
/** 現在のバージョン */
private static final int CURRENT_VERSION = 0;
/** Enabled piece types */
private static final int[] PIECE_ENABLE = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0};
/** Block colors */
private static final int[] BLOCK_COLORS =
{
Block.BLOCK_COLOR_RED,
Block.BLOCK_COLOR_GREEN,
Block.BLOCK_COLOR_BLUE,
Block.BLOCK_COLOR_YELLOW,
Block.BLOCK_COLOR_PURPLE
};
/** プレイヤーの数 */
private static final int MAX_PLAYERS = 2;
/** Names of garbage counter setting constants */
private final int GARBAGE_COUNTER_OFF = 0, GARBAGE_COUNTER_ON = 1, GARBAGE_COUNTER_FEVER = 2;
/** 邪魔ブロックタイプの表示名 */
//private final String[] GARBAGE_TYPE_STRING = {"NORMAL", "ONE RISE", "1-ATTACK"};
/** Names of garbage counter settings */
private final String[] GARBAGE_COUNTER_STRING = {"OFF", "ON", "FEVER"};
/** 各プレイヤーの枠の色 */
private final int[] PLAYER_COLOR_FRAME = {GameEngine.FRAME_COLOR_RED, GameEngine.FRAME_COLOR_BLUE};
/** このモードを所有するGameManager */
private GameManager owner;
/** 描画などのイベント処理 */
private EventReceiver receiver;
/** Rule settings for countering garbage not yet dropped */
private int[] garbageCounterMode;
/** 溜まっている邪魔ブロックの数 */
private int[] garbage;
/** 送った邪魔ブロックの数 */
private int[] garbageSent;
/** 最後にスコア獲得してから経過した時間 */
private int[] scgettime;
/** 使用するBGM */
private int bgmno;
/** ビッグ */
private boolean[] big;
/** 効果音ON/OFF */
private boolean[] enableSE;
/** マップ使用フラグ */
private boolean[] useMap;
/** 使用するマップセット番号 */
private int[] mapSet;
/** マップ番号(-1でランダム) */
private int[] mapNumber;
/** 最後に使ったプリセット番号 */
private int[] presetNumber;
/** 勝者 */
private int winnerID;
/** マップセットのプロパティファイル */
private CustomProperties[] propMap;
/** 最大マップ番号 */
private int[] mapMaxNo;
/** バックアップ用フィールド(マップをリプレイに保存するときに使用) */
private Field[] fldBackup;
/** マップ選択用乱数 */
private Random randMap;
/** バージョン */
private int version;
/** Flag for all clear */
private boolean[] zenKeshi;
/** Amount of points earned from most recent clear */
private int[] lastscore, lastmultiplier;
/** Amount of garbage added in current chain */
private int[] garbageAdd;
/** Score */
private int[] score;
/** Max amount of garbage dropped at once */
private int[] maxAttack;
/** Number of colors to use */
private int[] numColors;
/** Minimum chain count needed to send garbage */
private int[] rensaShibari;
/** Denominator for score-to-garbage conversion */
private int[] garbageRate;
/** Settings for hard garbage blocks */
private int[] garbageHard;
/** Hurryup開始までの秒数(0でHurryupなし) */
private int[] hurryupSeconds;
/*
* モード名
*/
@Override
public String getName() {
return "AVALANCHE VS-BATTLE (BETA)";
}
/*
* プレイヤー数
*/
@Override
public int getPlayers() {
return MAX_PLAYERS;
}
/*
* モードの初期化
*/
@Override
public void modeInit(GameManager manager) {
owner = manager;
receiver = owner.receiver;
garbageCounterMode = new int[MAX_PLAYERS];
garbage = new int[MAX_PLAYERS];
garbageSent = new int[MAX_PLAYERS];
scgettime = new int[MAX_PLAYERS];
bgmno = 0;
big = new boolean[MAX_PLAYERS];
enableSE = new boolean[MAX_PLAYERS];
hurryupSeconds = new int[MAX_PLAYERS];
useMap = new boolean[MAX_PLAYERS];
mapSet = new int[MAX_PLAYERS];
mapNumber = new int[MAX_PLAYERS];
presetNumber = new int[MAX_PLAYERS];
propMap = new CustomProperties[MAX_PLAYERS];
mapMaxNo = new int[MAX_PLAYERS];
fldBackup = new Field[MAX_PLAYERS];
randMap = new Random();
zenKeshi = new boolean[MAX_PLAYERS];
lastscore = new int[MAX_PLAYERS];
lastmultiplier = new int[MAX_PLAYERS];
garbageAdd = new int[MAX_PLAYERS];
score = new int[MAX_PLAYERS];
numColors = new int[MAX_PLAYERS];
maxAttack = new int[MAX_PLAYERS];
rensaShibari = new int[MAX_PLAYERS];
garbageRate = new int[MAX_PLAYERS];
garbageHard = new int[MAX_PLAYERS];
winnerID = -1;
}
/**
* スピードプリセットを読み込み
* @param engine GameEngine
* @param prop 読み込み元のプロパティファイル
* @param preset プリセット番号
*/
private void loadPreset(GameEngine engine, CustomProperties prop, int preset) {
engine.speed.gravity = prop.getProperty("avalanchevs.gravity." + preset, 4);
engine.speed.denominator = prop.getProperty("avalanchevs.denominator." + preset, 256);
engine.speed.are = prop.getProperty("avalanchevs.are." + preset, 24);
engine.speed.areLine = prop.getProperty("avalanchevs.areLine." + preset, 24);
engine.speed.lineDelay = prop.getProperty("avalanchevs.lineDelay." + preset, 10);
engine.speed.lockDelay = prop.getProperty("avalanchevs.lockDelay." + preset, 30);
engine.speed.das = prop.getProperty("avalanchevs.das." + preset, 14);
}
/**
* スピードプリセットを保存
* @param engine GameEngine
* @param prop 保存先のプロパティファイル
* @param preset プリセット番号
*/
private void savePreset(GameEngine engine, CustomProperties prop, int preset) {
prop.setProperty("avalanchevs.gravity." + preset, engine.speed.gravity);
prop.setProperty("avalanchevs.denominator." + preset, engine.speed.denominator);
prop.setProperty("avalanchevs.are." + preset, engine.speed.are);
prop.setProperty("avalanchevs.areLine." + preset, engine.speed.areLine);
prop.setProperty("avalanchevs.lineDelay." + preset, engine.speed.lineDelay);
prop.setProperty("avalanchevs.lockDelay." + preset, engine.speed.lockDelay);
prop.setProperty("avalanchevs.das." + preset, engine.speed.das);
}
/**
* スピード以外の設定を読み込み
* @param engine GameEngine
* @param prop 読み込み元のプロパティファイル
*/
private void loadOtherSetting(GameEngine engine, CustomProperties prop) {
int playerID = engine.playerID;
bgmno = prop.getProperty("avalanchevs.bgmno", 0);
garbageCounterMode[playerID] = prop.getProperty("avalanchevs.garbageCounterMode", GARBAGE_COUNTER_ON);
big[playerID] = prop.getProperty("avalanchevs.big.p" + playerID, false);
enableSE[playerID] = prop.getProperty("avalanchevs.enableSE.p" + playerID, true);
hurryupSeconds[playerID] = prop.getProperty("vsbattle.hurryupSeconds.p" + playerID, 192);
useMap[playerID] = prop.getProperty("avalanchevs.useMap.p" + playerID, false);
mapSet[playerID] = prop.getProperty("avalanchevs.mapSet.p" + playerID, 0);
mapNumber[playerID] = prop.getProperty("avalanchevs.mapNumber.p" + playerID, -1);
presetNumber[playerID] = prop.getProperty("avalanchevs.presetNumber.p" + playerID, 0);
maxAttack[playerID] = prop.getProperty("avalanchevs.maxAttack.p" + playerID, 30);
numColors[playerID] = prop.getProperty("avalanchevs.numColors.p" + playerID, 5);
rensaShibari[playerID] = prop.getProperty("avalanchevs.rensaShibari.p" + playerID, 1);
garbageRate[playerID] = prop.getProperty("avalanchevs.garbageRate.p" + playerID, 120);
garbageHard[playerID] = prop.getProperty("avalanchevs.garbageHard.p" + playerID, 0);
}
/**
* スピード以外の設定を保存
* @param engine GameEngine
* @param prop 保存先のプロパティファイル
*/
private void saveOtherSetting(GameEngine engine, CustomProperties prop) {
int playerID = engine.playerID;
prop.setProperty("avalanchevs.bgmno", bgmno);
prop.setProperty("avalanchevs.garbageCounterMode", garbageCounterMode[playerID]);
prop.setProperty("avalanchevs.big.p" + playerID, big[playerID]);
prop.setProperty("avalanchevs.enableSE.p" + playerID, enableSE[playerID]);
prop.setProperty("vsbattle.hurryupSeconds.p" + playerID, hurryupSeconds[playerID]);
prop.setProperty("avalanchevs.useMap.p" + playerID, useMap[playerID]);
prop.setProperty("avalanchevs.mapSet.p" + playerID, mapSet[playerID]);
prop.setProperty("avalanchevs.mapNumber.p" + playerID, mapNumber[playerID]);
prop.setProperty("avalanchevs.presetNumber.p" + playerID, presetNumber[playerID]);
prop.setProperty("avalanchevs.maxAttack.p" + playerID, maxAttack[playerID]);
prop.setProperty("avalanchevs.numColors.p" + playerID, numColors[playerID]);
prop.setProperty("avalanchevs.rensaShibari.p" + playerID, rensaShibari[playerID]);
prop.setProperty("avalanchevs.garbageRate.p" + playerID, garbageRate[playerID]);
prop.setProperty("avalanchevs.garbageHard.p" + playerID, garbageHard[playerID]);
}
/**
* マップ読み込み
* @param field フィールド
* @param prop 読み込み元のプロパティファイル
* @param preset 任意のID
*/
private void loadMap(Field field, CustomProperties prop, int id) {
field.reset();
//field.readProperty(prop, id);
field.stringToField(prop.getProperty("map." + id, ""));
field.setAllAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true);
field.setAllAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true);
field.setAllAttribute(Block.BLOCK_ATTRIBUTE_SELFPLACED, false);
}
/**
* マップ保存
* @param field フィールド
* @param prop 保存先のプロパティファイル
* @param id 任意のID
*/
private void saveMap(Field field, CustomProperties prop, int id) {
//field.writeProperty(prop, id);
prop.setProperty("map." + id, field.fieldToString());
}
/**
* プレビュー用にマップを読み込み
* @param engine GameEngine
* @param playerID プレイヤー番号
* @param id マップID
* @param forceReload trueにするとマップファイルを強制再読み込み
*/
private void loadMapPreview(GameEngine engine, int playerID, int id, boolean forceReload) {
if((propMap[playerID] == null) || (forceReload)) {
mapMaxNo[playerID] = 0;
propMap[playerID] = receiver.loadProperties("config/map/vsbattle/" + mapSet[playerID] + ".map");
}
if((propMap[playerID] == null) && (engine.field != null)) {
engine.field.reset();
} else if(propMap[playerID] != null) {
mapMaxNo[playerID] = propMap[playerID].getProperty("map.maxMapNumber", 0);
engine.createFieldIfNeeded();
loadMap(engine.field, propMap[playerID], id);
engine.field.setAllSkin(engine.getSkin());
}
}
/*
* 各プレイヤーの初期化
*/
@Override
public void playerInit(GameEngine engine, int playerID) {
if(playerID == 1) {
engine.randSeed = owner.engine[0].randSeed;
engine.random = new Random(owner.engine[0].randSeed);
}
engine.framecolor = PLAYER_COLOR_FRAME[playerID];
engine.clearMode = GameEngine.CLEAR_COLOR;
engine.garbageColorClear = true;
engine.lineGravityType = GameEngine.LINE_GRAVITY_CASCADE;
for(int i = 0; i < Piece.PIECE_COUNT; i++)
engine.nextPieceEnable[i] = (PIECE_ENABLE[i] == 1);
engine.blockColors = BLOCK_COLORS;
engine.randomBlockColor = true;
engine.connectBlocks = false;
garbage[playerID] = 0;
garbageSent[playerID] = 0;
score[playerID] = 0;
zenKeshi[playerID] = false;
scgettime[playerID] = 0;
if(engine.owner.replayMode == false) {
loadOtherSetting(engine, engine.owner.modeConfig);
loadPreset(engine, engine.owner.modeConfig, -1 - playerID);
version = CURRENT_VERSION;
} else {
loadOtherSetting(engine, engine.owner.replayProp);
loadPreset(engine, engine.owner.replayProp, -1 - playerID);
version = owner.replayProp.getProperty("avalanchevs.version", 0);
}
}
/*
* 設定画面の処理
*/
@Override
public boolean onSetting(GameEngine engine, int playerID) {
// メニュー
if((engine.owner.replayMode == false) && (engine.statc[4] == 0)) {
// 上
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_UP)) {
engine.statc[2]--;
if(engine.statc[2] < 0) engine.statc[2] = 21;
engine.playSE("cursor");
}
// 下
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN)) {
engine.statc[2]++;
if(engine.statc[2] > 21) engine.statc[2] = 0;
engine.playSE("cursor");
}
// 設定変更
int change = 0;
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT)) change = -1;
if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) change = 1;
if(change != 0) {
engine.playSE("change");
int m = 1;
if(engine.ctrl.isPress(Controller.BUTTON_E)) m = 100;
if(engine.ctrl.isPress(Controller.BUTTON_F)) m = 1000;
switch(engine.statc[2]) {
case 0:
engine.speed.gravity += change * m;
if(engine.speed.gravity < -1) engine.speed.gravity = 99999;
if(engine.speed.gravity > 99999) engine.speed.gravity = -1;
break;
case 1:
engine.speed.denominator += change * m;
if(engine.speed.denominator < -1) engine.speed.denominator = 99999;
if(engine.speed.denominator > 99999) engine.speed.denominator = -1;
break;
case 2:
engine.speed.are += change;
if(engine.speed.are < 0) engine.speed.are = 99;
if(engine.speed.are > 99) engine.speed.are = 0;
break;
case 3:
engine.speed.areLine += change;
if(engine.speed.areLine < 0) engine.speed.areLine = 99;
if(engine.speed.areLine > 99) engine.speed.areLine = 0;
break;
case 4:
engine.speed.lineDelay += change;
if(engine.speed.lineDelay < 0) engine.speed.lineDelay = 99;
if(engine.speed.lineDelay > 99) engine.speed.lineDelay = 0;
break;
case 5:
engine.speed.lockDelay += change;
if(engine.speed.lockDelay < 0) engine.speed.lockDelay = 99;
if(engine.speed.lockDelay > 99) engine.speed.lockDelay = 0;
break;
case 6:
engine.speed.das += change;
if(engine.speed.das < 0) engine.speed.das = 99;
if(engine.speed.das > 99) engine.speed.das = 0;
break;
case 7:
case 8:
presetNumber[playerID] += change;
if(presetNumber[playerID] < 0) presetNumber[playerID] = 99;
if(presetNumber[playerID] > 99) presetNumber[playerID] = 0;
break;
case 9:
garbageCounterMode[playerID] += change;
if(garbageCounterMode[playerID] < 0) garbageCounterMode[playerID] = 2;
if(garbageCounterMode[playerID] > 2) garbageCounterMode[playerID] = 0;
break;
case 10:
maxAttack[playerID] += change;
if(maxAttack[playerID] < 0) maxAttack[playerID] = 99;
if(maxAttack[playerID] > 99) maxAttack[playerID] = 0;
break;
case 11:
numColors[playerID] += change;
if(numColors[playerID] < 3) numColors[playerID] = 5;
if(numColors[playerID] > 5) numColors[playerID] = 3;
break;
case 12:
rensaShibari[playerID] += change;
if(rensaShibari[playerID] < 1) rensaShibari[playerID] = 20;
if(rensaShibari[playerID] > 20) rensaShibari[playerID] = 1;
break;
case 13:
garbageRate[playerID] += change*10;
if(garbageRate[playerID] < 10) garbageRate[playerID] = 1000;
if(garbageRate[playerID] > 1000) garbageRate[playerID] = 10;
break;
case 14:
big[playerID] = !big[playerID];
break;
case 15:
enableSE[playerID] = !enableSE[playerID];
break;
case 16:
hurryupSeconds[playerID] += change;
if(hurryupSeconds[playerID] < 0) hurryupSeconds[playerID] = 300;
if(hurryupSeconds[playerID] > 300) hurryupSeconds[playerID] = 0;
break;
case 17:
garbageHard[playerID] += change;
if(garbageHard[playerID] < 0) garbageHard[playerID] = 9;
if(garbageHard[playerID] > 9) garbageHard[playerID] = 0;
break;
case 18:
bgmno += change;
if(bgmno < 0) bgmno = BGMStatus.BGM_COUNT - 1;
if(bgmno > BGMStatus.BGM_COUNT - 1) bgmno = 0;
break;
case 19:
useMap[playerID] = !useMap[playerID];
if(!useMap[playerID]) {
if(engine.field != null) engine.field.reset();
} else {
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
}
break;
case 20:
mapSet[playerID] += change;
if(mapSet[playerID] < 0) mapSet[playerID] = 99;
if(mapSet[playerID] > 99) mapSet[playerID] = 0;
if(useMap[playerID]) {
mapNumber[playerID] = -1;
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
}
break;
case 21:
if(useMap[playerID]) {
mapNumber[playerID] += change;
if(mapNumber[playerID] < -1) mapNumber[playerID] = mapMaxNo[playerID] - 1;
if(mapNumber[playerID] > mapMaxNo[playerID] - 1) mapNumber[playerID] = -1;
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
} else {
mapNumber[playerID] = -1;
}
break;
}
}
// 決定
if(engine.ctrl.isPush(Controller.BUTTON_A) && (engine.statc[3] >= 5)) {
engine.playSE("decide");
if(engine.statc[2] == 7) {
loadPreset(engine, owner.modeConfig, presetNumber[playerID]);
} else if(engine.statc[2] == 8) {
savePreset(engine, owner.modeConfig, presetNumber[playerID]);
receiver.saveModeConfig(owner.modeConfig);
} else {
saveOtherSetting(engine, owner.modeConfig);
savePreset(engine, owner.modeConfig, -1 - playerID);
receiver.saveModeConfig(owner.modeConfig);
engine.statc[4] = 1;
}
}
// キャンセル
if(engine.ctrl.isPush(Controller.BUTTON_B)) {
engine.quitflag = true;
}
// プレビュー用マップ読み込み
if(useMap[playerID] && (engine.statc[3] == 0)) {
loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true);
}
// ランダムマッププレビュー
if(useMap[playerID] && (propMap[playerID] != null) && (mapNumber[playerID] < 0)) {
if(engine.statc[3] % 30 == 0) {
engine.statc[5]++;
if(engine.statc[5] >= mapMaxNo[playerID]) engine.statc[5] = 0;
loadMapPreview(engine, playerID, engine.statc[5], false);
}
}
engine.statc[3]++;
} else if(engine.statc[4] == 0) {
engine.statc[3]++;
engine.statc[2] = 0;
if(engine.statc[3] >= 60) {
engine.statc[2] = 9;
}
if(engine.statc[3] >= 120) {
engine.statc[4] = 1;
}
} else {
// 開始
if((owner.engine[0].statc[4] == 1) && (owner.engine[1].statc[4] == 1) && (playerID == 1)) {
owner.engine[0].stat = GameEngine.STAT_READY;
owner.engine[1].stat = GameEngine.STAT_READY;
owner.engine[0].resetStatc();
owner.engine[1].resetStatc();
}
// キャンセル
else if(engine.ctrl.isPush(Controller.BUTTON_B)) {
engine.statc[4] = 0;
}
}
return true;
}
/*
* 設定画面の描画
*/
@Override
public void renderSetting(GameEngine engine, int playerID) {
if(engine.statc[4] == 0) {
if(engine.statc[2] < 9) {
if(owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, (engine.statc[2] * 2) + 1, "b",
(playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "GRAVITY", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 1, String.valueOf(engine.speed.gravity), (engine.statc[2] == 0));
receiver.drawMenuFont(engine, playerID, 0, 2, "G-MAX", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(engine.speed.denominator), (engine.statc[2] == 1));
receiver.drawMenuFont(engine, playerID, 0, 4, "ARE", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(engine.speed.are), (engine.statc[2] == 2));
receiver.drawMenuFont(engine, playerID, 0, 6, "ARE LINE", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 7, String.valueOf(engine.speed.areLine), (engine.statc[2] == 3));
receiver.drawMenuFont(engine, playerID, 0, 8, "LINE DELAY", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 9, String.valueOf(engine.speed.lineDelay), (engine.statc[2] == 4));
receiver.drawMenuFont(engine, playerID, 0, 10, "LOCK DELAY", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 11, String.valueOf(engine.speed.lockDelay), (engine.statc[2] == 5));
receiver.drawMenuFont(engine, playerID, 0, 12, "DAS", EventReceiver.COLOR_ORANGE);
receiver.drawMenuFont(engine, playerID, 1, 13, String.valueOf(engine.speed.das), (engine.statc[2] == 6));
receiver.drawMenuFont(engine, playerID, 0, 14, "LOAD", EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 1, 15, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 7));
receiver.drawMenuFont(engine, playerID, 0, 16, "SAVE", EventReceiver.COLOR_GREEN);
receiver.drawMenuFont(engine, playerID, 1, 17, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 8));
} else if(engine.statc[2] < 19) {
if(owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 9) * 2) + 1, "b",
(playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "COUNTER", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 1, GARBAGE_COUNTER_STRING[garbageCounterMode[playerID]], (engine.statc[2] == 9));
receiver.drawMenuFont(engine, playerID, 0, 2, "MAX ATTACK", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(maxAttack[playerID]), (engine.statc[2] == 10));
receiver.drawMenuFont(engine, playerID, 0, 4, "COLORS", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(numColors[playerID]), (engine.statc[2] == 11));
receiver.drawMenuFont(engine, playerID, 0, 6, "MIN CHAIN", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 7, String.valueOf(rensaShibari[playerID]), (engine.statc[2] == 12));
receiver.drawMenuFont(engine, playerID, 0, 8, "OJAMA RATE", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 9, String.valueOf(garbageRate[playerID]), (engine.statc[2] == 13));
receiver.drawMenuFont(engine, playerID, 0, 10, "BIG", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 11, GeneralUtil.getONorOFF(big[playerID]), (engine.statc[2] == 14));
receiver.drawMenuFont(engine, playerID, 0, 12, "SE", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 13, GeneralUtil.getONorOFF(enableSE[playerID]), (engine.statc[2] == 15));
receiver.drawMenuFont(engine, playerID, 0, 14, "HURRYUP", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 15, (hurryupSeconds[playerID] == 0) ? "NONE" : hurryupSeconds[playerID]+"SEC",
(engine.statc[2] == 16));
receiver.drawMenuFont(engine, playerID, 0, 16, "HARD OJAMA", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 17, String.valueOf(garbageHard[playerID]), (engine.statc[2] == 17));
receiver.drawMenuFont(engine, playerID, 0, 18, "BGM", EventReceiver.COLOR_PINK);
receiver.drawMenuFont(engine, playerID, 1, 19, String.valueOf(bgmno), (engine.statc[2] == 18));
} else {
if(owner.replayMode == false) {
receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 19) * 2) + 1, "b",
(playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE);
}
receiver.drawMenuFont(engine, playerID, 0, 0, "USE MAP", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 1, GeneralUtil.getONorOFF(useMap[playerID]), (engine.statc[2] == 19));
receiver.drawMenuFont(engine, playerID, 0, 2, "MAP SET", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(mapSet[playerID]), (engine.statc[2] == 20));
receiver.drawMenuFont(engine, playerID, 0, 4, "MAP NO.", EventReceiver.COLOR_CYAN);
receiver.drawMenuFont(engine, playerID, 1, 5, (mapNumber[playerID] < 0) ? "RANDOM" : mapNumber[playerID]+"/"+(mapMaxNo[playerID]-1),
(engine.statc[2] == 21));
}
} else {
receiver.drawMenuFont(engine, playerID, 3, 10, "WAIT", EventReceiver.COLOR_YELLOW);
}
}
/*
* Readyの時の初期化処理(初期化前)
*/
@Override
public boolean onReady(GameEngine engine, int playerID) {
if(engine.statc[0] == 0) {
engine.numColors = numColors[playerID];
// マップ読み込み・リプレイ保存用にバックアップ
if(useMap[playerID]) {
if(owner.replayMode) {
engine.createFieldIfNeeded();
loadMap(engine.field, owner.replayProp, playerID);
engine.field.setAllSkin(engine.getSkin());
} else {
if(propMap[playerID] == null) {
propMap[playerID] = receiver.loadProperties("config/map/vsbattle/" + mapSet[playerID] + ".map");
}
if(propMap[playerID] != null) {
engine.createFieldIfNeeded();
if(mapNumber[playerID] < 0) {
if((playerID == 1) && (useMap[0]) && (mapNumber[0] < 0)) {
engine.field.copy(owner.engine[0].field);
} else {
int no = (mapMaxNo[playerID] < 1) ? 0 : randMap.nextInt(mapMaxNo[playerID]);
loadMap(engine.field, propMap[playerID], no);
}
} else {
loadMap(engine.field, propMap[playerID], mapNumber[playerID]);
}
engine.field.setAllSkin(engine.getSkin());
fldBackup[playerID] = new Field(engine.field);
}
}
} else if(engine.field != null) {
engine.field.reset();
}
}
return false;
}
/*
* ゲーム開始時の処理
*/
@Override
public void startGame(GameEngine engine, int playerID) {
engine.b2bEnable = false;
engine.comboType = GameEngine.COMBO_TYPE_DISABLE;
engine.big = big[playerID];
engine.enableSE = enableSE[playerID];
if(playerID == 1) owner.bgmStatus.bgm = bgmno;
engine.colorClearSize = big[playerID] ? 12 : 4;
engine.tspinAllowKick = false;
engine.tspinEnable = false;
engine.useAllSpinBonus = false;
}
/*
* スコア表示
*/
@Override
public void renderLast(GameEngine engine, int playerID) {
// ステータス表示
if(playerID == 0) {
receiver.drawScoreFont(engine, playerID, -1, 0, "AVALANCHE VS", EventReceiver.COLOR_GREEN);
receiver.drawScoreFont(engine, playerID, -1, 2, "GARBAGE", EventReceiver.COLOR_PURPLE);
String garbageStr1P = String.valueOf(garbage[0]);
if (garbageAdd[0] > 0)
garbageStr1P = garbageStr1P + "(+" + String.valueOf(garbageAdd[0]) + ")";
String garbageStr2P = String.valueOf(garbage[1]);
if (garbageAdd[1] > 0)
garbageStr2P = garbageStr2P + "(+" + String.valueOf(garbageAdd[1]) + ")";
receiver.drawScoreFont(engine, playerID, -1, 3, "1P:", EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, 3, 3, garbageStr1P, (garbage[0] > 0));
receiver.drawScoreFont(engine, playerID, -1, 4, "2P:", EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, 3, 4, garbageStr2P, (garbage[1] > 0));
receiver.drawScoreFont(engine, playerID, -1, 6, "ATTACK", EventReceiver.COLOR_GREEN);
receiver.drawScoreFont(engine, playerID, -1, 7, "1P: " + String.valueOf(garbageSent[0]), EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, -1, 8, "2P: " + String.valueOf(garbageSent[1]), EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, -1, 10, "SCORE", EventReceiver.COLOR_PURPLE);
receiver.drawScoreFont(engine, playerID, -1, 11, "1P: " + String.valueOf(score[0]), EventReceiver.COLOR_RED);
receiver.drawScoreFont(engine, playerID, -1, 12, "2P: " + String.valueOf(score[1]), EventReceiver.COLOR_BLUE);
receiver.drawScoreFont(engine, playerID, -1, 14, "TIME", EventReceiver.COLOR_GREEN);
receiver.drawScoreFont(engine, playerID, -1, 15, GeneralUtil.getTime(engine.statistics.time));
}
if (!owner.engine[playerID].gameActive)
return;
if(zenKeshi[playerID])
receiver.drawMenuFont(engine, playerID, 1, 21, "ZENKESHI!", EventReceiver.COLOR_YELLOW);
if (garbageHard[playerID] > 0 && engine.field != null)
for (int x = 0; x < engine.field.getWidth(); x++)
for (int y = 0; y < engine.field.getHeight(); y++)
{
int hard = engine.field.getBlock(x, y).hard;
if (hard > 0)
receiver.drawMenuFont(engine, playerID, x, y, String.valueOf(hard), EventReceiver.COLOR_YELLOW);
}
}
/*
* スコア計算
*/
@Override
public void calcScore(GameEngine engine, int playerID, int avalanche) {
int enemyID = 0;
if(playerID == 0) enemyID = 1;
if (big[playerID])
avalanche >>= 2;
// ラインクリアボーナス
int pts = avalanche*10;
int garbageNew = 0;
boolean cleared = avalanche > 0;
if (cleared) {
if (zenKeshi[playerID])
garbageNew += 30;
if (engine.field.isEmpty()) {
engine.playSE("bravo");
zenKeshi[playerID] = true;
engine.statistics.score += 2100;
}
else
zenKeshi[playerID] = false;
int chain = engine.chain;
engine.playSE("combo" + Math.min(chain, 20));
int multiplier = engine.field.colorClearExtraCount;
if (big[playerID])
multiplier >>= 2;
if (engine.field.colorsCleared > 1)
multiplier += (engine.field.colorsCleared-1)*2;
/*
if (multiplier < 0)
multiplier = 0;
if (chain == 0)
firstExtra = avalanche > engine.colorClearSize;
*/
if (chain == 2)
multiplier += 8;
else if (chain == 3)
multiplier += 16;
else if (chain >= 4)
multiplier += 32*(chain-3);
/*
if (firstExtra)
multiplier++;
*/
if (multiplier > 999)
multiplier = 999;
if (multiplier < 1)
multiplier = 1;
lastscore[playerID] = pts;
lastmultiplier[playerID] = multiplier;
scgettime[playerID] = 120;
int ptsTotal = pts*multiplier;
score[playerID] += ptsTotal;
if (hurryupSeconds[playerID] > 0 && engine.statistics.time > hurryupSeconds[playerID])
ptsTotal <<= engine.statistics.time / (hurryupSeconds[playerID] * 60);
garbageNew += (ptsTotal+garbageRate[playerID]-1)/garbageRate[playerID];
if (chain >= rensaShibari[playerID])
{
garbageSent[playerID] += garbageNew;
if (garbageCounterMode[playerID] != GARBAGE_COUNTER_OFF)
{
if (garbage[playerID] > 0)
{
int delta = Math.min(garbage[playerID], garbageNew);
garbage[playerID] -= delta;
garbageNew -= delta;
}
if (garbageAdd[playerID] > 0 && garbageNew > 0)
{
int delta = Math.min(garbageAdd[playerID], garbageNew);
garbageAdd[playerID] -= delta;
garbageNew -= delta;
}
}
if (garbageNew > 0)
garbageAdd[enemyID] += garbageNew;
}
}
if ((!cleared || garbageCounterMode[playerID] != GARBAGE_COUNTER_FEVER)
&& !engine.field.canCascade() && garbage[playerID] > 0)
{
int drop = Math.min(garbage[playerID], maxAttack[playerID]);
garbage[playerID] -= drop;
engine.field.garbageDrop(engine, drop, big[playerID], garbageHard[playerID]);
}
}
public boolean lineClearEnd(GameEngine engine, int playerID) {
int enemyID = 0;
if(playerID == 0) enemyID = 1;
if (garbageAdd[enemyID] > 0)
{
garbage[enemyID] += garbageAdd[enemyID];
garbageAdd[enemyID] = 0;
}
if (garbageCounterMode[playerID] != GARBAGE_COUNTER_FEVER && garbage[playerID] > 0)
{
int drop = Math.min(garbage[playerID], maxAttack[playerID]);
garbage[playerID] -= drop;
engine.field.garbageDrop(engine, drop, big[playerID], garbageHard[playerID]);
return true;
}
return false;
}
/*
* 各フレームの最後の処理
*/
@Override
public void onLast(GameEngine engine, int playerID) {
scgettime[playerID]++;
int width = 1;
if (engine.field != null)
width = engine.field.getWidth();
int blockHeight = receiver.getBlockGraphicsHeight(engine, playerID);
// せり上がりメーター
if(garbage[playerID] * blockHeight / width > engine.meterValue) {
engine.meterValue++;
} else if(garbage[playerID] * blockHeight / width < engine.meterValue) {
engine.meterValue--;
}
if(garbage[playerID] >= 5*width) engine.meterColor = GameEngine.METER_COLOR_RED;
else if(garbage[playerID] >= width) engine.meterColor = GameEngine.METER_COLOR_ORANGE;
else if(garbage[playerID] >= 1) engine.meterColor = GameEngine.METER_COLOR_YELLOW;
else engine.meterColor = GameEngine.METER_COLOR_GREEN;
// 決着
if((playerID == 1) && (owner.engine[0].gameActive)) {
if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) {
// 引き分け
winnerID = -1;
owner.engine[0].gameActive = false;
owner.engine[1].gameActive = false;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
} else if((owner.engine[0].stat != GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) {
// 1P勝利
winnerID = 0;
owner.engine[0].gameActive = false;
owner.engine[1].gameActive = false;
owner.engine[0].stat = GameEngine.STAT_EXCELLENT;
owner.engine[0].resetStatc();
owner.engine[0].statc[1] = 1;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
} else if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat != GameEngine.STAT_GAMEOVER)) {
// 2P勝利
winnerID = 1;
owner.engine[0].gameActive = false;
owner.engine[1].gameActive = false;
owner.engine[1].stat = GameEngine.STAT_EXCELLENT;
owner.engine[1].resetStatc();
owner.engine[1].statc[1] = 1;
owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING;
}
}
}
/*
* 結果画面の描画
*/
@Override
public void renderResult(GameEngine engine, int playerID) {
receiver.drawMenuFont(engine, playerID, 0, 1, "RESULT", EventReceiver.COLOR_ORANGE);
if(winnerID == -1) {
receiver.drawMenuFont(engine, playerID, 6, 2, "DRAW", EventReceiver.COLOR_GREEN);
} else if(winnerID == playerID) {
receiver.drawMenuFont(engine, playerID, 6, 2, "WIN!", EventReceiver.COLOR_YELLOW);
} else {
receiver.drawMenuFont(engine, playerID, 6, 2, "LOSE", EventReceiver.COLOR_WHITE);
}
receiver.drawMenuFont(engine, playerID, 0, 3, "ATTACK", EventReceiver.COLOR_ORANGE);
String strScore = String.format("%10d", garbageSent[playerID]);
receiver.drawMenuFont(engine, playerID, 0, 4, strScore);
receiver.drawMenuFont(engine, playerID, 0, 5, "LINE", EventReceiver.COLOR_ORANGE);
String strLines = String.format("%10d", engine.statistics.lines);
receiver.drawMenuFont(engine, playerID, 0, 6, strLines);
receiver.drawMenuFont(engine, playerID, 0, 7, "PIECE", EventReceiver.COLOR_ORANGE);
String strPiece = String.format("%10d", engine.statistics.totalPieceLocked);
receiver.drawMenuFont(engine, playerID, 0, 8, strPiece);
receiver.drawMenuFont(engine, playerID, 0, 9, "ATTACK/MIN", EventReceiver.COLOR_ORANGE);
float apm = (float)(garbageSent[playerID] * 3600) / (float)(engine.statistics.time);
String strAPM = String.format("%10g", apm);
receiver.drawMenuFont(engine, playerID, 0, 10, strAPM);
receiver.drawMenuFont(engine, playerID, 0, 11, "LINE/MIN", EventReceiver.COLOR_ORANGE);
String strLPM = String.format("%10g", engine.statistics.lpm);
receiver.drawMenuFont(engine, playerID, 0, 12, strLPM);
receiver.drawMenuFont(engine, playerID, 0, 13, "PIECE/SEC", EventReceiver.COLOR_ORANGE);
String strPPS = String.format("%10g", engine.statistics.pps);
receiver.drawMenuFont(engine, playerID, 0, 14, strPPS);
receiver.drawMenuFont(engine, playerID, 0, 15, "TIME", EventReceiver.COLOR_ORANGE);
String strTime = String.format("%10s", GeneralUtil.getTime(owner.engine[0].statistics.time));
receiver.drawMenuFont(engine, playerID, 0, 16, strTime);
}
/*
* リプレイ保存時の処理
*/
@Override
public void saveReplay(GameEngine engine, int playerID, CustomProperties prop) {
saveOtherSetting(engine, owner.replayProp);
savePreset(engine, owner.replayProp, -1 - playerID);
if(useMap[playerID] && (fldBackup[playerID] != null)) {
saveMap(fldBackup[playerID], owner.replayProp, playerID);
}
owner.replayProp.setProperty("avalanchevs.version", version);
}
}
| Add preliminary Fever support to Avalanche VS Mode
| src/org/game_host/hebo/nullpomino/game/subsystem/mode/AvalancheVSMode.java | Add preliminary Fever support to Avalanche VS Mode |
|
Java | bsd-3-clause | 5a77ee2ed7403b0746c41acfcb40ecd2bf126f7e | 0 | wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy | /*
* Copyright (c) 2012, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.dsl.processor.node;
import static com.oracle.truffle.dsl.processor.Utils.*;
import static javax.lang.model.element.Modifier.*;
import java.util.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import com.oracle.truffle.api.dsl.*;
import com.oracle.truffle.api.nodes.*;
import com.oracle.truffle.dsl.processor.*;
import com.oracle.truffle.dsl.processor.ast.*;
import com.oracle.truffle.dsl.processor.node.NodeChildData.Cardinality;
import com.oracle.truffle.dsl.processor.node.SpecializationGroup.TypeGuard;
import com.oracle.truffle.dsl.processor.template.*;
import com.oracle.truffle.dsl.processor.typesystem.*;
public class NodeCodeGenerator extends CompilationUnitFactory<NodeData> {
private static final String THIS_NODE_LOCAL_VAR_NAME = "thisNode";
private static final String EXECUTE_GENERIC_NAME = "executeGeneric0";
private static final String EXECUTE_SPECIALIZE_NAME = "executeAndSpecialize0";
private static final String EXECUTE_POLYMORPHIC_NAME = "executePolymorphic0";
private static final String UPDATE_TYPES_NAME = "updateTypes";
private static final String COPY_WITH_CONSTRUCTOR_NAME = "copyWithConstructor";
private static final String CREATE_SPECIALIZATION_NAME = "createSpecialization";
public NodeCodeGenerator(ProcessorContext context) {
super(context);
}
private TypeMirror getUnexpectedValueException() {
return getContext().getTruffleTypes().getUnexpectedValueException();
}
private static String factoryClassName(NodeData node) {
return node.getNodeId() + "Factory";
}
private static String nodeSpecializationClassName(SpecializationData specialization) {
String nodeid = resolveNodeId(specialization.getNode());
String name = Utils.firstLetterUpperCase(nodeid);
name += Utils.firstLetterUpperCase(specialization.getId());
name += "Node";
return name;
}
private static String nodePolymorphicClassName(NodeData node) {
return Utils.firstLetterUpperCase(resolveNodeId(node)) + "PolymorphicNode";
}
private static String resolveNodeId(NodeData node) {
String nodeid = node.getNodeId();
if (nodeid.endsWith("Node") && !nodeid.equals("Node")) {
nodeid = nodeid.substring(0, nodeid.length() - 4);
}
return nodeid;
}
private static String valueNameEvaluated(ActualParameter targetParameter) {
return valueName(targetParameter) + "Evaluated";
}
private static String implicitTypeName(ActualParameter param) {
return param.getLocalName() + "ImplicitType";
}
private static String polymorphicTypeName(ActualParameter param) {
return param.getLocalName() + "PolymorphicType";
}
private static String valueName(ActualParameter param) {
return param.getLocalName();
}
private static CodeTree createAccessChild(NodeExecutionData targetExecution, String thisReference) {
String reference = thisReference;
if (reference == null) {
reference = "this";
}
CodeTreeBuilder builder = CodeTreeBuilder.createBuilder();
Element accessElement = targetExecution.getChild().getAccessElement();
if (accessElement == null || accessElement.getKind() == ElementKind.METHOD) {
builder.string(reference).string(".").string(targetExecution.getChild().getName());
} else if (accessElement.getKind() == ElementKind.FIELD) {
builder.string(reference).string(".").string(accessElement.getSimpleName().toString());
} else {
throw new AssertionError();
}
if (targetExecution.isIndexed()) {
builder.string("[" + targetExecution.getIndex() + "]");
}
return builder.getRoot();
}
private static String castValueName(ActualParameter parameter) {
return valueName(parameter) + "Cast";
}
private void addInternalValueParameters(CodeExecutableElement method, TemplateMethod specialization, boolean forceFrame, boolean evaluated) {
if (forceFrame && specialization.getSpecification().findParameterSpec("frame") != null) {
method.addParameter(new CodeVariableElement(getContext().getTruffleTypes().getFrame(), "frameValue"));
}
for (ActualParameter parameter : specialization.getParameters()) {
ParameterSpec spec = parameter.getSpecification();
if (forceFrame && spec.getName().equals("frame")) {
continue;
}
if (spec.isLocal()) {
continue;
}
String name = valueName(parameter);
if (evaluated && spec.isSignature()) {
name = valueNameEvaluated(parameter);
}
method.addParameter(new CodeVariableElement(parameter.getType(), name));
}
}
private void addInternalValueParameterNames(CodeTreeBuilder builder, TemplateMethod source, TemplateMethod specialization, String unexpectedValueName, boolean forceFrame,
Map<String, String> customNames) {
if (forceFrame && specialization.getSpecification().findParameterSpec("frame") != null) {
builder.string("frameValue");
}
for (ActualParameter parameter : specialization.getParameters()) {
ParameterSpec spec = parameter.getSpecification();
if (forceFrame && spec.getName().equals("frame")) {
continue;
}
if (parameter.getSpecification().isLocal()) {
continue;
}
ActualParameter sourceParameter = source.findParameter(parameter.getLocalName());
if (customNames != null && customNames.containsKey(parameter.getLocalName())) {
builder.string(customNames.get(parameter.getLocalName()));
} else if (unexpectedValueName != null && parameter.getLocalName().equals(unexpectedValueName)) {
builder.cast(parameter.getType(), CodeTreeBuilder.singleString("ex.getResult()"));
} else if (sourceParameter != null) {
builder.string(valueName(sourceParameter, parameter));
} else {
builder.string(valueName(parameter));
}
}
}
private String valueName(ActualParameter sourceParameter, ActualParameter targetParameter) {
if (!sourceParameter.getSpecification().isSignature()) {
return valueName(targetParameter);
} else if (sourceParameter.getTypeSystemType() != null && targetParameter.getTypeSystemType() != null) {
if (sourceParameter.getTypeSystemType().needsCastTo(getContext(), targetParameter.getTypeSystemType())) {
return castValueName(targetParameter);
}
}
return valueName(targetParameter);
}
private CodeTree createTemplateMethodCall(CodeTreeBuilder parent, CodeTree target, TemplateMethod sourceMethod, TemplateMethod targetMethod, String unexpectedValueName,
String... customSignatureValueNames) {
CodeTreeBuilder builder = parent.create();
boolean castedValues = sourceMethod != targetMethod;
builder.startGroup();
ExecutableElement method = targetMethod.getMethod();
if (method == null) {
throw new UnsupportedOperationException();
}
TypeElement targetClass = Utils.findNearestEnclosingType(method.getEnclosingElement());
NodeData node = (NodeData) targetMethod.getTemplate();
if (target == null) {
boolean accessible = targetMethod.canBeAccessedByInstanceOf(getContext(), node.getNodeType());
if (accessible) {
if (builder.findMethod().getModifiers().contains(STATIC)) {
if (method.getModifiers().contains(STATIC)) {
builder.type(targetClass.asType());
} else {
builder.string(THIS_NODE_LOCAL_VAR_NAME);
}
} else {
if (targetMethod instanceof ExecutableTypeData) {
builder.string("this");
} else {
builder.string("super");
}
}
} else {
if (method.getModifiers().contains(STATIC)) {
builder.type(targetClass.asType());
} else {
ActualParameter firstParameter = null;
for (ActualParameter searchParameter : targetMethod.getParameters()) {
if (searchParameter.getSpecification().isSignature()) {
firstParameter = searchParameter;
break;
}
}
if (firstParameter == null) {
throw new AssertionError();
}
ActualParameter sourceParameter = sourceMethod.findParameter(firstParameter.getLocalName());
if (castedValues && sourceParameter != null) {
builder.string(valueName(sourceParameter, firstParameter));
} else {
builder.string(valueName(firstParameter));
}
}
}
builder.string(".");
} else {
builder.tree(target);
}
builder.startCall(method.getSimpleName().toString());
int signatureIndex = 0;
for (ActualParameter targetParameter : targetMethod.getParameters()) {
ActualParameter valueParameter = null;
if (sourceMethod != null) {
valueParameter = sourceMethod.findParameter(targetParameter.getLocalName());
}
if (valueParameter == null) {
valueParameter = targetParameter;
}
TypeMirror targetType = targetParameter.getType();
TypeMirror valueType = null;
if (valueParameter != null) {
valueType = valueParameter.getType();
}
if (signatureIndex < customSignatureValueNames.length && targetParameter.getSpecification().isSignature()) {
builder.string(customSignatureValueNames[signatureIndex]);
signatureIndex++;
} else if (targetParameter.getSpecification().isLocal()) {
builder.startGroup();
if (builder.findMethod().getModifiers().contains(Modifier.STATIC)) {
builder.string(THIS_NODE_LOCAL_VAR_NAME).string(".");
} else {
builder.string("this.");
}
builder.string(targetParameter.getSpecification().getName());
builder.end();
} else if (unexpectedValueName != null && targetParameter.getLocalName().equals(unexpectedValueName)) {
builder.cast(targetParameter.getType(), CodeTreeBuilder.singleString("ex.getResult()"));
} else if (!Utils.needsCastTo(getContext(), valueType, targetType)) {
builder.startGroup();
builder.string(valueName(targetParameter));
builder.end();
} else {
builder.string(castValueName(targetParameter));
}
}
builder.end().end();
return builder.getRoot();
}
private static String baseClassName(NodeData node) {
String nodeid = resolveNodeId(node);
String name = Utils.firstLetterUpperCase(nodeid);
name += "BaseNode";
return name;
}
private static CodeTree createCallTypeSystemMethod(ProcessorContext context, CodeTreeBuilder parent, NodeData node, String methodName, CodeTree... args) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
startCallTypeSystemMethod(context, builder, node.getTypeSystem(), methodName);
for (CodeTree arg : args) {
builder.tree(arg);
}
builder.end().end();
return builder.getRoot();
}
private static void startCallTypeSystemMethod(ProcessorContext context, CodeTreeBuilder body, TypeSystemData typeSystem, String methodName) {
VariableElement singleton = TypeSystemCodeGenerator.findSingleton(context, typeSystem);
assert singleton != null;
body.startGroup();
body.staticReference(singleton.getEnclosingElement().asType(), singleton.getSimpleName().toString());
body.string(".").startCall(methodName);
}
/**
* <pre>
* variant1 $condition != null
*
* $type $name = defaultValue($type);
* if ($condition) {
* $name = $value;
* }
*
* variant2 $condition != null
* $type $name = $value;
* </pre>
*
* .
*/
private static CodeTree createLazyAssignment(CodeTreeBuilder parent, String name, TypeMirror type, CodeTree condition, CodeTree value) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (condition == null) {
builder.declaration(type, name, value);
} else {
builder.declaration(type, name, new CodeTreeBuilder(parent).defaultValue(type).getRoot());
builder.startIf().tree(condition).end();
builder.startBlock();
builder.startStatement();
builder.string(name);
builder.string(" = ");
builder.tree(value);
builder.end(); // statement
builder.end(); // block
}
return builder.getRoot();
}
protected void emitEncounteredSynthetic(CodeTreeBuilder builder, TemplateMethod current) {
CodeTreeBuilder nodes = builder.create();
CodeTreeBuilder arguments = builder.create();
nodes.startCommaGroup();
arguments.startCommaGroup();
boolean empty = true;
for (ActualParameter parameter : current.getParameters()) {
NodeExecutionData executionData = parameter.getSpecification().getExecution();
if (executionData != null) {
if (executionData.isShortCircuit()) {
nodes.nullLiteral();
arguments.string(valueName(parameter.getPreviousParameter()));
}
nodes.tree(createAccessChild(executionData, null));
arguments.string(valueName(parameter));
empty = false;
}
}
nodes.end();
arguments.end();
builder.startThrow().startNew(getContext().getType(UnsupportedSpecializationException.class));
builder.string("this");
builder.startNewArray(getContext().getTruffleTypes().getNodeArray(), null);
builder.tree(nodes.getRoot());
builder.end();
if (!empty) {
builder.tree(arguments.getRoot());
}
builder.end().end();
}
private static List<ExecutableElement> findUserConstructors(TypeMirror nodeType) {
List<ExecutableElement> constructors = new ArrayList<>();
for (ExecutableElement constructor : ElementFilter.constructorsIn(Utils.fromTypeMirror(nodeType).getEnclosedElements())) {
if (constructor.getModifiers().contains(PRIVATE)) {
continue;
}
if (isCopyConstructor(constructor)) {
continue;
}
constructors.add(constructor);
}
if (constructors.isEmpty()) {
constructors.add(new CodeExecutableElement(null, Utils.getSimpleName(nodeType)));
}
return constructors;
}
private static ExecutableElement findCopyConstructor(TypeMirror type) {
for (ExecutableElement constructor : ElementFilter.constructorsIn(Utils.fromTypeMirror(type).getEnclosedElements())) {
if (constructor.getModifiers().contains(PRIVATE)) {
continue;
}
if (isCopyConstructor(constructor)) {
return constructor;
}
}
return null;
}
private static boolean isCopyConstructor(ExecutableElement element) {
if (element.getParameters().size() != 1) {
return false;
}
VariableElement var = element.getParameters().get(0);
TypeElement enclosingType = Utils.findNearestEnclosingType(var);
if (Utils.typeEquals(var.asType(), enclosingType.asType())) {
return true;
}
List<TypeElement> types = Utils.getDirectSuperTypes(enclosingType);
for (TypeElement type : types) {
if (!(type instanceof CodeTypeElement)) {
// no copy constructors which are not generated types
return false;
}
if (Utils.typeEquals(var.asType(), type.asType())) {
return true;
}
}
return false;
}
@Override
@SuppressWarnings("unchecked")
protected void createChildren(NodeData node) {
List<CodeTypeElement> casts = new ArrayList<>(getElement().getEnclosedElements());
getElement().getEnclosedElements().clear();
Map<NodeData, List<TypeElement>> childTypes = new LinkedHashMap<>();
for (NodeData nodeChild : node.getEnclosingNodes()) {
NodeCodeGenerator generator = new NodeCodeGenerator(getContext());
childTypes.put(nodeChild, generator.process(null, nodeChild).getEnclosedElements());
}
if (node.needsFactory() || node.getNodeDeclaringChildren().size() > 0) {
NodeFactoryFactory factory = new NodeFactoryFactory(context, childTypes);
add(factory, node);
factory.getElement().getEnclosedElements().addAll(casts);
}
}
protected CodeTree createCastType(TypeSystemData typeSystem, TypeData sourceType, TypeData targetType, boolean expect, CodeTree value) {
if (targetType == null) {
return value;
} else if (sourceType != null && !sourceType.needsCastTo(getContext(), targetType)) {
return value;
}
CodeTreeBuilder builder = CodeTreeBuilder.createBuilder();
String targetMethodName;
if (expect) {
targetMethodName = TypeSystemCodeGenerator.expectTypeMethodName(targetType);
} else {
targetMethodName = TypeSystemCodeGenerator.asTypeMethodName(targetType);
}
startCallTypeSystemMethod(getContext(), builder, typeSystem, targetMethodName);
builder.tree(value);
builder.end().end();
return builder.getRoot();
}
protected CodeTree createExpectType(TypeSystemData typeSystem, TypeData sourceType, TypeData targetType, CodeTree expression) {
return createCastType(typeSystem, sourceType, targetType, true, expression);
}
public CodeTree createDeoptimize(CodeTreeBuilder parent) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.startStatement();
builder.startStaticCall(getContext().getTruffleTypes().getCompilerDirectives(), "transferToInterpreterAndInvalidate").end();
builder.end();
return builder.getRoot();
}
private class NodeFactoryFactory extends ClassElementFactory<NodeData> {
private final Map<NodeData, List<TypeElement>> childTypes;
private CodeTypeElement generatedNode;
public NodeFactoryFactory(ProcessorContext context, Map<NodeData, List<TypeElement>> childElements) {
super(context);
this.childTypes = childElements;
}
@Override
protected CodeTypeElement create(NodeData node) {
Modifier visibility = Utils.getVisibility(node.getTemplateType().getModifiers());
CodeTypeElement clazz = createClass(node, modifiers(), factoryClassName(node), null, false);
if (visibility != null) {
clazz.getModifiers().add(visibility);
}
clazz.getModifiers().add(Modifier.FINAL);
clazz.add(createConstructorUsingFields(modifiers(PRIVATE), clazz));
return clazz;
}
@Override
protected void createChildren(NodeData node) {
CodeTypeElement clazz = getElement();
Modifier createVisibility = Utils.getVisibility(clazz.getModifiers());
CodeTypeElement polymorphicNode = null;
if (node.needsFactory()) {
NodeBaseFactory factory = new NodeBaseFactory(context);
add(factory, node.getGenericSpecialization() == null ? node.getSpecializations().get(0) : node.getGenericSpecialization());
generatedNode = factory.getElement();
if (node.needsRewrites(context)) {
clazz.add(createCreateGenericMethod(node, createVisibility));
}
createFactoryMethods(node, clazz, createVisibility);
for (SpecializationData specialization : node.getSpecializations()) {
if (!specialization.isReachable()) {
continue;
}
if (specialization.isPolymorphic() && node.isPolymorphic()) {
PolymorphicNodeFactory polymorphicFactory = new PolymorphicNodeFactory(getContext(), generatedNode);
add(polymorphicFactory, specialization);
polymorphicNode = polymorphicFactory.getElement();
continue;
}
add(new SpecializedNodeFactory(context, generatedNode), specialization);
}
TypeMirror nodeFactory = Utils.getDeclaredType(Utils.fromTypeMirror(getContext().getType(NodeFactory.class)), node.getNodeType());
clazz.getImplements().add(nodeFactory);
clazz.add(createCreateNodeMethod(node));
clazz.add(createGetNodeClassMethod(node));
clazz.add(createGetNodeSignaturesMethod());
clazz.add(createGetChildrenSignatureMethod(node));
clazz.add(createGetInstanceMethod(node, createVisibility));
clazz.add(createInstanceConstant(node, clazz.asType()));
}
if (polymorphicNode != null) {
patchParameterType(clazz, UPDATE_TYPES_NAME, generatedNode.asType(), polymorphicNode.asType());
}
for (NodeData childNode : childTypes.keySet()) {
if (childNode.getTemplateType().getModifiers().contains(Modifier.PRIVATE)) {
continue;
}
for (TypeElement type : childTypes.get(childNode)) {
Set<Modifier> typeModifiers = ((CodeTypeElement) type).getModifiers();
Modifier visibility = Utils.getVisibility(type.getModifiers());
typeModifiers.clear();
if (visibility != null) {
typeModifiers.add(visibility);
}
typeModifiers.add(Modifier.STATIC);
typeModifiers.add(Modifier.FINAL);
clazz.add(type);
}
}
List<NodeData> children = node.getNodeDeclaringChildren();
if (node.getDeclaringNode() == null && children.size() > 0) {
clazz.add(createGetFactories(node));
}
}
private void patchParameterType(CodeTypeElement enclosingClass, String methodName, TypeMirror originalType, TypeMirror newType) {
for (TypeElement enclosedType : ElementFilter.typesIn(enclosingClass.getEnclosedElements())) {
CodeTypeElement type = (CodeTypeElement) enclosedType;
ExecutableElement method = type.getMethod(methodName);
for (VariableElement v : method.getParameters()) {
CodeVariableElement var = (CodeVariableElement) v;
if (Utils.typeEquals(var.getType(), originalType)) {
var.setType(newType);
}
}
}
}
private CodeExecutableElement createGetNodeClassMethod(NodeData node) {
TypeMirror returnType = Utils.getDeclaredType(Utils.fromTypeMirror(getContext().getType(Class.class)), node.getNodeType());
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getNodeClass");
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn().typeLiteral(node.getNodeType()).end();
return method;
}
private CodeExecutableElement createGetNodeSignaturesMethod() {
TypeElement listType = Utils.fromTypeMirror(getContext().getType(List.class));
TypeMirror classType = getContext().getType(Class.class);
TypeMirror returnType = Utils.getDeclaredType(listType, Utils.getDeclaredType(listType, classType));
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getNodeSignatures");
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startStaticCall(getContext().getType(Arrays.class), "asList");
List<ExecutableElement> constructors = findUserConstructors(generatedNode.asType());
for (ExecutableElement constructor : constructors) {
builder.tree(createAsList(builder, Utils.asTypeMirrors(constructor.getParameters()), classType));
}
builder.end();
builder.end();
return method;
}
private CodeExecutableElement createGetChildrenSignatureMethod(NodeData node) {
Types types = getContext().getEnvironment().getTypeUtils();
TypeElement listType = Utils.fromTypeMirror(getContext().getType(List.class));
TypeMirror classType = getContext().getType(Class.class);
TypeMirror nodeType = getContext().getTruffleTypes().getNode();
TypeMirror wildcardNodeType = types.getWildcardType(nodeType, null);
classType = Utils.getDeclaredType(Utils.fromTypeMirror(classType), wildcardNodeType);
TypeMirror returnType = Utils.getDeclaredType(listType, classType);
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getExecutionSignature");
CodeTreeBuilder builder = method.createBuilder();
List<TypeMirror> signatureTypes = new ArrayList<>();
assert !node.getSpecializations().isEmpty();
SpecializationData data = node.getSpecializations().get(0);
for (ActualParameter parameter : data.getSignatureParameters()) {
signatureTypes.add(parameter.getSpecification().getExecution().getNodeType());
}
builder.startReturn().tree(createAsList(builder, signatureTypes, classType)).end();
return method;
}
private CodeTree createAsList(CodeTreeBuilder parent, List<TypeMirror> types, TypeMirror elementClass) {
CodeTreeBuilder builder = parent.create();
builder.startGroup();
builder.type(getContext().getType(Arrays.class));
builder.string(".<").type(elementClass).string(">");
builder.startCall("asList");
for (TypeMirror typeMirror : types) {
builder.typeLiteral(typeMirror);
}
builder.end().end();
return builder.getRoot();
}
private CodeExecutableElement createCreateNodeMethod(NodeData node) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), node.getNodeType(), "createNode");
CodeVariableElement arguments = new CodeVariableElement(getContext().getType(Object.class), "arguments");
method.setVarArgs(true);
method.addParameter(arguments);
CodeTreeBuilder builder = method.createBuilder();
List<ExecutableElement> signatures = findUserConstructors(generatedNode.asType());
boolean ifStarted = false;
for (ExecutableElement element : signatures) {
ifStarted = builder.startIf(ifStarted);
builder.string("arguments.length == " + element.getParameters().size());
int index = 0;
for (VariableElement param : element.getParameters()) {
if (Utils.isObject(param.asType())) {
continue;
}
builder.string(" && ");
if (!param.asType().getKind().isPrimitive()) {
builder.string("(arguments[" + index + "] == null || ");
}
builder.string("arguments[" + index + "] instanceof ");
builder.type(Utils.boxType(getContext(), param.asType()));
if (!param.asType().getKind().isPrimitive()) {
builder.string(")");
}
index++;
}
builder.end();
builder.startBlock();
builder.startReturn().startCall("create");
index = 0;
for (VariableElement param : element.getParameters()) {
builder.startGroup();
if (!Utils.isObject(param.asType())) {
builder.string("(").type(param.asType()).string(") ");
}
builder.string("arguments[").string(String.valueOf(index)).string("]");
builder.end();
index++;
}
builder.end().end();
builder.end(); // block
}
builder.startElseBlock();
builder.startThrow().startNew(getContext().getType(IllegalArgumentException.class));
builder.doubleQuote("Invalid create signature.");
builder.end().end();
builder.end(); // else block
return method;
}
private ExecutableElement createGetInstanceMethod(NodeData node, Modifier visibility) {
TypeElement nodeFactoryType = Utils.fromTypeMirror(getContext().getType(NodeFactory.class));
TypeMirror returnType = Utils.getDeclaredType(nodeFactoryType, node.getNodeType());
CodeExecutableElement method = new CodeExecutableElement(modifiers(), returnType, "getInstance");
if (visibility != null) {
method.getModifiers().add(visibility);
}
method.getModifiers().add(Modifier.STATIC);
String varName = instanceVarName(node);
CodeTreeBuilder builder = method.createBuilder();
builder.startIf();
builder.string(varName).string(" == null");
builder.end().startBlock();
builder.startStatement();
builder.string(varName);
builder.string(" = ");
builder.startNew(factoryClassName(node)).end();
builder.end();
builder.end();
builder.startReturn().string(varName).end();
return method;
}
private String instanceVarName(NodeData node) {
if (node.getDeclaringNode() != null) {
return Utils.firstLetterLowerCase(factoryClassName(node)) + "Instance";
} else {
return "instance";
}
}
private CodeVariableElement createInstanceConstant(NodeData node, TypeMirror factoryType) {
String varName = instanceVarName(node);
CodeVariableElement var = new CodeVariableElement(modifiers(), factoryType, varName);
var.getModifiers().add(Modifier.PRIVATE);
var.getModifiers().add(Modifier.STATIC);
return var;
}
private ExecutableElement createGetFactories(NodeData node) {
List<NodeData> children = node.getNodeDeclaringChildren();
if (node.needsFactory()) {
children.add(node);
}
List<TypeMirror> nodeTypesList = new ArrayList<>();
TypeMirror prev = null;
boolean allSame = true;
for (NodeData child : children) {
nodeTypesList.add(child.getNodeType());
if (prev != null && !Utils.typeEquals(child.getNodeType(), prev)) {
allSame = false;
}
prev = child.getNodeType();
}
TypeMirror commonNodeSuperType = Utils.getCommonSuperType(getContext(), nodeTypesList.toArray(new TypeMirror[nodeTypesList.size()]));
Types types = getContext().getEnvironment().getTypeUtils();
TypeMirror factoryType = getContext().getType(NodeFactory.class);
TypeMirror baseType;
if (allSame) {
baseType = Utils.getDeclaredType(Utils.fromTypeMirror(factoryType), commonNodeSuperType);
} else {
baseType = Utils.getDeclaredType(Utils.fromTypeMirror(factoryType), types.getWildcardType(commonNodeSuperType, null));
}
TypeMirror listType = Utils.getDeclaredType(Utils.fromTypeMirror(getContext().getType(List.class)), baseType);
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, STATIC), listType, "getFactories");
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startStaticCall(getContext().getType(Arrays.class), "asList");
for (NodeData child : children) {
builder.startGroup();
NodeData childNode = child;
List<NodeData> factories = new ArrayList<>();
while (childNode.getDeclaringNode() != null) {
factories.add(childNode);
childNode = childNode.getDeclaringNode();
}
Collections.reverse(factories);
for (NodeData nodeData : factories) {
builder.string(factoryClassName(nodeData)).string(".");
}
builder.string("getInstance()");
builder.end();
}
builder.end();
builder.end();
return method;
}
private void createFactoryMethods(NodeData node, CodeTypeElement clazz, Modifier createVisibility) {
List<ExecutableElement> constructors = findUserConstructors(generatedNode.asType());
for (ExecutableElement constructor : constructors) {
clazz.add(createCreateMethod(node, createVisibility, constructor));
}
}
private CodeExecutableElement createCreateMethod(NodeData node, Modifier visibility, ExecutableElement constructor) {
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), constructor);
method.setSimpleName(CodeNames.of("create"));
method.getModifiers().clear();
if (visibility != null) {
method.getModifiers().add(visibility);
}
method.getModifiers().add(Modifier.STATIC);
method.setReturnType(node.getNodeType());
CodeTreeBuilder body = method.createBuilder();
body.startReturn();
if (node.getSpecializations().isEmpty()) {
body.nullLiteral();
} else {
body.startCall(nodeSpecializationClassName(node.getSpecializations().get(0)), CREATE_SPECIALIZATION_NAME);
for (VariableElement var : method.getParameters()) {
body.string(var.getSimpleName().toString());
}
body.end();
}
body.end();
return method;
}
private CodeExecutableElement createCreateGenericMethod(NodeData node, Modifier visibility) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(), node.getNodeType(), "createGeneric");
if (visibility != null) {
method.getModifiers().add(visibility);
}
method.getModifiers().add(Modifier.STATIC);
method.addParameter(new CodeVariableElement(node.getNodeType(), THIS_NODE_LOCAL_VAR_NAME));
CodeTreeBuilder body = method.createBuilder();
SpecializationData found = null;
List<SpecializationData> specializations = node.getSpecializations();
for (int i = 0; i < specializations.size(); i++) {
if (specializations.get(i).isReachable()) {
found = specializations.get(i);
}
}
if (found == null) {
body.startThrow().startNew(getContext().getType(UnsupportedOperationException.class)).end().end();
} else {
body.startReturn().startCall(nodeSpecializationClassName(found), CREATE_SPECIALIZATION_NAME).startGroup().string(THIS_NODE_LOCAL_VAR_NAME).end().end().end();
}
return method;
}
}
private class NodeBaseFactory extends ClassElementFactory<SpecializationData> {
public NodeBaseFactory(ProcessorContext context) {
super(context);
}
@Override
protected CodeTypeElement create(SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTypeElement clazz = createClass(node, modifiers(PRIVATE, ABSTRACT, STATIC), baseClassName(node), node.getNodeType(), false);
for (NodeChildData child : node.getChildren()) {
clazz.add(createChildField(child));
if (child.getAccessElement() != null && child.getAccessElement().getModifiers().contains(Modifier.ABSTRACT)) {
ExecutableElement getter = (ExecutableElement) child.getAccessElement();
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), getter);
method.getModifiers().remove(Modifier.ABSTRACT);
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn().string("this.").string(child.getName()).end();
clazz.add(method);
}
}
for (NodeFieldData field : node.getFields()) {
if (!field.isGenerated()) {
continue;
}
clazz.add(new CodeVariableElement(modifiers(PROTECTED, FINAL), field.getType(), field.getName()));
if (field.getGetter() != null && field.getGetter().getModifiers().contains(Modifier.ABSTRACT)) {
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), field.getGetter());
method.getModifiers().remove(Modifier.ABSTRACT);
method.createBuilder().startReturn().string("this.").string(field.getName()).end();
clazz.add(method);
}
}
for (String assumption : node.getAssumptions()) {
clazz.add(createAssumptionField(assumption));
}
createConstructors(node, clazz);
return clazz;
}
@Override
protected void createChildren(SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTypeElement clazz = getElement();
SpecializationGroup rootGroup = createSpecializationGroups(node);
if (node.needsRewrites(context)) {
if (node.isPolymorphic()) {
CodeVariableElement var = new CodeVariableElement(modifiers(PROTECTED), clazz.asType(), "next0");
var.getAnnotationMirrors().add(new CodeAnnotationMirror(getContext().getTruffleTypes().getChildAnnotation()));
clazz.add(var);
CodeExecutableElement genericCachedExecute = createCachedExecute(node, node.getPolymorphicSpecialization());
clazz.add(genericCachedExecute);
getElement().add(createUpdateTypes(clazz.asType()));
}
for (CodeExecutableElement method : createImplicitChildrenAccessors()) {
clazz.add(method);
}
clazz.add(createGenericExecuteAndSpecialize(node, rootGroup));
clazz.add(createInfoMessage(node));
}
if (needsInvokeCopyConstructorMethod()) {
clazz.add(createCopy(clazz.asType(), null));
}
if (node.getGenericSpecialization() != null && node.getGenericSpecialization().isReachable()) {
clazz.add(createGenericExecute(node, rootGroup));
}
}
protected boolean needsInvokeCopyConstructorMethod() {
return getModel().getNode().isPolymorphic();
}
protected CodeExecutableElement createCopy(TypeMirror baseType, SpecializationData specialization) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), baseType, COPY_WITH_CONSTRUCTOR_NAME);
if (specialization == null) {
method.getModifiers().add(ABSTRACT);
} else {
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startNew(getElement().asType());
builder.string("this");
for (ActualParameter param : getImplicitTypeParameters(specialization)) {
builder.string(implicitTypeName(param));
}
builder.end().end();
}
return method;
}
private List<CodeExecutableElement> createImplicitChildrenAccessors() {
NodeData node = getModel().getNode();
List<Set<TypeData>> prototype = Collections.nCopies(node.getGenericSpecialization().getParameters().size(), null);
List<Set<TypeData>> expectTypes = new ArrayList<>(prototype);
for (ExecutableTypeData executableType : node.getExecutableTypes()) {
for (int i = 0; i < executableType.getEvaluatedCount(); i++) {
ActualParameter parameter = executableType.getSignatureParameter(i);
if (i >= expectTypes.size()) {
break;
}
Set<TypeData> types = expectTypes.get(i);
if (types == null) {
types = new TreeSet<>();
expectTypes.set(i, types);
}
types.add(parameter.getTypeSystemType());
}
}
List<CodeExecutableElement> methods = new ArrayList<>();
List<Set<TypeData>> visitedList = new ArrayList<>(prototype);
for (SpecializationData spec : node.getSpecializations()) {
int signatureIndex = -1;
for (ActualParameter param : spec.getParameters()) {
if (!param.getSpecification().isSignature()) {
continue;
}
signatureIndex++;
Set<TypeData> visitedTypeData = visitedList.get(signatureIndex);
if (visitedTypeData == null) {
visitedTypeData = new TreeSet<>();
visitedList.set(signatureIndex, visitedTypeData);
}
if (visitedTypeData.contains(param.getTypeSystemType())) {
continue;
}
visitedTypeData.add(param.getTypeSystemType());
Set<TypeData> expect = expectTypes.get(signatureIndex);
if (expect == null) {
expect = Collections.emptySet();
}
methods.addAll(createExecuteChilds(param, expect));
}
}
return methods;
}
private CodeTree truffleBooleanOption(CodeTreeBuilder parent, String name) {
CodeTreeBuilder builder = parent.create();
builder.staticReference(getContext().getTruffleTypes().getTruffleOptions(), name);
return builder.getRoot();
}
private Element createInfoMessage(NodeData node) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, STATIC), getContext().getType(String.class), "createInfo0");
method.addParameter(new CodeVariableElement(getContext().getType(String.class), "message"));
addInternalValueParameters(method, node.getGenericSpecialization(), false, false);
CodeTreeBuilder builder = method.createBuilder();
builder.startIf().tree(truffleBooleanOption(builder, TruffleTypes.OPTION_DETAILED_REWRITE_REASONS)).end();
builder.startBlock();
builder.startStatement().string("StringBuilder builder = new StringBuilder(message)").end();
builder.startStatement().startCall("builder", "append").doubleQuote(" (").end().end();
String sep = null;
for (ActualParameter parameter : node.getGenericSpecialization().getSignatureParameters()) {
builder.startStatement();
builder.string("builder");
if (sep != null) {
builder.startCall(".append").doubleQuote(sep).end();
}
builder.startCall(".append").doubleQuote(parameter.getLocalName()).end();
builder.startCall(".append").doubleQuote(" = ").end();
builder.startCall(".append").string(parameter.getLocalName()).end();
builder.end();
if (!Utils.isPrimitive(parameter.getType())) {
builder.startIf().string(parameter.getLocalName() + " != null").end();
builder.startBlock();
}
builder.startStatement();
if (Utils.isPrimitive(parameter.getType())) {
builder.startCall("builder.append").doubleQuote(" (" + Utils.getSimpleName(parameter.getType()) + ")").end();
} else {
builder.startCall("builder.append").doubleQuote(" (").end();
builder.startCall(".append").string(parameter.getLocalName() + ".getClass().getSimpleName()").end();
builder.startCall(".append").doubleQuote(")").end();
}
builder.end();
if (!Utils.isPrimitive(parameter.getType())) {
builder.end();
}
sep = ", ";
}
builder.startStatement().startCall("builder", "append").doubleQuote(")").end().end();
builder.startReturn().string("builder.toString()").end();
builder.end();
builder.startElseBlock();
builder.startReturn().string("message").end();
builder.end();
return method;
}
private CodeExecutableElement createCachedExecute(NodeData node, SpecializationData polymorph) {
CodeExecutableElement cachedExecute = new CodeExecutableElement(modifiers(PROTECTED, ABSTRACT), polymorph.getReturnType().getType(), EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameters(cachedExecute, polymorph, true, false);
ExecutableTypeData sourceExecutableType = node.findExecutableType(polymorph.getReturnType().getTypeSystemType(), 0);
boolean sourceThrowsUnexpected = sourceExecutableType != null && sourceExecutableType.hasUnexpectedValue(getContext());
if (sourceThrowsUnexpected && sourceExecutableType.getType().equals(node.getGenericSpecialization().getReturnType().getTypeSystemType())) {
sourceThrowsUnexpected = false;
}
if (sourceThrowsUnexpected) {
cachedExecute.getThrownTypes().add(getContext().getType(UnexpectedResultException.class));
}
return cachedExecute;
}
private void createConstructors(NodeData node, CodeTypeElement clazz) {
List<ExecutableElement> constructors = findUserConstructors(node.getNodeType());
ExecutableElement sourceSectionConstructor = null;
if (constructors.isEmpty()) {
clazz.add(createUserConstructor(clazz, null));
} else {
for (ExecutableElement constructor : constructors) {
clazz.add(createUserConstructor(clazz, constructor));
if (NodeParser.isSourceSectionConstructor(context, constructor)) {
sourceSectionConstructor = constructor;
}
}
}
if (node.needsRewrites(getContext())) {
clazz.add(createCopyConstructor(clazz, findCopyConstructor(node.getNodeType()), sourceSectionConstructor));
}
}
private CodeExecutableElement createUserConstructor(CodeTypeElement type, ExecutableElement superConstructor) {
CodeExecutableElement method = new CodeExecutableElement(null, type.getSimpleName().toString());
CodeTreeBuilder builder = method.createBuilder();
NodeData node = getModel().getNode();
if (superConstructor != null) {
for (VariableElement param : superConstructor.getParameters()) {
method.getParameters().add(CodeVariableElement.clone(param));
}
}
if (superConstructor != null) {
builder.startStatement().startSuperCall();
for (VariableElement param : superConstructor.getParameters()) {
builder.string(param.getSimpleName().toString());
}
builder.end().end();
}
for (VariableElement var : type.getFields()) {
NodeChildData child = node.findChild(var.getSimpleName().toString());
if (child != null) {
method.getParameters().add(new CodeVariableElement(child.getOriginalType(), child.getName()));
} else {
method.getParameters().add(new CodeVariableElement(var.asType(), var.getSimpleName().toString()));
}
builder.startStatement();
String fieldName = var.getSimpleName().toString();
CodeTree init = createStaticCast(builder, child, fieldName);
builder.string("this.").string(fieldName).string(" = ").tree(init);
builder.end();
}
return method;
}
private CodeTree createStaticCast(CodeTreeBuilder parent, NodeChildData child, String fieldName) {
NodeData parentNode = getModel().getNode();
if (child != null) {
CreateCastData createCast = parentNode.findCast(child.getName());
if (createCast != null) {
return createTemplateMethodCall(parent, null, parentNode.getGenericSpecialization(), createCast, null, fieldName);
}
}
return CodeTreeBuilder.singleString(fieldName);
}
private CodeExecutableElement createCopyConstructor(CodeTypeElement type, ExecutableElement superConstructor, ExecutableElement sourceSectionConstructor) {
CodeExecutableElement method = new CodeExecutableElement(null, type.getSimpleName().toString());
CodeTreeBuilder builder = method.createBuilder();
method.getParameters().add(new CodeVariableElement(type.asType(), "copy"));
if (superConstructor != null) {
builder.startStatement().startSuperCall().string("copy").end().end();
} else if (sourceSectionConstructor != null) {
builder.startStatement().startSuperCall().string("copy.getSourceSection()").end().end();
}
for (VariableElement var : type.getFields()) {
builder.startStatement();
final String varName = var.getSimpleName().toString();
final TypeMirror varType = var.asType();
String copyAccess = "copy." + varName;
if (Utils.isAssignable(getContext(), varType, getContext().getTruffleTypes().getNodeArray())) {
copyAccess += ".clone()";
}
CodeTree init = CodeTreeBuilder.singleString(copyAccess);
builder.startStatement().string("this.").string(varName).string(" = ").tree(init).end();
}
return method;
}
private CodeVariableElement createAssumptionField(String assumption) {
CodeVariableElement var = new CodeVariableElement(getContext().getTruffleTypes().getAssumption(), assumption);
var.getModifiers().add(Modifier.FINAL);
return var;
}
private CodeVariableElement createChildField(NodeChildData child) {
TypeMirror type = child.getNodeType();
CodeVariableElement var = new CodeVariableElement(type, child.getName());
var.getModifiers().add(Modifier.PROTECTED);
DeclaredType annotationType;
if (child.getCardinality() == Cardinality.MANY) {
var.getModifiers().add(Modifier.FINAL);
annotationType = getContext().getTruffleTypes().getChildrenAnnotation();
} else {
annotationType = getContext().getTruffleTypes().getChildAnnotation();
}
var.getAnnotationMirrors().add(new CodeAnnotationMirror(annotationType));
return var;
}
private CodeExecutableElement createGenericExecuteAndSpecialize(final NodeData node, SpecializationGroup rootGroup) {
TypeMirror genericReturnType = node.getGenericSpecialization().getReturnType().getType();
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, FINAL), genericReturnType, EXECUTE_SPECIALIZE_NAME);
method.addParameter(new CodeVariableElement(getContext().getType(int.class), "minimumState"));
addInternalValueParameters(method, node.getGenericSpecialization(), true, false);
method.addParameter(new CodeVariableElement(getContext().getType(String.class), "reason"));
CodeTreeBuilder builder = method.createBuilder();
builder.startStatement();
builder.startStaticCall(getContext().getTruffleTypes().getCompilerAsserts(), "neverPartOfCompilation").end();
builder.end();
String currentNode = "this";
for (SpecializationData specialization : node.getSpecializations()) {
if (!specialization.getExceptions().isEmpty()) {
currentNode = "current";
builder.declaration(baseClassName(node), currentNode, "this");
break;
}
}
builder.startStatement().string("String message = ").startCall("createInfo0").string("reason");
addInternalValueParameterNames(builder, node.getGenericSpecialization(), node.getGenericSpecialization(), null, false, null);
builder.end().end();
final String currentNodeVar = currentNode;
builder.tree(createExecuteTree(builder, node.getGenericSpecialization(), rootGroup, true, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createGenericInvokeAndSpecialize(b, node.getGenericSpecialization(), current, currentNodeVar);
}
}, null, false, true, false));
boolean firstUnreachable = true;
for (SpecializationData current : node.getSpecializations()) {
if (current.isReachable()) {
continue;
}
if (firstUnreachable) {
emitEncounteredSynthetic(builder, current);
firstUnreachable = false;
}
}
emitUnreachableSpecializations(builder, node);
return method;
}
private SpecializationGroup createSpecializationGroups(final NodeData node) {
List<SpecializationData> specializations = node.getSpecializations();
List<SpecializationData> filteredSpecializations = new ArrayList<>();
for (SpecializationData current : specializations) {
if (current.isUninitialized() || current.isPolymorphic() || !current.isReachable()) {
continue;
}
filteredSpecializations.add(current);
}
return SpecializationGroup.create(filteredSpecializations);
}
private CodeExecutableElement createGenericExecute(NodeData node, SpecializationGroup group) {
TypeMirror genericReturnType = node.getGenericSpecialization().getReturnType().getType();
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, FINAL), genericReturnType, EXECUTE_GENERIC_NAME);
if (!node.needsFrame(getContext())) {
method.getAnnotationMirrors().add(new CodeAnnotationMirror(getContext().getTruffleTypes().getSlowPath()));
}
addInternalValueParameters(method, node.getGenericSpecialization(), node.needsFrame(getContext()), false);
final CodeTreeBuilder builder = method.createBuilder();
builder.tree(createExecuteTree(builder, node.getGenericSpecialization(), group, false, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createGenericInvoke(builder, current.getNode().getGenericSpecialization(), current);
}
}, null, false, true, false));
emitUnreachableSpecializations(builder, node);
return method;
}
private void emitUnreachableSpecializations(final CodeTreeBuilder builder, NodeData node) {
for (SpecializationData current : node.getSpecializations()) {
if (current.isReachable()) {
continue;
}
builder.string("// unreachable ").string(current.getId()).newLine();
}
}
protected CodeTree createExecuteTree(CodeTreeBuilder outerParent, final SpecializationData source, final SpecializationGroup group, final boolean checkMinimumState,
final CodeBlock<SpecializationData> guardedblock, final CodeTree elseBlock, boolean forceElse, final boolean emitAssumptions, final boolean typedCasts) {
return guard(outerParent, source, group, checkMinimumState, new CodeBlock<Integer>() {
public CodeTree create(CodeTreeBuilder parent, Integer ifCount) {
CodeTreeBuilder builder = parent.create();
if (group.getSpecialization() != null) {
builder.tree(guardedblock.create(builder, group.getSpecialization()));
assert group.getChildren().isEmpty() : "missed a specialization";
} else {
for (SpecializationGroup childGroup : group.getChildren()) {
builder.tree(createExecuteTree(builder, source, childGroup, checkMinimumState, guardedblock, null, false, emitAssumptions, typedCasts));
}
}
return builder.getRoot();
}
}, elseBlock, forceElse, emitAssumptions, typedCasts);
}
private CodeTree guard(CodeTreeBuilder parent, SpecializationData source, SpecializationGroup group, boolean checkMinimumState, CodeBlock<Integer> bodyBlock, CodeTree elseBlock,
boolean forceElse, boolean emitAssumptions, boolean typedCasts) {
CodeTreeBuilder builder = parent.create();
int ifCount = emitGuards(builder, source, group, checkMinimumState, emitAssumptions, typedCasts);
if (isReachableGroup(group, ifCount, checkMinimumState)) {
builder.tree(bodyBlock.create(builder, ifCount));
}
builder.end(ifCount);
if (elseBlock != null) {
if (ifCount > 0 || forceElse) {
builder.tree(elseBlock);
}
}
return builder.getRoot();
}
private boolean isReachableGroup(SpecializationGroup group, int ifCount, boolean checkMinimumState) {
if (ifCount != 0) {
return true;
}
SpecializationGroup previous = group.getPreviousGroup();
if (previous == null || previous.findElseConnectableGuards(checkMinimumState).isEmpty()) {
return true;
}
/*
* Hacky else case. In this case the specialization is not reachable due to previous
* else branch. This is only true if the minimum state is not checked.
*/
if (previous.getGuards().size() == 1 && previous.getTypeGuards().isEmpty() && previous.getAssumptions().isEmpty() && !checkMinimumState &&
(previous.getParent() == null || previous.getMaxSpecializationIndex() != previous.getParent().getMaxSpecializationIndex())) {
return false;
}
return true;
}
private int emitGuards(CodeTreeBuilder builder, SpecializationData source, SpecializationGroup group, boolean checkMinimumState, boolean emitAssumptions, boolean typedCasts) {
NodeData node = source.getNode();
CodeTreeBuilder guardsBuilder = builder.create();
CodeTreeBuilder castBuilder = builder.create();
CodeTreeBuilder guardsCastBuilder = builder.create();
String guardsAnd = "";
String guardsCastAnd = "";
boolean minimumState = checkMinimumState;
if (minimumState) {
int groupMaxIndex = group.getUncheckedSpecializationIndex();
if (groupMaxIndex > -1) {
guardsBuilder.string(guardsAnd);
guardsBuilder.string("minimumState < " + groupMaxIndex);
guardsAnd = " && ";
}
}
if (emitAssumptions) {
for (String assumption : group.getAssumptions()) {
guardsBuilder.string(guardsAnd);
guardsBuilder.string("this");
guardsBuilder.string(".").string(assumption).string(".isValid()");
guardsAnd = " && ";
}
}
for (TypeGuard typeGuard : group.getTypeGuards()) {
ActualParameter valueParam = source.getSignatureParameter(typeGuard.getSignatureIndex());
if (valueParam == null) {
/*
* If used inside a execute evaluated method then the value param may not exist.
* In that case we assume that the value is executed generic or of the current
* specialization.
*/
if (group.getSpecialization() != null) {
valueParam = group.getSpecialization().getSignatureParameter(typeGuard.getSignatureIndex());
} else {
valueParam = node.getGenericSpecialization().getSignatureParameter(typeGuard.getSignatureIndex());
}
}
NodeExecutionData execution = valueParam.getSpecification().getExecution();
CodeTree implicitGuard = createTypeGuard(guardsBuilder, execution, valueParam, typeGuard.getType(), typedCasts);
if (implicitGuard != null) {
guardsBuilder.string(guardsAnd);
guardsBuilder.tree(implicitGuard);
guardsAnd = " && ";
}
CodeTree cast = createCast(castBuilder, execution, valueParam, typeGuard.getType(), checkMinimumState, typedCasts);
if (cast != null) {
castBuilder.tree(cast);
}
}
List<GuardData> elseGuards = group.findElseConnectableGuards(checkMinimumState);
for (GuardData guard : group.getGuards()) {
if (elseGuards.contains(guard)) {
continue;
}
if (needsTypeGuard(source, group, guard)) {
guardsCastBuilder.tree(createMethodGuard(builder, guardsCastAnd, source, guard));
guardsCastAnd = " && ";
} else {
guardsBuilder.tree(createMethodGuard(builder, guardsAnd, source, guard));
guardsAnd = " && ";
}
}
int ifCount = startGuardIf(builder, guardsBuilder, 0, elseGuards);
builder.tree(castBuilder.getRoot());
ifCount = startGuardIf(builder, guardsCastBuilder, ifCount, elseGuards);
return ifCount;
}
private int startGuardIf(CodeTreeBuilder builder, CodeTreeBuilder conditionBuilder, int ifCount, List<GuardData> elseGuard) {
int newIfCount = ifCount;
if (!conditionBuilder.isEmpty()) {
if (ifCount == 0 && !elseGuard.isEmpty()) {
builder.startElseIf();
} else {
builder.startIf();
}
builder.tree(conditionBuilder.getRoot());
builder.end().startBlock();
newIfCount++;
} else if (ifCount == 0 && !elseGuard.isEmpty()) {
builder.startElseBlock();
newIfCount++;
}
return newIfCount;
}
private boolean needsTypeGuard(SpecializationData source, SpecializationGroup group, GuardData guard) {
int signatureIndex = 0;
for (ActualParameter parameter : guard.getParameters()) {
if (!parameter.getSpecification().isSignature()) {
continue;
}
TypeGuard typeGuard = group.findTypeGuard(signatureIndex);
if (typeGuard != null) {
TypeData requiredType = typeGuard.getType();
ActualParameter sourceParameter = source.findParameter(parameter.getLocalName());
if (sourceParameter == null) {
sourceParameter = source.getNode().getGenericSpecialization().findParameter(parameter.getLocalName());
}
if (Utils.needsCastTo(getContext(), sourceParameter.getType(), requiredType.getPrimitiveType())) {
return true;
}
}
signatureIndex++;
}
return false;
}
private CodeTree createTypeGuard(CodeTreeBuilder parent, NodeExecutionData execution, ActualParameter source, TypeData targetType, boolean typedCasts) {
NodeData node = execution.getChild().getNodeData();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
TypeData sourceType = source.getTypeSystemType();
if (!sourceType.needsCastTo(getContext(), targetType)) {
return null;
}
builder.startGroup();
if (execution.isShortCircuit()) {
ActualParameter shortCircuit = source.getPreviousParameter();
assert shortCircuit != null;
builder.string("(");
builder.string("!").string(valueName(shortCircuit));
builder.string(" || ");
}
String castMethodName;
String castTypeName = null;
List<TypeData> types = getModel().getNode().getTypeSystem().lookupSourceTypes(targetType);
if (types.size() > 1) {
castMethodName = TypeSystemCodeGenerator.isImplicitTypeMethodName(targetType);
if (typedCasts) {
castTypeName = implicitTypeName(source);
}
} else {
castMethodName = TypeSystemCodeGenerator.isTypeMethodName(targetType);
}
startCallTypeSystemMethod(getContext(), builder, node.getTypeSystem(), castMethodName);
builder.string(valueName(source));
if (castTypeName != null) {
builder.string(castTypeName);
}
builder.end().end(); // call
if (execution.isShortCircuit()) {
builder.string(")");
}
builder.end(); // group
return builder.getRoot();
}
// TODO merge redundancies with #createTypeGuard
private CodeTree createCast(CodeTreeBuilder parent, NodeExecutionData execution, ActualParameter source, TypeData targetType, boolean checkMinimumState, boolean typedCasts) {
NodeData node = execution.getChild().getNodeData();
TypeData sourceType = source.getTypeSystemType();
if (!sourceType.needsCastTo(getContext(), targetType)) {
return null;
}
CodeTree condition = null;
if (execution.isShortCircuit()) {
ActualParameter shortCircuit = source.getPreviousParameter();
assert shortCircuit != null;
condition = CodeTreeBuilder.singleString(valueName(shortCircuit));
}
String castMethodName;
String castTypeName = null;
List<TypeData> types = getModel().getNode().getTypeSystem().lookupSourceTypes(targetType);
if (types.size() > 1) {
castMethodName = TypeSystemCodeGenerator.asImplicitTypeMethodName(targetType);
if (typedCasts) {
castTypeName = implicitTypeName(source);
}
} else {
castMethodName = TypeSystemCodeGenerator.asTypeMethodName(targetType);
}
List<CodeTree> args = new ArrayList<>();
args.add(CodeTreeBuilder.singleString(valueName(source)));
if (castTypeName != null) {
args.add(CodeTreeBuilder.singleString(castTypeName));
}
CodeTree value = createCallTypeSystemMethod(context, parent, node, castMethodName, args.toArray(new CodeTree[0]));
CodeTreeBuilder builder = parent.create();
builder.tree(createLazyAssignment(parent, castValueName(source), targetType.getPrimitiveType(), condition, value));
if (checkMinimumState && types.size() > 1) {
CodeTree castType = createCallTypeSystemMethod(context, parent, node, TypeSystemCodeGenerator.getImplicitClass(targetType), CodeTreeBuilder.singleString(valueName(source)));
builder.tree(createLazyAssignment(builder, implicitTypeName(source), getContext().getType(Class.class), condition, castType));
}
return builder.getRoot();
}
private CodeTree createMethodGuard(CodeTreeBuilder parent, String prefix, SpecializationData source, GuardData guard) {
CodeTreeBuilder builder = parent.create();
builder.string(prefix);
if (guard.isNegated()) {
builder.string("!");
}
builder.tree(createTemplateMethodCall(builder, null, source, guard, null));
return builder.getRoot();
}
protected CodeTree createGenericInvoke(CodeTreeBuilder parent, SpecializationData source, SpecializationData current) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (current.getMethod() == null) {
emitEncounteredSynthetic(builder, current);
} else {
builder.startReturn().tree(createTemplateMethodCall(builder, null, source, current, null)).end();
}
return encloseThrowsWithFallThrough(current, builder.getRoot());
}
protected CodeTree createGenericInvokeAndSpecialize(CodeTreeBuilder parent, SpecializationData source, SpecializationData current, String currentNodeVar) {
CodeTreeBuilder builder = parent.create();
CodeTreeBuilder prefix = parent.create();
NodeData node = current.getNode();
if (current.isGeneric() && node.isPolymorphic()) {
builder.startIf().string(currentNodeVar).string(".next0 == null && minimumState > 0").end().startBlock();
builder.tree(createRewritePolymorphic(builder, node, currentNodeVar));
builder.end();
builder.startElseBlock();
builder.tree(createRewriteGeneric(builder, source, current, currentNodeVar));
builder.end();
} else {
if (current.getExceptions().isEmpty()) {
builder.tree(createGenericInvoke(builder, source, current, createReplaceCall(builder, current, currentNodeVar, currentNodeVar, null), null));
} else {
builder.startStatement().string(currentNodeVar).string(" = ").tree(createReplaceCall(builder, current, currentNodeVar, currentNodeVar, null)).end();
builder.tree(createGenericInvoke(builder, source, current, null, CodeTreeBuilder.singleString(currentNodeVar)));
}
}
CodeTreeBuilder root = parent.create();
root.tree(prefix.getRoot());
root.tree(encloseThrowsWithFallThrough(current, builder.getRoot()));
return root.getRoot();
}
private CodeTree createRewriteGeneric(CodeTreeBuilder parent, SpecializationData source, SpecializationData current, String currentNode) {
NodeData node = current.getNode();
CodeTreeBuilder builder = parent.create();
builder.declaration(getContext().getTruffleTypes().getNode(), "root", currentNode);
builder.startIf().string(currentNode).string(".next0 != null").end().startBlock();
/*
* Communicates to the caller of executeAndSpecialize that it was rewritten to generic.
* Its important that this is used instead of the currentNode since the caller is this.
* CurrentNode may not be this anymore at this place.
*/
builder.statement("this.next0 = null");
builder.tree(createFindRoot(builder, node, false));
builder.end();
builder.end();
builder.tree(createGenericInvoke(builder, source, current, createReplaceCall(builder, current, "root", "(" + baseClassName(node) + ") root", null), null));
return builder.getRoot();
}
protected CodeTree createFindRoot(CodeTreeBuilder parent, NodeData node, boolean countDepth) {
CodeTreeBuilder builder = parent.create();
builder.startDoBlock();
builder.startAssert().string("root != null").string(" : ").doubleQuote("No polymorphic parent node.").end();
builder.startStatement().string("root = ").string("root.getParent()").end();
if (countDepth) {
builder.statement("depth++");
}
builder.end();
builder.startDoWhile();
builder.string("!").startParantheses().instanceOf("root", nodePolymorphicClassName(node)).end();
builder.end();
return builder.getRoot();
}
private CodeTree encloseThrowsWithFallThrough(SpecializationData current, CodeTree tree) {
if (current.getExceptions().isEmpty()) {
return tree;
}
CodeTreeBuilder builder = new CodeTreeBuilder(null);
builder.startTryBlock();
builder.tree(tree);
for (SpecializationThrowsData exception : current.getExceptions()) {
builder.end().startCatchBlock(exception.getJavaClass(), "rewriteEx");
builder.string("// fall through").newLine();
}
builder.end();
return builder.getRoot();
}
protected CodeTree createGenericInvoke(CodeTreeBuilder parent, SpecializationData source, SpecializationData current, CodeTree replaceCall, CodeTree replaceVar) {
assert replaceCall == null || replaceVar == null;
CodeTreeBuilder builder = parent.create();
CodeTree replace = replaceVar;
if (replace == null) {
replace = replaceCall;
}
if (current.isGeneric()) {
builder.startReturn().tree(replace).string(".").startCall(EXECUTE_GENERIC_NAME);
addInternalValueParameterNames(builder, source, current, null, current.getNode().needsFrame(getContext()), null);
builder.end().end();
} else if (current.getMethod() == null) {
if (replaceCall != null) {
builder.statement(replaceCall);
}
emitEncounteredSynthetic(builder, current);
} else if (!current.canBeAccessedByInstanceOf(getContext(), source.getNode().getNodeType())) {
if (replaceCall != null) {
builder.statement(replaceCall);
}
builder.startReturn().tree(createTemplateMethodCall(parent, null, source, current, null)).end();
} else {
replace.add(new CodeTree(CodeTreeKind.STRING, null, "."));
builder.startReturn().tree(createTemplateMethodCall(parent, replace, source, current, null)).end();
}
return builder.getRoot();
}
protected CodeTree createReplaceCall(CodeTreeBuilder builder, SpecializationData current, String target, String source, String message) {
String className = nodeSpecializationClassName(current);
CodeTreeBuilder replaceCall = builder.create();
if (target != null) {
replaceCall.startCall(target, "replace");
} else {
replaceCall.startCall("replace");
}
replaceCall.startGroup().cast(baseClassName(current.getNode())).startCall(className, CREATE_SPECIALIZATION_NAME).string(source);
for (ActualParameter param : current.getSignatureParameters()) {
NodeChildData child = param.getSpecification().getExecution().getChild();
List<TypeData> types = child.getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
if (types.size() > 1) {
replaceCall.string(implicitTypeName(param));
}
}
replaceCall.end().end();
if (message == null) {
replaceCall.string("message");
} else {
replaceCall.doubleQuote(message);
}
replaceCall.end();
return replaceCall.getRoot();
}
private CodeTree createRewritePolymorphic(CodeTreeBuilder parent, NodeData node, String currentNode) {
String polyClassName = nodePolymorphicClassName(node);
String uninitializedName = nodeSpecializationClassName(node.getUninitializedSpecialization());
CodeTreeBuilder builder = parent.create();
builder.declaration(getElement().asType(), "currentCopy", currentNode + "." + COPY_WITH_CONSTRUCTOR_NAME + "()");
for (ActualParameter param : getModel().getSignatureParameters()) {
NodeExecutionData execution = param.getSpecification().getExecution();
builder.startStatement().tree(createAccessChild(execution, "currentCopy")).string(" = ").nullLiteral().end();
}
builder.startStatement().string("currentCopy.next0 = ").startNew(uninitializedName).string("currentCopy").end().end();
builder.declaration(polyClassName, "polymorphic", builder.create().startNew(polyClassName).string(currentNode).end());
builder.startStatement().string("polymorphic.next0 = ").string("currentCopy").end();
builder.startStatement().startCall(currentNode, "replace").string("polymorphic").string("message").end().end();
builder.startReturn();
builder.startCall("currentCopy.next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(builder, node.getGenericSpecialization(), node.getGenericSpecialization(), null, true, null);
builder.end();
builder.end();
return builder.getRoot();
}
protected CodeTree createCastingExecute(CodeTreeBuilder parent, SpecializationData specialization, ExecutableTypeData executable, ExecutableTypeData castExecutable) {
TypeData type = executable.getType();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
NodeData node = specialization.getNode();
ExecutableTypeData castedType = node.findExecutableType(type, 0);
TypeData primaryType = castExecutable.getType();
boolean needsTry = castExecutable.hasUnexpectedValue(getContext());
boolean returnVoid = type.isVoid();
List<ActualParameter> executeParameters = new ArrayList<>();
for (ActualParameter sourceParameter : executable.getSignatureParameters()) {
ActualParameter targetParameter = castExecutable.findParameter(sourceParameter.getLocalName());
if (targetParameter != null) {
executeParameters.add(targetParameter);
}
}
// execute names are enforced no cast
String[] executeParameterNames = new String[executeParameters.size()];
for (int i = 0; i < executeParameterNames.length; i++) {
executeParameterNames[i] = valueName(executeParameters.get(i));
}
builder.tree(createExecuteChildren(builder, executable, specialization, executeParameters, null));
CodeTree primaryExecuteCall = createTemplateMethodCall(builder, null, executable, castExecutable, null, executeParameterNames);
if (needsTry) {
if (!returnVoid) {
builder.declaration(primaryType.getPrimitiveType(), "value");
}
builder.startTryBlock();
if (returnVoid) {
builder.statement(primaryExecuteCall);
} else {
builder.startStatement();
builder.string("value = ");
builder.tree(primaryExecuteCall);
builder.end();
}
builder.end().startCatchBlock(getUnexpectedValueException(), "ex");
if (returnVoid) {
builder.string("// ignore").newLine();
} else {
builder.startReturn();
builder.tree(createExpectExecutableType(node, specialization.getNode().getTypeSystem().getGenericTypeData(), castedType, CodeTreeBuilder.singleString("ex.getResult()")));
builder.end();
}
builder.end();
if (!returnVoid) {
builder.startReturn();
builder.tree(createExpectExecutableType(node, castExecutable.getReturnType().getTypeSystemType(), executable, CodeTreeBuilder.singleString("value")));
builder.end();
}
} else {
if (returnVoid) {
builder.statement(primaryExecuteCall);
} else {
builder.startReturn();
builder.tree(createExpectExecutableType(node, castExecutable.getReturnType().getTypeSystemType(), executable, primaryExecuteCall));
builder.end();
}
}
return builder.getRoot();
}
protected CodeTree createExpectExecutableType(NodeData node, TypeData sourceType, ExecutableTypeData castedType, CodeTree value) {
boolean hasUnexpected = castedType.hasUnexpectedValue(getContext());
return createCastType(node.getTypeSystem(), sourceType, castedType.getType(), hasUnexpected, value);
}
protected CodeTree createExecuteChildren(CodeTreeBuilder parent, ExecutableTypeData sourceExecutable, SpecializationData specialization, List<ActualParameter> targetParameters,
ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = parent.create();
for (ActualParameter targetParameter : targetParameters) {
if (!targetParameter.getSpecification().isSignature()) {
continue;
}
NodeExecutionData execution = targetParameter.getSpecification().getExecution();
CodeTree executionExpressions = createExecuteChild(builder, execution, sourceExecutable, targetParameter, unexpectedParameter);
CodeTree unexpectedTree = createCatchUnexpectedTree(builder, executionExpressions, specialization, sourceExecutable, targetParameter, execution.isShortCircuit(), unexpectedParameter);
CodeTree shortCircuitTree = createShortCircuitTree(builder, unexpectedTree, specialization, targetParameter, unexpectedParameter);
if (shortCircuitTree == executionExpressions) {
if (containsNewLine(executionExpressions)) {
builder.declaration(targetParameter.getType(), valueName(targetParameter));
builder.tree(shortCircuitTree);
} else {
builder.startStatement().type(targetParameter.getType()).string(" ").tree(shortCircuitTree).end();
}
} else {
builder.tree(shortCircuitTree);
}
}
return builder.getRoot();
}
private ExecutableTypeData resolveExecutableType(NodeExecutionData execution, TypeData type) {
ExecutableTypeData targetExecutable = execution.getChild().findExecutableType(getContext(), type);
if (targetExecutable == null) {
targetExecutable = execution.getChild().findAnyGenericExecutableType(getContext());
}
return targetExecutable;
}
private CodeTree createExecuteChild(CodeTreeBuilder parent, NodeExecutionData execution, ExecutableTypeData sourceExecutable, ActualParameter targetParameter,
ActualParameter unexpectedParameter) {
SpecializationData specialization = getModel();
TreeSet<TypeData> possiblePolymorphicTypes = lookupPolymorphicTargetTypes(targetParameter);
if (specialization.isPolymorphic() && targetParameter.getTypeSystemType().isGeneric() && unexpectedParameter == null && possiblePolymorphicTypes.size() > 1) {
CodeTreeBuilder builder = parent.create();
boolean elseIf = false;
for (TypeData possiblePolymoprhicType : possiblePolymorphicTypes) {
if (possiblePolymoprhicType.isGeneric()) {
continue;
}
elseIf = builder.startIf(elseIf);
ActualParameter sourceParameter = sourceExecutable.findParameter(targetParameter.getLocalName());
TypeData sourceType = sourceParameter != null ? sourceParameter.getTypeSystemType() : null;
builder.string(polymorphicTypeName(targetParameter)).string(" == ").typeLiteral(possiblePolymoprhicType.getPrimitiveType());
builder.end().startBlock();
builder.startStatement();
builder.tree(createExecuteChildExpression(parent, execution, sourceType, new ActualParameter(targetParameter, possiblePolymoprhicType), unexpectedParameter, null));
builder.end();
builder.end();
}
builder.startElseBlock();
builder.startStatement().tree(createExecuteChildImplicit(parent, execution, sourceExecutable, targetParameter, unexpectedParameter)).end();
builder.end();
return builder.getRoot();
} else {
return createExecuteChildImplicit(parent, execution, sourceExecutable, targetParameter, unexpectedParameter);
}
}
protected final List<ActualParameter> getImplicitTypeParameters(SpecializationData model) {
List<ActualParameter> parameter = new ArrayList<>();
for (ActualParameter param : model.getSignatureParameters()) {
NodeChildData child = param.getSpecification().getExecution().getChild();
List<TypeData> types = child.getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
if (types.size() > 1) {
parameter.add(param);
}
}
return parameter;
}
protected final TreeSet<TypeData> lookupPolymorphicTargetTypes(ActualParameter param) {
SpecializationData specialization = getModel();
TreeSet<TypeData> possiblePolymorphicTypes = new TreeSet<>();
for (SpecializationData otherSpecialization : specialization.getNode().getSpecializations()) {
if (!otherSpecialization.isSpecialized()) {
continue;
}
ActualParameter otherParameter = otherSpecialization.findParameter(param.getLocalName());
if (otherParameter != null) {
possiblePolymorphicTypes.add(otherParameter.getTypeSystemType());
}
}
return possiblePolymorphicTypes;
}
private CodeTree createExecuteChildImplicit(CodeTreeBuilder parent, NodeExecutionData execution, ExecutableTypeData sourceExecutable, ActualParameter param, ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = parent.create();
ActualParameter sourceParameter = sourceExecutable.findParameter(param.getLocalName());
String childExecuteName = createExecuteChildMethodName(param, sourceParameter != null);
if (childExecuteName != null) {
builder.string(valueName(param));
builder.string(" = ");
builder.startCall(childExecuteName);
for (ActualParameter parameters : sourceExecutable.getParameters()) {
if (parameters.getSpecification().isSignature()) {
continue;
}
builder.string(parameters.getLocalName());
}
if (sourceParameter != null) {
builder.string(valueNameEvaluated(sourceParameter));
}
builder.string(implicitTypeName(param));
builder.end();
} else {
List<TypeData> sourceTypes = execution.getChild().getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
TypeData expectType = sourceParameter != null ? sourceParameter.getTypeSystemType() : null;
if (sourceTypes.size() > 1) {
builder.tree(createExecuteChildImplicitExpressions(parent, param, expectType));
} else {
builder.tree(createExecuteChildExpression(parent, execution, expectType, param, unexpectedParameter, null));
}
}
return builder.getRoot();
}
private String createExecuteChildMethodName(ActualParameter param, boolean expect) {
NodeExecutionData execution = param.getSpecification().getExecution();
NodeChildData child = execution.getChild();
if (child.getExecuteWith().size() > 0) {
return null;
}
List<TypeData> sourceTypes = child.getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
if (sourceTypes.size() <= 1) {
return null;
}
String prefix = expect ? "expect" : "execute";
String suffix = execution.getIndex() > -1 ? String.valueOf(execution.getIndex()) : "";
return prefix + Utils.firstLetterUpperCase(child.getName()) + Utils.firstLetterUpperCase(Utils.getSimpleName(param.getType())) + suffix;
}
private List<CodeExecutableElement> createExecuteChilds(ActualParameter param, Set<TypeData> expectTypes) {
CodeExecutableElement executeMethod = createExecuteChild(param, null);
if (executeMethod == null) {
return Collections.emptyList();
}
List<CodeExecutableElement> childs = new ArrayList<>();
childs.add(executeMethod);
for (TypeData expectType : expectTypes) {
CodeExecutableElement method = createExecuteChild(param, expectType);
if (method != null) {
childs.add(method);
}
}
return childs;
}
private CodeExecutableElement createExecuteChild(ActualParameter param, TypeData expectType) {
String childExecuteName = createExecuteChildMethodName(param, expectType != null);
if (childExecuteName == null) {
return null;
}
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, expectType != null ? STATIC : FINAL), param.getType(), childExecuteName);
method.getThrownTypes().add(getContext().getTruffleTypes().getUnexpectedValueException());
method.addParameter(new CodeVariableElement(getContext().getTruffleTypes().getFrame(), "frameValue"));
if (expectType != null) {
method.addParameter(new CodeVariableElement(expectType.getPrimitiveType(), valueNameEvaluated(param)));
}
method.addParameter(new CodeVariableElement(getContext().getType(Class.class), implicitTypeName(param)));
CodeTreeBuilder builder = method.createBuilder();
builder.declaration(param.getType(), valueName(param));
builder.tree(createExecuteChildImplicitExpressions(builder, param, expectType));
builder.startReturn().string(valueName(param)).end();
return method;
}
private CodeTree createExecuteChildImplicitExpressions(CodeTreeBuilder parent, ActualParameter targetParameter, TypeData expectType) {
CodeTreeBuilder builder = parent.create();
NodeData node = getModel().getNode();
NodeExecutionData execution = targetParameter.getSpecification().getExecution();
List<TypeData> sourceTypes = node.getTypeSystem().lookupSourceTypes(targetParameter.getTypeSystemType());
boolean elseIf = false;
int index = 0;
for (TypeData sourceType : sourceTypes) {
if (index < sourceTypes.size() - 1) {
elseIf = builder.startIf(elseIf);
builder.string(implicitTypeName(targetParameter)).string(" == ").typeLiteral(sourceType.getPrimitiveType());
builder.end();
builder.startBlock();
} else {
builder.startElseBlock();
}
ExecutableTypeData implictExecutableTypeData = execution.getChild().findExecutableType(getContext(), sourceType);
if (implictExecutableTypeData == null) {
/*
* For children with executeWith.size() > 0 an executable type may not exist so
* use the generic executable type which is guaranteed to exist. An expect call
* is inserted automatically by #createExecuteExpression.
*/
implictExecutableTypeData = execution.getChild().getNodeData().findExecutableType(node.getTypeSystem().getGenericTypeData(), execution.getChild().getExecuteWith().size());
}
ImplicitCastData cast = execution.getChild().getNodeData().getTypeSystem().lookupCast(sourceType, targetParameter.getTypeSystemType());
CodeTree execute = createExecuteChildExpression(builder, execution, expectType, targetParameter, null, cast);
builder.statement(execute);
builder.end();
index++;
}
return builder.getRoot();
}
private CodeTree createExecuteChildExpression(CodeTreeBuilder parent, NodeExecutionData execution, TypeData sourceParameterType, ActualParameter targetParameter,
ActualParameter unexpectedParameter, ImplicitCastData cast) {
// assignments: targetType <- castTargetType <- castSourceType <- sourceType
TypeData sourceType = sourceParameterType;
TypeData targetType = targetParameter.getTypeSystemType();
TypeData castSourceType = targetType;
TypeData castTargetType = targetType;
if (cast != null) {
castSourceType = cast.getSourceType();
castTargetType = cast.getTargetType();
}
CodeTree expression;
if (sourceType == null) {
ExecutableTypeData targetExecutable = resolveExecutableType(execution, castSourceType);
expression = createExecuteChildExpression(parent, execution, targetExecutable, unexpectedParameter);
sourceType = targetExecutable.getType();
} else {
expression = CodeTreeBuilder.singleString(valueNameEvaluated(targetParameter));
}
// target = expectTargetType(implicitCast(expectCastSourceType(source)))
TypeSystemData typeSystem = execution.getChild().getNodeData().getTypeSystem();
expression = createExpectType(typeSystem, sourceType, castSourceType, expression);
expression = createImplicitCast(parent, typeSystem, cast, expression);
expression = createExpectType(typeSystem, castTargetType, targetType, expression);
CodeTreeBuilder builder = parent.create();
builder.string(valueName(targetParameter));
builder.string(" = ");
builder.tree(expression);
return builder.getRoot();
}
private CodeTree createImplicitCast(CodeTreeBuilder parent, TypeSystemData typeSystem, ImplicitCastData cast, CodeTree expression) {
if (cast == null) {
return expression;
}
CodeTreeBuilder builder = parent.create();
startCallTypeSystemMethod(getContext(), builder, typeSystem, cast.getMethodName());
builder.tree(expression);
builder.end().end();
return builder.getRoot();
}
private boolean containsNewLine(CodeTree tree) {
if (tree.getCodeKind() == CodeTreeKind.NEW_LINE) {
return true;
}
for (CodeTree codeTree : tree.getEnclosedElements()) {
if (containsNewLine(codeTree)) {
return true;
}
}
return false;
}
private boolean hasUnexpected(ActualParameter sourceParameter, ActualParameter targetParameter, ActualParameter unexpectedParameter) {
NodeExecutionData execution = targetParameter.getSpecification().getExecution();
if (getModel().isPolymorphic() && targetParameter.getTypeSystemType().isGeneric() && unexpectedParameter == null) {
// check for other polymorphic types
TreeSet<TypeData> polymorphicTargetTypes = lookupPolymorphicTargetTypes(targetParameter);
if (polymorphicTargetTypes.size() > 1) {
for (TypeData polymorphicTargetType : polymorphicTargetTypes) {
if (hasUnexpectedType(execution, sourceParameter, polymorphicTargetType)) {
return true;
}
}
}
}
if (hasUnexpectedType(execution, sourceParameter, targetParameter.getTypeSystemType())) {
return true;
}
return false;
}
private boolean hasUnexpectedType(NodeExecutionData execution, ActualParameter sourceParameter, TypeData targetType) {
List<TypeData> implicitSourceTypes = getModel().getNode().getTypeSystem().lookupSourceTypes(targetType);
for (TypeData implicitSourceType : implicitSourceTypes) {
TypeData sourceType;
ExecutableTypeData targetExecutable = resolveExecutableType(execution, implicitSourceType);
if (sourceParameter != null) {
sourceType = sourceParameter.getTypeSystemType();
} else {
if (targetExecutable.hasUnexpectedValue(getContext())) {
return true;
}
sourceType = targetExecutable.getType();
}
ImplicitCastData cast = getModel().getNode().getTypeSystem().lookupCast(implicitSourceType, targetType);
if (cast != null) {
if (cast.getSourceType().needsCastTo(getContext(), targetType)) {
return true;
}
}
if (sourceType.needsCastTo(getContext(), targetType)) {
return true;
}
}
return false;
}
private CodeTree createCatchUnexpectedTree(CodeTreeBuilder parent, CodeTree body, SpecializationData specialization, ExecutableTypeData currentExecutable, ActualParameter param,
boolean shortCircuit, ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
ActualParameter sourceParameter = currentExecutable.findParameter(param.getLocalName());
boolean unexpected = hasUnexpected(sourceParameter, param, unexpectedParameter);
if (!unexpected) {
return body;
}
if (!shortCircuit) {
builder.declaration(param.getType(), valueName(param));
}
builder.startTryBlock();
if (containsNewLine(body)) {
builder.tree(body);
} else {
builder.statement(body);
}
builder.end().startCatchBlock(getUnexpectedValueException(), "ex");
SpecializationData generic = specialization.getNode().getGenericSpecialization();
ActualParameter genericParameter = generic.findParameter(param.getLocalName());
List<ActualParameter> genericParameters = generic.getParametersAfter(genericParameter);
builder.tree(createExecuteChildren(parent, currentExecutable, generic, genericParameters, genericParameter));
if (specialization.isPolymorphic()) {
builder.tree(createReturnOptimizeTypes(builder, currentExecutable, specialization, param));
} else {
builder.tree(createReturnExecuteAndSpecialize(builder, currentExecutable, specialization, param,
"Expected " + param.getLocalName() + " instanceof " + Utils.getSimpleName(param.getType())));
}
builder.end(); // catch block
return builder.getRoot();
}
private CodeTree createReturnOptimizeTypes(CodeTreeBuilder parent, ExecutableTypeData currentExecutable, SpecializationData specialization, ActualParameter param) {
NodeData node = specialization.getNode();
SpecializationData polymorphic = node.getPolymorphicSpecialization();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.startStatement().string(polymorphicTypeName(param)).string(" = ").typeLiteral(getContext().getType(Object.class)).end();
builder.startReturn();
CodeTreeBuilder execute = new CodeTreeBuilder(builder);
execute.startCall("next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(execute, specialization, polymorphic, param.getLocalName(), true, null);
execute.end();
TypeData sourceType = polymorphic.getReturnType().getTypeSystemType();
builder.tree(createExpectExecutableType(node, sourceType, currentExecutable, execute.getRoot()));
builder.end();
return builder.getRoot();
}
private CodeTree createExecuteChildExpression(CodeTreeBuilder parent, NodeExecutionData targetExecution, ExecutableTypeData targetExecutable, ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (targetExecution != null) {
builder.tree(createAccessChild(targetExecution, null));
builder.string(".");
}
builder.startCall(targetExecutable.getMethodName());
// TODO this should be merged with #createTemplateMethodCall
int index = 0;
for (ActualParameter parameter : targetExecutable.getParameters()) {
if (!parameter.getSpecification().isSignature()) {
builder.string(parameter.getLocalName());
} else {
if (index < targetExecution.getChild().getExecuteWith().size()) {
NodeChildData child = targetExecution.getChild().getExecuteWith().get(index);
ParameterSpec spec = getModel().getSpecification().findParameterSpec(child.getName());
List<ActualParameter> specializationParams = getModel().findParameters(spec);
if (specializationParams.isEmpty()) {
builder.defaultValue(parameter.getType());
continue;
}
ActualParameter specializationParam = specializationParams.get(0);
TypeData targetType = parameter.getTypeSystemType();
TypeData sourceType = specializationParam.getTypeSystemType();
String localName = specializationParam.getLocalName();
if (unexpectedParameter != null && unexpectedParameter.getLocalName().equals(specializationParam.getLocalName())) {
localName = "ex.getResult()";
sourceType = getModel().getNode().getTypeSystem().getGenericTypeData();
}
CodeTree value = CodeTreeBuilder.singleString(localName);
if (sourceType.needsCastTo(getContext(), targetType)) {
value = createCallTypeSystemMethod(getContext(), builder, getModel().getNode(), TypeSystemCodeGenerator.asTypeMethodName(targetType), value);
}
builder.tree(value);
} else {
builder.defaultValue(parameter.getType());
}
index++;
}
}
builder.end();
return builder.getRoot();
}
private CodeTree createShortCircuitTree(CodeTreeBuilder parent, CodeTree body, SpecializationData specialization, ActualParameter parameter, ActualParameter exceptionParam) {
NodeExecutionData execution = parameter.getSpecification().getExecution();
if (execution == null || !execution.isShortCircuit()) {
return body;
}
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
ActualParameter shortCircuitParam = specialization.getPreviousParam(parameter);
builder.tree(createShortCircuitValue(builder, specialization, execution, shortCircuitParam, exceptionParam));
builder.declaration(parameter.getType(), valueName(parameter), CodeTreeBuilder.createBuilder().defaultValue(parameter.getType()));
builder.startIf().string(shortCircuitParam.getLocalName()).end();
builder.startBlock();
if (containsNewLine(body)) {
builder.tree(body);
} else {
builder.statement(body);
}
builder.end();
return builder.getRoot();
}
private CodeTree createShortCircuitValue(CodeTreeBuilder parent, SpecializationData specialization, NodeExecutionData execution, ActualParameter shortCircuitParam,
ActualParameter exceptionParam) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
int shortCircuitIndex = 0;
for (NodeExecutionData otherExectuion : specialization.getNode().getChildExecutions()) {
if (otherExectuion.isShortCircuit()) {
if (otherExectuion == execution) {
break;
}
shortCircuitIndex++;
}
}
builder.startStatement().type(shortCircuitParam.getType()).string(" ").string(valueName(shortCircuitParam)).string(" = ");
ShortCircuitData shortCircuitData = specialization.getShortCircuits().get(shortCircuitIndex);
builder.tree(createTemplateMethodCall(builder, null, specialization, shortCircuitData, exceptionParam != null ? exceptionParam.getLocalName() : null));
builder.end(); // statement
return builder.getRoot();
}
protected CodeTree createReturnExecuteAndSpecialize(CodeTreeBuilder parent, ExecutableTypeData executable, SpecializationData current, ActualParameter exceptionParam, String reason) {
NodeData node = current.getNode();
SpecializationData generic = node.getGenericSpecialization();
CodeTreeBuilder specializeCall = new CodeTreeBuilder(parent);
specializeCall.startCall(EXECUTE_SPECIALIZE_NAME);
specializeCall.string(String.valueOf(node.getSpecializations().indexOf(current)));
addInternalValueParameterNames(specializeCall, generic, node.getGenericSpecialization(), exceptionParam != null ? exceptionParam.getLocalName() : null, true, null);
specializeCall.doubleQuote(reason);
specializeCall.end().end();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.startReturn();
builder.tree(createExpectExecutableType(node, generic.getReturnType().getTypeSystemType(), executable, specializeCall.getRoot()));
builder.end();
return builder.getRoot();
}
protected final CodeExecutableElement createUpdateTypes(TypeMirror polymorphicType) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED), getContext().getType(void.class), UPDATE_TYPES_NAME);
method.getParameters().add(new CodeVariableElement(polymorphicType, "polymorphic"));
CodeTreeBuilder builder = method.createBuilder();
if (getModel().isPolymorphic()) {
builder.startStatement();
builder.startCall("next0", "updateTypes").string("polymorphic").end();
builder.end();
} else if (getModel().isSpecialized()) {
for (ActualParameter parameter : getModel().getParameters()) {
if (!parameter.getSpecification().isSignature()) {
continue;
}
if (lookupPolymorphicTargetTypes(parameter).size() <= 1) {
continue;
}
builder.startStatement();
builder.startCall("polymorphic", createUpdateTypeName(parameter));
builder.typeLiteral(parameter.getType());
builder.end().end();
}
builder.startStatement().startCall("super", UPDATE_TYPES_NAME).string("polymorphic").end().end();
}
return method;
}
protected String createUpdateTypeName(ActualParameter parameter) {
return "update" + Utils.firstLetterUpperCase(parameter.getLocalName()) + "Type";
}
}
private class PolymorphicNodeFactory extends SpecializedNodeFactory {
public PolymorphicNodeFactory(ProcessorContext context, CodeTypeElement nodeGen) {
super(context, nodeGen);
}
@Override
public CodeTypeElement create(SpecializationData polymorph) {
NodeData node = polymorph.getNode();
TypeMirror baseType = node.getNodeType();
if (nodeGen != null) {
baseType = nodeGen.asType();
}
CodeTypeElement clazz = createClass(node, modifiers(PRIVATE, STATIC, FINAL), nodePolymorphicClassName(node), baseType, false);
clazz.getAnnotationMirrors().add(createNodeInfo(node, NodeCost.POLYMORPHIC));
for (ActualParameter polymorphParameter : polymorph.getSignatureParameters()) {
if (!polymorphParameter.getTypeSystemType().isGeneric()) {
continue;
}
Set<TypeData> types = new HashSet<>();
for (SpecializationData specialization : node.getSpecializations()) {
if (!specialization.isSpecialized()) {
continue;
}
ActualParameter parameter = specialization.findParameter(polymorphParameter.getLocalName());
assert parameter != null;
types.add(parameter.getTypeSystemType());
}
CodeVariableElement var = new CodeVariableElement(modifiers(PRIVATE), getContext().getType(Class.class), polymorphicTypeName(polymorphParameter));
var.getAnnotationMirrors().add(new CodeAnnotationMirror(getContext().getTruffleTypes().getCompilationFinal()));
clazz.add(var);
}
return clazz;
}
@Override
protected void createChildren(SpecializationData specialization) {
CodeTypeElement clazz = getElement();
createConstructors(clazz);
createExecuteMethods(specialization);
getElement().add(createUpdateTypes(nodeGen.asType()));
for (ActualParameter parameter : specialization.getParameters()) {
if (!parameter.getSpecification().isSignature()) {
continue;
}
if (lookupPolymorphicTargetTypes(parameter).size() <= 1) {
continue;
}
getElement().add(createUpdateType(parameter));
}
if (needsInvokeCopyConstructorMethod()) {
clazz.add(createCopy(nodeGen.asType(), specialization));
}
createCachedExecuteMethods(specialization);
}
private ExecutableElement createUpdateType(ActualParameter parameter) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED), getContext().getType(void.class), createUpdateTypeName(parameter));
method.getParameters().add(new CodeVariableElement(getContext().getType(Class.class), "type"));
CodeTreeBuilder builder = method.createBuilder();
String fieldName = polymorphicTypeName(parameter);
builder.startIf().string(fieldName).isNull().end().startBlock();
builder.startStatement().string(fieldName).string(" = ").string("type").end();
builder.end();
builder.startElseIf().string(fieldName).string(" != ").string("type").end();
builder.startBlock();
builder.startStatement().string(fieldName).string(" = ").typeLiteral(getContext().getType(Object.class)).end();
builder.end();
return method;
}
}
private class SpecializedNodeFactory extends NodeBaseFactory {
protected final CodeTypeElement nodeGen;
public SpecializedNodeFactory(ProcessorContext context, CodeTypeElement nodeGen) {
super(context);
this.nodeGen = nodeGen;
}
@Override
public CodeTypeElement create(SpecializationData specialization) {
NodeData node = specialization.getNode();
TypeMirror baseType = node.getNodeType();
if (nodeGen != null) {
baseType = nodeGen.asType();
}
CodeTypeElement clazz = createClass(node, modifiers(PRIVATE, STATIC, FINAL), nodeSpecializationClassName(specialization), baseType, false);
NodeCost cost;
if (specialization.isGeneric()) {
cost = NodeCost.MEGAMORPHIC;
} else if (specialization.isUninitialized()) {
cost = NodeCost.UNINITIALIZED;
} else if (specialization.isPolymorphic()) {
cost = NodeCost.POLYMORPHIC;
} else if (specialization.isSpecialized()) {
cost = NodeCost.MONOMORPHIC;
} else {
throw new AssertionError();
}
clazz.getAnnotationMirrors().add(createNodeInfo(node, cost));
return clazz;
}
protected CodeAnnotationMirror createNodeInfo(NodeData node, NodeCost cost) {
String shortName = node.getShortName();
CodeAnnotationMirror nodeInfoMirror = new CodeAnnotationMirror(getContext().getTruffleTypes().getNodeInfoAnnotation());
if (shortName != null) {
nodeInfoMirror.setElementValue(nodeInfoMirror.findExecutableElement("shortName"), new CodeAnnotationValue(shortName));
}
DeclaredType nodeinfoCost = getContext().getTruffleTypes().getNodeCost();
VariableElement varKind = Utils.findVariableElement(nodeinfoCost, cost.name());
nodeInfoMirror.setElementValue(nodeInfoMirror.findExecutableElement("cost"), new CodeAnnotationValue(varKind));
return nodeInfoMirror;
}
@Override
protected void createChildren(SpecializationData specialization) {
CodeTypeElement clazz = getElement();
createConstructors(clazz);
createExecuteMethods(specialization);
createCachedExecuteMethods(specialization);
if (specialization.getNode().isPolymorphic()) {
getElement().add(createUpdateTypes(nodeGen.asType()));
}
if (needsInvokeCopyConstructorMethod()) {
clazz.add(createCopy(nodeGen.asType(), specialization));
}
if (!specialization.isUninitialized() && specialization.getNode().needsRewrites(context)) {
clazz.add(createCopyConstructorFactoryMethod(nodeGen.asType(), specialization));
} else {
for (ExecutableElement constructor : ElementFilter.constructorsIn(clazz.getEnclosedElements())) {
if (constructor.getParameters().size() == 1 && ((CodeVariableElement) constructor.getParameters().get(0)).getType().equals(nodeGen.asType())) {
// skip copy constructor - not used
continue;
}
clazz.add(createConstructorFactoryMethod(specialization, constructor));
}
}
}
protected void createConstructors(CodeTypeElement clazz) {
TypeElement superTypeElement = Utils.fromTypeMirror(clazz.getSuperclass());
SpecializationData specialization = getModel();
NodeData node = specialization.getNode();
for (ExecutableElement constructor : ElementFilter.constructorsIn(superTypeElement.getEnclosedElements())) {
if (specialization.isUninitialized()) {
// ignore copy constructors for uninitialized if not polymorphic
if (isCopyConstructor(constructor) && !node.isPolymorphic()) {
continue;
}
} else if (node.getUninitializedSpecialization() != null) {
// ignore others than copy constructors for specialized nodes
if (!isCopyConstructor(constructor)) {
continue;
}
}
CodeExecutableElement superConstructor = createSuperConstructor(clazz, constructor);
if (superConstructor == null) {
continue;
}
CodeTree body = superConstructor.getBodyTree();
CodeTreeBuilder builder = superConstructor.createBuilder();
builder.tree(body);
if (node.isPolymorphic()) {
if (specialization.isSpecialized() || specialization.isPolymorphic()) {
builder.statement("this.next0 = copy.next0");
}
}
if (superConstructor != null) {
for (ActualParameter param : getImplicitTypeParameters(getModel())) {
clazz.add(new CodeVariableElement(modifiers(PRIVATE, FINAL), getContext().getType(Class.class), implicitTypeName(param)));
superConstructor.getParameters().add(new CodeVariableElement(getContext().getType(Class.class), implicitTypeName(param)));
builder.startStatement();
builder.string("this.").string(implicitTypeName(param)).string(" = ").string(implicitTypeName(param));
builder.end();
}
clazz.add(superConstructor);
}
}
}
protected void createExecuteMethods(SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTypeElement clazz = getElement();
for (ExecutableTypeData execType : node.getExecutableTypes()) {
if (execType.isFinal()) {
continue;
}
CodeExecutableElement executeMethod = createExecutableTypeOverride(execType, true);
clazz.add(executeMethod);
CodeTreeBuilder builder = executeMethod.getBuilder();
CodeTree result = createExecuteBody(builder, specialization, execType);
if (result != null) {
builder.tree(result);
} else {
clazz.remove(executeMethod);
}
}
}
protected void createCachedExecuteMethods(SpecializationData specialization) {
NodeData node = specialization.getNode();
if (!node.isPolymorphic()) {
return;
}
CodeTypeElement clazz = getElement();
final SpecializationData polymorphic = node.getPolymorphicSpecialization();
ExecutableElement executeCached = nodeGen.getMethod(EXECUTE_POLYMORPHIC_NAME);
CodeExecutableElement executeMethod = CodeExecutableElement.clone(getContext().getEnvironment(), executeCached);
executeMethod.getModifiers().remove(Modifier.ABSTRACT);
CodeTreeBuilder builder = executeMethod.createBuilder();
if (specialization.isGeneric() || specialization.isPolymorphic()) {
builder.startThrow().startNew(getContext().getType(AssertionError.class));
builder.doubleQuote("Should not be reached.");
builder.end().end();
} else if (specialization.isUninitialized()) {
builder.tree(createAppendPolymorphic(builder, specialization));
} else {
CodeTreeBuilder elseBuilder = new CodeTreeBuilder(builder);
elseBuilder.startReturn().startCall("this.next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(elseBuilder, polymorphic, polymorphic, null, true, null);
elseBuilder.end().end();
boolean forceElse = specialization.getExceptions().size() > 0;
builder.tree(createExecuteTree(builder, polymorphic, SpecializationGroup.create(specialization), false, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createGenericInvoke(b, polymorphic, current);
}
}, elseBuilder.getRoot(), forceElse, true, true));
}
clazz.add(executeMethod);
}
private CodeTree createAppendPolymorphic(CodeTreeBuilder parent, SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.tree(createDeoptimize(builder));
builder.declaration(getContext().getTruffleTypes().getNode(), "root", "this");
builder.declaration(getContext().getType(int.class), "depth", "0");
builder.tree(createFindRoot(builder, node, true));
builder.newLine();
builder.startIf().string("depth > ").string(String.valueOf(node.getPolymorphicDepth())).end();
builder.startBlock();
String message = "Polymorphic limit reached (" + node.getPolymorphicDepth() + ")";
String castRoot = "(" + baseClassName(node) + ") root";
builder.tree(createGenericInvoke(builder, node.getPolymorphicSpecialization(), node.getGenericSpecialization(),
createReplaceCall(builder, node.getGenericSpecialization(), "root", castRoot, message), null));
builder.end();
builder.startElseBlock();
builder.startStatement().string("next0 = ");
builder.startNew(nodeSpecializationClassName(node.getUninitializedSpecialization())).string("this").end();
builder.end();
CodeTreeBuilder specializeCall = new CodeTreeBuilder(builder);
specializeCall.startCall(EXECUTE_SPECIALIZE_NAME);
specializeCall.string("0");
addInternalValueParameterNames(specializeCall, specialization, node.getGenericSpecialization(), null, true, null);
specializeCall.startGroup().doubleQuote("Uninitialized polymorphic (").string(" + depth + ").doubleQuote("/" + node.getPolymorphicDepth() + ")").end();
specializeCall.end().end();
builder.declaration(node.getGenericSpecialization().getReturnType().getType(), "result", specializeCall.getRoot());
CodeTree root = builder.create().cast(nodePolymorphicClassName(node)).string("root").getRoot();
builder.startIf().string("this.next0 != null").end().startBlock();
builder.startStatement().string("(").tree(root).string(").").startCall(UPDATE_TYPES_NAME).tree(root).end().end();
builder.end();
if (Utils.isVoid(builder.findMethod().getReturnType())) {
builder.returnStatement();
} else {
builder.startReturn().string("result").end();
}
builder.end();
return builder.getRoot();
}
private CodeTree createExecuteBody(CodeTreeBuilder parent, SpecializationData specialization, ExecutableTypeData execType) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
List<ExecutableTypeData> primaryExecutes = findFunctionalExecutableType(specialization, execType.getEvaluatedCount());
if (primaryExecutes.contains(execType) || primaryExecutes.isEmpty()) {
builder.tree(createFunctionalExecute(builder, specialization, execType));
} else if (needsCastingExecuteMethod(execType)) {
assert !primaryExecutes.isEmpty();
builder.tree(createCastingExecute(builder, specialization, execType, primaryExecutes.get(0)));
} else {
return null;
}
return builder.getRoot();
}
private CodeExecutableElement createExecutableTypeOverride(ExecutableTypeData execType, boolean evaluated) {
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), execType.getMethod());
CodeTreeBuilder builder = method.createBuilder();
int i = 0;
int signatureIndex = -1;
for (VariableElement param : method.getParameters()) {
CodeVariableElement var = CodeVariableElement.clone(param);
ActualParameter actualParameter = i < execType.getParameters().size() ? execType.getParameters().get(i) : null;
String name;
if (actualParameter != null) {
if (actualParameter.getSpecification().isSignature()) {
signatureIndex++;
}
if (evaluated && actualParameter.getSpecification().isSignature()) {
name = valueNameEvaluated(actualParameter);
} else {
name = valueName(actualParameter);
}
int varArgCount = getModel().getSignatureSize() - signatureIndex;
if (evaluated && actualParameter.isTypeVarArgs()) {
ActualParameter baseVarArgs = actualParameter;
name = valueName(baseVarArgs) + "Args";
builder.startAssert().string(name).string(" != null").end();
builder.startAssert().string(name).string(".length == ").string(String.valueOf(varArgCount)).end();
if (varArgCount > 0) {
List<ActualParameter> varArgsParameter = execType.getParameters().subList(i, execType.getParameters().size());
for (ActualParameter varArg : varArgsParameter) {
if (varArgCount <= 0) {
break;
}
TypeMirror type = baseVarArgs.getType();
if (type.getKind() == TypeKind.ARRAY) {
type = ((ArrayType) type).getComponentType();
}
builder.declaration(type, valueNameEvaluated(varArg), name + "[" + varArg.getTypeVarArgsIndex() + "]");
varArgCount--;
}
}
}
} else {
name = "arg" + i;
}
var.setName(name);
method.getParameters().set(i, var);
i++;
}
method.getAnnotationMirrors().clear();
method.getModifiers().remove(Modifier.ABSTRACT);
return method;
}
private boolean needsCastingExecuteMethod(ExecutableTypeData execType) {
if (execType.isAbstract()) {
return true;
}
if (execType.getType().isGeneric()) {
return true;
}
return false;
}
private List<ExecutableTypeData> findFunctionalExecutableType(SpecializationData specialization, int evaluatedCount) {
TypeData primaryType = specialization.getReturnType().getTypeSystemType();
List<ExecutableTypeData> otherTypes = specialization.getNode().getExecutableTypes(evaluatedCount);
List<ExecutableTypeData> filteredTypes = new ArrayList<>();
for (ExecutableTypeData compareType : otherTypes) {
if (!Utils.typeEquals(compareType.getType().getPrimitiveType(), primaryType.getPrimitiveType())) {
continue;
}
filteredTypes.add(compareType);
}
// no direct matches found use generic where the type is Object
if (filteredTypes.isEmpty()) {
for (ExecutableTypeData compareType : otherTypes) {
if (compareType.getType().isGeneric() && !compareType.hasUnexpectedValue(getContext())) {
filteredTypes.add(compareType);
}
}
}
if (filteredTypes.isEmpty()) {
for (ExecutableTypeData compareType : otherTypes) {
if (compareType.getType().isGeneric()) {
filteredTypes.add(compareType);
}
}
}
return filteredTypes;
}
private CodeTree createFunctionalExecute(CodeTreeBuilder parent, final SpecializationData specialization, final ExecutableTypeData executable) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (specialization.isUninitialized()) {
builder.tree(createDeoptimize(builder));
}
builder.tree(createExecuteChildren(builder, executable, specialization, specialization.getParameters(), null));
CodeTree returnSpecialized = null;
if (specialization.findNextSpecialization() != null) {
CodeTreeBuilder returnBuilder = new CodeTreeBuilder(builder);
returnBuilder.tree(createDeoptimize(builder));
returnBuilder.tree(createReturnExecuteAndSpecialize(builder, executable, specialization, null, "One of guards " + specialization.getGuardDefinitions() + " failed"));
returnSpecialized = returnBuilder.getRoot();
}
builder.tree(createExecuteTree(builder, specialization, SpecializationGroup.create(specialization), false, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createExecute(b, executable, specialization);
}
}, returnSpecialized, false, false, false));
return builder.getRoot();
}
private CodeTree createExecute(CodeTreeBuilder parent, ExecutableTypeData executable, SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (!specialization.getExceptions().isEmpty() || !specialization.getAssumptions().isEmpty()) {
builder.startTryBlock();
}
for (String assumption : specialization.getAssumptions()) {
builder.startStatement();
builder.string("this.").string(assumption).string(".check()");
builder.end();
}
CodeTreeBuilder returnBuilder = new CodeTreeBuilder(parent);
if (specialization.isPolymorphic()) {
returnBuilder.startCall("next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(returnBuilder, specialization, specialization, null, true, null);
returnBuilder.end();
} else if (specialization.isUninitialized()) {
returnBuilder.startCall("super", EXECUTE_SPECIALIZE_NAME);
returnBuilder.string("0");
addInternalValueParameterNames(returnBuilder, specialization, specialization, null, true, null);
returnBuilder.doubleQuote("Uninitialized monomorphic");
returnBuilder.end();
} else if (specialization.getMethod() == null && !node.needsRewrites(context)) {
emitEncounteredSynthetic(builder, specialization);
} else if (specialization.isGeneric()) {
returnBuilder.startCall("super", EXECUTE_GENERIC_NAME);
addInternalValueParameterNames(returnBuilder, specialization, specialization, null, node.needsFrame(getContext()), null);
returnBuilder.end();
} else {
returnBuilder.tree(createTemplateMethodCall(returnBuilder, null, specialization, specialization, null));
}
if (!returnBuilder.isEmpty()) {
TypeData targetType = node.getTypeSystem().findTypeData(builder.findMethod().getReturnType());
TypeData sourceType = specialization.getReturnType().getTypeSystemType();
builder.startReturn();
if (targetType == null || sourceType == null) {
builder.tree(returnBuilder.getRoot());
} else if (sourceType.needsCastTo(getContext(), targetType)) {
String castMethodName = TypeSystemCodeGenerator.expectTypeMethodName(targetType);
if (!executable.hasUnexpectedValue(context)) {
castMethodName = TypeSystemCodeGenerator.asTypeMethodName(targetType);
}
builder.tree(createCallTypeSystemMethod(context, parent, node, castMethodName, returnBuilder.getRoot()));
} else {
builder.tree(returnBuilder.getRoot());
}
builder.end();
}
if (!specialization.getExceptions().isEmpty()) {
for (SpecializationThrowsData exception : specialization.getExceptions()) {
builder.end().startCatchBlock(exception.getJavaClass(), "ex");
builder.tree(createDeoptimize(builder));
builder.tree(createReturnExecuteAndSpecialize(parent, executable, specialization, null, "Thrown " + Utils.getSimpleName(exception.getJavaClass())));
}
builder.end();
}
if (!specialization.getAssumptions().isEmpty()) {
builder.end().startCatchBlock(getContext().getTruffleTypes().getInvalidAssumption(), "ex");
builder.tree(createReturnExecuteAndSpecialize(parent, executable, specialization, null, "Assumption failed"));
builder.end();
}
return builder.getRoot();
}
protected CodeExecutableElement createCopyConstructorFactoryMethod(TypeMirror baseType, SpecializationData specialization) {
List<ActualParameter> implicitTypeParams = getImplicitTypeParameters(specialization);
CodeVariableElement[] parameters = new CodeVariableElement[implicitTypeParams.size() + 1];
int i = 0;
String baseName = "current";
parameters[i++] = new CodeVariableElement(specialization.getNode().getNodeType(), baseName);
for (ActualParameter implicitTypeParam : implicitTypeParams) {
parameters[i++] = new CodeVariableElement(getContext().getType(Class.class), implicitTypeName(implicitTypeParam));
}
CodeExecutableElement method = new CodeExecutableElement(modifiers(STATIC), specialization.getNode().getNodeType(), CREATE_SPECIALIZATION_NAME, parameters);
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startNew(getElement().asType());
builder.startGroup().cast(baseType, CodeTreeBuilder.singleString(baseName)).end();
for (ActualParameter param : implicitTypeParams) {
builder.string(implicitTypeName(param));
}
builder.end().end();
return method;
}
protected CodeExecutableElement createConstructorFactoryMethod(SpecializationData specialization, ExecutableElement constructor) {
List<? extends VariableElement> parameters = constructor.getParameters();
CodeExecutableElement method = new CodeExecutableElement(modifiers(STATIC), specialization.getNode().getNodeType(), CREATE_SPECIALIZATION_NAME,
parameters.toArray(new CodeVariableElement[parameters.size()]));
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startNew(getElement().asType());
for (VariableElement param : parameters) {
builder.string(((CodeVariableElement) param).getName());
}
builder.end().end();
return method;
}
}
private interface CodeBlock<T> {
CodeTree create(CodeTreeBuilder parent, T value);
}
}
| graal/com.oracle.truffle.dsl.processor/src/com/oracle/truffle/dsl/processor/node/NodeCodeGenerator.java | /*
* Copyright (c) 2012, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.dsl.processor.node;
import static com.oracle.truffle.dsl.processor.Utils.*;
import static javax.lang.model.element.Modifier.*;
import java.util.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import com.oracle.truffle.api.dsl.*;
import com.oracle.truffle.api.nodes.*;
import com.oracle.truffle.dsl.processor.*;
import com.oracle.truffle.dsl.processor.ast.*;
import com.oracle.truffle.dsl.processor.node.NodeChildData.Cardinality;
import com.oracle.truffle.dsl.processor.node.SpecializationGroup.TypeGuard;
import com.oracle.truffle.dsl.processor.template.*;
import com.oracle.truffle.dsl.processor.typesystem.*;
public class NodeCodeGenerator extends CompilationUnitFactory<NodeData> {
private static final String THIS_NODE_LOCAL_VAR_NAME = "thisNode";
private static final String EXECUTE_GENERIC_NAME = "executeGeneric0";
private static final String EXECUTE_SPECIALIZE_NAME = "executeAndSpecialize0";
private static final String EXECUTE_POLYMORPHIC_NAME = "executePolymorphic0";
private static final String UPDATE_TYPES_NAME = "updateTypes";
private static final String COPY_WITH_CONSTRUCTOR_NAME = "copyWithConstructor";
private static final String CREATE_SPECIALIZATION_NAME = "createSpecialization";
public NodeCodeGenerator(ProcessorContext context) {
super(context);
}
private TypeMirror getUnexpectedValueException() {
return getContext().getTruffleTypes().getUnexpectedValueException();
}
private static String factoryClassName(NodeData node) {
return node.getNodeId() + "Factory";
}
private static String nodeSpecializationClassName(SpecializationData specialization) {
String nodeid = resolveNodeId(specialization.getNode());
String name = Utils.firstLetterUpperCase(nodeid);
name += Utils.firstLetterUpperCase(specialization.getId());
name += "Node";
return name;
}
private static String nodePolymorphicClassName(NodeData node) {
return Utils.firstLetterUpperCase(resolveNodeId(node)) + "PolymorphicNode";
}
private static String resolveNodeId(NodeData node) {
String nodeid = node.getNodeId();
if (nodeid.endsWith("Node") && !nodeid.equals("Node")) {
nodeid = nodeid.substring(0, nodeid.length() - 4);
}
return nodeid;
}
private static String valueNameEvaluated(ActualParameter targetParameter) {
return valueName(targetParameter) + "Evaluated";
}
private static String implicitTypeName(ActualParameter param) {
return param.getLocalName() + "ImplicitType";
}
private static String polymorphicTypeName(ActualParameter param) {
return param.getLocalName() + "PolymorphicType";
}
private static String valueName(ActualParameter param) {
return param.getLocalName();
}
private static CodeTree createAccessChild(NodeExecutionData targetExecution, String thisReference) {
String reference = thisReference;
if (reference == null) {
reference = "this";
}
CodeTreeBuilder builder = CodeTreeBuilder.createBuilder();
Element accessElement = targetExecution.getChild().getAccessElement();
if (accessElement == null || accessElement.getKind() == ElementKind.METHOD) {
builder.string(reference).string(".").string(targetExecution.getChild().getName());
} else if (accessElement.getKind() == ElementKind.FIELD) {
builder.string(reference).string(".").string(accessElement.getSimpleName().toString());
} else {
throw new AssertionError();
}
if (targetExecution.isIndexed()) {
builder.string("[" + targetExecution.getIndex() + "]");
}
return builder.getRoot();
}
private static String castValueName(ActualParameter parameter) {
return valueName(parameter) + "Cast";
}
private void addInternalValueParameters(CodeExecutableElement method, TemplateMethod specialization, boolean forceFrame, boolean evaluated) {
if (forceFrame && specialization.getSpecification().findParameterSpec("frame") != null) {
method.addParameter(new CodeVariableElement(getContext().getTruffleTypes().getFrame(), "frameValue"));
}
for (ActualParameter parameter : specialization.getParameters()) {
ParameterSpec spec = parameter.getSpecification();
if (forceFrame && spec.getName().equals("frame")) {
continue;
}
if (spec.isLocal()) {
continue;
}
String name = valueName(parameter);
if (evaluated && spec.isSignature()) {
name = valueNameEvaluated(parameter);
}
method.addParameter(new CodeVariableElement(parameter.getType(), name));
}
}
private void addInternalValueParameterNames(CodeTreeBuilder builder, TemplateMethod source, TemplateMethod specialization, String unexpectedValueName, boolean forceFrame,
Map<String, String> customNames) {
if (forceFrame && specialization.getSpecification().findParameterSpec("frame") != null) {
builder.string("frameValue");
}
for (ActualParameter parameter : specialization.getParameters()) {
ParameterSpec spec = parameter.getSpecification();
if (forceFrame && spec.getName().equals("frame")) {
continue;
}
if (parameter.getSpecification().isLocal()) {
continue;
}
ActualParameter sourceParameter = source.findParameter(parameter.getLocalName());
if (customNames != null && customNames.containsKey(parameter.getLocalName())) {
builder.string(customNames.get(parameter.getLocalName()));
} else if (unexpectedValueName != null && parameter.getLocalName().equals(unexpectedValueName)) {
builder.cast(parameter.getType(), CodeTreeBuilder.singleString("ex.getResult()"));
} else if (sourceParameter != null) {
builder.string(valueName(sourceParameter, parameter));
} else {
builder.string(valueName(parameter));
}
}
}
private String valueName(ActualParameter sourceParameter, ActualParameter targetParameter) {
if (!sourceParameter.getSpecification().isSignature()) {
return valueName(targetParameter);
} else if (sourceParameter.getTypeSystemType() != null && targetParameter.getTypeSystemType() != null) {
if (sourceParameter.getTypeSystemType().needsCastTo(getContext(), targetParameter.getTypeSystemType())) {
return castValueName(targetParameter);
}
}
return valueName(targetParameter);
}
private CodeTree createTemplateMethodCall(CodeTreeBuilder parent, CodeTree target, TemplateMethod sourceMethod, TemplateMethod targetMethod, String unexpectedValueName,
String... customSignatureValueNames) {
CodeTreeBuilder builder = parent.create();
boolean castedValues = sourceMethod != targetMethod;
builder.startGroup();
ExecutableElement method = targetMethod.getMethod();
if (method == null) {
throw new UnsupportedOperationException();
}
TypeElement targetClass = Utils.findNearestEnclosingType(method.getEnclosingElement());
NodeData node = (NodeData) targetMethod.getTemplate();
if (target == null) {
boolean accessible = targetMethod.canBeAccessedByInstanceOf(getContext(), node.getNodeType());
if (accessible) {
if (builder.findMethod().getModifiers().contains(STATIC)) {
if (method.getModifiers().contains(STATIC)) {
builder.type(targetClass.asType());
} else {
builder.string(THIS_NODE_LOCAL_VAR_NAME);
}
} else {
if (targetMethod instanceof ExecutableTypeData) {
builder.string("this");
} else {
builder.string("super");
}
}
} else {
if (method.getModifiers().contains(STATIC)) {
builder.type(targetClass.asType());
} else {
ActualParameter firstParameter = null;
for (ActualParameter searchParameter : targetMethod.getParameters()) {
if (searchParameter.getSpecification().isSignature()) {
firstParameter = searchParameter;
break;
}
}
if (firstParameter == null) {
throw new AssertionError();
}
ActualParameter sourceParameter = sourceMethod.findParameter(firstParameter.getLocalName());
if (castedValues && sourceParameter != null) {
builder.string(valueName(sourceParameter, firstParameter));
} else {
builder.string(valueName(firstParameter));
}
}
}
builder.string(".");
} else {
builder.tree(target);
}
builder.startCall(method.getSimpleName().toString());
int signatureIndex = 0;
for (ActualParameter targetParameter : targetMethod.getParameters()) {
ActualParameter valueParameter = null;
if (sourceMethod != null) {
valueParameter = sourceMethod.findParameter(targetParameter.getLocalName());
}
if (valueParameter == null) {
valueParameter = targetParameter;
}
TypeMirror targetType = targetParameter.getType();
TypeMirror valueType = null;
if (valueParameter != null) {
valueType = valueParameter.getType();
}
if (signatureIndex < customSignatureValueNames.length && targetParameter.getSpecification().isSignature()) {
builder.string(customSignatureValueNames[signatureIndex]);
signatureIndex++;
} else if (targetParameter.getSpecification().isLocal()) {
builder.startGroup();
if (builder.findMethod().getModifiers().contains(Modifier.STATIC)) {
builder.string(THIS_NODE_LOCAL_VAR_NAME).string(".");
} else {
builder.string("this.");
}
builder.string(targetParameter.getSpecification().getName());
builder.end();
} else if (unexpectedValueName != null && targetParameter.getLocalName().equals(unexpectedValueName)) {
builder.cast(targetParameter.getType(), CodeTreeBuilder.singleString("ex.getResult()"));
} else if (!Utils.needsCastTo(getContext(), valueType, targetType)) {
builder.startGroup();
builder.string(valueName(targetParameter));
builder.end();
} else {
builder.string(castValueName(targetParameter));
}
}
builder.end().end();
return builder.getRoot();
}
private static String baseClassName(NodeData node) {
String nodeid = resolveNodeId(node);
String name = Utils.firstLetterUpperCase(nodeid);
name += "BaseNode";
return name;
}
private static CodeTree createCallTypeSystemMethod(ProcessorContext context, CodeTreeBuilder parent, NodeData node, String methodName, CodeTree... args) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
startCallTypeSystemMethod(context, builder, node.getTypeSystem(), methodName);
for (CodeTree arg : args) {
builder.tree(arg);
}
builder.end().end();
return builder.getRoot();
}
private static void startCallTypeSystemMethod(ProcessorContext context, CodeTreeBuilder body, TypeSystemData typeSystem, String methodName) {
VariableElement singleton = TypeSystemCodeGenerator.findSingleton(context, typeSystem);
assert singleton != null;
body.startGroup();
body.staticReference(singleton.getEnclosingElement().asType(), singleton.getSimpleName().toString());
body.string(".").startCall(methodName);
}
/**
* <pre>
* variant1 $condition != null
*
* $type $name = defaultValue($type);
* if ($condition) {
* $name = $value;
* }
*
* variant2 $condition != null
* $type $name = $value;
* </pre>
*
* .
*/
private static CodeTree createLazyAssignment(CodeTreeBuilder parent, String name, TypeMirror type, CodeTree condition, CodeTree value) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (condition == null) {
builder.declaration(type, name, value);
} else {
builder.declaration(type, name, new CodeTreeBuilder(parent).defaultValue(type).getRoot());
builder.startIf().tree(condition).end();
builder.startBlock();
builder.startStatement();
builder.string(name);
builder.string(" = ");
builder.tree(value);
builder.end(); // statement
builder.end(); // block
}
return builder.getRoot();
}
protected void emitEncounteredSynthetic(CodeTreeBuilder builder, TemplateMethod current) {
CodeTreeBuilder nodes = builder.create();
CodeTreeBuilder arguments = builder.create();
nodes.startCommaGroup();
arguments.startCommaGroup();
boolean empty = true;
for (ActualParameter parameter : current.getParameters()) {
NodeExecutionData executionData = parameter.getSpecification().getExecution();
if (executionData != null) {
if (executionData.isShortCircuit()) {
nodes.nullLiteral();
arguments.string(valueName(parameter.getPreviousParameter()));
}
nodes.tree(createAccessChild(executionData, null));
arguments.string(valueName(parameter));
empty = false;
}
}
nodes.end();
arguments.end();
builder.startThrow().startNew(getContext().getType(UnsupportedSpecializationException.class));
builder.string("this");
builder.startNewArray(getContext().getTruffleTypes().getNodeArray(), null);
builder.tree(nodes.getRoot());
builder.end();
if (!empty) {
builder.tree(arguments.getRoot());
}
builder.end().end();
}
private static List<ExecutableElement> findUserConstructors(TypeMirror nodeType) {
List<ExecutableElement> constructors = new ArrayList<>();
for (ExecutableElement constructor : ElementFilter.constructorsIn(Utils.fromTypeMirror(nodeType).getEnclosedElements())) {
if (constructor.getModifiers().contains(PRIVATE)) {
continue;
}
if (isCopyConstructor(constructor)) {
continue;
}
constructors.add(constructor);
}
if (constructors.isEmpty()) {
constructors.add(new CodeExecutableElement(null, Utils.getSimpleName(nodeType)));
}
return constructors;
}
private static ExecutableElement findCopyConstructor(TypeMirror type) {
for (ExecutableElement constructor : ElementFilter.constructorsIn(Utils.fromTypeMirror(type).getEnclosedElements())) {
if (constructor.getModifiers().contains(PRIVATE)) {
continue;
}
if (isCopyConstructor(constructor)) {
return constructor;
}
}
return null;
}
private static boolean isCopyConstructor(ExecutableElement element) {
if (element.getParameters().size() != 1) {
return false;
}
VariableElement var = element.getParameters().get(0);
TypeElement enclosingType = Utils.findNearestEnclosingType(var);
if (Utils.typeEquals(var.asType(), enclosingType.asType())) {
return true;
}
List<TypeElement> types = Utils.getDirectSuperTypes(enclosingType);
for (TypeElement type : types) {
if (!(type instanceof CodeTypeElement)) {
// no copy constructors which are not generated types
return false;
}
if (Utils.typeEquals(var.asType(), type.asType())) {
return true;
}
}
return false;
}
@Override
@SuppressWarnings("unchecked")
protected void createChildren(NodeData node) {
List<CodeTypeElement> casts = new ArrayList<>(getElement().getEnclosedElements());
getElement().getEnclosedElements().clear();
Map<NodeData, List<TypeElement>> childTypes = new LinkedHashMap<>();
for (NodeData nodeChild : node.getEnclosingNodes()) {
NodeCodeGenerator generator = new NodeCodeGenerator(getContext());
childTypes.put(nodeChild, generator.process(null, nodeChild).getEnclosedElements());
}
if (node.needsFactory() || node.getNodeDeclaringChildren().size() > 0) {
NodeFactoryFactory factory = new NodeFactoryFactory(context, childTypes);
add(factory, node);
factory.getElement().getEnclosedElements().addAll(casts);
}
}
protected CodeTree createCastType(TypeSystemData typeSystem, TypeData sourceType, TypeData targetType, boolean expect, CodeTree value) {
if (targetType == null) {
return value;
} else if (sourceType != null && !sourceType.needsCastTo(getContext(), targetType)) {
return value;
}
CodeTreeBuilder builder = CodeTreeBuilder.createBuilder();
String targetMethodName;
if (expect) {
targetMethodName = TypeSystemCodeGenerator.expectTypeMethodName(targetType);
} else {
targetMethodName = TypeSystemCodeGenerator.asTypeMethodName(targetType);
}
startCallTypeSystemMethod(getContext(), builder, typeSystem, targetMethodName);
builder.tree(value);
builder.end().end();
return builder.getRoot();
}
protected CodeTree createExpectType(TypeSystemData typeSystem, TypeData sourceType, TypeData targetType, CodeTree expression) {
return createCastType(typeSystem, sourceType, targetType, true, expression);
}
public CodeTree createDeoptimize(CodeTreeBuilder parent) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.startStatement();
builder.startStaticCall(getContext().getTruffleTypes().getCompilerDirectives(), "transferToInterpreterAndInvalidate").end();
builder.end();
return builder.getRoot();
}
private class NodeFactoryFactory extends ClassElementFactory<NodeData> {
private final Map<NodeData, List<TypeElement>> childTypes;
private CodeTypeElement generatedNode;
public NodeFactoryFactory(ProcessorContext context, Map<NodeData, List<TypeElement>> childElements) {
super(context);
this.childTypes = childElements;
}
@Override
protected CodeTypeElement create(NodeData node) {
Modifier visibility = Utils.getVisibility(node.getTemplateType().getModifiers());
CodeTypeElement clazz = createClass(node, modifiers(), factoryClassName(node), null, false);
if (visibility != null) {
clazz.getModifiers().add(visibility);
}
clazz.getModifiers().add(Modifier.FINAL);
clazz.add(createConstructorUsingFields(modifiers(PRIVATE), clazz));
return clazz;
}
@Override
protected void createChildren(NodeData node) {
CodeTypeElement clazz = getElement();
Modifier createVisibility = Utils.getVisibility(clazz.getModifiers());
CodeTypeElement polymorphicNode = null;
if (node.needsFactory()) {
NodeBaseFactory factory = new NodeBaseFactory(context);
add(factory, node.getGenericSpecialization() == null ? node.getSpecializations().get(0) : node.getGenericSpecialization());
generatedNode = factory.getElement();
if (node.needsRewrites(context)) {
clazz.add(createCreateGenericMethod(node, createVisibility));
}
createFactoryMethods(node, clazz, createVisibility);
for (SpecializationData specialization : node.getSpecializations()) {
if (!specialization.isReachable()) {
continue;
}
if (specialization.isPolymorphic() && node.isPolymorphic()) {
PolymorphicNodeFactory polymorphicFactory = new PolymorphicNodeFactory(getContext(), generatedNode);
add(polymorphicFactory, specialization);
polymorphicNode = polymorphicFactory.getElement();
continue;
}
add(new SpecializedNodeFactory(context, generatedNode), specialization);
}
TypeMirror nodeFactory = Utils.getDeclaredType(Utils.fromTypeMirror(getContext().getType(NodeFactory.class)), node.getNodeType());
clazz.getImplements().add(nodeFactory);
clazz.add(createCreateNodeMethod(node));
clazz.add(createGetNodeClassMethod(node));
clazz.add(createGetNodeSignaturesMethod());
clazz.add(createGetChildrenSignatureMethod(node));
clazz.add(createGetInstanceMethod(node, createVisibility));
clazz.add(createInstanceConstant(node, clazz.asType()));
}
if (polymorphicNode != null) {
patchParameterType(clazz, UPDATE_TYPES_NAME, generatedNode.asType(), polymorphicNode.asType());
}
for (NodeData childNode : childTypes.keySet()) {
if (childNode.getTemplateType().getModifiers().contains(Modifier.PRIVATE)) {
continue;
}
for (TypeElement type : childTypes.get(childNode)) {
Set<Modifier> typeModifiers = ((CodeTypeElement) type).getModifiers();
Modifier visibility = Utils.getVisibility(type.getModifiers());
typeModifiers.clear();
if (visibility != null) {
typeModifiers.add(visibility);
}
typeModifiers.add(Modifier.STATIC);
typeModifiers.add(Modifier.FINAL);
clazz.add(type);
}
}
List<NodeData> children = node.getNodeDeclaringChildren();
if (node.getDeclaringNode() == null && children.size() > 0) {
clazz.add(createGetFactories(node));
}
}
private void patchParameterType(CodeTypeElement enclosingClass, String methodName, TypeMirror originalType, TypeMirror newType) {
for (TypeElement enclosedType : ElementFilter.typesIn(enclosingClass.getEnclosedElements())) {
CodeTypeElement type = (CodeTypeElement) enclosedType;
ExecutableElement method = type.getMethod(methodName);
for (VariableElement v : method.getParameters()) {
CodeVariableElement var = (CodeVariableElement) v;
if (Utils.typeEquals(var.getType(), originalType)) {
var.setType(newType);
}
}
}
}
private CodeExecutableElement createGetNodeClassMethod(NodeData node) {
TypeMirror returnType = Utils.getDeclaredType(Utils.fromTypeMirror(getContext().getType(Class.class)), node.getNodeType());
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getNodeClass");
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn().typeLiteral(node.getNodeType()).end();
return method;
}
private CodeExecutableElement createGetNodeSignaturesMethod() {
TypeElement listType = Utils.fromTypeMirror(getContext().getType(List.class));
TypeMirror classType = getContext().getType(Class.class);
TypeMirror returnType = Utils.getDeclaredType(listType, Utils.getDeclaredType(listType, classType));
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getNodeSignatures");
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startStaticCall(getContext().getType(Arrays.class), "asList");
List<ExecutableElement> constructors = findUserConstructors(generatedNode.asType());
for (ExecutableElement constructor : constructors) {
builder.tree(createAsList(builder, Utils.asTypeMirrors(constructor.getParameters()), classType));
}
builder.end();
builder.end();
return method;
}
private CodeExecutableElement createGetChildrenSignatureMethod(NodeData node) {
Types types = getContext().getEnvironment().getTypeUtils();
TypeElement listType = Utils.fromTypeMirror(getContext().getType(List.class));
TypeMirror classType = getContext().getType(Class.class);
TypeMirror nodeType = getContext().getTruffleTypes().getNode();
TypeMirror wildcardNodeType = types.getWildcardType(nodeType, null);
classType = Utils.getDeclaredType(Utils.fromTypeMirror(classType), wildcardNodeType);
TypeMirror returnType = Utils.getDeclaredType(listType, classType);
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, "getExecutionSignature");
CodeTreeBuilder builder = method.createBuilder();
List<TypeMirror> signatureTypes = new ArrayList<>();
assert !node.getSpecializations().isEmpty();
SpecializationData data = node.getSpecializations().get(0);
for (ActualParameter parameter : data.getSignatureParameters()) {
signatureTypes.add(parameter.getSpecification().getExecution().getNodeType());
}
builder.startReturn().tree(createAsList(builder, signatureTypes, classType)).end();
return method;
}
private CodeTree createAsList(CodeTreeBuilder parent, List<TypeMirror> types, TypeMirror elementClass) {
CodeTreeBuilder builder = parent.create();
builder.startGroup();
builder.type(getContext().getType(Arrays.class));
builder.string(".<").type(elementClass).string(">");
builder.startCall("asList");
for (TypeMirror typeMirror : types) {
builder.typeLiteral(typeMirror);
}
builder.end().end();
return builder.getRoot();
}
private CodeExecutableElement createCreateNodeMethod(NodeData node) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), node.getNodeType(), "createNode");
CodeVariableElement arguments = new CodeVariableElement(getContext().getType(Object.class), "arguments");
method.setVarArgs(true);
method.addParameter(arguments);
CodeTreeBuilder builder = method.createBuilder();
List<ExecutableElement> signatures = findUserConstructors(generatedNode.asType());
boolean ifStarted = false;
for (ExecutableElement element : signatures) {
ifStarted = builder.startIf(ifStarted);
builder.string("arguments.length == " + element.getParameters().size());
int index = 0;
for (VariableElement param : element.getParameters()) {
if (Utils.isObject(param.asType())) {
continue;
}
builder.string(" && ");
if (!param.asType().getKind().isPrimitive()) {
builder.string("(arguments[" + index + "] == null || ");
}
builder.string("arguments[" + index + "] instanceof ");
builder.type(Utils.boxType(getContext(), param.asType()));
if (!param.asType().getKind().isPrimitive()) {
builder.string(")");
}
index++;
}
builder.end();
builder.startBlock();
builder.startReturn().startCall("create");
index = 0;
for (VariableElement param : element.getParameters()) {
builder.startGroup();
if (!Utils.isObject(param.asType())) {
builder.string("(").type(param.asType()).string(") ");
}
builder.string("arguments[").string(String.valueOf(index)).string("]");
builder.end();
index++;
}
builder.end().end();
builder.end(); // block
}
builder.startElseBlock();
builder.startThrow().startNew(getContext().getType(IllegalArgumentException.class));
builder.doubleQuote("Invalid create signature.");
builder.end().end();
builder.end(); // else block
return method;
}
private ExecutableElement createGetInstanceMethod(NodeData node, Modifier visibility) {
TypeElement nodeFactoryType = Utils.fromTypeMirror(getContext().getType(NodeFactory.class));
TypeMirror returnType = Utils.getDeclaredType(nodeFactoryType, node.getNodeType());
CodeExecutableElement method = new CodeExecutableElement(modifiers(), returnType, "getInstance");
if (visibility != null) {
method.getModifiers().add(visibility);
}
method.getModifiers().add(Modifier.STATIC);
String varName = instanceVarName(node);
CodeTreeBuilder builder = method.createBuilder();
builder.startIf();
builder.string(varName).string(" == null");
builder.end().startBlock();
builder.startStatement();
builder.string(varName);
builder.string(" = ");
builder.startNew(factoryClassName(node)).end();
builder.end();
builder.end();
builder.startReturn().string(varName).end();
return method;
}
private String instanceVarName(NodeData node) {
if (node.getDeclaringNode() != null) {
return Utils.firstLetterLowerCase(factoryClassName(node)) + "Instance";
} else {
return "instance";
}
}
private CodeVariableElement createInstanceConstant(NodeData node, TypeMirror factoryType) {
String varName = instanceVarName(node);
CodeVariableElement var = new CodeVariableElement(modifiers(), factoryType, varName);
var.getModifiers().add(Modifier.PRIVATE);
var.getModifiers().add(Modifier.STATIC);
return var;
}
private ExecutableElement createGetFactories(NodeData node) {
List<NodeData> children = node.getNodeDeclaringChildren();
if (node.needsFactory()) {
children.add(node);
}
List<TypeMirror> nodeTypesList = new ArrayList<>();
TypeMirror prev = null;
boolean allSame = true;
for (NodeData child : children) {
nodeTypesList.add(child.getNodeType());
if (prev != null && !Utils.typeEquals(child.getNodeType(), prev)) {
allSame = false;
}
prev = child.getNodeType();
}
TypeMirror commonNodeSuperType = Utils.getCommonSuperType(getContext(), nodeTypesList.toArray(new TypeMirror[nodeTypesList.size()]));
Types types = getContext().getEnvironment().getTypeUtils();
TypeMirror factoryType = getContext().getType(NodeFactory.class);
TypeMirror baseType;
if (allSame) {
baseType = Utils.getDeclaredType(Utils.fromTypeMirror(factoryType), commonNodeSuperType);
} else {
baseType = Utils.getDeclaredType(Utils.fromTypeMirror(factoryType), types.getWildcardType(commonNodeSuperType, null));
}
TypeMirror listType = Utils.getDeclaredType(Utils.fromTypeMirror(getContext().getType(List.class)), baseType);
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, STATIC), listType, "getFactories");
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startStaticCall(getContext().getType(Arrays.class), "asList");
for (NodeData child : children) {
builder.startGroup();
NodeData childNode = child;
List<NodeData> factories = new ArrayList<>();
while (childNode.getDeclaringNode() != null) {
factories.add(childNode);
childNode = childNode.getDeclaringNode();
}
Collections.reverse(factories);
for (NodeData nodeData : factories) {
builder.string(factoryClassName(nodeData)).string(".");
}
builder.string("getInstance()");
builder.end();
}
builder.end();
builder.end();
return method;
}
private void createFactoryMethods(NodeData node, CodeTypeElement clazz, Modifier createVisibility) {
List<ExecutableElement> constructors = findUserConstructors(generatedNode.asType());
for (ExecutableElement constructor : constructors) {
clazz.add(createCreateMethod(node, createVisibility, constructor));
}
}
private CodeExecutableElement createCreateMethod(NodeData node, Modifier visibility, ExecutableElement constructor) {
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), constructor);
method.setSimpleName(CodeNames.of("create"));
method.getModifiers().clear();
if (visibility != null) {
method.getModifiers().add(visibility);
}
method.getModifiers().add(Modifier.STATIC);
method.setReturnType(node.getNodeType());
CodeTreeBuilder body = method.createBuilder();
body.startReturn();
if (node.getSpecializations().isEmpty()) {
body.nullLiteral();
} else {
body.startCall(nodeSpecializationClassName(node.getSpecializations().get(0)), CREATE_SPECIALIZATION_NAME);
for (VariableElement var : method.getParameters()) {
body.string(var.getSimpleName().toString());
}
body.end();
}
body.end();
return method;
}
private CodeExecutableElement createCreateGenericMethod(NodeData node, Modifier visibility) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(), node.getNodeType(), "createGeneric");
if (visibility != null) {
method.getModifiers().add(visibility);
}
method.getModifiers().add(Modifier.STATIC);
method.addParameter(new CodeVariableElement(node.getNodeType(), THIS_NODE_LOCAL_VAR_NAME));
CodeTreeBuilder body = method.createBuilder();
SpecializationData found = null;
List<SpecializationData> specializations = node.getSpecializations();
for (int i = 0; i < specializations.size(); i++) {
if (specializations.get(i).isReachable()) {
found = specializations.get(i);
}
}
if (found == null) {
body.startThrow().startNew(getContext().getType(UnsupportedOperationException.class)).end().end();
} else {
body.startReturn().startCall(nodeSpecializationClassName(found), CREATE_SPECIALIZATION_NAME).startGroup().string(THIS_NODE_LOCAL_VAR_NAME).end().end().end();
}
return method;
}
}
private class NodeBaseFactory extends ClassElementFactory<SpecializationData> {
public NodeBaseFactory(ProcessorContext context) {
super(context);
}
@Override
protected CodeTypeElement create(SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTypeElement clazz = createClass(node, modifiers(PRIVATE, ABSTRACT, STATIC), baseClassName(node), node.getNodeType(), false);
for (NodeChildData child : node.getChildren()) {
clazz.add(createChildField(child));
if (child.getAccessElement() != null && child.getAccessElement().getModifiers().contains(Modifier.ABSTRACT)) {
ExecutableElement getter = (ExecutableElement) child.getAccessElement();
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), getter);
method.getModifiers().remove(Modifier.ABSTRACT);
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn().string("this.").string(child.getName()).end();
clazz.add(method);
}
}
for (NodeFieldData field : node.getFields()) {
if (!field.isGenerated()) {
continue;
}
clazz.add(new CodeVariableElement(modifiers(PROTECTED, FINAL), field.getType(), field.getName()));
if (field.getGetter() != null && field.getGetter().getModifiers().contains(Modifier.ABSTRACT)) {
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), field.getGetter());
method.getModifiers().remove(Modifier.ABSTRACT);
method.createBuilder().startReturn().string("this.").string(field.getName()).end();
clazz.add(method);
}
}
for (String assumption : node.getAssumptions()) {
clazz.add(createAssumptionField(assumption));
}
createConstructors(node, clazz);
return clazz;
}
@Override
protected void createChildren(SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTypeElement clazz = getElement();
SpecializationGroup rootGroup = createSpecializationGroups(node);
if (node.needsRewrites(context)) {
if (node.isPolymorphic()) {
CodeVariableElement var = new CodeVariableElement(modifiers(PROTECTED), clazz.asType(), "next0");
var.getAnnotationMirrors().add(new CodeAnnotationMirror(getContext().getTruffleTypes().getChildAnnotation()));
clazz.add(var);
CodeExecutableElement genericCachedExecute = createCachedExecute(node, node.getPolymorphicSpecialization());
clazz.add(genericCachedExecute);
getElement().add(createUpdateTypes(clazz.asType()));
}
for (CodeExecutableElement method : createImplicitChildrenAccessors()) {
clazz.add(method);
}
clazz.add(createGenericExecuteAndSpecialize(node, rootGroup));
clazz.add(createInfoMessage(node));
}
if (needsInvokeCopyConstructorMethod()) {
clazz.add(createCopy(clazz.asType(), null));
}
if (node.getGenericSpecialization() != null && node.getGenericSpecialization().isReachable()) {
clazz.add(createGenericExecute(node, rootGroup));
}
}
protected boolean needsInvokeCopyConstructorMethod() {
return getModel().getNode().isPolymorphic();
}
protected CodeExecutableElement createCopy(TypeMirror baseType, SpecializationData specialization) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), baseType, COPY_WITH_CONSTRUCTOR_NAME);
if (specialization == null) {
method.getModifiers().add(ABSTRACT);
} else {
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startNew(getElement().asType());
builder.string("this");
for (ActualParameter param : getImplicitTypeParameters(specialization)) {
builder.string(implicitTypeName(param));
}
builder.end().end();
}
return method;
}
private List<CodeExecutableElement> createImplicitChildrenAccessors() {
NodeData node = getModel().getNode();
List<Set<TypeData>> prototype = Collections.nCopies(node.getGenericSpecialization().getParameters().size(), null);
List<Set<TypeData>> expectTypes = new ArrayList<>(prototype);
for (ExecutableTypeData executableType : node.getExecutableTypes()) {
for (int i = 0; i < executableType.getEvaluatedCount(); i++) {
ActualParameter parameter = executableType.getSignatureParameter(i);
if (i >= expectTypes.size()) {
break;
}
Set<TypeData> types = expectTypes.get(i);
if (types == null) {
types = new TreeSet<>();
expectTypes.set(i, types);
}
types.add(parameter.getTypeSystemType());
}
}
List<CodeExecutableElement> methods = new ArrayList<>();
List<Set<TypeData>> visitedList = new ArrayList<>(prototype);
for (SpecializationData spec : node.getSpecializations()) {
int signatureIndex = -1;
for (ActualParameter param : spec.getParameters()) {
if (!param.getSpecification().isSignature()) {
continue;
}
signatureIndex++;
Set<TypeData> visitedTypeData = visitedList.get(signatureIndex);
if (visitedTypeData == null) {
visitedTypeData = new TreeSet<>();
visitedList.set(signatureIndex, visitedTypeData);
}
if (visitedTypeData.contains(param.getTypeSystemType())) {
continue;
}
visitedTypeData.add(param.getTypeSystemType());
Set<TypeData> expect = expectTypes.get(signatureIndex);
if (expect == null) {
expect = Collections.emptySet();
}
methods.addAll(createExecuteChilds(param, expect));
}
}
return methods;
}
private CodeTree truffleBooleanOption(CodeTreeBuilder parent, String name) {
CodeTreeBuilder builder = parent.create();
builder.staticReference(getContext().getTruffleTypes().getTruffleOptions(), name);
return builder.getRoot();
}
private Element createInfoMessage(NodeData node) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, STATIC), getContext().getType(String.class), "createInfo0");
method.addParameter(new CodeVariableElement(getContext().getType(String.class), "message"));
addInternalValueParameters(method, node.getGenericSpecialization(), false, false);
CodeTreeBuilder builder = method.createBuilder();
builder.startIf().tree(truffleBooleanOption(builder, TruffleTypes.OPTION_DETAILED_REWRITE_REASONS)).end();
builder.startBlock();
builder.startStatement().string("StringBuilder builder = new StringBuilder(message)").end();
builder.startStatement().startCall("builder", "append").doubleQuote(" (").end().end();
String sep = null;
for (ActualParameter parameter : node.getGenericSpecialization().getSignatureParameters()) {
builder.startStatement();
builder.string("builder");
if (sep != null) {
builder.startCall(".append").doubleQuote(sep).end();
}
builder.startCall(".append").doubleQuote(parameter.getLocalName()).end();
builder.startCall(".append").doubleQuote(" = ").end();
builder.startCall(".append").string(parameter.getLocalName()).end();
builder.end();
if (!Utils.isPrimitive(parameter.getType())) {
builder.startIf().string(parameter.getLocalName() + " != null").end();
builder.startBlock();
}
builder.startStatement();
if (Utils.isPrimitive(parameter.getType())) {
builder.startCall("builder.append").doubleQuote(" (" + Utils.getSimpleName(parameter.getType()) + ")").end();
} else {
builder.startCall("builder.append").doubleQuote(" (").end();
builder.startCall(".append").string(parameter.getLocalName() + ".getClass().getSimpleName()").end();
builder.startCall(".append").doubleQuote(")").end();
}
builder.end();
if (!Utils.isPrimitive(parameter.getType())) {
builder.end();
}
sep = ", ";
}
builder.startStatement().startCall("builder", "append").doubleQuote(")").end().end();
builder.startReturn().string("builder.toString()").end();
builder.end();
builder.startElseBlock();
builder.startReturn().string("message").end();
builder.end();
return method;
}
private CodeExecutableElement createCachedExecute(NodeData node, SpecializationData polymorph) {
CodeExecutableElement cachedExecute = new CodeExecutableElement(modifiers(PROTECTED, ABSTRACT), polymorph.getReturnType().getType(), EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameters(cachedExecute, polymorph, true, false);
ExecutableTypeData sourceExecutableType = node.findExecutableType(polymorph.getReturnType().getTypeSystemType(), 0);
boolean sourceThrowsUnexpected = sourceExecutableType != null && sourceExecutableType.hasUnexpectedValue(getContext());
if (sourceThrowsUnexpected && sourceExecutableType.getType().equals(node.getGenericSpecialization().getReturnType().getTypeSystemType())) {
sourceThrowsUnexpected = false;
}
if (sourceThrowsUnexpected) {
cachedExecute.getThrownTypes().add(getContext().getType(UnexpectedResultException.class));
}
return cachedExecute;
}
private void createConstructors(NodeData node, CodeTypeElement clazz) {
List<ExecutableElement> constructors = findUserConstructors(node.getNodeType());
ExecutableElement sourceSectionConstructor = null;
if (constructors.isEmpty()) {
clazz.add(createUserConstructor(clazz, null));
} else {
for (ExecutableElement constructor : constructors) {
clazz.add(createUserConstructor(clazz, constructor));
if (NodeParser.isSourceSectionConstructor(context, constructor)) {
sourceSectionConstructor = constructor;
}
}
}
if (node.needsRewrites(getContext())) {
clazz.add(createCopyConstructor(clazz, findCopyConstructor(node.getNodeType()), sourceSectionConstructor));
}
}
private CodeExecutableElement createUserConstructor(CodeTypeElement type, ExecutableElement superConstructor) {
CodeExecutableElement method = new CodeExecutableElement(null, type.getSimpleName().toString());
CodeTreeBuilder builder = method.createBuilder();
NodeData node = getModel().getNode();
if (superConstructor != null) {
for (VariableElement param : superConstructor.getParameters()) {
method.getParameters().add(CodeVariableElement.clone(param));
}
}
if (superConstructor != null) {
builder.startStatement().startSuperCall();
for (VariableElement param : superConstructor.getParameters()) {
builder.string(param.getSimpleName().toString());
}
builder.end().end();
}
for (VariableElement var : type.getFields()) {
NodeChildData child = node.findChild(var.getSimpleName().toString());
if (child != null) {
method.getParameters().add(new CodeVariableElement(child.getOriginalType(), child.getName()));
} else {
method.getParameters().add(new CodeVariableElement(var.asType(), var.getSimpleName().toString()));
}
builder.startStatement();
String fieldName = var.getSimpleName().toString();
CodeTree init = createStaticCast(builder, child, fieldName);
builder.string("this.").string(fieldName).string(" = ").tree(init);
builder.end();
}
return method;
}
private CodeTree createStaticCast(CodeTreeBuilder parent, NodeChildData child, String fieldName) {
NodeData parentNode = getModel().getNode();
if (child != null) {
CreateCastData createCast = parentNode.findCast(child.getName());
if (createCast != null) {
return createTemplateMethodCall(parent, null, parentNode.getGenericSpecialization(), createCast, null, fieldName);
}
}
return CodeTreeBuilder.singleString(fieldName);
}
private CodeExecutableElement createCopyConstructor(CodeTypeElement type, ExecutableElement superConstructor, ExecutableElement sourceSectionConstructor) {
CodeExecutableElement method = new CodeExecutableElement(null, type.getSimpleName().toString());
CodeTreeBuilder builder = method.createBuilder();
method.getParameters().add(new CodeVariableElement(type.asType(), "copy"));
if (superConstructor != null) {
builder.startStatement().startSuperCall().string("copy").end().end();
} else if (sourceSectionConstructor != null) {
builder.startStatement().startSuperCall().string("copy.getSourceSection()").end().end();
}
for (VariableElement var : type.getFields()) {
builder.startStatement();
final String varName = var.getSimpleName().toString();
final TypeMirror varType = var.asType();
String copyAccess = "copy." + varName;
if (Utils.isAssignable(getContext(), varType, getContext().getTruffleTypes().getNodeArray())) {
copyAccess += ".clone()";
}
CodeTree init = CodeTreeBuilder.singleString(copyAccess);
builder.startStatement().string("this.").string(varName).string(" = ").tree(init).end();
}
return method;
}
private CodeVariableElement createAssumptionField(String assumption) {
CodeVariableElement var = new CodeVariableElement(getContext().getTruffleTypes().getAssumption(), assumption);
var.getModifiers().add(Modifier.FINAL);
return var;
}
private CodeVariableElement createChildField(NodeChildData child) {
TypeMirror type = child.getNodeType();
CodeVariableElement var = new CodeVariableElement(type, child.getName());
var.getModifiers().add(Modifier.PROTECTED);
DeclaredType annotationType;
if (child.getCardinality() == Cardinality.MANY) {
var.getModifiers().add(Modifier.FINAL);
annotationType = getContext().getTruffleTypes().getChildrenAnnotation();
} else {
annotationType = getContext().getTruffleTypes().getChildAnnotation();
}
var.getAnnotationMirrors().add(new CodeAnnotationMirror(annotationType));
return var;
}
private CodeExecutableElement createGenericExecuteAndSpecialize(final NodeData node, SpecializationGroup rootGroup) {
TypeMirror genericReturnType = node.getGenericSpecialization().getReturnType().getType();
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, FINAL), genericReturnType, EXECUTE_SPECIALIZE_NAME);
method.addParameter(new CodeVariableElement(getContext().getType(int.class), "minimumState"));
addInternalValueParameters(method, node.getGenericSpecialization(), true, false);
method.addParameter(new CodeVariableElement(getContext().getType(String.class), "reason"));
CodeTreeBuilder builder = method.createBuilder();
builder.startStatement();
builder.startStaticCall(getContext().getTruffleTypes().getCompilerAsserts(), "neverPartOfCompilation").end();
builder.end();
String currentNode = "this";
for (SpecializationData specialization : node.getSpecializations()) {
if (!specialization.getExceptions().isEmpty()) {
currentNode = "current";
builder.declaration(baseClassName(node), currentNode, "this");
break;
}
}
builder.startStatement().string("String message = ").startCall("createInfo0").string("reason");
addInternalValueParameterNames(builder, node.getGenericSpecialization(), node.getGenericSpecialization(), null, false, null);
builder.end().end();
final String currentNodeVar = currentNode;
builder.tree(createExecuteTree(builder, node.getGenericSpecialization(), rootGroup, true, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createGenericInvokeAndSpecialize(b, node.getGenericSpecialization(), current, currentNodeVar);
}
}, null, false, true, false));
boolean firstUnreachable = true;
for (SpecializationData current : node.getSpecializations()) {
if (current.isReachable()) {
continue;
}
if (firstUnreachable) {
emitEncounteredSynthetic(builder, current);
firstUnreachable = false;
}
}
emitUnreachableSpecializations(builder, node);
return method;
}
private SpecializationGroup createSpecializationGroups(final NodeData node) {
List<SpecializationData> specializations = node.getSpecializations();
List<SpecializationData> filteredSpecializations = new ArrayList<>();
for (SpecializationData current : specializations) {
if (current.isUninitialized() || current.isPolymorphic() || !current.isReachable()) {
continue;
}
filteredSpecializations.add(current);
}
return SpecializationGroup.create(filteredSpecializations);
}
private CodeExecutableElement createGenericExecute(NodeData node, SpecializationGroup group) {
TypeMirror genericReturnType = node.getGenericSpecialization().getReturnType().getType();
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, FINAL), genericReturnType, EXECUTE_GENERIC_NAME);
if (!node.needsFrame(getContext())) {
method.getAnnotationMirrors().add(new CodeAnnotationMirror(getContext().getTruffleTypes().getSlowPath()));
}
addInternalValueParameters(method, node.getGenericSpecialization(), node.needsFrame(getContext()), false);
final CodeTreeBuilder builder = method.createBuilder();
builder.tree(createExecuteTree(builder, node.getGenericSpecialization(), group, false, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createGenericInvoke(builder, current.getNode().getGenericSpecialization(), current);
}
}, null, false, true, false));
emitUnreachableSpecializations(builder, node);
return method;
}
private void emitUnreachableSpecializations(final CodeTreeBuilder builder, NodeData node) {
for (SpecializationData current : node.getSpecializations()) {
if (current.isReachable()) {
continue;
}
builder.string("// unreachable ").string(current.getId()).newLine();
}
}
protected CodeTree createExecuteTree(CodeTreeBuilder outerParent, final SpecializationData source, final SpecializationGroup group, final boolean checkMinimumState,
final CodeBlock<SpecializationData> guardedblock, final CodeTree elseBlock, boolean forceElse, final boolean emitAssumptions, final boolean typedCasts) {
return guard(outerParent, source, group, checkMinimumState, new CodeBlock<Integer>() {
public CodeTree create(CodeTreeBuilder parent, Integer ifCount) {
CodeTreeBuilder builder = parent.create();
if (group.getSpecialization() != null) {
builder.tree(guardedblock.create(builder, group.getSpecialization()));
assert group.getChildren().isEmpty() : "missed a specialization";
} else {
for (SpecializationGroup childGroup : group.getChildren()) {
builder.tree(createExecuteTree(builder, source, childGroup, checkMinimumState, guardedblock, null, false, emitAssumptions, typedCasts));
}
}
return builder.getRoot();
}
}, elseBlock, forceElse, emitAssumptions, typedCasts);
}
private CodeTree guard(CodeTreeBuilder parent, SpecializationData source, SpecializationGroup group, boolean checkMinimumState, CodeBlock<Integer> bodyBlock, CodeTree elseBlock,
boolean forceElse, boolean emitAssumptions, boolean typedCasts) {
CodeTreeBuilder builder = parent.create();
int ifCount = emitGuards(builder, source, group, checkMinimumState, emitAssumptions, typedCasts);
if (isReachableGroup(group, ifCount, checkMinimumState)) {
builder.tree(bodyBlock.create(builder, ifCount));
}
builder.end(ifCount);
if (elseBlock != null) {
if (ifCount > 0 || forceElse) {
builder.tree(elseBlock);
}
}
return builder.getRoot();
}
private boolean isReachableGroup(SpecializationGroup group, int ifCount, boolean checkMinimumState) {
if (ifCount != 0) {
return true;
}
SpecializationGroup previous = group.getPreviousGroup();
if (previous == null || previous.findElseConnectableGuards(checkMinimumState).isEmpty()) {
return true;
}
/*
* Hacky else case. In this case the specialization is not reachable due to previous
* else branch. This is only true if the minimum state is not checked.
*/
if (previous.getGuards().size() == 1 && previous.getTypeGuards().isEmpty() && previous.getAssumptions().isEmpty() && !checkMinimumState &&
(previous.getParent() == null || previous.getMaxSpecializationIndex() != previous.getParent().getMaxSpecializationIndex())) {
return false;
}
return true;
}
private int emitGuards(CodeTreeBuilder builder, SpecializationData source, SpecializationGroup group, boolean checkMinimumState, boolean emitAssumptions, boolean typedCasts) {
NodeData node = source.getNode();
CodeTreeBuilder guardsBuilder = builder.create();
CodeTreeBuilder castBuilder = builder.create();
CodeTreeBuilder guardsCastBuilder = builder.create();
String guardsAnd = "";
String guardsCastAnd = "";
boolean minimumState = checkMinimumState;
if (minimumState) {
int groupMaxIndex = group.getUncheckedSpecializationIndex();
if (groupMaxIndex > -1) {
guardsBuilder.string(guardsAnd);
guardsBuilder.string("minimumState < " + groupMaxIndex);
guardsAnd = " && ";
}
}
if (emitAssumptions) {
for (String assumption : group.getAssumptions()) {
guardsBuilder.string(guardsAnd);
guardsBuilder.string("this");
guardsBuilder.string(".").string(assumption).string(".isValid()");
guardsAnd = " && ";
}
}
for (TypeGuard typeGuard : group.getTypeGuards()) {
ActualParameter valueParam = source.getSignatureParameter(typeGuard.getSignatureIndex());
if (valueParam == null) {
/*
* If used inside a execute evaluated method then the value param may not exist.
* In that case we assume that the value is executed generic or of the current
* specialization.
*/
if (group.getSpecialization() != null) {
valueParam = group.getSpecialization().getSignatureParameter(typeGuard.getSignatureIndex());
} else {
valueParam = node.getGenericSpecialization().getSignatureParameter(typeGuard.getSignatureIndex());
}
}
NodeExecutionData execution = valueParam.getSpecification().getExecution();
CodeTree implicitGuard = createTypeGuard(guardsBuilder, execution, valueParam, typeGuard.getType(), typedCasts);
if (implicitGuard != null) {
guardsBuilder.string(guardsAnd);
guardsBuilder.tree(implicitGuard);
guardsAnd = " && ";
}
CodeTree cast = createCast(castBuilder, execution, valueParam, typeGuard.getType(), checkMinimumState, typedCasts);
if (cast != null) {
castBuilder.tree(cast);
}
}
List<GuardData> elseGuards = group.findElseConnectableGuards(checkMinimumState);
for (GuardData guard : group.getGuards()) {
if (elseGuards.contains(guard)) {
continue;
}
if (needsTypeGuard(source, group, guard)) {
guardsCastBuilder.tree(createMethodGuard(builder, guardsCastAnd, source, guard));
guardsCastAnd = " && ";
} else {
guardsBuilder.tree(createMethodGuard(builder, guardsAnd, source, guard));
guardsAnd = " && ";
}
}
int ifCount = startGuardIf(builder, guardsBuilder, 0, elseGuards);
builder.tree(castBuilder.getRoot());
ifCount = startGuardIf(builder, guardsCastBuilder, ifCount, elseGuards);
return ifCount;
}
private int startGuardIf(CodeTreeBuilder builder, CodeTreeBuilder conditionBuilder, int ifCount, List<GuardData> elseGuard) {
int newIfCount = ifCount;
if (!conditionBuilder.isEmpty()) {
if (ifCount == 0 && !elseGuard.isEmpty()) {
builder.startElseIf();
} else {
builder.startIf();
}
builder.tree(conditionBuilder.getRoot());
builder.end().startBlock();
newIfCount++;
} else if (ifCount == 0 && !elseGuard.isEmpty()) {
builder.startElseBlock();
newIfCount++;
}
return newIfCount;
}
private boolean needsTypeGuard(SpecializationData source, SpecializationGroup group, GuardData guard) {
int signatureIndex = 0;
for (ActualParameter parameter : guard.getParameters()) {
if (!parameter.getSpecification().isSignature()) {
continue;
}
TypeGuard typeGuard = group.findTypeGuard(signatureIndex);
if (typeGuard != null) {
TypeData requiredType = typeGuard.getType();
ActualParameter sourceParameter = source.findParameter(parameter.getLocalName());
if (sourceParameter == null) {
sourceParameter = source.getNode().getGenericSpecialization().findParameter(parameter.getLocalName());
}
if (Utils.needsCastTo(getContext(), sourceParameter.getType(), requiredType.getPrimitiveType())) {
return true;
}
}
signatureIndex++;
}
return false;
}
private CodeTree createTypeGuard(CodeTreeBuilder parent, NodeExecutionData execution, ActualParameter source, TypeData targetType, boolean typedCasts) {
NodeData node = execution.getChild().getNodeData();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
TypeData sourceType = source.getTypeSystemType();
if (!sourceType.needsCastTo(getContext(), targetType)) {
return null;
}
builder.startGroup();
if (execution.isShortCircuit()) {
ActualParameter shortCircuit = source.getPreviousParameter();
assert shortCircuit != null;
builder.string("(");
builder.string("!").string(valueName(shortCircuit));
builder.string(" || ");
}
String castMethodName;
String castTypeName = null;
List<TypeData> types = getModel().getNode().getTypeSystem().lookupSourceTypes(targetType);
if (types.size() > 1) {
castMethodName = TypeSystemCodeGenerator.isImplicitTypeMethodName(targetType);
if (typedCasts) {
castTypeName = implicitTypeName(source);
}
} else {
castMethodName = TypeSystemCodeGenerator.isTypeMethodName(targetType);
}
startCallTypeSystemMethod(getContext(), builder, node.getTypeSystem(), castMethodName);
builder.string(valueName(source));
if (castTypeName != null) {
builder.string(castTypeName);
}
builder.end().end(); // call
if (execution.isShortCircuit()) {
builder.string(")");
}
builder.end(); // group
return builder.getRoot();
}
// TODO merge redundancies with #createTypeGuard
private CodeTree createCast(CodeTreeBuilder parent, NodeExecutionData execution, ActualParameter source, TypeData targetType, boolean checkMinimumState, boolean typedCasts) {
NodeData node = execution.getChild().getNodeData();
TypeData sourceType = source.getTypeSystemType();
if (!sourceType.needsCastTo(getContext(), targetType)) {
return null;
}
CodeTree condition = null;
if (execution.isShortCircuit()) {
ActualParameter shortCircuit = source.getPreviousParameter();
assert shortCircuit != null;
condition = CodeTreeBuilder.singleString(valueName(shortCircuit));
}
String castMethodName;
String castTypeName = null;
List<TypeData> types = getModel().getNode().getTypeSystem().lookupSourceTypes(targetType);
if (types.size() > 1) {
castMethodName = TypeSystemCodeGenerator.asImplicitTypeMethodName(targetType);
if (typedCasts) {
castTypeName = implicitTypeName(source);
}
} else {
castMethodName = TypeSystemCodeGenerator.asTypeMethodName(targetType);
}
List<CodeTree> args = new ArrayList<>();
args.add(CodeTreeBuilder.singleString(valueName(source)));
if (castTypeName != null) {
args.add(CodeTreeBuilder.singleString(castTypeName));
}
CodeTree value = createCallTypeSystemMethod(context, parent, node, castMethodName, args.toArray(new CodeTree[0]));
CodeTreeBuilder builder = parent.create();
builder.tree(createLazyAssignment(parent, castValueName(source), targetType.getPrimitiveType(), condition, value));
if (checkMinimumState && types.size() > 1) {
CodeTree castType = createCallTypeSystemMethod(context, parent, node, TypeSystemCodeGenerator.getImplicitClass(targetType), CodeTreeBuilder.singleString(valueName(source)));
builder.tree(createLazyAssignment(builder, implicitTypeName(source), getContext().getType(Class.class), condition, castType));
}
return builder.getRoot();
}
private CodeTree createMethodGuard(CodeTreeBuilder parent, String prefix, SpecializationData source, GuardData guard) {
CodeTreeBuilder builder = parent.create();
builder.string(prefix);
if (guard.isNegated()) {
builder.string("!");
}
builder.tree(createTemplateMethodCall(builder, null, source, guard, null));
return builder.getRoot();
}
protected CodeTree createGenericInvoke(CodeTreeBuilder parent, SpecializationData source, SpecializationData current) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (current.getMethod() == null) {
emitEncounteredSynthetic(builder, current);
} else {
builder.startReturn().tree(createTemplateMethodCall(builder, null, source, current, null)).end();
}
return encloseThrowsWithFallThrough(current, builder.getRoot());
}
protected CodeTree createGenericInvokeAndSpecialize(CodeTreeBuilder parent, SpecializationData source, SpecializationData current, String currentNodeVar) {
CodeTreeBuilder builder = parent.create();
CodeTreeBuilder prefix = parent.create();
NodeData node = current.getNode();
if (current.isGeneric() && node.isPolymorphic()) {
builder.startIf().string(currentNodeVar).string(".next0 == null && minimumState > 0").end().startBlock();
builder.tree(createRewritePolymorphic(builder, node, currentNodeVar));
builder.end();
builder.startElseBlock();
builder.tree(createRewriteGeneric(builder, source, current, currentNodeVar));
builder.end();
} else {
if (current.getExceptions().isEmpty()) {
builder.tree(createGenericInvoke(builder, source, current, createReplaceCall(builder, current, currentNodeVar, currentNodeVar, null), null));
} else {
builder.startStatement().string(currentNodeVar).string(" = ").tree(createReplaceCall(builder, current, currentNodeVar, currentNodeVar, null)).end();
builder.tree(createGenericInvoke(builder, source, current, null, CodeTreeBuilder.singleString(currentNodeVar)));
}
}
CodeTreeBuilder root = parent.create();
root.tree(prefix.getRoot());
root.tree(encloseThrowsWithFallThrough(current, builder.getRoot()));
return root.getRoot();
}
private CodeTree createRewriteGeneric(CodeTreeBuilder parent, SpecializationData source, SpecializationData current, String currentNode) {
NodeData node = current.getNode();
CodeTreeBuilder builder = parent.create();
builder.declaration(getContext().getTruffleTypes().getNode(), "root", currentNode);
builder.startIf().string(currentNode).string(".next0 != null").end().startBlock();
/*
* Communicates to the caller of executeAndSpecialize that it was rewritten to generic.
* Its important that this is used instead of the currentNode since the caller is this.
* CurrentNode may not be this anymore at this place.
*/
builder.statement("this.next0 = null");
builder.tree(createFindRoot(builder, node, false));
builder.end();
builder.end();
builder.tree(createGenericInvoke(builder, source, current, createReplaceCall(builder, current, "root", "(" + baseClassName(node) + ") root", null), null));
return builder.getRoot();
}
protected CodeTree createFindRoot(CodeTreeBuilder parent, NodeData node, boolean countDepth) {
CodeTreeBuilder builder = parent.create();
builder.startDoBlock();
builder.startAssert().string("root != null").string(" : ").doubleQuote("No polymorphic parent node.").end();
builder.startStatement().string("root = ").string("root.getParent()").end();
if (countDepth) {
builder.statement("depth++");
}
builder.end();
builder.startDoWhile();
builder.string("!").startParantheses().instanceOf("root", nodePolymorphicClassName(node)).end();
builder.end();
return builder.getRoot();
}
private CodeTree encloseThrowsWithFallThrough(SpecializationData current, CodeTree tree) {
if (current.getExceptions().isEmpty()) {
return tree;
}
CodeTreeBuilder builder = new CodeTreeBuilder(null);
builder.startTryBlock();
builder.tree(tree);
for (SpecializationThrowsData exception : current.getExceptions()) {
builder.end().startCatchBlock(exception.getJavaClass(), "rewriteEx");
builder.string("// fall through").newLine();
}
builder.end();
return builder.getRoot();
}
protected CodeTree createGenericInvoke(CodeTreeBuilder parent, SpecializationData source, SpecializationData current, CodeTree replaceCall, CodeTree replaceVar) {
assert replaceCall == null || replaceVar == null;
CodeTreeBuilder builder = parent.create();
CodeTree replace = replaceVar;
if (replace == null) {
replace = replaceCall;
}
if (current.isGeneric()) {
builder.startReturn().tree(replace).string(".").startCall(EXECUTE_GENERIC_NAME);
addInternalValueParameterNames(builder, source, current, null, current.getNode().needsFrame(getContext()), null);
builder.end().end();
} else if (current.getMethod() == null) {
if (replaceCall != null) {
builder.statement(replaceCall);
}
emitEncounteredSynthetic(builder, current);
} else if (!current.canBeAccessedByInstanceOf(getContext(), source.getNode().getNodeType())) {
if (replaceCall != null) {
builder.statement(replaceCall);
}
builder.startReturn().tree(createTemplateMethodCall(parent, null, source, current, null)).end();
} else {
replace.add(new CodeTree(CodeTreeKind.STRING, null, "."));
builder.startReturn().tree(createTemplateMethodCall(parent, replace, source, current, null)).end();
}
return builder.getRoot();
}
protected CodeTree createReplaceCall(CodeTreeBuilder builder, SpecializationData current, String target, String source, String message) {
String className = nodeSpecializationClassName(current);
CodeTreeBuilder replaceCall = builder.create();
if (target != null) {
replaceCall.startCall(target, "replace");
} else {
replaceCall.startCall("replace");
}
replaceCall.startGroup().cast(baseClassName(current.getNode())).startCall(className, CREATE_SPECIALIZATION_NAME).string(source);
for (ActualParameter param : current.getSignatureParameters()) {
NodeChildData child = param.getSpecification().getExecution().getChild();
List<TypeData> types = child.getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
if (types.size() > 1) {
replaceCall.string(implicitTypeName(param));
}
}
replaceCall.end().end();
if (message == null) {
replaceCall.string("message");
} else {
replaceCall.doubleQuote(message);
}
replaceCall.end();
return replaceCall.getRoot();
}
private CodeTree createRewritePolymorphic(CodeTreeBuilder parent, NodeData node, String currentNode) {
String polyClassName = nodePolymorphicClassName(node);
String uninitializedName = nodeSpecializationClassName(node.getUninitializedSpecialization());
CodeTreeBuilder builder = parent.create();
builder.declaration(getElement().asType(), "currentCopy", currentNode + "." + COPY_WITH_CONSTRUCTOR_NAME + "()");
for (ActualParameter param : getModel().getSignatureParameters()) {
NodeExecutionData execution = param.getSpecification().getExecution();
builder.startStatement().tree(createAccessChild(execution, "currentCopy")).string(" = ").nullLiteral().end();
}
builder.startStatement().string("currentCopy.next0 = ").startNew(uninitializedName).string("currentCopy").end().end();
builder.declaration(polyClassName, "polymorphic", builder.create().startNew(polyClassName).string(currentNode).end());
builder.startStatement().string("polymorphic.next0 = ").string("currentCopy").end();
builder.startStatement().startCall(currentNode, "replace").string("polymorphic").string("message").end().end();
builder.startReturn();
builder.startCall("currentCopy.next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(builder, node.getGenericSpecialization(), node.getGenericSpecialization(), null, true, null);
builder.end();
builder.end();
return builder.getRoot();
}
protected CodeTree createCastingExecute(CodeTreeBuilder parent, SpecializationData specialization, ExecutableTypeData executable, ExecutableTypeData castExecutable) {
TypeData type = executable.getType();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
NodeData node = specialization.getNode();
ExecutableTypeData castedType = node.findExecutableType(type, 0);
TypeData primaryType = castExecutable.getType();
boolean needsTry = castExecutable.hasUnexpectedValue(getContext());
boolean returnVoid = type.isVoid();
List<ActualParameter> executeParameters = new ArrayList<>();
for (ActualParameter sourceParameter : executable.getSignatureParameters()) {
ActualParameter targetParameter = castExecutable.findParameter(sourceParameter.getLocalName());
if (targetParameter != null) {
executeParameters.add(targetParameter);
}
}
// execute names are enforced no cast
String[] executeParameterNames = new String[executeParameters.size()];
for (int i = 0; i < executeParameterNames.length; i++) {
executeParameterNames[i] = valueName(executeParameters.get(i));
}
builder.tree(createExecuteChildren(builder, executable, specialization, executeParameters, null));
CodeTree primaryExecuteCall = createTemplateMethodCall(builder, null, executable, castExecutable, null, executeParameterNames);
if (needsTry) {
if (!returnVoid) {
builder.declaration(primaryType.getPrimitiveType(), "value");
}
builder.startTryBlock();
if (returnVoid) {
builder.statement(primaryExecuteCall);
} else {
builder.startStatement();
builder.string("value = ");
builder.tree(primaryExecuteCall);
builder.end();
}
builder.end().startCatchBlock(getUnexpectedValueException(), "ex");
if (returnVoid) {
builder.string("// ignore").newLine();
} else {
builder.startReturn();
builder.tree(createExpectExecutableType(node, specialization.getNode().getTypeSystem().getGenericTypeData(), castedType, CodeTreeBuilder.singleString("ex.getResult()")));
builder.end();
}
builder.end();
if (!returnVoid) {
builder.startReturn();
builder.tree(createExpectExecutableType(node, castExecutable.getReturnType().getTypeSystemType(), executable, CodeTreeBuilder.singleString("value")));
builder.end();
}
} else {
if (returnVoid) {
builder.statement(primaryExecuteCall);
} else {
builder.startReturn();
builder.tree(createExpectExecutableType(node, castExecutable.getReturnType().getTypeSystemType(), executable, primaryExecuteCall));
builder.end();
}
}
return builder.getRoot();
}
protected CodeTree createExpectExecutableType(NodeData node, TypeData sourceType, ExecutableTypeData castedType, CodeTree value) {
boolean hasUnexpected = castedType.hasUnexpectedValue(getContext());
return createCastType(node.getTypeSystem(), sourceType, castedType.getType(), hasUnexpected, value);
}
protected CodeTree createExecuteChildren(CodeTreeBuilder parent, ExecutableTypeData sourceExecutable, SpecializationData specialization, List<ActualParameter> targetParameters,
ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = parent.create();
for (ActualParameter targetParameter : targetParameters) {
if (!targetParameter.getSpecification().isSignature()) {
continue;
}
NodeExecutionData execution = targetParameter.getSpecification().getExecution();
CodeTree executionExpressions = createExecuteChild(builder, execution, sourceExecutable, targetParameter, unexpectedParameter);
CodeTree unexpectedTree = createCatchUnexpectedTree(builder, executionExpressions, specialization, sourceExecutable, targetParameter, execution.isShortCircuit(), unexpectedParameter);
CodeTree shortCircuitTree = createShortCircuitTree(builder, unexpectedTree, specialization, targetParameter, unexpectedParameter);
if (shortCircuitTree == executionExpressions) {
if (containsNewLine(executionExpressions)) {
builder.declaration(targetParameter.getType(), valueName(targetParameter));
builder.tree(shortCircuitTree);
} else {
builder.startStatement().type(targetParameter.getType()).string(" ").tree(shortCircuitTree).end();
}
} else {
builder.tree(shortCircuitTree);
}
}
return builder.getRoot();
}
private ExecutableTypeData resolveExecutableType(NodeExecutionData execution, TypeData type) {
ExecutableTypeData targetExecutable = execution.getChild().findExecutableType(getContext(), type);
if (targetExecutable == null) {
targetExecutable = execution.getChild().findAnyGenericExecutableType(getContext());
}
return targetExecutable;
}
private CodeTree createExecuteChild(CodeTreeBuilder parent, NodeExecutionData execution, ExecutableTypeData sourceExecutable, ActualParameter targetParameter,
ActualParameter unexpectedParameter) {
SpecializationData specialization = getModel();
TreeSet<TypeData> possiblePolymorphicTypes = lookupPolymorphicTargetTypes(targetParameter);
if (specialization.isPolymorphic() && targetParameter.getTypeSystemType().isGeneric() && unexpectedParameter == null && possiblePolymorphicTypes.size() > 1) {
CodeTreeBuilder builder = parent.create();
boolean elseIf = false;
for (TypeData possiblePolymoprhicType : possiblePolymorphicTypes) {
if (possiblePolymoprhicType.isGeneric()) {
continue;
}
elseIf = builder.startIf(elseIf);
ActualParameter sourceParameter = sourceExecutable.findParameter(targetParameter.getLocalName());
TypeData sourceType = sourceParameter != null ? sourceParameter.getTypeSystemType() : null;
builder.string(polymorphicTypeName(targetParameter)).string(" == ").typeLiteral(possiblePolymoprhicType.getPrimitiveType());
builder.end().startBlock();
builder.startStatement();
builder.tree(createExecuteChildExpression(parent, execution, sourceType, new ActualParameter(targetParameter, possiblePolymoprhicType), unexpectedParameter, null));
builder.end();
builder.end();
}
builder.startElseBlock();
builder.startStatement().tree(createExecuteChildImplicit(parent, execution, sourceExecutable, targetParameter, unexpectedParameter)).end();
builder.end();
return builder.getRoot();
} else {
return createExecuteChildImplicit(parent, execution, sourceExecutable, targetParameter, unexpectedParameter);
}
}
protected final List<ActualParameter> getImplicitTypeParameters(SpecializationData model) {
List<ActualParameter> parameter = new ArrayList<>();
for (ActualParameter param : model.getSignatureParameters()) {
NodeChildData child = param.getSpecification().getExecution().getChild();
List<TypeData> types = child.getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
if (types.size() > 1) {
parameter.add(param);
}
}
return parameter;
}
protected final TreeSet<TypeData> lookupPolymorphicTargetTypes(ActualParameter param) {
SpecializationData specialization = getModel();
TreeSet<TypeData> possiblePolymorphicTypes = new TreeSet<>();
for (SpecializationData otherSpecialization : specialization.getNode().getSpecializations()) {
if (!otherSpecialization.isSpecialized()) {
continue;
}
ActualParameter otherParameter = otherSpecialization.findParameter(param.getLocalName());
if (otherParameter != null) {
possiblePolymorphicTypes.add(otherParameter.getTypeSystemType());
}
}
return possiblePolymorphicTypes;
}
private CodeTree createExecuteChildImplicit(CodeTreeBuilder parent, NodeExecutionData execution, ExecutableTypeData sourceExecutable, ActualParameter param, ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = parent.create();
ActualParameter sourceParameter = sourceExecutable.findParameter(param.getLocalName());
String childExecuteName = createExecuteChildMethodName(param, sourceParameter != null);
if (childExecuteName != null) {
builder.string(valueName(param));
builder.string(" = ");
builder.startCall(childExecuteName);
for (ActualParameter parameters : sourceExecutable.getParameters()) {
if (parameters.getSpecification().isSignature()) {
continue;
}
builder.string(parameters.getLocalName());
}
if (sourceParameter != null) {
builder.string(valueNameEvaluated(sourceParameter));
}
builder.string(implicitTypeName(param));
builder.end();
} else {
List<TypeData> sourceTypes = execution.getChild().getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
TypeData expectType = sourceParameter != null ? sourceParameter.getTypeSystemType() : null;
if (sourceTypes.size() > 1) {
builder.tree(createExecuteChildImplicitExpressions(parent, param, expectType));
} else {
builder.tree(createExecuteChildExpression(parent, execution, expectType, param, unexpectedParameter, null));
}
}
return builder.getRoot();
}
private String createExecuteChildMethodName(ActualParameter param, boolean expect) {
NodeExecutionData execution = param.getSpecification().getExecution();
NodeChildData child = execution.getChild();
if (child.getExecuteWith().size() > 0) {
return null;
}
List<TypeData> sourceTypes = child.getNodeData().getTypeSystem().lookupSourceTypes(param.getTypeSystemType());
if (sourceTypes.size() <= 1) {
return null;
}
String prefix = expect ? "expect" : "execute";
String suffix = execution.getIndex() > -1 ? String.valueOf(execution.getIndex()) : "";
return prefix + Utils.firstLetterUpperCase(child.getName()) + Utils.firstLetterUpperCase(Utils.getSimpleName(param.getType())) + suffix;
}
private List<CodeExecutableElement> createExecuteChilds(ActualParameter param, Set<TypeData> expectTypes) {
CodeExecutableElement executeMethod = createExecuteChild(param, null);
if (executeMethod == null) {
return Collections.emptyList();
}
List<CodeExecutableElement> childs = new ArrayList<>();
childs.add(executeMethod);
for (TypeData expectType : expectTypes) {
CodeExecutableElement method = createExecuteChild(param, expectType);
if (method != null) {
childs.add(method);
}
}
return childs;
}
private CodeExecutableElement createExecuteChild(ActualParameter param, TypeData expectType) {
String childExecuteName = createExecuteChildMethodName(param, expectType != null);
if (childExecuteName == null) {
return null;
}
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, expectType != null ? STATIC : FINAL), param.getType(), childExecuteName);
method.getThrownTypes().add(getContext().getTruffleTypes().getUnexpectedValueException());
method.addParameter(new CodeVariableElement(getContext().getTruffleTypes().getFrame(), "frameValue"));
if (expectType != null) {
method.addParameter(new CodeVariableElement(expectType.getPrimitiveType(), valueNameEvaluated(param)));
}
method.addParameter(new CodeVariableElement(getContext().getType(Class.class), implicitTypeName(param)));
CodeTreeBuilder builder = method.createBuilder();
builder.declaration(param.getType(), valueName(param));
builder.tree(createExecuteChildImplicitExpressions(builder, param, expectType));
builder.startReturn().string(valueName(param)).end();
return method;
}
private CodeTree createExecuteChildImplicitExpressions(CodeTreeBuilder parent, ActualParameter targetParameter, TypeData expectType) {
CodeTreeBuilder builder = parent.create();
NodeData node = getModel().getNode();
NodeExecutionData execution = targetParameter.getSpecification().getExecution();
List<TypeData> sourceTypes = node.getTypeSystem().lookupSourceTypes(targetParameter.getTypeSystemType());
boolean elseIf = false;
int index = 0;
for (TypeData sourceType : sourceTypes) {
if (index < sourceTypes.size() - 1) {
elseIf = builder.startIf(elseIf);
builder.string(implicitTypeName(targetParameter)).string(" == ").typeLiteral(sourceType.getPrimitiveType());
builder.end();
builder.startBlock();
} else {
builder.startElseBlock();
}
ExecutableTypeData implictExecutableTypeData = execution.getChild().findExecutableType(getContext(), sourceType);
if (implictExecutableTypeData == null) {
/*
* For children with executeWith.size() > 0 an executable type may not exist so
* use the generic executable type which is guaranteed to exist. An expect call
* is inserted automatically by #createExecuteExpression.
*/
implictExecutableTypeData = execution.getChild().getNodeData().findExecutableType(node.getTypeSystem().getGenericTypeData(), execution.getChild().getExecuteWith().size());
}
ImplicitCastData cast = execution.getChild().getNodeData().getTypeSystem().lookupCast(sourceType, targetParameter.getTypeSystemType());
CodeTree execute = createExecuteChildExpression(builder, execution, expectType, targetParameter, null, cast);
builder.statement(execute);
builder.end();
index++;
}
return builder.getRoot();
}
private CodeTree createExecuteChildExpression(CodeTreeBuilder parent, NodeExecutionData execution, TypeData sourceParameterType, ActualParameter targetParameter,
ActualParameter unexpectedParameter, ImplicitCastData cast) {
// assignments: targetType <- castTargetType <- castSourceType <- sourceType
TypeData sourceType = sourceParameterType;
TypeData targetType = targetParameter.getTypeSystemType();
TypeData castSourceType = targetType;
TypeData castTargetType = targetType;
if (cast != null) {
castSourceType = cast.getSourceType();
castTargetType = cast.getTargetType();
}
CodeTree expression;
if (sourceType == null) {
ExecutableTypeData targetExecutable = resolveExecutableType(execution, castSourceType);
expression = createExecuteChildExpression(parent, execution, targetExecutable, unexpectedParameter);
sourceType = targetExecutable.getType();
} else {
expression = CodeTreeBuilder.singleString(valueNameEvaluated(targetParameter));
}
// target = expectTargetType(implicitCast(expectCastSourceType(source)))
TypeSystemData typeSystem = execution.getChild().getNodeData().getTypeSystem();
expression = createExpectType(typeSystem, sourceType, castSourceType, expression);
expression = createImplicitCast(parent, typeSystem, cast, expression);
expression = createExpectType(typeSystem, castTargetType, targetType, expression);
CodeTreeBuilder builder = parent.create();
builder.string(valueName(targetParameter));
builder.string(" = ");
builder.tree(expression);
return builder.getRoot();
}
private CodeTree createImplicitCast(CodeTreeBuilder parent, TypeSystemData typeSystem, ImplicitCastData cast, CodeTree expression) {
if (cast == null) {
return expression;
}
CodeTreeBuilder builder = parent.create();
startCallTypeSystemMethod(getContext(), builder, typeSystem, cast.getMethodName());
builder.tree(expression);
builder.end().end();
return builder.getRoot();
}
private boolean containsNewLine(CodeTree tree) {
if (tree.getCodeKind() == CodeTreeKind.NEW_LINE) {
return true;
}
for (CodeTree codeTree : tree.getEnclosedElements()) {
if (containsNewLine(codeTree)) {
return true;
}
}
return false;
}
private boolean hasUnexpected(ActualParameter sourceParameter, ActualParameter targetParameter, ActualParameter unexpectedParameter) {
NodeExecutionData execution = targetParameter.getSpecification().getExecution();
if (getModel().isPolymorphic() && targetParameter.getTypeSystemType().isGeneric() && unexpectedParameter == null) {
// check for other polymorphic types
TreeSet<TypeData> polymorphicTargetTypes = lookupPolymorphicTargetTypes(targetParameter);
if (polymorphicTargetTypes.size() > 1) {
for (TypeData polymorphicTargetType : polymorphicTargetTypes) {
if (hasUnexpectedType(execution, sourceParameter, polymorphicTargetType)) {
return true;
}
}
}
}
if (hasUnexpectedType(execution, sourceParameter, targetParameter.getTypeSystemType())) {
return true;
}
return false;
}
private boolean hasUnexpectedType(NodeExecutionData execution, ActualParameter sourceParameter, TypeData targetType) {
List<TypeData> implicitSourceTypes = getModel().getNode().getTypeSystem().lookupSourceTypes(targetType);
for (TypeData implicitSourceType : implicitSourceTypes) {
TypeData sourceType;
ExecutableTypeData targetExecutable = resolveExecutableType(execution, implicitSourceType);
if (sourceParameter != null) {
sourceType = sourceParameter.getTypeSystemType();
} else {
if (targetExecutable.hasUnexpectedValue(getContext())) {
return true;
}
sourceType = targetExecutable.getType();
}
ImplicitCastData cast = getModel().getNode().getTypeSystem().lookupCast(implicitSourceType, targetType);
if (cast != null) {
if (cast.getSourceType().needsCastTo(getContext(), targetType)) {
return true;
}
}
if (sourceType.needsCastTo(getContext(), targetType)) {
return true;
}
}
return false;
}
private CodeTree createCatchUnexpectedTree(CodeTreeBuilder parent, CodeTree body, SpecializationData specialization, ExecutableTypeData currentExecutable, ActualParameter param,
boolean shortCircuit, ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
ActualParameter sourceParameter = currentExecutable.findParameter(param.getLocalName());
boolean unexpected = hasUnexpected(sourceParameter, param, unexpectedParameter);
if (!unexpected) {
return body;
}
if (!shortCircuit) {
builder.declaration(param.getType(), valueName(param));
}
builder.startTryBlock();
if (containsNewLine(body)) {
builder.tree(body);
} else {
builder.statement(body);
}
builder.end().startCatchBlock(getUnexpectedValueException(), "ex");
SpecializationData generic = specialization.getNode().getGenericSpecialization();
ActualParameter genericParameter = generic.findParameter(param.getLocalName());
List<ActualParameter> genericParameters = generic.getParametersAfter(genericParameter);
builder.tree(createExecuteChildren(parent, currentExecutable, generic, genericParameters, genericParameter));
if (specialization.isPolymorphic()) {
builder.tree(createReturnOptimizeTypes(builder, currentExecutable, specialization, param));
} else {
builder.tree(createReturnExecuteAndSpecialize(builder, currentExecutable, specialization, param,
"Expected " + param.getLocalName() + " instanceof " + Utils.getSimpleName(param.getType())));
}
builder.end(); // catch block
return builder.getRoot();
}
private CodeTree createReturnOptimizeTypes(CodeTreeBuilder parent, ExecutableTypeData currentExecutable, SpecializationData specialization, ActualParameter param) {
NodeData node = specialization.getNode();
SpecializationData polymorphic = node.getPolymorphicSpecialization();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.startStatement().string(polymorphicTypeName(param)).string(" = ").typeLiteral(getContext().getType(Object.class)).end();
builder.startReturn();
CodeTreeBuilder execute = new CodeTreeBuilder(builder);
execute.startCall("next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(execute, specialization, polymorphic, param.getLocalName(), true, null);
execute.end();
TypeData sourceType = polymorphic.getReturnType().getTypeSystemType();
builder.tree(createExpectExecutableType(node, sourceType, currentExecutable, execute.getRoot()));
builder.end();
return builder.getRoot();
}
private CodeTree createExecuteChildExpression(CodeTreeBuilder parent, NodeExecutionData targetExecution, ExecutableTypeData targetExecutable, ActualParameter unexpectedParameter) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (targetExecution != null) {
builder.tree(createAccessChild(targetExecution, null));
builder.string(".");
}
builder.startCall(targetExecutable.getMethodName());
// TODO this should be merged with #createTemplateMethodCall
int index = 0;
for (ActualParameter parameter : targetExecutable.getParameters()) {
if (!parameter.getSpecification().isSignature()) {
builder.string(parameter.getLocalName());
} else {
if (index < targetExecution.getChild().getExecuteWith().size()) {
NodeChildData child = targetExecution.getChild().getExecuteWith().get(index);
ParameterSpec spec = getModel().getSpecification().findParameterSpec(child.getName());
List<ActualParameter> specializationParams = getModel().findParameters(spec);
if (specializationParams.isEmpty()) {
builder.defaultValue(parameter.getType());
continue;
}
ActualParameter specializationParam = specializationParams.get(0);
TypeData targetType = parameter.getTypeSystemType();
TypeData sourceType = specializationParam.getTypeSystemType();
String localName = specializationParam.getLocalName();
if (unexpectedParameter != null && unexpectedParameter.getLocalName().equals(specializationParam.getLocalName())) {
localName = "ex.getResult()";
sourceType = getModel().getNode().getTypeSystem().getGenericTypeData();
}
CodeTree value = CodeTreeBuilder.singleString(localName);
if (sourceType.needsCastTo(getContext(), targetType)) {
value = createCallTypeSystemMethod(getContext(), builder, getModel().getNode(), TypeSystemCodeGenerator.asTypeMethodName(targetType), value);
}
builder.tree(value);
} else {
builder.defaultValue(parameter.getType());
}
index++;
}
}
builder.end();
return builder.getRoot();
}
private CodeTree createShortCircuitTree(CodeTreeBuilder parent, CodeTree body, SpecializationData specialization, ActualParameter parameter, ActualParameter exceptionParam) {
NodeExecutionData execution = parameter.getSpecification().getExecution();
if (execution == null || !execution.isShortCircuit()) {
return body;
}
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
ActualParameter shortCircuitParam = specialization.getPreviousParam(parameter);
builder.tree(createShortCircuitValue(builder, specialization, execution, shortCircuitParam, exceptionParam));
builder.declaration(parameter.getType(), valueName(parameter), CodeTreeBuilder.createBuilder().defaultValue(parameter.getType()));
builder.startIf().string(shortCircuitParam.getLocalName()).end();
builder.startBlock();
if (containsNewLine(body)) {
builder.tree(body);
} else {
builder.statement(body);
}
builder.end();
return builder.getRoot();
}
private CodeTree createShortCircuitValue(CodeTreeBuilder parent, SpecializationData specialization, NodeExecutionData execution, ActualParameter shortCircuitParam,
ActualParameter exceptionParam) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
int shortCircuitIndex = 0;
for (NodeExecutionData otherExectuion : specialization.getNode().getChildExecutions()) {
if (otherExectuion.isShortCircuit()) {
if (otherExectuion == execution) {
break;
}
shortCircuitIndex++;
}
}
builder.startStatement().type(shortCircuitParam.getType()).string(" ").string(valueName(shortCircuitParam)).string(" = ");
ShortCircuitData shortCircuitData = specialization.getShortCircuits().get(shortCircuitIndex);
builder.tree(createTemplateMethodCall(builder, null, specialization, shortCircuitData, exceptionParam != null ? exceptionParam.getLocalName() : null));
builder.end(); // statement
return builder.getRoot();
}
protected CodeTree createReturnExecuteAndSpecialize(CodeTreeBuilder parent, ExecutableTypeData executable, SpecializationData current, ActualParameter exceptionParam, String reason) {
NodeData node = current.getNode();
SpecializationData generic = node.getGenericSpecialization();
CodeTreeBuilder specializeCall = new CodeTreeBuilder(parent);
specializeCall.startCall(EXECUTE_SPECIALIZE_NAME);
/**
* zwei: An experimental hack.<br>
* We reduce the minimumState value argument by 1 when a specialized node calls
* BaseNode#executeAndSpecialize. This change is intended to change the rewriting
* behavior of a node using @ImplicitCast to guard its operand type. If one of its
* operand's type changes, it now can rewrite to the same specialiazed node with an
* updated operand implicit type.
*/
specializeCall.string(String.valueOf(node.getSpecializations().indexOf(current) - 1));
addInternalValueParameterNames(specializeCall, generic, node.getGenericSpecialization(), exceptionParam != null ? exceptionParam.getLocalName() : null, true, null);
specializeCall.doubleQuote(reason);
specializeCall.end().end();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.startReturn();
builder.tree(createExpectExecutableType(node, generic.getReturnType().getTypeSystemType(), executable, specializeCall.getRoot()));
builder.end();
return builder.getRoot();
}
protected final CodeExecutableElement createUpdateTypes(TypeMirror polymorphicType) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED), getContext().getType(void.class), UPDATE_TYPES_NAME);
method.getParameters().add(new CodeVariableElement(polymorphicType, "polymorphic"));
CodeTreeBuilder builder = method.createBuilder();
if (getModel().isPolymorphic()) {
builder.startStatement();
builder.startCall("next0", "updateTypes").string("polymorphic").end();
builder.end();
} else if (getModel().isSpecialized()) {
for (ActualParameter parameter : getModel().getParameters()) {
if (!parameter.getSpecification().isSignature()) {
continue;
}
if (lookupPolymorphicTargetTypes(parameter).size() <= 1) {
continue;
}
builder.startStatement();
builder.startCall("polymorphic", createUpdateTypeName(parameter));
builder.typeLiteral(parameter.getType());
builder.end().end();
}
builder.startStatement().startCall("super", UPDATE_TYPES_NAME).string("polymorphic").end().end();
}
return method;
}
protected String createUpdateTypeName(ActualParameter parameter) {
return "update" + Utils.firstLetterUpperCase(parameter.getLocalName()) + "Type";
}
}
private class PolymorphicNodeFactory extends SpecializedNodeFactory {
public PolymorphicNodeFactory(ProcessorContext context, CodeTypeElement nodeGen) {
super(context, nodeGen);
}
@Override
public CodeTypeElement create(SpecializationData polymorph) {
NodeData node = polymorph.getNode();
TypeMirror baseType = node.getNodeType();
if (nodeGen != null) {
baseType = nodeGen.asType();
}
CodeTypeElement clazz = createClass(node, modifiers(PRIVATE, STATIC, FINAL), nodePolymorphicClassName(node), baseType, false);
clazz.getAnnotationMirrors().add(createNodeInfo(node, NodeCost.POLYMORPHIC));
for (ActualParameter polymorphParameter : polymorph.getSignatureParameters()) {
if (!polymorphParameter.getTypeSystemType().isGeneric()) {
continue;
}
Set<TypeData> types = new HashSet<>();
for (SpecializationData specialization : node.getSpecializations()) {
if (!specialization.isSpecialized()) {
continue;
}
ActualParameter parameter = specialization.findParameter(polymorphParameter.getLocalName());
assert parameter != null;
types.add(parameter.getTypeSystemType());
}
CodeVariableElement var = new CodeVariableElement(modifiers(PRIVATE), getContext().getType(Class.class), polymorphicTypeName(polymorphParameter));
var.getAnnotationMirrors().add(new CodeAnnotationMirror(getContext().getTruffleTypes().getCompilationFinal()));
clazz.add(var);
}
return clazz;
}
@Override
protected void createChildren(SpecializationData specialization) {
CodeTypeElement clazz = getElement();
createConstructors(clazz);
createExecuteMethods(specialization);
getElement().add(createUpdateTypes(nodeGen.asType()));
for (ActualParameter parameter : specialization.getParameters()) {
if (!parameter.getSpecification().isSignature()) {
continue;
}
if (lookupPolymorphicTargetTypes(parameter).size() <= 1) {
continue;
}
getElement().add(createUpdateType(parameter));
}
if (needsInvokeCopyConstructorMethod()) {
clazz.add(createCopy(nodeGen.asType(), specialization));
}
createCachedExecuteMethods(specialization);
}
private ExecutableElement createUpdateType(ActualParameter parameter) {
CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED), getContext().getType(void.class), createUpdateTypeName(parameter));
method.getParameters().add(new CodeVariableElement(getContext().getType(Class.class), "type"));
CodeTreeBuilder builder = method.createBuilder();
String fieldName = polymorphicTypeName(parameter);
builder.startIf().string(fieldName).isNull().end().startBlock();
builder.startStatement().string(fieldName).string(" = ").string("type").end();
builder.end();
builder.startElseIf().string(fieldName).string(" != ").string("type").end();
builder.startBlock();
builder.startStatement().string(fieldName).string(" = ").typeLiteral(getContext().getType(Object.class)).end();
builder.end();
return method;
}
}
private class SpecializedNodeFactory extends NodeBaseFactory {
protected final CodeTypeElement nodeGen;
public SpecializedNodeFactory(ProcessorContext context, CodeTypeElement nodeGen) {
super(context);
this.nodeGen = nodeGen;
}
@Override
public CodeTypeElement create(SpecializationData specialization) {
NodeData node = specialization.getNode();
TypeMirror baseType = node.getNodeType();
if (nodeGen != null) {
baseType = nodeGen.asType();
}
CodeTypeElement clazz = createClass(node, modifiers(PRIVATE, STATIC, FINAL), nodeSpecializationClassName(specialization), baseType, false);
NodeCost cost;
if (specialization.isGeneric()) {
cost = NodeCost.MEGAMORPHIC;
} else if (specialization.isUninitialized()) {
cost = NodeCost.UNINITIALIZED;
} else if (specialization.isPolymorphic()) {
cost = NodeCost.POLYMORPHIC;
} else if (specialization.isSpecialized()) {
cost = NodeCost.MONOMORPHIC;
} else {
throw new AssertionError();
}
clazz.getAnnotationMirrors().add(createNodeInfo(node, cost));
return clazz;
}
protected CodeAnnotationMirror createNodeInfo(NodeData node, NodeCost cost) {
String shortName = node.getShortName();
CodeAnnotationMirror nodeInfoMirror = new CodeAnnotationMirror(getContext().getTruffleTypes().getNodeInfoAnnotation());
if (shortName != null) {
nodeInfoMirror.setElementValue(nodeInfoMirror.findExecutableElement("shortName"), new CodeAnnotationValue(shortName));
}
DeclaredType nodeinfoCost = getContext().getTruffleTypes().getNodeCost();
VariableElement varKind = Utils.findVariableElement(nodeinfoCost, cost.name());
nodeInfoMirror.setElementValue(nodeInfoMirror.findExecutableElement("cost"), new CodeAnnotationValue(varKind));
return nodeInfoMirror;
}
@Override
protected void createChildren(SpecializationData specialization) {
CodeTypeElement clazz = getElement();
createConstructors(clazz);
createExecuteMethods(specialization);
createCachedExecuteMethods(specialization);
if (specialization.getNode().isPolymorphic()) {
getElement().add(createUpdateTypes(nodeGen.asType()));
}
if (needsInvokeCopyConstructorMethod()) {
clazz.add(createCopy(nodeGen.asType(), specialization));
}
if (!specialization.isUninitialized() && specialization.getNode().needsRewrites(context)) {
clazz.add(createCopyConstructorFactoryMethod(nodeGen.asType(), specialization));
} else {
for (ExecutableElement constructor : ElementFilter.constructorsIn(clazz.getEnclosedElements())) {
if (constructor.getParameters().size() == 1 && ((CodeVariableElement) constructor.getParameters().get(0)).getType().equals(nodeGen.asType())) {
// skip copy constructor - not used
continue;
}
clazz.add(createConstructorFactoryMethod(specialization, constructor));
}
}
}
protected void createConstructors(CodeTypeElement clazz) {
TypeElement superTypeElement = Utils.fromTypeMirror(clazz.getSuperclass());
SpecializationData specialization = getModel();
NodeData node = specialization.getNode();
for (ExecutableElement constructor : ElementFilter.constructorsIn(superTypeElement.getEnclosedElements())) {
if (specialization.isUninitialized()) {
// ignore copy constructors for uninitialized if not polymorphic
if (isCopyConstructor(constructor) && !node.isPolymorphic()) {
continue;
}
} else if (node.getUninitializedSpecialization() != null) {
// ignore others than copy constructors for specialized nodes
if (!isCopyConstructor(constructor)) {
continue;
}
}
CodeExecutableElement superConstructor = createSuperConstructor(clazz, constructor);
if (superConstructor == null) {
continue;
}
CodeTree body = superConstructor.getBodyTree();
CodeTreeBuilder builder = superConstructor.createBuilder();
builder.tree(body);
if (node.isPolymorphic()) {
if (specialization.isSpecialized() || specialization.isPolymorphic()) {
builder.statement("this.next0 = copy.next0");
}
}
if (superConstructor != null) {
for (ActualParameter param : getImplicitTypeParameters(getModel())) {
clazz.add(new CodeVariableElement(modifiers(PRIVATE, FINAL), getContext().getType(Class.class), implicitTypeName(param)));
superConstructor.getParameters().add(new CodeVariableElement(getContext().getType(Class.class), implicitTypeName(param)));
builder.startStatement();
builder.string("this.").string(implicitTypeName(param)).string(" = ").string(implicitTypeName(param));
builder.end();
}
clazz.add(superConstructor);
}
}
}
protected void createExecuteMethods(SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTypeElement clazz = getElement();
for (ExecutableTypeData execType : node.getExecutableTypes()) {
if (execType.isFinal()) {
continue;
}
CodeExecutableElement executeMethod = createExecutableTypeOverride(execType, true);
clazz.add(executeMethod);
CodeTreeBuilder builder = executeMethod.getBuilder();
CodeTree result = createExecuteBody(builder, specialization, execType);
if (result != null) {
builder.tree(result);
} else {
clazz.remove(executeMethod);
}
}
}
protected void createCachedExecuteMethods(SpecializationData specialization) {
NodeData node = specialization.getNode();
if (!node.isPolymorphic()) {
return;
}
CodeTypeElement clazz = getElement();
final SpecializationData polymorphic = node.getPolymorphicSpecialization();
ExecutableElement executeCached = nodeGen.getMethod(EXECUTE_POLYMORPHIC_NAME);
CodeExecutableElement executeMethod = CodeExecutableElement.clone(getContext().getEnvironment(), executeCached);
executeMethod.getModifiers().remove(Modifier.ABSTRACT);
CodeTreeBuilder builder = executeMethod.createBuilder();
if (specialization.isGeneric() || specialization.isPolymorphic()) {
builder.startThrow().startNew(getContext().getType(AssertionError.class));
builder.doubleQuote("Should not be reached.");
builder.end().end();
} else if (specialization.isUninitialized()) {
builder.tree(createAppendPolymorphic(builder, specialization));
} else {
CodeTreeBuilder elseBuilder = new CodeTreeBuilder(builder);
elseBuilder.startReturn().startCall("this.next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(elseBuilder, polymorphic, polymorphic, null, true, null);
elseBuilder.end().end();
boolean forceElse = specialization.getExceptions().size() > 0;
builder.tree(createExecuteTree(builder, polymorphic, SpecializationGroup.create(specialization), false, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createGenericInvoke(b, polymorphic, current);
}
}, elseBuilder.getRoot(), forceElse, true, true));
}
clazz.add(executeMethod);
}
private CodeTree createAppendPolymorphic(CodeTreeBuilder parent, SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
builder.tree(createDeoptimize(builder));
builder.declaration(getContext().getTruffleTypes().getNode(), "root", "this");
builder.declaration(getContext().getType(int.class), "depth", "0");
builder.tree(createFindRoot(builder, node, true));
builder.newLine();
builder.startIf().string("depth > ").string(String.valueOf(node.getPolymorphicDepth())).end();
builder.startBlock();
String message = "Polymorphic limit reached (" + node.getPolymorphicDepth() + ")";
String castRoot = "(" + baseClassName(node) + ") root";
builder.tree(createGenericInvoke(builder, node.getPolymorphicSpecialization(), node.getGenericSpecialization(),
createReplaceCall(builder, node.getGenericSpecialization(), "root", castRoot, message), null));
builder.end();
builder.startElseBlock();
builder.startStatement().string("next0 = ");
builder.startNew(nodeSpecializationClassName(node.getUninitializedSpecialization())).string("this").end();
builder.end();
CodeTreeBuilder specializeCall = new CodeTreeBuilder(builder);
specializeCall.startCall(EXECUTE_SPECIALIZE_NAME);
specializeCall.string("0");
addInternalValueParameterNames(specializeCall, specialization, node.getGenericSpecialization(), null, true, null);
specializeCall.startGroup().doubleQuote("Uninitialized polymorphic (").string(" + depth + ").doubleQuote("/" + node.getPolymorphicDepth() + ")").end();
specializeCall.end().end();
builder.declaration(node.getGenericSpecialization().getReturnType().getType(), "result", specializeCall.getRoot());
CodeTree root = builder.create().cast(nodePolymorphicClassName(node)).string("root").getRoot();
builder.startIf().string("this.next0 != null").end().startBlock();
builder.startStatement().string("(").tree(root).string(").").startCall(UPDATE_TYPES_NAME).tree(root).end().end();
builder.end();
if (Utils.isVoid(builder.findMethod().getReturnType())) {
builder.returnStatement();
} else {
builder.startReturn().string("result").end();
}
builder.end();
return builder.getRoot();
}
private CodeTree createExecuteBody(CodeTreeBuilder parent, SpecializationData specialization, ExecutableTypeData execType) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
List<ExecutableTypeData> primaryExecutes = findFunctionalExecutableType(specialization, execType.getEvaluatedCount());
if (primaryExecutes.contains(execType) || primaryExecutes.isEmpty()) {
builder.tree(createFunctionalExecute(builder, specialization, execType));
} else if (needsCastingExecuteMethod(execType)) {
assert !primaryExecutes.isEmpty();
builder.tree(createCastingExecute(builder, specialization, execType, primaryExecutes.get(0)));
} else {
return null;
}
return builder.getRoot();
}
private CodeExecutableElement createExecutableTypeOverride(ExecutableTypeData execType, boolean evaluated) {
CodeExecutableElement method = CodeExecutableElement.clone(getContext().getEnvironment(), execType.getMethod());
CodeTreeBuilder builder = method.createBuilder();
int i = 0;
int signatureIndex = -1;
for (VariableElement param : method.getParameters()) {
CodeVariableElement var = CodeVariableElement.clone(param);
ActualParameter actualParameter = i < execType.getParameters().size() ? execType.getParameters().get(i) : null;
String name;
if (actualParameter != null) {
if (actualParameter.getSpecification().isSignature()) {
signatureIndex++;
}
if (evaluated && actualParameter.getSpecification().isSignature()) {
name = valueNameEvaluated(actualParameter);
} else {
name = valueName(actualParameter);
}
int varArgCount = getModel().getSignatureSize() - signatureIndex;
if (evaluated && actualParameter.isTypeVarArgs()) {
ActualParameter baseVarArgs = actualParameter;
name = valueName(baseVarArgs) + "Args";
builder.startAssert().string(name).string(" != null").end();
builder.startAssert().string(name).string(".length == ").string(String.valueOf(varArgCount)).end();
if (varArgCount > 0) {
List<ActualParameter> varArgsParameter = execType.getParameters().subList(i, execType.getParameters().size());
for (ActualParameter varArg : varArgsParameter) {
if (varArgCount <= 0) {
break;
}
TypeMirror type = baseVarArgs.getType();
if (type.getKind() == TypeKind.ARRAY) {
type = ((ArrayType) type).getComponentType();
}
builder.declaration(type, valueNameEvaluated(varArg), name + "[" + varArg.getTypeVarArgsIndex() + "]");
varArgCount--;
}
}
}
} else {
name = "arg" + i;
}
var.setName(name);
method.getParameters().set(i, var);
i++;
}
method.getAnnotationMirrors().clear();
method.getModifiers().remove(Modifier.ABSTRACT);
return method;
}
private boolean needsCastingExecuteMethod(ExecutableTypeData execType) {
if (execType.isAbstract()) {
return true;
}
if (execType.getType().isGeneric()) {
return true;
}
return false;
}
private List<ExecutableTypeData> findFunctionalExecutableType(SpecializationData specialization, int evaluatedCount) {
TypeData primaryType = specialization.getReturnType().getTypeSystemType();
List<ExecutableTypeData> otherTypes = specialization.getNode().getExecutableTypes(evaluatedCount);
List<ExecutableTypeData> filteredTypes = new ArrayList<>();
for (ExecutableTypeData compareType : otherTypes) {
if (!Utils.typeEquals(compareType.getType().getPrimitiveType(), primaryType.getPrimitiveType())) {
continue;
}
filteredTypes.add(compareType);
}
// no direct matches found use generic where the type is Object
if (filteredTypes.isEmpty()) {
for (ExecutableTypeData compareType : otherTypes) {
if (compareType.getType().isGeneric() && !compareType.hasUnexpectedValue(getContext())) {
filteredTypes.add(compareType);
}
}
}
if (filteredTypes.isEmpty()) {
for (ExecutableTypeData compareType : otherTypes) {
if (compareType.getType().isGeneric()) {
filteredTypes.add(compareType);
}
}
}
return filteredTypes;
}
private CodeTree createFunctionalExecute(CodeTreeBuilder parent, final SpecializationData specialization, final ExecutableTypeData executable) {
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (specialization.isUninitialized()) {
builder.tree(createDeoptimize(builder));
}
builder.tree(createExecuteChildren(builder, executable, specialization, specialization.getParameters(), null));
CodeTree returnSpecialized = null;
if (specialization.findNextSpecialization() != null) {
CodeTreeBuilder returnBuilder = new CodeTreeBuilder(builder);
returnBuilder.tree(createDeoptimize(builder));
returnBuilder.tree(createReturnExecuteAndSpecialize(builder, executable, specialization, null, "One of guards " + specialization.getGuardDefinitions() + " failed"));
returnSpecialized = returnBuilder.getRoot();
}
builder.tree(createExecuteTree(builder, specialization, SpecializationGroup.create(specialization), false, new CodeBlock<SpecializationData>() {
public CodeTree create(CodeTreeBuilder b, SpecializationData current) {
return createExecute(b, executable, specialization);
}
}, returnSpecialized, false, false, false));
return builder.getRoot();
}
private CodeTree createExecute(CodeTreeBuilder parent, ExecutableTypeData executable, SpecializationData specialization) {
NodeData node = specialization.getNode();
CodeTreeBuilder builder = new CodeTreeBuilder(parent);
if (!specialization.getExceptions().isEmpty() || !specialization.getAssumptions().isEmpty()) {
builder.startTryBlock();
}
for (String assumption : specialization.getAssumptions()) {
builder.startStatement();
builder.string("this.").string(assumption).string(".check()");
builder.end();
}
CodeTreeBuilder returnBuilder = new CodeTreeBuilder(parent);
if (specialization.isPolymorphic()) {
returnBuilder.startCall("next0", EXECUTE_POLYMORPHIC_NAME);
addInternalValueParameterNames(returnBuilder, specialization, specialization, null, true, null);
returnBuilder.end();
} else if (specialization.isUninitialized()) {
returnBuilder.startCall("super", EXECUTE_SPECIALIZE_NAME);
returnBuilder.string("0");
addInternalValueParameterNames(returnBuilder, specialization, specialization, null, true, null);
returnBuilder.doubleQuote("Uninitialized monomorphic");
returnBuilder.end();
} else if (specialization.getMethod() == null && !node.needsRewrites(context)) {
emitEncounteredSynthetic(builder, specialization);
} else if (specialization.isGeneric()) {
returnBuilder.startCall("super", EXECUTE_GENERIC_NAME);
addInternalValueParameterNames(returnBuilder, specialization, specialization, null, node.needsFrame(getContext()), null);
returnBuilder.end();
} else {
returnBuilder.tree(createTemplateMethodCall(returnBuilder, null, specialization, specialization, null));
}
if (!returnBuilder.isEmpty()) {
TypeData targetType = node.getTypeSystem().findTypeData(builder.findMethod().getReturnType());
TypeData sourceType = specialization.getReturnType().getTypeSystemType();
builder.startReturn();
if (targetType == null || sourceType == null) {
builder.tree(returnBuilder.getRoot());
} else if (sourceType.needsCastTo(getContext(), targetType)) {
String castMethodName = TypeSystemCodeGenerator.expectTypeMethodName(targetType);
if (!executable.hasUnexpectedValue(context)) {
castMethodName = TypeSystemCodeGenerator.asTypeMethodName(targetType);
}
builder.tree(createCallTypeSystemMethod(context, parent, node, castMethodName, returnBuilder.getRoot()));
} else {
builder.tree(returnBuilder.getRoot());
}
builder.end();
}
if (!specialization.getExceptions().isEmpty()) {
for (SpecializationThrowsData exception : specialization.getExceptions()) {
builder.end().startCatchBlock(exception.getJavaClass(), "ex");
builder.tree(createDeoptimize(builder));
builder.tree(createReturnExecuteAndSpecialize(parent, executable, specialization, null, "Thrown " + Utils.getSimpleName(exception.getJavaClass())));
}
builder.end();
}
if (!specialization.getAssumptions().isEmpty()) {
builder.end().startCatchBlock(getContext().getTruffleTypes().getInvalidAssumption(), "ex");
builder.tree(createReturnExecuteAndSpecialize(parent, executable, specialization, null, "Assumption failed"));
builder.end();
}
return builder.getRoot();
}
protected CodeExecutableElement createCopyConstructorFactoryMethod(TypeMirror baseType, SpecializationData specialization) {
List<ActualParameter> implicitTypeParams = getImplicitTypeParameters(specialization);
CodeVariableElement[] parameters = new CodeVariableElement[implicitTypeParams.size() + 1];
int i = 0;
String baseName = "current";
parameters[i++] = new CodeVariableElement(specialization.getNode().getNodeType(), baseName);
for (ActualParameter implicitTypeParam : implicitTypeParams) {
parameters[i++] = new CodeVariableElement(getContext().getType(Class.class), implicitTypeName(implicitTypeParam));
}
CodeExecutableElement method = new CodeExecutableElement(modifiers(STATIC), specialization.getNode().getNodeType(), CREATE_SPECIALIZATION_NAME, parameters);
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startNew(getElement().asType());
builder.startGroup().cast(baseType, CodeTreeBuilder.singleString(baseName)).end();
for (ActualParameter param : implicitTypeParams) {
builder.string(implicitTypeName(param));
}
builder.end().end();
return method;
}
protected CodeExecutableElement createConstructorFactoryMethod(SpecializationData specialization, ExecutableElement constructor) {
List<? extends VariableElement> parameters = constructor.getParameters();
CodeExecutableElement method = new CodeExecutableElement(modifiers(STATIC), specialization.getNode().getNodeType(), CREATE_SPECIALIZATION_NAME,
parameters.toArray(new CodeVariableElement[parameters.size()]));
CodeTreeBuilder builder = method.createBuilder();
builder.startReturn();
builder.startNew(getElement().asType());
for (VariableElement param : parameters) {
builder.string(((CodeVariableElement) param).getName());
}
builder.end().end();
return method;
}
}
private interface CodeBlock<T> {
CodeTree create(CodeTreeBuilder parent, T value);
}
}
| Revert local change made in dsl.processor
| graal/com.oracle.truffle.dsl.processor/src/com/oracle/truffle/dsl/processor/node/NodeCodeGenerator.java | Revert local change made in dsl.processor |
|
Java | apache-2.0 | 95d5fe4eb7891d30e89554b288f6dcab85a8cec3 | 0 | rbheemana/Sqoop-Automated,rbheemana/Cobol-to-Hive | src/com/savy3/CobolField.java | package com.savy3.hadoop.hive.serde3.cobol;
import java.nio.charset.Charset;
import java.util.Arrays;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import com.savy3.hadoop.hive.serde2.cobol.CobolSerdeException;
public class CobolField implements HiveColumn{
protected String name;
protected String debugInfo;
protected TypeInfo typeInfo;
protected ObjectInspector oi;
protected int compType = 0;;
protected int decimalLocation = 0;
protected int length = 0;
protected CobolFieldType type;
protected int levelNo;
protected int offset;
// constructor
public CobolField(String debugInfo,int levelNo,String name, int length) {
this.debugInfo = debugInfo;
this.name = name;
// this.typeInfo = typeInfo;
this.length = length;
this.levelNo = levelNo;
}
public ObjectInspector getOi() {
return oi;
}
public CobolFieldType getType() {
return type;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getLevelNo() {
return levelNo;
}
public String getDebugInfo() {
return debugInfo;
}
public CobolField() {
}
public String toString() {
return ("CobolField :[ Name : " + name + ", type : " + typeInfo
+ ", offset :" + offset + " ]");
}
@Override
public String getName() {
return this.name;
}
@Override
public TypeInfo getTypeInfo() {
return this.typeInfo;
}
@Override
public int getOffset() {
return this.offset;
}
@Override
public int getLength() {
return this.length;
}
public Object deserialize(byte[] rowBytes) throws CobolSerdeException{
if (this.type == CobolFieldType.STRING)
return ((CobolStringField)this).deserialize(rowBytes);
if (this.type == CobolFieldType.NUMBER)
return ((CobolNumberField)this).deserialize(rowBytes);
return null;
}
protected byte[] getBytes(byte[] rowBytes){
if (offset + length < rowBytes.length) {
return Arrays.copyOfRange(rowBytes, offset, offset + length);
}
else{
if (offset > rowBytes.length)
System.out.println("Corrupted cobol layout; Offset position:"+offset+" greater than record length :"+rowBytes.length+"--"+this.toString());
return Arrays.copyOfRange(rowBytes, offset, rowBytes.length);
}
}
public byte[] transcodeField(byte[] source) {
byte[] result = new String(source, Charset.forName("ebcdic-cp-us")).getBytes(Charset.forName("ascii"));
if (result.length != source.length) {
throw new AssertionError("EBCDIC TO ASCII conversion for column:"+this.name+"failed"+result.length + "!=" + source.length);
}
return result;
}
public int getSize() {
// TODO Auto-generated method stub
return this.length;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + levelNo;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CobolField other = (CobolField) obj;
if (levelNo != other.levelNo)
return false;
return true;
}
} | Delete CobolField.java | src/com/savy3/CobolField.java | Delete CobolField.java |
||
Java | mit | 8011a61876aa9734cd448d408a73fceb554ddce2 | 0 | andreas-eberle/settlers-remake,phirschbeck/settlers-remake,Peter-Maximilian/settlers-remake,JKatzwinkel/settlers-remake,jsettlers/settlers-remake,phirschbeck/settlers-remake,andreasb242/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,jsettlers/settlers-remake,jsettlers/settlers-remake,andreasb242/settlers-remake,andreas-eberle/settlers-remake,phirschbeck/settlers-remake | /*******************************************************************************
* Copyright (c) 2015
*
* 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 jsettlers.tests.autoreplay;
import static org.junit.Assert.assertEquals;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Collection;
import jsettlers.TestUtils;
import jsettlers.common.CommonConstants;
import jsettlers.common.resources.ResourceManager;
import jsettlers.logic.constants.Constants;
import jsettlers.logic.map.save.MapFileHeader;
import jsettlers.logic.map.save.MapList;
import jsettlers.main.replay.ReplayTool;
import jsettlers.tests.utils.CountingInputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class AutoReplayIT {
static {
CommonConstants.ENABLE_CONSOLE_LOGGING = true;
CommonConstants.CONTROL_ALL = true;
TestUtils.setupResourcesManager();
}
private static final String remainingReplay = "out/remainingReplay.log";
private static final Object lock = new Object();
@Parameters(name = "{index}: {0} : {1}")
public static Collection<Object[]> replaySets() {
return Arrays.asList(new Object[][] {
{ "basicProduction-mountainlake", 15 },
{ "fullProduction-mountainlake", 10 },
{ "fullProduction-mountainlake", 20 },
{ "fullProduction-mountainlake", 30 },
{ "fullProduction-mountainlake", 40 },
{ "fullProduction-mountainlake", 50 },
{ "fullProduction-mountainlake", 69 },
{ "fighting-testmap", 8 }
});
}
private final String folderName;
private final int targetTimeMinutes;
public AutoReplayIT(String folderName, int targetTimeMinutes) {
this.folderName = folderName;
this.targetTimeMinutes = targetTimeMinutes;
}
@Test
public void testReplay() throws IOException {
synchronized (lock) {
Path savegameFile = replayAndGetSavegame(getReplayPath(), targetTimeMinutes);
Path expectedFile = getSavegamePath();
compareMapFiles(expectedFile, savegameFile);
Files.delete(savegameFile);
}
}
private Path getSavegamePath() {
return Paths.get("resources/autoreplay/" + folderName + "/savegame-" + targetTimeMinutes + "m.map");
}
private Path getReplayPath() {
return Paths.get("resources/autoreplay/" + folderName + "/replay.log");
}
private static void compareMapFiles(Path expectedFile, Path actualFile) throws IOException {
System.out.println("Comparing expected '" + expectedFile + "' with actual '" + actualFile + "'");
try (BufferedInputStream expectedStream = new BufferedInputStream(Files.newInputStream(expectedFile));
CountingInputStream actualStream = new CountingInputStream(new BufferedInputStream(Files.newInputStream(actualFile)))) {
MapFileHeader expectedHeader = MapFileHeader.readFromStream(expectedStream);
MapFileHeader actualHeader = MapFileHeader.readFromStream(actualStream);
assertEquals(expectedHeader.getBaseMapId(), actualHeader.getBaseMapId());
int e, a;
while ((e = expectedStream.read()) != -1 & (a = actualStream.read()) != -1) {
assertEquals("difference at byte " + (actualStream.getByteCounter() - 1), a, e);
}
assertEquals("files have different lengths", e, a);
}
}
private static Path replayAndGetSavegame(Path replayPath, int targetTimeMinutes) throws IOException {
Constants.FOG_OF_WAR_DEFAULT_ENABLED = false;
ReplayTool.replayAndCreateSavegame(replayPath.toFile(), targetTimeMinutes * 60 * 1000, remainingReplay);
Path savegameFile = findSavegameFile();
System.out.println("Replayed: " + replayPath + " and created savegame: " + savegameFile);
return savegameFile;
}
private static Path findSavegameFile() throws IOException { // TODO implement better way to find the correct savegame
Path saveDirPath = new File(ResourceManager.getSaveDirectory(), "save").toPath();
final Path[] newestFile = new Path[1];
Files.walkFileTree(saveDirPath, new SimpleFileVisitor<Path>() {
private FileTime newestCreationTime = null;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(MapList.MAP_EXTENSION)
&& (newestCreationTime == null || newestCreationTime.compareTo(attrs.creationTime()) < 0)) {
newestCreationTime = attrs.creationTime();
newestFile[0] = file;
}
return super.visitFile(file, attrs);
}
});
return newestFile[0];
}
public static void main(String[] args) throws IOException {
System.out.println("Creating reference files for replays...");
for (Object[] replaySet : replaySets()) {
String folderName = (String) replaySet[0];
int targetTimeMinutes = (Integer) replaySet[1];
AutoReplayIT replayIT = new AutoReplayIT(folderName, targetTimeMinutes);
Path newSavegame = AutoReplayIT.replayAndGetSavegame(replayIT.getReplayPath(), targetTimeMinutes);
Path expectedSavegamePath = replayIT.getSavegamePath();
try {
compareMapFiles(expectedSavegamePath, newSavegame);
System.out.println("New savegame is equal to old one => won't replace.");
Files.delete(newSavegame);
} catch (AssertionError | NoSuchFileException ex) { // if the files are not equal, replace the existing one.
Files.move(newSavegame, expectedSavegamePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Replacing reference file '" + expectedSavegamePath + "' with new savegame '" + newSavegame + "'");
}
}
}
}
| jsettlers.tests/tests/jsettlers/tests/autoreplay/AutoReplayIT.java | /*******************************************************************************
* Copyright (c) 2015
*
* 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 jsettlers.tests.autoreplay;
import static org.junit.Assert.assertEquals;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Collection;
import jsettlers.TestUtils;
import jsettlers.common.CommonConstants;
import jsettlers.common.resources.ResourceManager;
import jsettlers.logic.constants.Constants;
import jsettlers.logic.map.save.MapFileHeader;
import jsettlers.logic.map.save.MapList;
import jsettlers.main.replay.ReplayTool;
import jsettlers.tests.utils.CountingInputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class AutoReplayIT {
static {
CommonConstants.ENABLE_CONSOLE_LOGGING = true;
CommonConstants.CONTROL_ALL = true;
TestUtils.setupResourcesManager();
}
private static final String remainingReplay = "out/remainingReplay.log";
private static final Object lock = new Object();
@Parameters(name = "{index}: {0} : {1}")
public static Collection<Object[]> replaySets() {
return Arrays.asList(new Object[][] {
{ "basicProduction-mountainlake", 15 },
{ "fullProduction-mountainlake", 10 },
{ "fullProduction-mountainlake", 20 },
{ "fullProduction-mountainlake", 30 },
{ "fullProduction-mountainlake", 40 },
{ "fullProduction-mountainlake", 50 },
{ "fullProduction-mountainlake", 69 },
{ "fighting-testmap", 8 }
});
}
private final String folderName;
private final int targetTimeMinutes;
public AutoReplayIT(String folderName, int targetTimeMinutes) {
this.folderName = folderName;
this.targetTimeMinutes = targetTimeMinutes;
}
@Test
public void testReplay() throws IOException {
synchronized (lock) {
Path savegameFile = replayAndGetSavegame(getReplayPath(), targetTimeMinutes);
Path expectedFile = getSavegamePath();
compareMapFiles(expectedFile, savegameFile);
Files.delete(savegameFile);
}
}
private Path getSavegamePath() {
return Paths.get("resources/autoreplay/" + folderName + "/savegame-" + targetTimeMinutes + "m.map");
}
private Path getReplayPath() {
return Paths.get("resources/autoreplay/" + folderName + "/replay.log");
}
private static void compareMapFiles(Path expectedFile, Path actualFile) throws IOException {
System.out.println("Comparing expected '" + expectedFile + "' with actual '" + actualFile + "'");
try (BufferedInputStream expectedStream = new BufferedInputStream(Files.newInputStream(expectedFile));
CountingInputStream actualStream = new CountingInputStream(new BufferedInputStream(Files.newInputStream(actualFile)))) {
MapFileHeader expectedHeader = MapFileHeader.readFromStream(expectedStream);
MapFileHeader actualHeader = MapFileHeader.readFromStream(actualStream);
assertEquals(expectedHeader.getBaseMapId(), actualHeader.getBaseMapId());
int e, a;
while ((e = expectedStream.read()) != -1 & (a = actualStream.read()) != -1) {
assertEquals("difference at byte " + (actualStream.getByteCounter() - 1), a, e);
}
assertEquals("files have different lengths", e, a);
}
}
private static Path replayAndGetSavegame(Path replayPath, int targetTimeMinutes) throws IOException {
Constants.FOG_OF_WAR_DEFAULT_ENABLED = false;
ReplayTool.replayAndCreateSavegame(replayPath.toFile(), targetTimeMinutes * 60 * 1000, remainingReplay);
Path savegameFile = findSavegameFile();
System.out.println("Replayed: " + replayPath + " and created savegame: " + savegameFile);
return savegameFile;
}
private static Path findSavegameFile() throws IOException { // TODO implement better way to find the correct savegame
Path saveDirPath = new File(ResourceManager.getSaveDirectory(), "save").toPath();
final Path[] newestFile = new Path[1];
Files.walkFileTree(saveDirPath, new SimpleFileVisitor<Path>() {
private FileTime newestCreationTime = null;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(MapList.MAP_EXTENSION)
&& (newestCreationTime == null || newestCreationTime.compareTo(attrs.creationTime()) < 0)) {
newestCreationTime = attrs.creationTime();
newestFile[0] = file;
}
return super.visitFile(file, attrs);
}
});
return newestFile[0];
}
public static void main(String[] args) throws IOException {
System.out.println("Creating reference files for replays...");
for (Object[] replaySet : replaySets()) {
String folderName = (String) replaySet[0];
int targetTimeMinutes = (Integer) replaySet[1];
AutoReplayIT replayIT = new AutoReplayIT(folderName, targetTimeMinutes);
Path newSavegame = AutoReplayIT.replayAndGetSavegame(replayIT.getReplayPath(), targetTimeMinutes);
Path expectedSavegamePath = replayIT.getSavegamePath();
try {
compareMapFiles(expectedSavegamePath, newSavegame);
System.out.println("New savegame is equal to old one => won't replace.");
} catch (AssertionError | NoSuchFileException ex) { // if the files are not equal, replace the existing one.
Files.move(newSavegame, expectedSavegamePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Replacing reference file '" + expectedSavegamePath + "' with new savegame '" + newSavegame + "'");
}
}
}
}
| Ensured deletion of generated auto replay savegames.
| jsettlers.tests/tests/jsettlers/tests/autoreplay/AutoReplayIT.java | Ensured deletion of generated auto replay savegames. |
|
Java | mit | d0c61d87ad766021ba49bd592991a55fc9370a15 | 0 | hhaslam11/Text-Fighter | package com.hotmail.kalebmarc.textfighter.main;
class Version {
private Version(){}
private static final String VERSION = "4.8DEV";
private static final String STAGE = "Alpha";
private static final String DESC = ""
+ "Text-Fighter is a Text-Based\n"
+ "Fighter RPG game, completely\n"
+ "written in Java. Text-Fighter\n"
+ "is made by Kaleb Haslam\n\n"
+ "Text-Fighter is currently in Alpha stage\n"
+ "which means it's still in early development,\n"
+ "and will contain lots of bugs and missing features.";
private static final String CHANGE_LOG = ""
+ "(Not compatible with previous saves)\n\n"
+ "New Stuff:\n"
+ "-\n"
+ "-\n"
+ "-\n"
+ "-\n"
+ "-\n\n"
+ "Bug Fixes:\n"
+ "-\n"
+ " ";
public static String get(){
return VERSION;
}
public static String getStage(){
return STAGE;
}
public static String getFull(){
return STAGE + " " + VERSION;
}
public static String getDesc(){
return DESC;
}
public static String getChange(){
return CHANGE_LOG;
}
}
| src/com/hotmail/kalebmarc/textfighter/main/Version.java | package com.hotmail.kalebmarc.textfighter.main;
class Version {
private Version(){}
private static final String VERSION = "4.7";
private static final String STAGE = "Alpha";
private static final String DESC = ""
+ "Text-Fighter is a Text-Based\n"
+ "Fighter RPG game, completely\n"
+ "written in Java. Text-Fighter\n"
+ "is made by Kaleb Haslam\n\n"
+ "Text-Fighter is currently in Alpha stage\n"
+ "which means it's still in early development,\n"
+ "and will contain lots of bugs and missing features.";
private static final String CHANGE_LOG = ""
+ "(Not compatible with previous saves)\n\n"
+ "New Stuff:\n"
+ "- Remove \"Not available\" in amour & weapon shop, and equip armour & equip weapon menu\n"
+ "- nogui on by default\n"
+ "- Potions\n"
+ "- NPC's\n"
+ "- Changed way to access cheat menu\n"
+ "- Added more cheats\n"
+ "- Loans\n"
+ "- Better save file names\n"
+ "- Usernames (Again...)\n"
+ "- General optimizations\n"
+ "- Auto Save\n\n"
+ "Bug Fixes:\n"
+ "- Remove crafting from help menu\n"
+ "- Fixed not showing option 1 in Body Armour menu\n"
+ "- Fixed showing no armour is equipped when starting new game";
public static String get(){
return VERSION;
}
public static String getStage(){
return STAGE;
}
public static String getFull(){
return STAGE + " " + VERSION;
}
public static String getDesc(){
return DESC;
}
public static String getChange(){
return CHANGE_LOG;
}
}
| Prepped for Alpha 4.8DEV
| src/com/hotmail/kalebmarc/textfighter/main/Version.java | Prepped for Alpha 4.8DEV |
|
Java | mit | 577219a02347002cfd7ae2f0c980dfc315fce490 | 0 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* https://leetcode.com/problems/number-of-operations-to-make-network-connected/
*/
public class Problem1319 {
public int makeConnected(int n, int[][] connections) {
if (connections.length < n - 1) {
return -1;
}
UnionFind uf = new UnionFind(n);
for (int i = 0; i < connections.length; i++) {
uf.union(connections[i][0], connections[i][1]);
}
int answer = 0;
Set<Integer> connected = new HashSet<>(); // number of connected computers
for (int i = 0; i < uf.map.length; i++) {
if (uf.map[i] == null) {
answer++; // number of remaining computers
} else {
connected.add(uf.map[i]);
}
}
return answer + connected.size() - 1;
}
private static class UnionFind {
private final Integer[] map;
public UnionFind(int n) {
this.map = new Integer[n];
}
public void union(int a, int b) {
if (map[a] == null) {
map[a] = a;
}
if (map[b] == null) {
map[b] = b;
}
if (map[a].equals(map[b])) {
return; // already connected
}
Integer value = map[a];
for (int i = 0; i < map.length; i++) {
if (map[i] == null) {
continue;
}
if (map[i].equals(value)) {
map[i] = map[b];
}
}
}
}
public static void main(String[] args) {
Problem1319 prob = new Problem1319();
System.out.println(prob.makeConnected(4, new int[][]{{0,1},{0,2},{1,2}})); // 1
System.out.println(prob.makeConnected(6, new int[][]{{0,1},{0,2},{0,3},{1,2},{1,3}})); // 2
System.out.println(prob.makeConnected(6, new int[][]{{0,1},{0,2},{0,3},{1,2},{1,3},{4,5}})); // 1
System.out.println(prob.makeConnected(6, new int[][]{{0,1},{0,2},{0,3},{1,2}})); // -1
System.out.println(prob.makeConnected(5, new int[][]{{0,1},{0,2},{3,4},{2,3}})); // 0
}
}
| src/main/java/leetcode/Problem1319.java | package leetcode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* https://leetcode.com/problems/number-of-operations-to-make-network-connected/
*/
public class Problem1319 {
public int makeConnected(int n, int[][] connections) {
if (connections.length < n - 1) {
return -1;
}
UnionFind uf = new UnionFind();
for (int i = 0; i < connections.length; i++) {
uf.union(connections[i][0], connections[i][1]);
}
int answer = new HashSet<>(uf.map.values()).size() - 1; // number of connected computers
// number of remaining computers
for (int i = 0; i < n; i++) {
if (!uf.map.containsKey(i)) {
answer++;
}
}
return answer;
}
private static class UnionFind {
private final Map<Integer, Integer> map = new HashMap<>();
public void union(int a, int b) {
if (!map.containsKey(a)) {
map.put(a, a);
}
if (!map.containsKey(b)) {
map.put(b, b);
}
if (map.get(a).equals(map.get(b))) {
return; // already connected
}
Integer value = map.get(a);
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
if (e.getValue().equals(value)) {
map.put(e.getKey(), map.get(b));
}
}
}
}
public static void main(String[] args) {
Problem1319 prob = new Problem1319();
System.out.println(prob.makeConnected(4, new int[][]{{0,1},{0,2},{1,2}})); // 1
System.out.println(prob.makeConnected(6, new int[][]{{0,1},{0,2},{0,3},{1,2},{1,3}})); // 2
System.out.println(prob.makeConnected(6, new int[][]{{0,1},{0,2},{0,3},{1,2},{1,3},{4,5}})); // 1
System.out.println(prob.makeConnected(6, new int[][]{{0,1},{0,2},{0,3},{1,2}})); // -1
System.out.println(prob.makeConnected(5, new int[][]{{0,1},{0,2},{3,4},{2,3}})); // 0
}
}
| Update problem 1319
| src/main/java/leetcode/Problem1319.java | Update problem 1319 |
|
Java | mit | baab39c11cf1b2f5d3234def708d65f7e0213b8f | 0 | StaySharp0/SimpleMerge | package view;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import model.Model;
import model.ModelInterface;
import view.UI.*;
import dataSet.MergeCompare;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.ResourceBundle;
public class MainController implements Initializable {
ModelInterface model;
// init FXML Objects
@FXML private Button btnLeftFileOpen, btnRightFileOpen,
btnLeftFileEdit, btnRightFileEdit,
btnLeftFileSave ,btnRightFileSave,
btnCompare,
btnMtoLeft, btnMtoRight;
private Button[] btnFileOpen, btnFileEdit, btnFileSave;
@FXML private TabPane tabLeft, tabRight;
@FXML private ListView<String> listLeft, listRight;
@FXML private TextField fieldLeftFile, fieldRightFile;
@FXML private TextArea textAreaLeft,textAreaRight;
private TabPane[] tabPanes;
private TextField[] textFields;
private ListView[] listViews;
private ObservableList[] listModels;
private TextArea[] textAreas;
private HashMap<String,btnAction> button;
private btnAction[] fileOpenUI = new FileOpenUI[2];
private ScreenMode[] editorUI = new EditorUI[2];
private btnAction[] fileSaveUI = new FileSaveUI[2];
// condition value
private Boolean[] condLoadFile = { false, false };
private Boolean condCompare = false;
private int condActiveOrder;
private int selectedIndex;
private int[] position = { Position.LEFT, Position.RIGHT };
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("init");
model = new Model();
// FXML value -> position array
btnFileOpen = new Button[] { btnLeftFileOpen, btnRightFileOpen };
btnFileEdit = new Button[] { btnLeftFileEdit, btnRightFileEdit };
btnFileSave = new Button[] { btnLeftFileSave, btnRightFileSave };
tabPanes = new TabPane[] { tabLeft, tabRight };
listViews = new ListView[] { listLeft, listRight};
listModels = new ObservableList[] { listLeft.getItems(), listRight.getItems() };
textFields = new TextField[]{ fieldLeftFile, fieldRightFile };
textAreas = new TextArea[] { textAreaLeft,textAreaRight };
button = new HashMap();
// init UI
for(int pos : position){
fileOpenUI[pos] = new FileOpenUI(pos, Main.getPrimaryStage(), textFields[pos], textAreas[pos]);
editorUI[pos] = new EditorUI(pos, tabPanes[pos], textFields[pos], textAreas[pos], btnFileEdit[pos]);
fileSaveUI[pos] = new FileSaveUI(pos, textFields[pos], textAreas[pos]);
button.put(btnFileOpen[pos].getId(), fileOpenUI[pos]);
button.put(btnFileEdit[pos].getId(), (btnAction) editorUI[pos]);
button.put(btnFileSave[pos].getId(), fileSaveUI[pos]);
}
}
public void SyncScrollBar() {
ScrollBar left = (ScrollBar) listLeft.lookup(".scroll-bar:vertical");
ScrollBar right = (ScrollBar) listRight.lookup(".scroll-bar:vertical");
left.valueProperty().bindBidirectional(right.valueProperty());
}
public void eventFileOpen(ActionEvent e) {
// Get Button
Control target = (Control)e.getSource();
btnAction ui = button.get(target.getId());
int pos = ui.getPosition();
// Call event
Boolean status = ui.onAction((source) -> {
System.out.println("FileOpen callback");
return model.load((File) source, pos);
});
if(condLoadFile[pos] && !status) return; //현재 불러온 파일이 있지만 다시 불러오기를 실패한 경우
editorUI[pos].ShowViewMode();
condLoadFile[pos] = status;
// Set button disable
btnFileEdit[pos].setDisable(!status);
btnFileSave[pos].setDisable(!status);
btnCompare.setDisable(!(condLoadFile[0] && condLoadFile[1]));
}
public void eventFileEdit(ActionEvent e) {
// Get Button
Control target = (Control)e.getSource();
btnAction ui = button.get(target.getId());
int pos = ui.getPosition();
// Call event
Boolean status = ui.onAction((source) -> {
System.out.println("FileEdit callback");
return model.edit((String) source, pos);
});
condCompare = false;
btnMtoRight.setDisable(!condCompare);
btnMtoLeft.setDisable(!condCompare);
}
public void eventFileSave(ActionEvent e) {
// Get Button
Control target = (Control)e.getSource();
btnAction ui = button.get(target.getId());
int pos = ui.getPosition();
// Call event
Boolean status = ui.onAction((source) -> {
System.out.println("Click:LeftFileSave");
return model.save((String) source, pos);
});
editorUI[pos].ShowViewMode();
}
public void eventCompare(ActionEvent e){
System.out.println("Click:Compare");
// model Data update
for(int pos : position) model.edit(textAreas[pos].getText(),pos);
MergeCompare data = model.compare();
updateListView(data);
}
public void evnetMergeToLeft(ActionEvent e){
System.out.println("Click:MergeToLeft");
if(!condCompare) return;
MergeCompare data = model.merge(selectedIndex,Position.LEFT);
updateListView(data);
}
public void evnetMergeToRight(ActionEvent e){
System.out.println("Click:MergeToRight");
if(!condCompare) return;
MergeCompare data = model.merge(selectedIndex,Position.RIGHT);
updateListView(data);
}
public void SyncSelectItem(Event e) {
ListView target = (ListView)e.getSource();
selectedIndex = target.getSelectionModel().getSelectedIndex();
for(int pos : position) listViews[pos].getSelectionModel().select(selectedIndex);
// Active Merge Button
boolean flag = !(selectedIndex % 2 == condActiveOrder); // 틀린 Index가 맞는 경우 true(setDisable 때문에 역을 함)
btnMtoLeft.setDisable(flag);
btnMtoRight.setDisable(flag);
}
private void updateListView(MergeCompare data) {
if( data == null ) {
System.out.println("err: Compare");
condCompare = false;
return;
}
condCompare = true;
condActiveOrder = data.getListActiveOrder();
for (int pos : position) {
listModels[pos].setAll(data.getListViewItem(pos));
editorUI[pos].ShowCompareMode();
listViews[pos].getStyleClass().removeAll("odd","even");
if (condActiveOrder == 1) { // 홀수번째가 틀린경우
listViews[pos].getStyleClass().add("odd");
} else if (condActiveOrder == 0) { //짝수번째가 틀린경우
listViews[pos].getStyleClass().add("even");
}
textAreas[pos].setText(data.getTextItem(pos));
}
}
}
| src/view/MainController.java | package view;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import model.Model;
import model.ModelInterface;
import view.UI.*;
import dataSet.MergeCompare;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.ResourceBundle;
public class MainController implements Initializable {
ModelInterface model;
// init FXML Objects
@FXML private Button btnLeftFileOpen, btnRightFileOpen,
btnLeftFileEdit, btnRightFileEdit,
btnLeftFileSave ,btnRightFileSave,
btnCompare,
btnMtoLeft, btnMtoRight;
private Button[] btnFileOpen, btnFileEdit, btnFileSave;
@FXML private TabPane tabLeft, tabRight;
@FXML private ListView<String> listLeft, listRight;
@FXML private TextField fieldLeftFile, fieldRightFile;
@FXML private TextArea textAreaLeft,textAreaRight;
private TabPane[] tabPanes;
private TextField[] textFields;
private ListView[] listViews;
private ObservableList[] listModels;
private TextArea[] textAreas;
private HashMap<String,btnAction> button;
private btnAction[] fileOpenUI = new FileOpenUI[2];
private ScreenMode[] editorUI = new EditorUI[2];
private btnAction[] fileSaveUI = new FileSaveUI[2];
// condition value
private Boolean[] condLoadFile = { false, false };
private Boolean condCompare = false;
private int condActiveOrder;
private int selectedIndex;
private int[] position = { Position.LEFT, Position.RIGHT };
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("init");
model = new Model();
// FXML value -> position array
btnFileOpen = new Button[] { btnLeftFileOpen, btnRightFileOpen };
btnFileEdit = new Button[] { btnLeftFileEdit, btnRightFileEdit };
btnFileSave = new Button[] { btnLeftFileSave, btnRightFileSave };
tabPanes = new TabPane[] { tabLeft, tabRight };
listViews = new ListView[] { listLeft, listRight};
listModels = new ObservableList[] { listLeft.getItems(), listRight.getItems() };
textFields = new TextField[]{ fieldLeftFile, fieldRightFile };
textAreas = new TextArea[] { textAreaLeft,textAreaRight };
button = new HashMap();
// init UI
for(int pos : position){
fileOpenUI[pos] = new FileOpenUI(pos, Main.getPrimaryStage(), textFields[pos], textAreas[pos]);
editorUI[pos] = new EditorUI(pos, tabPanes[pos], textFields[pos], textAreas[pos], btnFileEdit[pos]);
fileSaveUI[pos] = new FileSaveUI(pos, textFields[pos], textAreas[pos]);
button.put(btnFileOpen[pos].getId(), fileOpenUI[pos]);
button.put(btnFileEdit[pos].getId(), (btnAction) editorUI[pos]);
button.put(btnFileSave[pos].getId(), fileSaveUI[pos]);
}
}
public void SyncScrollBar() {
ScrollBar left = (ScrollBar) listLeft.lookup(".scroll-bar:vertical");
ScrollBar right = (ScrollBar) listRight.lookup(".scroll-bar:vertical");
left.valueProperty().bindBidirectional(right.valueProperty());
}
public void eventFileOpen(ActionEvent e) {
// Get Button
Control target = (Control)e.getSource();
btnAction ui = button.get(target.getId());
int pos = ui.getPosition();
// Call event
Boolean status = ui.onAction((source) -> {
System.out.println("FileOpen callback");
return model.load((File) source, pos);
});
if(condLoadFile[pos] && !status) return; //현재 불러온 파일이 있지만 다시 불러오기를 실패한 경우
editorUI[pos].ShowViewMode();
condLoadFile[pos] = status;
// Set button disable
btnFileEdit[pos].setDisable(!status);
btnFileSave[pos].setDisable(!status);
btnCompare.setDisable(!(condLoadFile[0] && condLoadFile[1]));
}
public void eventFileEdit(ActionEvent e) {
// Get Button
Control target = (Control)e.getSource();
btnAction ui = button.get(target.getId());
int pos = ui.getPosition();
// Call event
Boolean status = ui.onAction((source) -> {
System.out.println("FileEdit callback");
return model.edit((String) source, pos);
});
condCompare = false;
btnMtoRight.setDisable(!condCompare);
btnMtoLeft.setDisable(!condCompare);
}
public void eventFileSave(ActionEvent e) {
// Get Button
Control target = (Control)e.getSource();
btnAction ui = button.get(target.getId());
int pos = ui.getPosition();
// Call event
Boolean status = ui.onAction((source) -> {
System.out.println("Click:LeftFileSave");
return model.save((String) source, pos);
});
}
public void eventCompare(ActionEvent e){
System.out.println("Click:Compare");
// model Data update
for(int pos : position) model.edit(textAreas[pos].getText(),pos);
MergeCompare data = model.compare();
updateListView(data);
}
public void evnetMergeToLeft(ActionEvent e){
System.out.println("Click:MergeToLeft");
if(!condCompare) return;
MergeCompare data = model.merge(selectedIndex,Position.LEFT);
updateListView(data);
}
public void evnetMergeToRight(ActionEvent e){
System.out.println("Click:MergeToRight");
if(!condCompare) return;
MergeCompare data = model.merge(selectedIndex,Position.RIGHT);
updateListView(data);
}
public void SyncSelectItem(Event e) {
ListView target = (ListView)e.getSource();
selectedIndex = target.getSelectionModel().getSelectedIndex();
for(int pos : position) listViews[pos].getSelectionModel().select(selectedIndex);
// Active Merge Button
boolean flag = !(selectedIndex % 2 == condActiveOrder); // 틀린 Index가 맞는 경우 true(setDisable 때문에 역을 함)
btnMtoLeft.setDisable(flag);
btnMtoRight.setDisable(flag);
}
private void updateListView(MergeCompare data) {
if( data == null ) {
System.out.println("err: Compare");
condCompare = false;
return;
}
condCompare = true;
condActiveOrder = data.getListActiveOrder();
for (int pos : position) {
listModels[pos].setAll(data.getListViewItem(pos));
editorUI[pos].ShowCompareMode();
listViews[pos].getStyleClass().removeAll("odd","even");
if (condActiveOrder == 1) { // 홀수번째가 틀린경우
listViews[pos].getStyleClass().add("odd");
} else if (condActiveOrder == 0) { //짝수번째가 틀린경우
listViews[pos].getStyleClass().add("even");
}
textAreas[pos].setText(data.getTextItem(pos));
}
}
}
| Fix: save할시 view mode로 전환
| src/view/MainController.java | Fix: save할시 view mode로 전환 |
|
Java | mit | 12d283456354ce416f1a016de47a72317512d241 | 0 | ngageoint/geopackage-java,ngageoint/geopackage-java | package mil.nga.geopackage.extension.index;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.support.ConnectionSource;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureResultSet;
import mil.nga.geopackage.features.user.FeatureRow;
import mil.nga.geopackage.features.user.FeatureRowSync;
import mil.nga.sf.GeometryEnvelope;
import mil.nga.sf.proj.Projection;
/**
* Feature Table Index NGA Extension implementation. This extension is used to
* index Geometries within a feature table by their minimum bounding box for
* bounding box queries. This extension is required to provide an index
* implementation when a SQLite version is used before SpatialLite support
* (Android).
*
* @author osbornb
* @since 1.1.0
*/
public class FeatureTableIndex extends FeatureTableCoreIndex {
/**
* Logger
*/
private static final Logger log = Logger
.getLogger(FeatureTableIndex.class.getName());
/**
* Feature DAO
*/
private final FeatureDao featureDao;
/**
* Feature Row Sync for simultaneous same row queries
*/
private final FeatureRowSync featureRowSync = new FeatureRowSync();
/**
* Constructor
*
* @param geoPackage
* GeoPackage
* @param featureDao
* feature dao
*/
public FeatureTableIndex(GeoPackage geoPackage, FeatureDao featureDao) {
super(geoPackage, featureDao.getTableName(),
featureDao.getGeometryColumnName());
this.featureDao = featureDao;
}
/**
* {@inheritDoc}
*/
@Override
public Projection getProjection() {
return featureDao.getProjection();
}
/**
* Close the table index
*/
public void close() {
// Don't close anything, leave the GeoPackage connection open
}
/**
* Index the feature row. This method assumes that indexing has been
* completed and maintained as the last indexed time is updated.
*
* @param row
* feature row
* @return true if indexed
*/
public boolean index(FeatureRow row) {
TableIndex tableIndex = getTableIndex();
if (tableIndex == null) {
throw new GeoPackageException(
"GeoPackage table is not indexed. GeoPackage: "
+ getGeoPackage().getName() + ", Table: "
+ getTableName());
}
boolean indexed = index(tableIndex, row.getId(), row.getGeometry());
// Update the last indexed time
updateLastIndexed();
return indexed;
}
/**
* {@inheritDoc}
*/
@Override
protected int indexTable(final TableIndex tableIndex) {
int count = 0;
long offset = 0;
int chunkCount = 0;
String[] columns = featureDao.getIdAndGeometryColumnNames();
while (chunkCount >= 0) {
final long chunkOffset = offset;
try {
// Iterate through each row and index as a single transaction
ConnectionSource connectionSource = getGeoPackage()
.getDatabase().getConnectionSource();
chunkCount = TransactionManager.callInTransaction(
connectionSource, new Callable<Integer>() {
public Integer call() throws Exception {
FeatureResultSet resultSet = featureDao
.queryForChunk(columns, chunkLimit,
chunkOffset);
int count = indexRows(tableIndex, resultSet);
return count;
}
});
if (chunkCount > 0) {
count += chunkCount;
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to Index Table. GeoPackage: "
+ getGeoPackage().getName() + ", Table: "
+ getTableName(),
e);
}
offset += chunkLimit;
}
// Update the last indexed time
if (progress == null || progress.isActive()) {
updateLastIndexed();
}
return count;
}
/**
* Index the feature rows in the cursor
*
* @param tableIndex
* table index
* @param resultSet
* feature result
* @return count, -1 if no results or canceled
*/
private int indexRows(TableIndex tableIndex, FeatureResultSet resultSet) {
int count = -1;
try {
while ((progress == null || progress.isActive())
&& resultSet.moveToNext()) {
if (count < 0) {
count++;
}
try {
FeatureRow row = resultSet.getRow();
boolean indexed = index(tableIndex, row.getId(),
row.getGeometry());
if (indexed) {
count++;
}
if (progress != null) {
progress.addProgress(1);
}
} catch (Exception e) {
log.log(Level.SEVERE,
"Failed to index feature. Table: "
+ tableIndex.getTableName() + ", Position: "
+ resultSet.getPosition(),
e);
}
}
} finally {
resultSet.close();
}
return count;
}
/**
* Delete the index for the feature row
*
* @param row
* feature row
* @return deleted rows, should be 0 or 1
*/
public int deleteIndex(FeatureRow row) {
return deleteIndex(row.getId());
}
/**
* Get the feature row for the Geometry Index
*
* @param geometryIndex
* geometry index
* @return feature row
*/
public FeatureRow getFeatureRow(GeometryIndex geometryIndex) {
long geomId = geometryIndex.getGeomId();
// Get the row or lock for reading
FeatureRow row = featureRowSync.getRowOrLock(geomId);
if (row == null) {
// Query for the row and set in the sync
try {
row = featureDao.queryForIdRow(geomId);
} finally {
featureRowSync.setRow(geomId, row);
}
}
return row;
}
/**
* Query for all Features
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures() {
return featureDao.queryIn(queryIdsSQL());
}
/**
* Query for all Features
*
* @param distinct
* distinct rows
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct) {
return featureDao.queryIn(distinct, queryIdsSQL());
}
/**
* Query for all Features
*
* @param columns
* columns
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns) {
return featureDao.queryIn(columns, queryIdsSQL());
}
/**
* Query for all Features
*
* @param distinct
* distinct rows
* @param columns
* columns
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns) {
return featureDao.queryIn(distinct, columns, queryIdsSQL());
}
/**
* Count features
*
* @return count
* @since 3.5.1
*/
public int countFeatures() {
return featureDao.countIn(queryIdsSQL());
}
/**
* Count features
*
* @param column
* count column name
*
* @return count
* @since 3.5.1
*/
public int countColumnFeatures(String column) {
return featureDao.countIn(column, queryIdsSQL());
}
/**
* Count features
*
* @param distinct
* distinct column values
* @param column
* count column name
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column) {
return featureDao.countIn(distinct, column, queryIdsSQL());
}
/**
* Query for features
*
* @param fieldValues
* field values
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(Map<String, Object> fieldValues) {
return featureDao.queryIn(queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param fieldValues
* field values
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param columns
* columns
* @param fieldValues
* field values
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
Map<String, Object> fieldValues) {
return featureDao.queryIn(columns, queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param fieldValues
* field values
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(),
fieldValues);
}
/**
* Count features
*
* @param fieldValues
* field values
*
* @return count
* @since 3.4.0
*/
public int countFeatures(Map<String, Object> fieldValues) {
return featureDao.countIn(queryIdsSQL(), fieldValues);
}
/**
* Count features
*
* @param column
* count column name
* @param fieldValues
* field values
*
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, Map<String, Object> fieldValues) {
return featureDao.countIn(column, queryIdsSQL(), fieldValues);
}
/**
* Count features
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param fieldValues
* field values
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
Map<String, Object> fieldValues) {
return featureDao.countIn(distinct, column, queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param where
* where clause
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(String where) {
return featureDao.queryIn(queryIdsSQL(), where);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param where
* where clause
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String where) {
return featureDao.queryIn(distinct, queryIdsSQL(), where);
}
/**
* Query for features
*
* @param columns
* columns
* @param where
* where clause
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns, String where) {
return featureDao.queryIn(columns, queryIdsSQL(), where);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param where
* where clause
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
String where) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(), where);
}
/**
* Count features
*
* @param where
* where clause
*
* @return count
* @since 3.4.0
*/
public int countFeatures(String where) {
return featureDao.countIn(queryIdsSQL(), where);
}
/**
* Count features
*
* @param column
* count column name
* @param where
* where clause
*
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, String where) {
return featureDao.countIn(column, queryIdsSQL(), where);
}
/**
* Count features
*
* @param column
* count column name
* @param distinct
* distinct column values
* @param where
* where clause
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column, String where) {
return featureDao.countIn(distinct, column, queryIdsSQL(), where);
}
/**
* Query for features
*
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(String where, String[] whereArgs) {
return featureDao.queryIn(queryIdsSQL(), where, whereArgs);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String where,
String[] whereArgs) {
return featureDao.queryIn(distinct, queryIdsSQL(), where, whereArgs);
}
/**
* Query for features
*
* @param columns
* columns
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns, String where,
String[] whereArgs) {
return featureDao.queryIn(columns, queryIdsSQL(), where, whereArgs);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
String where, String[] whereArgs) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(), where,
whereArgs);
}
/**
* Count features
*
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return count
* @since 3.4.0
*/
public int countFeatures(String where, String[] whereArgs) {
return featureDao.countIn(queryIdsSQL(), where, whereArgs);
}
/**
* Count features
*
* @param column
* count column name
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, String where, String[] whereArgs) {
return featureDao.countIn(column, queryIdsSQL(), where, whereArgs);
}
/**
* Count features
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column, String where,
String[] whereArgs) {
return featureDao.countIn(distinct, column, queryIdsSQL(), where,
whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox) {
return queryFeatures(false, boundingBox);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox) {
return queryFeatures(distinct, boundingBox.buildEnvelope());
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox) {
return queryFeatures(false, columns, boundingBox);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox) {
return queryFeatures(distinct, columns, boundingBox.buildEnvelope());
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox) {
return countFeatures(false, null, boundingBox);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox) {
return countFeatures(false, column, boundingBox);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox) {
return countFeatures(distinct, column, boundingBox.buildEnvelope());
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Map<String, Object> fieldValues) {
return queryFeatures(false, boundingBox, fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return queryFeatures(distinct, boundingBox.buildEnvelope(),
fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return queryFeatures(false, columns, boundingBox, fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return queryFeatures(distinct, columns, boundingBox.buildEnvelope(),
fieldValues);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox,
Map<String, Object> fieldValues) {
return countFeatures(false, null, boundingBox, fieldValues);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Map<String, Object> fieldValues) {
return countFeatures(false, column, boundingBox, fieldValues);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return countFeatures(distinct, column, boundingBox.buildEnvelope(),
fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
String where) {
return queryFeatures(false, boundingBox, where);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, String where) {
return queryFeatures(distinct, boundingBox, where, null);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, String where) {
return queryFeatures(false, columns, boundingBox, where);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, String where) {
return queryFeatures(distinct, columns, boundingBox, where, null);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, String where) {
return countFeatures(false, null, boundingBox, where);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
String where) {
return countFeatures(false, column, boundingBox, where);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, String where) {
return countFeatures(distinct, column, boundingBox, where, null);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox, String where,
String[] whereArgs) {
return queryFeatures(false, boundingBox, where, whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, String where, String[] whereArgs) {
return queryFeatures(distinct, boundingBox.buildEnvelope(), where,
whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, String where, String[] whereArgs) {
return queryFeatures(false, columns, boundingBox, where, whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, String where, String[] whereArgs) {
return queryFeatures(distinct, columns, boundingBox.buildEnvelope(),
where, whereArgs);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, String where,
String[] whereArgs) {
return countFeatures(false, null, boundingBox, where, whereArgs);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
String where, String[] whereArgs) {
return countFeatures(false, column, boundingBox, where, whereArgs);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, String where, String[] whereArgs) {
return countFeatures(distinct, column, boundingBox.buildEnvelope(),
where, whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection) {
return queryFeatures(false, boundingBox, projection);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, featureBoundingBox);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection) {
return queryFeatures(false, columns, boundingBox, projection);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, columns, featureBoundingBox);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection) {
return countFeatures(false, null, boundingBox, projection);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection) {
return countFeatures(false, column, boundingBox, projection);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return countFeatures(distinct, column, featureBoundingBox);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection, Map<String, Object> fieldValues) {
return queryFeatures(false, boundingBox, projection, fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, featureBoundingBox, fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
return queryFeatures(false, columns, boundingBox, projection,
fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, columns, featureBoundingBox,
fieldValues);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
return countFeatures(false, null, boundingBox, projection, fieldValues);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection, Map<String, Object> fieldValues) {
return countFeatures(false, column, boundingBox, projection,
fieldValues);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return countFeatures(distinct, column, featureBoundingBox, fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection, String where) {
return queryFeatures(false, boundingBox, projection, where);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct row
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection, String where) {
return queryFeatures(distinct, boundingBox, projection, where, null);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection, String where) {
return queryFeatures(false, columns, boundingBox, projection, where);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection, String where) {
return queryFeatures(distinct, columns, boundingBox, projection, where,
null);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection,
String where) {
return countFeatures(false, null, boundingBox, projection, where);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection, String where) {
return countFeatures(false, column, boundingBox, projection, where);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection, String where) {
return countFeatures(distinct, column, boundingBox, projection, where,
null);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection, String where, String[] whereArgs) {
return queryFeatures(false, boundingBox, projection, where, whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, featureBoundingBox, where, whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
return queryFeatures(false, columns, boundingBox, projection, where,
whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, columns, featureBoundingBox, where,
whereArgs);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection,
String where, String[] whereArgs) {
return countFeatures(false, null, boundingBox, projection, where,
whereArgs);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection, String where, String[] whereArgs) {
return countFeatures(false, column, boundingBox, projection, where,
whereArgs);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return countFeatures(distinct, column, featureBoundingBox, where,
whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope) {
return featureDao.queryIn(queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope) {
return featureDao.queryIn(distinct, queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope) {
return featureDao.queryIn(columns, queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(envelope));
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope) {
return featureDao.countIn(queryIdsSQL(envelope));
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column name
* @param envelope
* geometry envelope
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope) {
return featureDao.countIn(column, queryIdsSQL(envelope));
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param envelope
* geometry envelope
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope) {
return featureDao.countIn(distinct, column, queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope,
Map<String, Object> fieldValues) {
return featureDao.queryIn(queryIdsSQL(envelope), fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, queryIdsSQL(envelope), fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.queryIn(columns, queryIdsSQL(envelope), fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(envelope),
fieldValues);
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope,
Map<String, Object> fieldValues) {
return featureDao.countIn(queryIdsSQL(envelope), fieldValues);
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column names
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope,
Map<String, Object> fieldValues) {
return featureDao.countIn(column, queryIdsSQL(envelope), fieldValues);
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column names
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.countIn(distinct, column, queryIdsSQL(envelope),
fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope,
String where) {
return queryFeatures(false, envelope, where);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope, String where) {
return queryFeatures(distinct, envelope, where, null);
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope, String where) {
return queryFeatures(false, columns, envelope, where);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope, String where) {
return queryFeatures(distinct, columns, envelope, where, null);
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope, String where) {
return countFeatures(false, null, envelope, where);
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope,
String where) {
return countFeatures(false, column, envelope, where);
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope, String where) {
return countFeatures(distinct, column, envelope, where, null);
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope,
String where, String[] whereArgs) {
return featureDao.queryIn(queryIdsSQL(envelope), where, whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.queryIn(distinct, queryIdsSQL(envelope), where,
whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.queryIn(columns, queryIdsSQL(envelope), where,
whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(envelope),
where, whereArgs);
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope, String where,
String[] whereArgs) {
return featureDao.countIn(queryIdsSQL(envelope), where, whereArgs);
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope,
String where, String[] whereArgs) {
return featureDao.countIn(column, queryIdsSQL(envelope), where,
whereArgs);
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.countIn(distinct, column, queryIdsSQL(envelope),
where, whereArgs);
}
}
| src/main/java/mil/nga/geopackage/extension/index/FeatureTableIndex.java | package mil.nga.geopackage.extension.index;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.support.ConnectionSource;
import mil.nga.geopackage.BoundingBox;
import mil.nga.geopackage.GeoPackage;
import mil.nga.geopackage.GeoPackageException;
import mil.nga.geopackage.features.user.FeatureDao;
import mil.nga.geopackage.features.user.FeatureResultSet;
import mil.nga.geopackage.features.user.FeatureRow;
import mil.nga.geopackage.features.user.FeatureRowSync;
import mil.nga.sf.GeometryEnvelope;
import mil.nga.sf.proj.Projection;
/**
* Feature Table Index NGA Extension implementation. This extension is used to
* index Geometries within a feature table by their minimum bounding box for
* bounding box queries. This extension is required to provide an index
* implementation when a SQLite version is used before SpatialLite support
* (Android).
*
* @author osbornb
* @since 1.1.0
*/
public class FeatureTableIndex extends FeatureTableCoreIndex {
/**
* Logger
*/
private static final Logger log = Logger
.getLogger(FeatureTableIndex.class.getName());
/**
* Feature DAO
*/
private final FeatureDao featureDao;
/**
* Feature Row Sync for simultaneous same row queries
*/
private final FeatureRowSync featureRowSync = new FeatureRowSync();
/**
* Constructor
*
* @param geoPackage
* GeoPackage
* @param featureDao
* feature dao
*/
public FeatureTableIndex(GeoPackage geoPackage, FeatureDao featureDao) {
super(geoPackage, featureDao.getTableName(),
featureDao.getGeometryColumnName());
this.featureDao = featureDao;
}
/**
* {@inheritDoc}
*/
@Override
public Projection getProjection() {
return featureDao.getProjection();
}
/**
* Close the table index
*/
public void close() {
// Don't close anything, leave the GeoPackage connection open
}
/**
* Index the feature row. This method assumes that indexing has been
* completed and maintained as the last indexed time is updated.
*
* @param row
* feature row
* @return true if indexed
*/
public boolean index(FeatureRow row) {
TableIndex tableIndex = getTableIndex();
if (tableIndex == null) {
throw new GeoPackageException(
"GeoPackage table is not indexed. GeoPackage: "
+ getGeoPackage().getName() + ", Table: "
+ getTableName());
}
boolean indexed = index(tableIndex, row.getId(), row.getGeometry());
// Update the last indexed time
updateLastIndexed();
return indexed;
}
/**
* {@inheritDoc}
*/
@Override
protected int indexTable(final TableIndex tableIndex) {
int count = 0;
long offset = 0;
int chunkCount = 0;
String[] columns = featureDao.getIdAndGeometryColumnNames();
while (chunkCount >= 0) {
final long chunkOffset = offset;
try {
// Iterate through each row and index as a single transaction
ConnectionSource connectionSource = getGeoPackage()
.getDatabase().getConnectionSource();
chunkCount = TransactionManager.callInTransaction(
connectionSource, new Callable<Integer>() {
public Integer call() throws Exception {
FeatureResultSet resultSet = featureDao
.queryForChunk(columns, chunkLimit,
chunkOffset);
int count = indexRows(tableIndex, resultSet);
return count;
}
});
if (chunkCount > 0) {
count += chunkCount;
}
} catch (SQLException e) {
throw new GeoPackageException(
"Failed to Index Table. GeoPackage: "
+ getGeoPackage().getName() + ", Table: "
+ getTableName(),
e);
}
offset += chunkLimit;
}
// Update the last indexed time
if (progress == null || progress.isActive()) {
updateLastIndexed();
}
return count;
}
/**
* Index the feature rows in the cursor
*
* @param tableIndex
* table index
* @param resultSet
* feature result
* @return count, -1 if no results or canceled
*/
private int indexRows(TableIndex tableIndex, FeatureResultSet resultSet) {
int count = -1;
try {
while ((progress == null || progress.isActive())
&& resultSet.moveToNext()) {
if (count < 0) {
count++;
}
try {
FeatureRow row = resultSet.getRow();
boolean indexed = index(tableIndex, row.getId(),
row.getGeometry());
if (indexed) {
count++;
}
if (progress != null) {
progress.addProgress(1);
}
} catch (Exception e) {
log.log(Level.SEVERE,
"Failed to index feature. Table: "
+ tableIndex.getTableName() + ", Position: "
+ resultSet.getPosition(),
e);
}
}
} finally {
resultSet.close();
}
return count;
}
/**
* Delete the index for the feature row
*
* @param row
* feature row
* @return deleted rows, should be 0 or 1
*/
public int deleteIndex(FeatureRow row) {
return deleteIndex(row.getId());
}
/**
* Get the feature row for the Geometry Index
*
* @param geometryIndex
* geometry index
* @return feature row
*/
public FeatureRow getFeatureRow(GeometryIndex geometryIndex) {
long geomId = geometryIndex.getGeomId();
// Get the row or lock for reading
FeatureRow row = featureRowSync.getRowOrLock(geomId);
if (row == null) {
// Query for the row and set in the sync
try {
row = featureDao.queryForIdRow(geomId);
} finally {
featureRowSync.setRow(geomId, row);
}
}
return row;
}
/**
* Query for all Features
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures() {
return featureDao.queryIn(queryIdsSQL());
}
/**
* Query for all Features
*
* @param distinct
* distinct rows
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct) {
return featureDao.queryIn(distinct, queryIdsSQL());
}
/**
* Query for all Features
*
* @param columns
* columns
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns) {
return featureDao.queryIn(columns, queryIdsSQL());
}
/**
* Query for all Features
*
* @param distinct
* distinct rows
* @param columns
* columns
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns) {
return featureDao.queryIn(distinct, columns, queryIdsSQL());
}
/**
* Count features
*
* @return count
* @since 3.5.1
*/
public int countFeatures() {
return featureDao.countIn(queryIdsSQL());
}
/**
* Count features
*
* @param column
* count column name
*
* @return count
* @since 3.5.1
*/
public int countColumnFeatures(String column) {
return featureDao.countIn(column, queryIdsSQL());
}
/**
* Count features
*
* @param distinct
* distinct column values
* @param column
* count column name
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column) {
return featureDao.countIn(distinct, column, queryIdsSQL());
}
/**
* Query for features
*
* @param fieldValues
* field values
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(Map<String, Object> fieldValues) {
return featureDao.queryIn(queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param fieldValues
* field values
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param columns
* columns
* @param fieldValues
* field values
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
Map<String, Object> fieldValues) {
return featureDao.queryIn(columns, queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param fieldValues
* field values
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(),
fieldValues);
}
/**
* Count features
*
* @param fieldValues
* field values
*
* @return count
* @since 3.4.0
*/
public int countFeatures(Map<String, Object> fieldValues) {
return featureDao.countIn(queryIdsSQL(), fieldValues);
}
/**
* Count features
*
* @param column
* count column name
* @param fieldValues
* field values
*
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, Map<String, Object> fieldValues) {
return featureDao.countIn(column, queryIdsSQL(), fieldValues);
}
/**
* Count features
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param fieldValues
* field values
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
Map<String, Object> fieldValues) {
return featureDao.countIn(distinct, column, queryIdsSQL(), fieldValues);
}
/**
* Query for features
*
* @param where
* where clause
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(String where) {
return featureDao.queryIn(queryIdsSQL(), where);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param where
* where clause
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String where) {
return featureDao.queryIn(distinct, queryIdsSQL(), where);
}
/**
* Query for features
*
* @param columns
* columns
* @param where
* where clause
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns, String where) {
return featureDao.queryIn(columns, queryIdsSQL(), where);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param where
* where clause
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
String where) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(), where);
}
/**
* Count features
*
* @param where
* where clause
*
* @return count
* @since 3.4.0
*/
public int countFeatures(String where) {
return featureDao.countIn(queryIdsSQL(), where);
}
/**
* Count features
*
* @param column
* count column name
* @param where
* where clause
*
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, String where) {
return featureDao.countIn(column, queryIdsSQL(), where);
}
/**
* Count features
*
* @param column
* count column name
* @param distinct
* distinct column values
* @param where
* where clause
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column, String where) {
return featureDao.countIn(distinct, column, queryIdsSQL(), where);
}
/**
* Query for features
*
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(String where, String[] whereArgs) {
return featureDao.queryIn(queryIdsSQL(), where, whereArgs);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String where,
String[] whereArgs) {
return featureDao.queryIn(distinct, queryIdsSQL(), where, whereArgs);
}
/**
* Query for features
*
* @param columns
* columns
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns, String where,
String[] whereArgs) {
return featureDao.queryIn(columns, queryIdsSQL(), where, whereArgs);
}
/**
* Query for features
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
String where, String[] whereArgs) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(), where,
whereArgs);
}
/**
* Count features
*
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return count
* @since 3.4.0
*/
public int countFeatures(String where, String[] whereArgs) {
return featureDao.countIn(queryIdsSQL(), where, whereArgs);
}
/**
* Count features
*
* @param column
* count column name
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, String where, String[] whereArgs) {
return featureDao.countIn(column, queryIdsSQL(), where, whereArgs);
}
/**
* Count features
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param where
* where clause
* @param whereArgs
* where arguments
*
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column, String where,
String[] whereArgs) {
return featureDao.countIn(distinct, column, queryIdsSQL(), where,
whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox) {
return queryFeatures(false, boundingBox);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox) {
return queryFeatures(distinct, boundingBox.buildEnvelope());
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox) {
return queryFeatures(false, columns, boundingBox);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox) {
return queryFeatures(distinct, columns, boundingBox.buildEnvelope());
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox) {
return countFeatures(false, null, boundingBox);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox) {
return countFeatures(false, column, boundingBox);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox) {
return countFeatures(distinct, column, boundingBox.buildEnvelope());
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Map<String, Object> fieldValues) {
return queryFeatures(false, boundingBox, fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return queryFeatures(distinct, boundingBox.buildEnvelope(),
fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return queryFeatures(false, columns, boundingBox, fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return queryFeatures(distinct, columns, boundingBox.buildEnvelope(),
fieldValues);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox,
Map<String, Object> fieldValues) {
return countFeatures(false, null, boundingBox, fieldValues);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Map<String, Object> fieldValues) {
return countFeatures(false, column, boundingBox, fieldValues);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column
* @param boundingBox
* bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Map<String, Object> fieldValues) {
return countFeatures(distinct, column, boundingBox.buildEnvelope(),
fieldValues);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
String where) {
return queryFeatures(false, boundingBox, where);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, String where) {
return queryFeatures(distinct, boundingBox, where, null);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, String where) {
return queryFeatures(false, columns, boundingBox, where);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, String where) {
return queryFeatures(distinct, columns, boundingBox, where, null);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, String where) {
return countFeatures(false, null, boundingBox, where);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
String where) {
return countFeatures(false, column, boundingBox, where);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, String where) {
return countFeatures(distinct, column, boundingBox, where, null);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox, String where,
String[] whereArgs) {
return queryFeatures(false, boundingBox, where, whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, String where, String[] whereArgs) {
return queryFeatures(distinct, boundingBox.buildEnvelope(), where,
whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, String where, String[] whereArgs) {
return queryFeatures(false, columns, boundingBox, where, whereArgs);
}
/**
* Query for Features within the bounding box, projected correctly
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, String where, String[] whereArgs) {
return queryFeatures(distinct, columns, boundingBox.buildEnvelope(),
where, whereArgs);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, String where,
String[] whereArgs) {
return countFeatures(false, null, boundingBox, where, whereArgs);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
String where, String[] whereArgs) {
return countFeatures(false, column, boundingBox, where, whereArgs);
}
/**
* Count the Features within the bounding box, projected correctly
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, String where, String[] whereArgs) {
return countFeatures(distinct, column, boundingBox.buildEnvelope(),
where, whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection) {
return queryFeatures(false, boundingBox, projection);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, featureBoundingBox);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection) {
return queryFeatures(false, columns, boundingBox, projection);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, columns, featureBoundingBox);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection) {
return countFeatures(false, null, boundingBox, projection);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection) {
return countFeatures(false, column, boundingBox, projection);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return countFeatures(distinct, column, featureBoundingBox);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection, Map<String, Object> fieldValues) {
return queryFeatures(false, boundingBox, projection, fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, featureBoundingBox, fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
return queryFeatures(false, columns, boundingBox, projection,
fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, columns, featureBoundingBox,
fieldValues);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
return countFeatures(false, null, boundingBox, projection, fieldValues);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection, Map<String, Object> fieldValues) {
return countFeatures(false, column, boundingBox, projection,
fieldValues);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection,
Map<String, Object> fieldValues) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return countFeatures(distinct, column, featureBoundingBox, fieldValues);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection, String where) {
return queryFeatures(false, boundingBox, projection, where);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct row
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection, String where) {
return queryFeatures(distinct, boundingBox, projection, where, null);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection, String where) {
return queryFeatures(false, columns, boundingBox, projection, where);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection, String where) {
return queryFeatures(distinct, columns, boundingBox, projection, where,
null);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection,
String where) {
return countFeatures(false, null, boundingBox, projection, where);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection, String where) {
return countFeatures(false, column, boundingBox, projection, where);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection, String where) {
return countFeatures(distinct, column, boundingBox, projection, where,
null);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(BoundingBox boundingBox,
Projection projection, String where, String[] whereArgs) {
return queryFeatures(false, boundingBox, projection, where, whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, featureBoundingBox, where, whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
return queryFeatures(false, columns, boundingBox, projection, where,
whereArgs);
}
/**
* Query for Features within the bounding box in the provided projection
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return queryFeatures(distinct, columns, featureBoundingBox, where,
whereArgs);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.4.0
*/
public int countFeatures(BoundingBox boundingBox, Projection projection,
String where, String[] whereArgs) {
return countFeatures(false, null, boundingBox, projection, where,
whereArgs);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, BoundingBox boundingBox,
Projection projection, String where, String[] whereArgs) {
return countFeatures(false, column, boundingBox, projection, where,
whereArgs);
}
/**
* Count the Features within the bounding box in the provided projection
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param boundingBox
* bounding box
* @param projection
* projection of the provided bounding box
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
BoundingBox boundingBox, Projection projection, String where,
String[] whereArgs) {
BoundingBox featureBoundingBox = getFeatureBoundingBox(boundingBox,
projection);
return countFeatures(distinct, column, featureBoundingBox, where,
whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope) {
return featureDao.queryIn(queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope) {
return featureDao.queryIn(distinct, queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope) {
return featureDao.queryIn(columns, queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(envelope));
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope) {
return featureDao.countIn(queryIdsSQL(envelope));
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column name
* @param envelope
* geometry envelope
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope) {
return featureDao.countIn(column, queryIdsSQL(envelope));
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param envelope
* geometry envelope
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope) {
return featureDao.countIn(distinct, column, queryIdsSQL(envelope));
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope,
Map<String, Object> fieldValues) {
return featureDao.queryIn(queryIdsSQL(envelope), fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, queryIdsSQL(envelope), fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.queryIn(columns, queryIdsSQL(envelope), fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(envelope),
fieldValues);
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope,
Map<String, Object> fieldValues) {
return featureDao.countIn(queryIdsSQL(envelope), fieldValues);
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column names
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope,
Map<String, Object> fieldValues) {
return featureDao.countIn(column, queryIdsSQL(envelope), fieldValues);
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column names
* @param envelope
* geometry envelope
* @param fieldValues
* field values
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope, Map<String, Object> fieldValues) {
return featureDao.countIn(distinct, column, queryIdsSQL(envelope),
fieldValues);
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope,
String where) {
return queryFeatures(false, envelope, where);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope, String where) {
return queryFeatures(distinct, envelope, where, null);
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope, String where) {
return queryFeatures(columns, envelope, where, null);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope, String where) {
return queryFeatures(distinct, columns, envelope, where, null);
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope, String where) {
return countFeatures(false, null, envelope, where);
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope,
String where) {
return countFeatures(false, column, envelope, where);
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope, String where) {
return countFeatures(distinct, column, envelope, where, null);
}
/**
* Query for Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.4.0
*/
public FeatureResultSet queryFeatures(GeometryEnvelope envelope,
String where, String[] whereArgs) {
return featureDao.queryIn(queryIdsSQL(envelope), where, whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.queryIn(distinct, queryIdsSQL(envelope), where,
whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.0
*/
public FeatureResultSet queryFeatures(String[] columns,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.queryIn(columns, queryIdsSQL(envelope), where,
whereArgs);
}
/**
* Query for Features within the Geometry Envelope
*
* @param distinct
* distinct rows
* @param columns
* columns
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return feature results
* @since 3.5.1
*/
public FeatureResultSet queryFeatures(boolean distinct, String[] columns,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.queryIn(distinct, columns, queryIdsSQL(envelope),
where, whereArgs);
}
/**
* Count the Features within the Geometry Envelope
*
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.4.0
*/
public int countFeatures(GeometryEnvelope envelope, String where,
String[] whereArgs) {
return featureDao.countIn(queryIdsSQL(envelope), where, whereArgs);
}
/**
* Count the Features within the Geometry Envelope
*
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(String column, GeometryEnvelope envelope,
String where, String[] whereArgs) {
return featureDao.countIn(column, queryIdsSQL(envelope), where,
whereArgs);
}
/**
* Count the Features within the Geometry Envelope
*
* @param distinct
* distinct column values
* @param column
* count column name
* @param envelope
* geometry envelope
* @param where
* where clause
* @param whereArgs
* where arguments
* @return count
* @since 3.5.1
*/
public int countFeatures(boolean distinct, String column,
GeometryEnvelope envelope, String where, String[] whereArgs) {
return featureDao.countIn(distinct, column, queryIdsSQL(envelope),
where, whereArgs);
}
}
| minor method call change
| src/main/java/mil/nga/geopackage/extension/index/FeatureTableIndex.java | minor method call change |
|
Java | mit | 6de454c80ea360f9754cfed83f02a14fc7015c9a | 0 | Damian3395/Contained,Damian3395/Contained,Damian3395/Contained | package com.contained.game.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import codechicken.lib.packet.PacketCustom;
import com.contained.game.Contained;
import com.contained.game.data.DataLogger;
import com.contained.game.entity.ExtendedPlayer;
import com.contained.game.item.DowsingRod;
import com.contained.game.item.ItemTerritory;
import com.contained.game.network.ClientPacketHandlerUtil;
import com.contained.game.util.MiniGameUtil;
import com.contained.game.util.Resources;
import com.contained.game.util.Util;
import com.contained.game.world.block.EmblemBlock;
import com.contained.game.world.block.TerritoryMachine;
public class PlayerMiniGame {
private String[] intro = {"The", "League of", "Demons of"
, " Avengers of", "Call of", "Warlords of", "Clan of"
, "The Order of", "Gods of", "Knights of", "Guardians of"};
private String[] words = {"Greater", "Lesser", "Beast", "Demon", "Your Mother", "My Mother", "His Mother"
, "Your Father", "My Father", "Family Matters", "Nerds", "PvP", "Treasures", "His Father"
, "Unforgiven", "Guards", "Oblivion", "Wrath", "Sin", "War", "Prophecy", "Creepers", "Notch"};
private String[] combine = {"And", "Or", "With", "Rather Than", "In Contrast", "But", "Besides"
, "Coupled With", "Beyond", "Under", "Above", "Nearly", "Aside From", "In Essence"};
private int gameMode, gameID, dim;
public static ItemStack[] firstPlace = {
new ItemStack(Items.diamond_axe, 1),
new ItemStack(Items.diamond_horse_armor, 1),
new ItemStack(Items.diamond_pickaxe, 1),
new ItemStack(Items.diamond_shovel, 1),
new ItemStack(Items.diamond_sword, 1),
new ItemStack(Items.diamond_boots, 1),
new ItemStack(Items.diamond_chestplate, 1),
new ItemStack(Items.diamond_helmet, 1),
new ItemStack(Items.diamond_leggings, 1),
new ItemStack(Items.diamond, 12),
new ItemStack(Blocks.enchanting_table, 1),
new ItemStack(Blocks.enchanting_table, 1),
new ItemStack(Blocks.ender_chest, 2),
new ItemStack(ItemTerritory.addTerritory, 64),
new ItemStack(Items.emerald, 16),
new ItemStack(Items.spawn_egg, 8, 51),
new ItemStack(Items.spawn_egg, 8, 54),
new ItemStack(DowsingRod.instanceFinite, 1),
new ItemStack(DowsingRod.instanceFinite, 1),
new ItemStack(DowsingRod.instanceFinite, 1),
new ItemStack(DowsingRod.instanceFinite, 1),
};
public static ItemStack[] secondPlace = {
new ItemStack(Items.golden_apple, 2),
new ItemStack(Items.golden_carrot, 2),
new ItemStack(Items.gold_ingot, 16),
new ItemStack(Blocks.rail, 32),
new ItemStack(Blocks.golden_rail, 16),
new ItemStack(EmblemBlock.earthEmblemAct, 2),
new ItemStack(EmblemBlock.fireEmblemAct, 2),
new ItemStack(EmblemBlock.waterEmblemAct, 2),
new ItemStack(EmblemBlock.windEmblemAct, 2),
new ItemStack(Blocks.obsidian, 8),
new ItemStack(TerritoryMachine.instance, 1),
new ItemStack(Items.experience_bottle, 32),
};
public static ItemStack[] thirdPlace = {
new ItemStack(Items.iron_axe, 1),
new ItemStack(Items.iron_hoe, 1),
new ItemStack(Items.iron_door, 1),
new ItemStack(Items.iron_horse_armor, 1),
new ItemStack(Items.iron_pickaxe, 1),
new ItemStack(Items.iron_shovel, 1),
new ItemStack(Items.iron_sword, 1),
new ItemStack(Items.iron_boots, 1),
new ItemStack(Items.iron_chestplate, 1),
new ItemStack(Items.iron_helmet, 1),
new ItemStack(Items.iron_leggings, 1),
new ItemStack(Items.bucket, 1),
new ItemStack(Items.shears, 1),
new ItemStack(Items.compass, 1),
new ItemStack(Items.iron_ingot, 16),
new ItemStack(Blocks.nether_brick, 64),
new ItemStack(Blocks.nether_brick_fence, 32),
new ItemStack(Blocks.nether_brick_stairs, 32),
};
public static ItemStack[] fourthPlace = {
new ItemStack(Items.stone_axe, 1),
new ItemStack(Items.wooden_axe, 1),
new ItemStack(Items.stone_hoe, 1),
new ItemStack(Items.wooden_door, 2),
new ItemStack(Items.stone_pickaxe, 1),
new ItemStack(Items.wooden_hoe, 1),
new ItemStack(Items.stone_shovel, 1),
new ItemStack(Items.wooden_pickaxe, 1),
new ItemStack(Items.stone_sword, 1),
new ItemStack(Items.wooden_shovel, 1),
new ItemStack(Items.wooden_sword, 1),
new ItemStack(Items.leather_boots, 1),
new ItemStack(Items.leather_chestplate, 1),
new ItemStack(Items.leather_helmet, 1),
new ItemStack(Items.leather_leggings, 1),
new ItemStack(Items.leather, 16),
new ItemStack(Items.fishing_rod, 1),
new ItemStack(Items.boat, 1),
new ItemStack(Items.bow, 1),
new ItemStack(Items.arrow, 24),
new ItemStack(Items.bed, 1),
new ItemStack(Items.cake, 1),
new ItemStack(Items.cookie, 16),
new ItemStack(Items.clock, 1),
new ItemStack(Items.saddle, 1)
};
public static ItemStack[] fifthPlace = {
new ItemStack(Items.apple,8),
new ItemStack(Items.record_11, 1),
new ItemStack(Items.baked_potato, 8),
new ItemStack(Items.record_13, 1),
new ItemStack(Items.cooked_beef, 8),
new ItemStack(Items.record_blocks, 1),
new ItemStack(Items.bone, 16),
new ItemStack(Items.record_cat, 1),
new ItemStack(Items.bowl, 8),
new ItemStack(Items.record_chirp, 1),
new ItemStack(Items.bread, 8),
new ItemStack(Items.record_far, 1),
new ItemStack(Items.carrot, 8),
new ItemStack(Items.record_mall, 1),
new ItemStack(Items.cooked_chicken, 8),
new ItemStack(Items.coal, 16),
new ItemStack(Items.record_mellohi, 1),
new ItemStack(Items.clay_ball, 16),
new ItemStack(Items.record_stal, 1),
new ItemStack(Items.cooked_fished, 8),
new ItemStack(Items.record_strad, 1),
new ItemStack(Items.cooked_porkchop, 8),
new ItemStack(Items.record_wait, 1),
new ItemStack(Items.egg, 16),
new ItemStack(Items.record_ward, 1),
new ItemStack(Items.feather, 16),
new ItemStack(Items.flint, 32),
new ItemStack(Items.sugar, 16),
new ItemStack(Items.wheat, 32),
new ItemStack(Items.string, 16),
};
public PlayerMiniGame(int playersPending) {
this(playersPending >= MiniGameUtil.getCapacity(Resources.PVP)
, playersPending >= MiniGameUtil.getCapacity(Resources.TREASURE));
}
public PlayerMiniGame(boolean enablePvP, boolean enableTreasure){
Random rand = new Random();
gameMode = -1;
if(Contained.PVP_GAMES < Resources.MAX_PVP_GAMES
&& Contained.TREASURE_GAMES < Resources.MAX_TREASURE_GAMES
&& enablePvP && enableTreasure) {
if(rand.nextBoolean())
gameMode = Resources.PVP;
else
gameMode = Resources.TREASURE;
}
else if (Contained.PVP_GAMES < Resources.MAX_PVP_GAMES && enablePvP)
gameMode = Resources.PVP;
else if(Contained.TREASURE_GAMES < Resources.MAX_TREASURE_GAMES && enableTreasure)
gameMode = Resources.TREASURE;
if (gameMode != -1) {
dim = getEmptyWorld(gameMode);
if(dim == -1)
gameMode = -1;
}
if (gameMode == -1)
return;
else if (gameMode == Resources.TREASURE)
Contained.TREASURE_GAMES++;
else if (gameMode == Resources.PVP)
Contained.PVP_GAMES++;
gameID = Contained.GAME_COUNT;
Contained.GAME_COUNT++;
}
public PlayerMiniGame(int dimID, int gameMode){
this.dim = dimID;
this.gameMode = gameMode;
this.gameID = -1;
}
public PlayerMiniGame(NBTTagCompound ntc) {
this.readFromNBT(ntc);
}
//Game Player To Random Team
public void addPlayer(EntityPlayer player){
if(player == null)
return;
ArrayList<PlayerTeam> teams = Contained.getTeamList(dim);
if (teams.size() < Contained.configs.gameNumTeams[gameMode])
createTeam(player);
else { //Randomize Teams
ArrayList<Integer> candidateTeams = new ArrayList<Integer>();
for(int i=0; i<teams.size(); i++) {
if (teams.get(i).numMembers() < Contained.configs.maxTeamSize[gameMode])
candidateTeams.add(i);
}
Collections.shuffle(candidateTeams);
if (candidateTeams.size() == 0)
Util.serverDebugMessage("[ERROR] Failed to add player to mini-game team, because they were all already full!");
else
addPlayerToTeam(player, candidateTeams.get(0));
}
}
private void addPlayerToTeam(EntityPlayer player, int team) {
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
pdata.joinMiniTeam(Contained.getTeamList(dim).get(team).id);
DataLogger.insertMiniGamePlayer(Util.getServerID(), gameID, gameMode, player.getDisplayName(), Contained.getTeamList(dim).get(team).displayName, Util.getDate());
}
public void removePlayer(EntityPlayerMP player) {
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
if(getTeamID(pdata) != -1){
pdata.revertMiniGameChanges();
DataLogger.deleteMiniGamePlayer(player.getDisplayName());
}
}
public void launchGame(ArrayList<EntityPlayer> playersJoining){
if (MiniGameUtil.isPvP(dim))
gameMode = Resources.PVP;
else if (MiniGameUtil.isTreasure(dim))
gameMode = Resources.TREASURE;
DataLogger.insertNewMiniGame(Util.getServerID(), gameID, gameMode, Util.getDate());
if(isGameReady()){
pickRandomTeamLeaders();
MiniGameUtil.startGame(this, playersJoining);
}
}
public void endGame(String winningTeamID, String winCondition){
ArrayList<PlayerTeam> teams = Contained.getTeamList(dim);
int winScore = 0;
for(int i = 0; i < teams.size(); i++){
if(teams.get(i).id.equals(winningTeamID)){
winScore = Contained.gameScores[dim][i];
DataLogger.insertGameScore(Util.getServerID(),
gameID, gameMode, teams.get(i).displayName,
Contained.gameScores[dim][i], Contained.timeLeft[dim], Util.getDate());
break;
}
}
Util.serverDebugMessage("Ending DIM"+dim+" game");
Contained.gameActive[dim] = false;
Contained.timeLeft[dim] = 0;
ClientPacketHandlerUtil.syncMinigameTime(dim);
Contained.getActiveTreasures(dim).clear();
Contained.getTeamList(dim).clear();
for(PlayerMiniGame game : Contained.miniGames)
if(game.getGameDimension() == dim){
Contained.miniGames.remove(game);
break;
}
for(int i = 0; i < Contained.gameScores[dim].length; i++)
Contained.gameScores[dim][i] = 0;
if(MiniGameUtil.isTreasure(dim))
Contained.getActiveTreasures(dim).clear();
for(EntityPlayer player : getOnlinePlayers()){
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
ExtendedPlayer properties = ExtendedPlayer.get(player);
int playerScore = 0;
if(MiniGameUtil.isPvP(dim) && pdata.teamID != null){
playerScore = (properties.curKills*3) - (properties.curDeaths*3) + properties.curAntiTerritory;
DataLogger.insertPVPScore(Util.getServerID(), gameID, player.getDisplayName(),
pdata.teamID, properties.curKills, properties.curDeaths,
properties.curAntiTerritory, Util.getDate());
if(!winCondition.equals("TIE")){
if(pdata.teamID.equalsIgnoreCase(winningTeamID))
properties.pvpWon++;
else if (!winningTeamID.equals("Debug") && !winningTeamID.equals("Kicked"))
properties.pvpLost++;
}
properties.kills+=properties.curKills;
properties.deaths+=properties.curDeaths;
properties.antiTerritory+=properties.curAntiTerritory;
}else if(MiniGameUtil.isTreasure(dim) && pdata.teamID != null){
playerScore = properties.curTreasuresOpened + properties.curAltersActivated*3;
DataLogger.insertTreasureScore(Util.getServerID(),
gameID, player.getDisplayName(), pdata.teamID,
properties.curTreasuresOpened, properties.curAltersActivated, Util.getDate());
if(!winCondition.equals("TIE")){
if(pdata.teamID.equalsIgnoreCase(winningTeamID))
properties.treasureWon++;
else if (!winningTeamID.equals("Debug") && !winningTeamID.equals("Kicked"))
properties.treasureLost++;
}
properties.treasuresOpened+=properties.curTreasuresOpened;
properties.altersActivated+=properties.curAltersActivated;
}
//Reward XP Points To Player
String teamMiniGame = pdata.teamID;
if(winningTeamID != null && winCondition != null){
boolean emptySlot = false;
int index = -1;
for(int i = 0; i < pdata.inventory.length; i++){
ItemStack item = pdata.inventory[i];
if(item == null){
emptySlot = true;
index = i;
break;
}
}
if(!emptySlot)
rewardXP(player, pdata, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, teamMiniGame.equals(winningTeamID));
}
Util.travelToDimension(0, player, false);
//Reward Item To Player
if(winningTeamID != null && teamMiniGame != null && winCondition != null){
if(player.inventory.getFirstEmptyStack() > -1)
rewardItem(player, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, teamMiniGame.equals(winningTeamID));
}
if(MiniGameUtil.isPvP(dim)){
PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_PVP_STATS);
syncScore.writeInt(properties.pvpWon);
syncScore.writeInt(properties.pvpLost);
syncScore.writeInt(properties.kills);
syncScore.writeInt(properties.deaths);
syncScore.writeInt(properties.antiTerritory);
Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player);
}else if(MiniGameUtil.isTreasure(dim)){
PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_TEASURE_STATS);
syncScore.writeInt(properties.treasureWon);
syncScore.writeInt(properties.treasureLost);
syncScore.writeInt(properties.treasuresOpened);
syncScore.writeInt(properties.altersActivated);
Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player);
}
}
PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED);
miniGamePacket.writeInt(dim);
Contained.channel.sendToDimension(miniGamePacket.toPacket(), 0);
}
public ArrayList<PlayerTeamIndividual> getGamePlayers() {
ArrayList<PlayerTeamIndividual> players = new ArrayList<PlayerTeamIndividual>();
for(PlayerTeamIndividual pdata : Contained.teamMemberData)
if(getTeamID(pdata) != -1)
players.add(pdata);
return players;
}
public List<EntityPlayer> getOnlinePlayers() {
WorldServer w = DimensionManager.getWorld(dim);
if (w != null && w.playerEntities != null)
return new ArrayList<EntityPlayer>(w.playerEntities);
else
return new ArrayList<EntityPlayer>();
}
private static boolean ignoreWinCondition(String condition) {
if (condition.equals("Debug") || condition.equals("Inactive") || condition.equals("Kicked"))
return true;
return false;
}
//Determine Your Reward Based on Your Contribution To The Teams' Total Score
public static void rewardItem(EntityPlayer player, int alters, int territory, int kills, int score, int totalScore, String winCondition, boolean inWinningTeam){
if (ignoreWinCondition(winCondition))
return;
double percentage = (double)((double) score / (double) totalScore);
//Special Rewards
if(winCondition.equals("EMBLEMS")){
switch(alters){
case 1: percentage+=0.1; break;
case 2: percentage+=0.25; break;
case 3: percentage+=0.5; break;
}
}else if(winCondition.equals("TERRITORY")){
double anti = territory;
double total = Math.pow((Contained.configs.pvpTerritorySize*2+1), 2.0);
percentage+=(anti/total);
}else if(winCondition.equals("MAX_KILLS")){
double total = Contained.configs.pvpMaxLives*Contained.configs.maxTeamSize[Resources.PVP];
percentage+=((double)kills/total);
}
ItemStack reward = null;
Random rand = new Random();
// If on the winning team, eligible for first, second, or third tier rewards.
// If on the losing team, only eligible for fourth or fifth tier rewards.
if (inWinningTeam && !winCondition.equals("TIE")) {
if(percentage >= 0.3)
reward = firstPlace[rand.nextInt(firstPlace.length)];
else if(percentage >= 0.2)
reward = secondPlace[rand.nextInt(secondPlace.length)];
else
reward = thirdPlace[rand.nextInt(thirdPlace.length)];
}
else {
if(percentage >= 0.2)
reward = fourthPlace[rand.nextInt(fourthPlace.length)];
else
reward = fifthPlace[rand.nextInt(fifthPlace.length)];
}
Util.displayMessage(player, Util.infoCode+"[PRIZE] Recieved "+reward.getDisplayName()+" (x"+reward.stackSize+")");
player.inventory.addItemStackToInventory(reward);
PacketCustom rewardPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM);
rewardPacket.writeItemStack(reward);
Contained.channel.sendTo(rewardPacket.toPacket(), (EntityPlayerMP) player);
}
//Determine Your Reward Based On Your Contribution To The Teams' Total Score
public static void rewardXP(EntityPlayer player, PlayerTeamIndividual pdata,
int alters, int territory, int kills,
int score, int totalScore, String winCondition, boolean inWinningTeam){
if (ignoreWinCondition(winCondition))
return;
double percentage = (double)((double) score / (double) totalScore);
//Find XP needed to Reach Next Level
int xpNeeded = 0;
if(pdata.level >= 0 && pdata.level <= 16){
xpNeeded = 2 * pdata.level + 7;
}else if(pdata.level >= 17 && pdata.level <= 31){
xpNeeded = 5 * pdata.level - 38;
}else{
xpNeeded = 9 * pdata.level - 158;
}
xpNeeded -= pdata.xp;
//Special Rewards
if(winCondition.equals("EMBLEMS")){
switch(alters){
case 1: percentage+=0.1; break;
case 2: percentage+=0.25; break;
case 3: percentage+=0.5; break;
}
}else if(winCondition.equals("TERRITORY")){
double anti = territory;
double total = Math.pow((Contained.configs.pvpTerritorySize*2+1), 2.0);
percentage+=(anti/total);
}else if(winCondition.equals("MAX_KILLS")){
double total = Contained.configs.pvpMaxLives*Contained.configs.maxTeamSize[Resources.PVP];
percentage+=((double)kills/total);
}
float multiplier = 20;
if (!inWinningTeam || winCondition.equals("TIE"))
multiplier = 4;
if(percentage >= 0.5)
xpNeeded*=0.9*multiplier;
else if(percentage >= 0.4)
xpNeeded*=0.75*multiplier;
else if(percentage >= 0.3)
xpNeeded*=0.5*multiplier;
else if(percentage >= 0.2)
xpNeeded*=0.25*multiplier;
else if(percentage >= 0.1)
xpNeeded*=0.1*multiplier;
else
xpNeeded*=0.05*multiplier;
Util.displayMessage(player, Util.infoCode+"[PRIZE] Recieved "+xpNeeded+" XP");
pdata.xp+=xpNeeded;
}
public boolean isGameReady() {
int teamPlayerCount = 0;
for(PlayerTeam team : Contained.getTeamList(dim))
teamPlayerCount += team.numMembers();
if (teamPlayerCount >= getCapacity())
return true;
return false;
}
// Index of this player's team in this dimension's team arraylist, or -1
// if the player does not currently belong to any of this dimension's teams.
public int getTeamID(PlayerTeamIndividual pdata) {
if (pdata.teamID == null)
return -1;
for (int i=0; i<Contained.getTeamList(dim).size(); i++) {
if (pdata.teamID.equals(Contained.getTeamList(dim).get(i).id))
return i;
}
return -1;
}
public int getGameDimension(){
return dim;
}
public int getGameID(){
return gameID;
}
public int getGameMode(){
return gameMode;
}
public int getCapacity(){
return MiniGameUtil.getCapacity(this.gameMode);
}
public int numPlayers() {
int count = 0;
for(PlayerTeamIndividual pdata : Contained.teamMemberData)
if(getTeamID(pdata) != -1)
count++;
return count;
}
public int numOnlinePlayers() {
return Math.min(getOnlinePlayers().size(), numPlayers());
}
private void pickRandomTeamLeaders(){
for(PlayerTeam team : Contained.getTeamList(dim)) {
List<String> teamPlayers = team.getTeamPlayers();
if (teamPlayers.size() != 0) {
Collections.shuffle(teamPlayers);
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(teamPlayers.get(0));
pdata.setTeamLeader();
}
else
Util.serverDebugMessage("[ERROR] Tried to set a leader for a team that had no members.");
}
}
private String generateName(){
Random rand = new Random();
String teamName = "";
do {
teamName = intro[rand.nextInt(intro.length)] + " " + words[rand.nextInt(words.length)];
if(rand.nextBoolean())
teamName += " " + combine[rand.nextInt(combine.length)] + " " + words[rand.nextInt(words.length)];
} while(teamName.length() > 20);
return teamName;
}
private boolean teamExists(String teamName){
WorldServer[] worlds = DimensionManager.getWorlds();
for(WorldServer world : worlds)
for(PlayerTeam team : Contained.getTeamList(world.provider.dimensionId))
if (team.displayName.toLowerCase().equals(teamName.toLowerCase()))
return true;
return false;
}
private boolean teamColorExists(int index){
for(PlayerTeam team : Contained.getTeamList(dim))
if(team.colorID == index)
return true;
return false;
}
private int getEmptyWorld(int gameMode){
ArrayList<Integer> pvpDims = new ArrayList<Integer>();
ArrayList<Integer> treasureDims = new ArrayList<Integer>();
for(int i=Resources.MIN_PVP_DIMID; i<=Resources.MAX_PVP_DIMID; i++)
pvpDims.add(i);
for(int i=Resources.MIN_TREASURE_DIMID; i<=Resources.MAX_TREASURE_DIMID; i++)
treasureDims.add(i);
for(PlayerMiniGame game : Contained.miniGames){
if(game != null){
if(game.gameMode == this.gameMode){
if (this.gameMode == Resources.PVP)
pvpDims.remove(new Integer(game.dim));
else if (this.gameMode == Resources.TREASURE)
treasureDims.remove(new Integer(game.dim));
}
}
}
if (gameMode == Resources.PVP && !pvpDims.isEmpty())
return pvpDims.get(0);
else if (gameMode == Resources.TREASURE && !treasureDims.isEmpty())
return treasureDims.get(0);
return -1;
}
private void createTeam(EntityPlayer player){
Random rand = new Random();
String teamName = generateName();
int colorID = rand.nextInt(PlayerTeam.formatColors.length);
while(teamExists(teamName))
teamName = generateName();
while(teamColorExists(colorID))
colorID = rand.nextInt(PlayerTeam.formatColors.length);
PlayerTeam newTeam = new PlayerTeam(teamName, colorID, dim);
Contained.getTeamList(dim).add(newTeam);
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
pdata.joinMiniTeam(newTeam.id);
DataLogger.insertMiniGamePlayer(Util.getServerID(), gameID, gameMode, player.getDisplayName(), teamName, Util.getDate());
}
public void testLaunch(EntityPlayer player){
createTeam(player);
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
pdata.setTeamLeader();
}
public void writeToNBT(NBTTagCompound ntc) {
ntc.setInteger("dimID", this.dim);
ntc.setInteger("gameID", this.gameID);
ntc.setInteger("gameMode", this.gameMode);
}
public void readFromNBT(NBTTagCompound ntc) {
this.dim = ntc.getInteger("dimID");
this.gameID = ntc.getInteger("gameID");
this.gameMode = ntc.getInteger("gameMode");
}
public static PlayerMiniGame get(int dim){
for(PlayerMiniGame game : Contained.miniGames)
if(game.dim == dim)
return game;
return null;
}
public static PlayerMiniGame get(String teamName){
for(PlayerMiniGame game : Contained.miniGames)
if(game.teamExists(teamName))
return game;
return null;
}
} | src/main/java/com/contained/game/user/PlayerMiniGame.java | package com.contained.game.user;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import codechicken.lib.packet.PacketCustom;
import com.contained.game.Contained;
import com.contained.game.data.DataLogger;
import com.contained.game.entity.ExtendedPlayer;
import com.contained.game.item.DowsingRod;
import com.contained.game.item.ItemTerritory;
import com.contained.game.network.ClientPacketHandlerUtil;
import com.contained.game.util.MiniGameUtil;
import com.contained.game.util.Resources;
import com.contained.game.util.Util;
import com.contained.game.world.block.EmblemBlock;
import com.contained.game.world.block.TerritoryMachine;
public class PlayerMiniGame {
private String[] intro = {"The", "League of", "Demons of"
, " Avengers of", "Call of", "Warlords of", "Clan of"
, "The Order of", "Gods of", "Knights of", "Guardians of"};
private String[] words = {"Greater", "Lesser", "Beast", "Demon", "Your Mother", "My Mother", "His Mother"
, "Your Father", "My Father", "Family Matters", "Nerds", "PvP", "Treasures", "His Father"
, "Unforgiven", "Guards", "Oblivion", "Wrath", "Sin", "War", "Prophecy", "Creepers", "Notch"};
private String[] combine = {"And", "Or", "With", "Rather Than", "In Contrast", "But", "Besides"
, "Coupled With", "Beyond", "Under", "Above", "Nearly", "Aside From", "In Essence"};
private int gameMode, gameID, dim;
public static ItemStack[] firstPlace = {
new ItemStack(Items.diamond_axe, 1),
new ItemStack(Items.diamond_horse_armor, 1),
new ItemStack(Items.diamond_pickaxe, 1),
new ItemStack(Items.diamond_shovel, 1),
new ItemStack(Items.diamond_sword, 1),
new ItemStack(Items.diamond_boots, 1),
new ItemStack(Items.diamond_chestplate, 1),
new ItemStack(Items.diamond_helmet, 1),
new ItemStack(Items.diamond_leggings, 1),
new ItemStack(Items.diamond, 12),
new ItemStack(Blocks.enchanting_table, 1),
new ItemStack(Blocks.enchanting_table, 1),
new ItemStack(Blocks.ender_chest, 2),
new ItemStack(ItemTerritory.addTerritory, 64),
new ItemStack(Items.emerald, 16),
new ItemStack(Items.spawn_egg, 8, 51),
new ItemStack(Items.spawn_egg, 8, 54),
new ItemStack(DowsingRod.instanceFinite, 1),
new ItemStack(DowsingRod.instanceFinite, 1),
new ItemStack(DowsingRod.instanceFinite, 1),
new ItemStack(DowsingRod.instanceFinite, 1),
};
public static ItemStack[] secondPlace = {
new ItemStack(Items.golden_apple, 2),
new ItemStack(Items.golden_carrot, 2),
new ItemStack(Items.gold_ingot, 16),
new ItemStack(Blocks.rail, 32),
new ItemStack(Blocks.golden_rail, 16),
new ItemStack(EmblemBlock.earthEmblemAct, 2),
new ItemStack(EmblemBlock.fireEmblemAct, 2),
new ItemStack(EmblemBlock.waterEmblemAct, 2),
new ItemStack(EmblemBlock.windEmblemAct, 2),
new ItemStack(Blocks.obsidian, 8),
new ItemStack(TerritoryMachine.instance, 1),
new ItemStack(Items.experience_bottle, 32),
};
public static ItemStack[] thirdPlace = {
new ItemStack(Items.iron_axe, 1),
new ItemStack(Items.iron_hoe, 1),
new ItemStack(Items.iron_door, 1),
new ItemStack(Items.iron_horse_armor, 1),
new ItemStack(Items.iron_pickaxe, 1),
new ItemStack(Items.iron_shovel, 1),
new ItemStack(Items.iron_sword, 1),
new ItemStack(Items.iron_boots, 1),
new ItemStack(Items.iron_chestplate, 1),
new ItemStack(Items.iron_helmet, 1),
new ItemStack(Items.iron_leggings, 1),
new ItemStack(Items.bucket, 1),
new ItemStack(Items.shears, 1),
new ItemStack(Items.compass, 1),
new ItemStack(Items.iron_ingot, 16),
new ItemStack(Blocks.nether_brick, 64),
new ItemStack(Blocks.nether_brick_fence, 32),
new ItemStack(Blocks.nether_brick_stairs, 32),
};
public static ItemStack[] fourthPlace = {
new ItemStack(Items.stone_axe, 1),
new ItemStack(Items.wooden_axe, 1),
new ItemStack(Items.stone_hoe, 1),
new ItemStack(Items.wooden_door, 2),
new ItemStack(Items.stone_pickaxe, 1),
new ItemStack(Items.wooden_hoe, 1),
new ItemStack(Items.stone_shovel, 1),
new ItemStack(Items.wooden_pickaxe, 1),
new ItemStack(Items.stone_sword, 1),
new ItemStack(Items.wooden_shovel, 1),
new ItemStack(Items.wooden_sword, 1),
new ItemStack(Items.leather_boots, 1),
new ItemStack(Items.leather_chestplate, 1),
new ItemStack(Items.leather_helmet, 1),
new ItemStack(Items.leather_leggings, 1),
new ItemStack(Items.leather, 16),
new ItemStack(Items.fishing_rod, 1),
new ItemStack(Items.boat, 1),
new ItemStack(Items.bow, 1),
new ItemStack(Items.arrow, 24),
new ItemStack(Items.bed, 1),
new ItemStack(Items.cake, 1),
new ItemStack(Items.cookie, 16),
new ItemStack(Items.clock, 1),
new ItemStack(Items.saddle, 1)
};
public static ItemStack[] fifthPlace = {
new ItemStack(Items.apple,8),
new ItemStack(Items.record_11, 1),
new ItemStack(Items.baked_potato, 8),
new ItemStack(Items.record_13, 1),
new ItemStack(Items.cooked_beef, 8),
new ItemStack(Items.record_blocks, 1),
new ItemStack(Items.bone, 16),
new ItemStack(Items.record_cat, 1),
new ItemStack(Items.bowl, 8),
new ItemStack(Items.record_chirp, 1),
new ItemStack(Items.bread, 8),
new ItemStack(Items.record_far, 1),
new ItemStack(Items.carrot, 8),
new ItemStack(Items.record_mall, 1),
new ItemStack(Items.cooked_chicken, 8),
new ItemStack(Items.coal, 16),
new ItemStack(Items.record_mellohi, 1),
new ItemStack(Items.clay_ball, 16),
new ItemStack(Items.record_stal, 1),
new ItemStack(Items.cooked_fished, 8),
new ItemStack(Items.record_strad, 1),
new ItemStack(Items.cooked_porkchop, 8),
new ItemStack(Items.record_wait, 1),
new ItemStack(Items.egg, 16),
new ItemStack(Items.record_ward, 1),
new ItemStack(Items.feather, 16),
new ItemStack(Items.flint, 32),
new ItemStack(Items.sugar, 16),
new ItemStack(Items.wheat, 32),
new ItemStack(Items.string, 16),
};
public PlayerMiniGame(int playersPending) {
this(playersPending >= MiniGameUtil.getCapacity(Resources.PVP)
, playersPending >= MiniGameUtil.getCapacity(Resources.TREASURE));
}
public PlayerMiniGame(boolean enablePvP, boolean enableTreasure){
Random rand = new Random();
gameMode = -1;
if(Contained.PVP_GAMES < Resources.MAX_PVP_GAMES
&& Contained.TREASURE_GAMES < Resources.MAX_TREASURE_GAMES
&& enablePvP && enableTreasure) {
if(rand.nextBoolean())
gameMode = Resources.PVP;
else
gameMode = Resources.TREASURE;
}
else if (Contained.PVP_GAMES < Resources.MAX_PVP_GAMES && enablePvP)
gameMode = Resources.PVP;
else if(Contained.TREASURE_GAMES < Resources.MAX_TREASURE_GAMES && enableTreasure)
gameMode = Resources.TREASURE;
if (gameMode != -1) {
dim = getEmptyWorld(gameMode);
if(dim == -1)
gameMode = -1;
}
if (gameMode == -1)
return;
else if (gameMode == Resources.TREASURE)
Contained.TREASURE_GAMES++;
else if (gameMode == Resources.PVP)
Contained.PVP_GAMES++;
gameID = Contained.GAME_COUNT;
Contained.GAME_COUNT++;
}
public PlayerMiniGame(int dimID, int gameMode){
this.dim = dimID;
this.gameMode = gameMode;
this.gameID = -1;
}
public PlayerMiniGame(NBTTagCompound ntc) {
this.readFromNBT(ntc);
}
//Game Player To Random Team
public void addPlayer(EntityPlayer player){
if(player == null)
return;
ArrayList<PlayerTeam> teams = Contained.getTeamList(dim);
if (teams.size() < Contained.configs.gameNumTeams[gameMode])
createTeam(player);
else { //Randomize Teams
ArrayList<Integer> candidateTeams = new ArrayList<Integer>();
for(int i=0; i<teams.size(); i++) {
if (teams.get(i).numMembers() < Contained.configs.maxTeamSize[gameMode])
candidateTeams.add(i);
}
Collections.shuffle(candidateTeams);
if (candidateTeams.size() == 0)
Util.serverDebugMessage("[ERROR] Failed to add player to mini-game team, because they were all already full!");
else
addPlayerToTeam(player, candidateTeams.get(0));
}
}
private void addPlayerToTeam(EntityPlayer player, int team) {
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
pdata.joinMiniTeam(Contained.getTeamList(dim).get(team).id);
DataLogger.insertMiniGamePlayer(Util.getServerID(), gameID, gameMode, player.getDisplayName(), Contained.getTeamList(dim).get(team).displayName, Util.getDate());
}
public void removePlayer(EntityPlayerMP player) {
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
if(getTeamID(pdata) != -1){
pdata.revertMiniGameChanges();
DataLogger.deleteMiniGamePlayer(player.getDisplayName());
}
}
public void launchGame(ArrayList<EntityPlayer> playersJoining){
if (MiniGameUtil.isPvP(dim))
gameMode = Resources.PVP;
else if (MiniGameUtil.isTreasure(dim))
gameMode = Resources.TREASURE;
DataLogger.insertNewMiniGame(Util.getServerID(), gameID, gameMode, Util.getDate());
if(isGameReady()){
pickRandomTeamLeaders();
MiniGameUtil.startGame(this, playersJoining);
}
}
public void endGame(String winningTeamID, String winCondition){
ArrayList<PlayerTeam> teams = Contained.getTeamList(dim);
int winScore = 0;
for(int i = 0; i < teams.size(); i++){
if(teams.get(i).id.equals(winningTeamID)){
winScore = Contained.gameScores[dim][i];
DataLogger.insertGameScore(Util.getServerID(),
gameID, gameMode, teams.get(i).displayName,
Contained.gameScores[dim][i], Contained.timeLeft[dim], Util.getDate());
break;
}
}
Util.serverDebugMessage("Ending DIM"+dim+" game");
Contained.gameActive[dim] = false;
Contained.timeLeft[dim] = 0;
ClientPacketHandlerUtil.syncMinigameTime(dim);
Contained.getActiveTreasures(dim).clear();
Contained.getTeamList(dim).clear();
for(PlayerMiniGame game : Contained.miniGames)
if(game.getGameDimension() == dim){
Contained.miniGames.remove(game);
break;
}
for(int i = 0; i < Contained.gameScores[dim].length; i++)
Contained.gameScores[dim][i] = 0;
if(MiniGameUtil.isTreasure(dim))
Contained.getActiveTreasures(dim).clear();
for(EntityPlayer player : getOnlinePlayers()){
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
ExtendedPlayer properties = ExtendedPlayer.get(player);
int playerScore = 0;
if(MiniGameUtil.isPvP(dim) && pdata.teamID != null){
playerScore = (properties.curKills*3) - (properties.curDeaths*3) + properties.curAntiTerritory;
DataLogger.insertPVPScore(Util.getServerID(), gameID, player.getDisplayName(),
pdata.teamID, properties.curKills, properties.curDeaths,
properties.curAntiTerritory, Util.getDate());
if(!winCondition.equals("TIE")){
if(pdata.teamID.equalsIgnoreCase(winningTeamID))
properties.pvpWon++;
else if (!winningTeamID.equals("Debug") && !winningTeamID.equals("Kicked"))
properties.pvpLost++;
}
properties.kills+=properties.curKills;
properties.deaths+=properties.curDeaths;
properties.antiTerritory+=properties.curAntiTerritory;
}else if(MiniGameUtil.isTreasure(dim) && pdata.teamID != null){
playerScore = properties.curTreasuresOpened + properties.curAltersActivated*3;
DataLogger.insertTreasureScore(Util.getServerID(),
gameID, player.getDisplayName(), pdata.teamID,
properties.curTreasuresOpened, properties.curAltersActivated, Util.getDate());
if(!winCondition.equals("TIE")){
if(pdata.teamID.equalsIgnoreCase(winningTeamID))
properties.treasureWon++;
else if (!winningTeamID.equals("Debug") && !winningTeamID.equals("Kicked"))
properties.treasureLost++;
}
properties.treasuresOpened+=properties.curTreasuresOpened;
properties.altersActivated+=properties.curAltersActivated;
}
//Reward XP Points To Player
String teamMiniGame = pdata.teamID;
if(winningTeamID != null && winCondition != null){
boolean emptySlot = false;
int index = -1;
for(int i = 0; i < pdata.inventory.length; i++){
ItemStack item = pdata.inventory[i];
if(item == null){
emptySlot = true;
index = i;
break;
}
}
if(!emptySlot)
rewardXP(player, pdata, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, teamMiniGame.equals(winningTeamID));
}
Util.travelToDimension(0, player, false);
//Reward Item To Player
if(winningTeamID != null && teamMiniGame != null && winCondition != null){
if(player.inventory.getFirstEmptyStack() > -1)
rewardItem(player, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, teamMiniGame.equals(winningTeamID));
}
if(MiniGameUtil.isPvP(dim)){
PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_PVP_STATS);
syncScore.writeInt(properties.pvpWon);
syncScore.writeInt(properties.pvpLost);
syncScore.writeInt(properties.kills);
syncScore.writeInt(properties.deaths);
syncScore.writeInt(properties.antiTerritory);
Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player);
}else if(MiniGameUtil.isTreasure(dim)){
PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_TEASURE_STATS);
syncScore.writeInt(properties.treasureWon);
syncScore.writeInt(properties.treasureLost);
syncScore.writeInt(properties.treasuresOpened);
syncScore.writeInt(properties.altersActivated);
Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player);
}
}
PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED);
miniGamePacket.writeInt(dim);
Contained.channel.sendToDimension(miniGamePacket.toPacket(), 0);
}
public ArrayList<PlayerTeamIndividual> getGamePlayers() {
ArrayList<PlayerTeamIndividual> players = new ArrayList<PlayerTeamIndividual>();
for(PlayerTeamIndividual pdata : Contained.teamMemberData)
if(getTeamID(pdata) != -1)
players.add(pdata);
return players;
}
public List<EntityPlayer> getOnlinePlayers() {
WorldServer w = DimensionManager.getWorld(dim);
if (w != null && w.playerEntities != null)
return new ArrayList<EntityPlayer>(w.playerEntities);
else
return new ArrayList<EntityPlayer>();
}
private static boolean ignoreWinCondition(String condition) {
if (condition.equals("Debug") || condition.equals("Inactive") || condition.equals("Kicked"))
return true;
return false;
}
//Determine Your Reward Based on Your Contribution To The Teams' Total Score
public static void rewardItem(EntityPlayer player, int alters, int territory, int kills, int score, int totalScore, String winCondition, boolean inWinningTeam){
if (ignoreWinCondition(winCondition))
return;
double percentage = (double)((double) score / (double) totalScore);
//Special Rewards
if(winCondition.equals("EMBLEMS")){
switch(alters){
case 1: percentage+=0.1; break;
case 2: percentage+=0.25; break;
case 3: percentage+=0.5; break;
}
}else if(winCondition.equals("TERRITORY")){
double anti = territory;
double total = Math.pow((Contained.configs.pvpTerritorySize*2+1), 2.0);
percentage+=(anti/total);
}else if(winCondition.equals("MAX_KILLS")){
double total = Contained.configs.pvpMaxLives*Contained.configs.maxTeamSize[Resources.PVP];
percentage+=((double)kills/total);
}
ItemStack reward = null;
Random rand = new Random();
// If on the winning team, eligible for first, second, or third tier rewards.
// If on the losing team, only eligible for fourth or fifth tier rewards.
if (inWinningTeam && !winCondition.equals("TIE")) {
if(percentage >= 0.3)
reward = firstPlace[rand.nextInt(firstPlace.length)];
else if(percentage >= 0.2)
reward = secondPlace[rand.nextInt(secondPlace.length)];
else
reward = thirdPlace[rand.nextInt(thirdPlace.length)];
}
else {
if(percentage >= 0.2)
reward = fourthPlace[rand.nextInt(fourthPlace.length)];
else
reward = fifthPlace[rand.nextInt(fifthPlace.length)];
}
Util.displayMessage(player, Util.infoCode+"[PRIZE] Recieved "+reward.getDisplayName()+" (x"+reward.stackSize+")");
player.inventory.addItemStackToInventory(reward);
PacketCustom rewardPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM);
rewardPacket.writeItemStack(reward);
Contained.channel.sendTo(rewardPacket.toPacket(), (EntityPlayerMP) player);
}
//Determine Your Reward Based On Your Contribution To The Teams' Total Score
public static void rewardXP(EntityPlayer player, PlayerTeamIndividual pdata,
int alters, int territory, int kills,
int score, int totalScore, String winCondition, boolean inWinningTeam){
if (ignoreWinCondition(winCondition))
return;
double percentage = (double)((double) score / (double) totalScore);
//Find XP needed to Reach Next Level
int xpNeeded = 0;
if(pdata.level >= 0 && pdata.level <= 16){
xpNeeded = 2 * pdata.level + 7;
}else if(pdata.level >= 17 && pdata.level <= 31){
xpNeeded = 5 * pdata.level - 38;
}else{
xpNeeded = 9 * pdata.level - 158;
}
xpNeeded -= pdata.xp;
//Special Rewards
if(winCondition.equals("EMBLEMS")){
switch(alters){
case 1: percentage+=0.1; break;
case 2: percentage+=0.25; break;
case 3: percentage+=0.5; break;
}
}else if(winCondition.equals("TERRITORY")){
double anti = territory;
double total = Math.pow((Contained.configs.pvpTerritorySize*2+1), 2.0);
percentage+=(anti/total);
}else if(winCondition.equals("MAX_KILLS")){
double total = Contained.configs.pvpMaxLives*Contained.configs.maxTeamSize[Resources.PVP];
percentage+=((double)kills/total);
}
float multiplier = 20;
if (!inWinningTeam || winCondition.equals("TIE"))
multiplier = 4;
if(percentage >= 0.5)
xpNeeded*=0.9*multiplier;
else if(percentage >= 0.4)
xpNeeded*=0.75*multiplier;
else if(percentage >= 0.3)
xpNeeded*=0.5*multiplier;
else if(percentage >= 0.2)
xpNeeded*=0.25*multiplier;
else if(percentage >= 0.1)
xpNeeded*=0.1*multiplier;
else
xpNeeded*=0.05*multiplier;
Util.displayMessage(player, Util.infoCode+"[PRIZE] Recieved "+xpNeeded+" XP");
pdata.xp+=xpNeeded;
}
public boolean isGameReady() {
int teamPlayerCount = 0;
for(PlayerTeam team : Contained.getTeamList(dim))
teamPlayerCount += team.numMembers();
if (teamPlayerCount >= getCapacity())
return true;
return false;
}
// Index of this player's team in this dimension's team arraylist, or -1
// if the player does not currently belong to any of this dimension's teams.
public int getTeamID(PlayerTeamIndividual pdata) {
if (pdata.teamID == null)
return -1;
for (int i=0; i<Contained.getTeamList(dim).size(); i++) {
if (pdata.teamID.equals(Contained.getTeamList(dim).get(i).id))
return i;
}
return -1;
}
public int getGameDimension(){
return dim;
}
public int getGameID(){
return gameID;
}
public int getGameMode(){
return gameMode;
}
public int getCapacity(){
return MiniGameUtil.getCapacity(this.gameMode);
}
public int numPlayers() {
int count = 0;
for(PlayerTeamIndividual pdata : Contained.teamMemberData)
if(getTeamID(pdata) != -1)
count++;
return count;
}
public int numOnlinePlayers() {
return Math.min(getOnlinePlayers().size(), numPlayers());
}
private void pickRandomTeamLeaders(){
for(PlayerTeam team : Contained.getTeamList(dim)) {
List<String> teamPlayers = team.getTeamPlayers();
if (teamPlayers.size() != 0) {
Collections.shuffle(teamPlayers);
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(teamPlayers.get(0));
pdata.setTeamLeader();
}
else
Util.serverDebugMessage("[ERROR] Tried to set a leader for a team that had no members.");
}
}
private String generateName(){
Random rand = new Random();
String teamName = "";
do {
teamName = intro[rand.nextInt(intro.length)] + " " + words[rand.nextInt(words.length)];
if(rand.nextBoolean())
teamName += " " + combine[rand.nextInt(combine.length)] + " " + words[rand.nextInt(words.length)];
} while(teamName.length() > 20);
return teamName;
}
private boolean teamExists(String teamName){
WorldServer[] worlds = DimensionManager.getWorlds();
for(WorldServer world : worlds)
for(PlayerTeam team : Contained.getTeamList(world.provider.dimensionId))
if (team.displayName.toLowerCase().equals(teamName.toLowerCase()))
return true;
return false;
}
private boolean teamColorExists(int index){
for(PlayerTeam team : Contained.getTeamList(dim))
if(team.colorID == index)
return true;
return false;
}
private int getEmptyWorld(int gameMode){
int dim = -1;
ArrayList<Integer> pvpDims = new ArrayList<Integer>();
ArrayList<Integer> treasureDims = new ArrayList<Integer>();
for(int i=Resources.MIN_PVP_DIMID; i<=Resources.MAX_PVP_DIMID; i++)
pvpDims.add(i);
for(int i=Resources.MIN_TREASURE_DIMID; i<=Resources.MAX_TREASURE_DIMID; i++)
treasureDims.add(i);
for(PlayerMiniGame game : Contained.miniGames){
if(game != null){
if(game.gameMode == gameMode){
if(gameMode == Resources.PVP)
pvpDims.remove(new Integer(game.dim));
else if(gameMode == Resources.TREASURE)
treasureDims.remove(new Integer(game.dim));
}
}
}
if(gameMode == Resources.PVP && !pvpDims.isEmpty())
return pvpDims.get(0);
else if(!treasureDims.isEmpty())
return treasureDims.get(0);
return dim;
}
private void createTeam(EntityPlayer player){
Random rand = new Random();
String teamName = generateName();
int colorID = rand.nextInt(PlayerTeam.formatColors.length);
while(teamExists(teamName))
teamName = generateName();
while(teamColorExists(colorID))
colorID = rand.nextInt(PlayerTeam.formatColors.length);
PlayerTeam newTeam = new PlayerTeam(teamName, colorID, dim);
Contained.getTeamList(dim).add(newTeam);
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
pdata.joinMiniTeam(newTeam.id);
DataLogger.insertMiniGamePlayer(Util.getServerID(), gameID, gameMode, player.getDisplayName(), teamName, Util.getDate());
}
public void testLaunch(EntityPlayer player){
createTeam(player);
PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player);
pdata.setTeamLeader();
}
public void writeToNBT(NBTTagCompound ntc) {
ntc.setInteger("dimID", this.dim);
ntc.setInteger("gameID", this.gameID);
ntc.setInteger("gameMode", this.gameMode);
}
public void readFromNBT(NBTTagCompound ntc) {
this.dim = ntc.getInteger("dimID");
this.gameID = ntc.getInteger("gameID");
this.gameMode = ntc.getInteger("gameMode");
}
public static PlayerMiniGame get(int dim){
for(PlayerMiniGame game : Contained.miniGames)
if(game.dim == dim)
return game;
return null;
}
public static PlayerMiniGame get(String teamName){
for(PlayerMiniGame game : Contained.miniGames)
if(game.teamExists(teamName))
return game;
return null;
}
} | Misc negligible fixes
| src/main/java/com/contained/game/user/PlayerMiniGame.java | Misc negligible fixes |
|
Java | mit | 08273c9abbf0737d95dcba30b5842818477b120e | 0 | daviddaw/clase1617 | package matematicas.geometria;
public class TrianguloRectangulo {
private double cateto1;
private double cateto2;
public TrianguloRectangulo(double cateto1, double cateto2) {
this.cateto1 = cateto1;
this.cateto2 = cateto2;
}
public double getCateto1() {
return cateto1;
}
public void setCateto1(double cateto1) {
this.cateto1 = cateto1;
}
public double getCateto2() {
return cateto2;
}
public void setCateto2(double cateto2) {
this.cateto2 = cateto2;
}
public double getHipotenusa() {
return Math.sqrt(Math.pow(cateto1, 2)+Math.pow(cateto2, 2));
}
}
| poo/src/matematicas/geometria/TrianguloRectangulo.java | package matematicas.geometria;
public class TrianguloRectangulo {
private int cateto1;
private int cateto2;
}
| metodo getHipotenusa() | poo/src/matematicas/geometria/TrianguloRectangulo.java | metodo getHipotenusa() |
|
Java | mit | fd372adc0e84057581f18faa8e1b3c9428306fa3 | 0 | VSETH-GECO/BASS | package ch.ethz.geco.bass.server.auth;
import ch.ethz.geco.bass.util.SQLite;
import org.java_websocket.WebSocket;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class UserManager {
/**
* The logger of this class
*/
private static final Logger logger = LoggerFactory.getLogger(UserManager.class);
/**
* Holds a mapping of the currently open sessions to the user who opened the session.
*/
private static final Map<String, User> validSessions = new HashMap<>();
// Check database integrity
static {
try {
if (!SQLite.tableExists("Users")) {
logger.debug("User table does not exist, creating...");
Connection con = SQLite.getConnection();
PreparedStatement statement = con.prepareStatement("CREATE TABLE Users (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Password TEXT NOT NULL)");
statement.execute();
logger.debug("User table created!");
} else {
logger.debug("User table already exists.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Tries to login a user with the give credentials and return a valid session token on success. If it fails, this will return null.
*
* @param ws the web socket which tried to login
* @param user the user name
* @param pw the password
*/
public static void login(WebSocket ws, String user, String pw) {
try {
Connection con = SQLite.getConnection();
// Get hashed password
PreparedStatement statement = con.prepareStatement("SELECT * FROM Users WHERE Username = ?;");
statement.setString(1, user);
ResultSet result = statement.executeQuery();
String hash = result.getString("Password");
if (BCrypt.checkpw(pw, hash)) {
// Logout old session if existing
logout(user);
String token = UUID.randomUUID().toString();
validSessions.put(token, new User(("" + result.getInt("ID")), user));
// TODO: Send session token to interface
} else {
// TODO: Send wrong password notification
}
} catch (SQLException e) {
// TODO: Send internal error notification
e.printStackTrace();
}
}
/**
* Tries to register a new user. Returns true if the registration was successful, false otherwise.
* It could fail because of duplicate user names or internal errors.
*
* @param ws the web socket which wants to register a new user
* @param user the user name
* @param pw the password
*/
public static void register(WebSocket ws, String user, String pw) {
try {
Connection con = SQLite.getConnection();
PreparedStatement queryStatement = con.prepareStatement("SELECT * FROM Users WHERE Username = ?;");
queryStatement.setString(1, user);
ResultSet result = queryStatement.executeQuery();
// Check if there is already a user with that name
if (!result.next()) {
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO Users VALUES (?, ?)");
insertStatement.setString(1, user);
insertStatement.setString(2, pw);
insertStatement.executeUpdate();
// TODO: Send registration successful notification
} else {
// TODO: Send name already taken notification
}
} catch (SQLException e) {
// TODO: Send internal error notification
e.printStackTrace();
}
}
/**
* Tries to delete the given user. Only works in combination with a valid session for that user.
* Do NOT call this function without checking if the user has a valid session.
*
* @param ws the web socket which wants to delete a user
* @param userID the user ID of the user to delete
* @param token a valid session token for the given user
*/
public static void delete(WebSocket ws, String userID, String token) {
if (isValidSession(token, userID)) {
try {
Connection con = SQLite.getConnection();
PreparedStatement deleteStatement = con.prepareStatement("DELETE * FROM Users WHERE ID = ?;");
deleteStatement.setString(1, userID);
deleteStatement.executeUpdate();
// TODO: Send account successfully deleted notification
} catch (SQLException e) {
// TODO: Send internal error notification
e.printStackTrace();
}
}
}
/**
* Performs a logout on the given user by removing it's session from the list of valid sessions.
*
* @param user the user to logout
* @return true if the logout was successful, false if the given user was not logged in
*/
private static boolean logout(String user) {
boolean isLoggedIn = false;
for (Map.Entry<String, User> curEntry : validSessions.entrySet()) {
if (curEntry.getValue().getName().equals(user)) {
validSessions.remove(curEntry.getKey());
isLoggedIn = true;
}
}
return isLoggedIn;
}
/**
* Returns whether or not the given session token is valid in combination with the given user.
*
* @param token the session token to check
* @param userID the ID of the user
* @return if the token is valid
*/
public static boolean isValidSession(String token, String userID) {
User user = validSessions.get(token);
return user != null && user.getUserID().equals(userID);
}
}
| src/main/java/ch/ethz/geco/bass/server/auth/UserManager.java | package ch.ethz.geco.bass.server.auth;
import ch.ethz.geco.bass.util.SQLite;
import org.java_websocket.WebSocket;
import org.mindrot.jbcrypt.BCrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class UserManager {
/**
* The logger of this class
*/
private static final Logger logger = LoggerFactory.getLogger(UserManager.class);
/**
* Holds a mapping of the currently open sessions to the user who opened the session.
*/
private static final Map<String, User> validSessions = new HashMap<>();
// Check database integrity
static {
try {
if (!SQLite.tableExists("Users")) {
logger.debug("User table does not exist, creating...");
Connection con = SQLite.getConnection();
PreparedStatement statement = con.prepareStatement("CREATE TABLE Users (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Password TEXT NOT NULL)");
statement.execute();
logger.debug("User table created!");
} else {
logger.debug("User table already exists.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* Tries to login a user with the give credentials and return a valid session token on success. If it fails, this will return null.
*
* @param ws The web socket which tried to login
* @param user the user name
* @param pw the password
*/
public static void login(WebSocket ws, String user, String pw) {
try {
Connection con = SQLite.getConnection();
// Get hashed password
PreparedStatement statement = con.prepareStatement("SELECT * FROM Users WHERE Username = ?;");
statement.setString(1, user);
ResultSet result = statement.executeQuery();
String hash = result.getString("Password");
if (BCrypt.checkpw(pw, hash)) {
// Logout old session if existing
logout(user);
String token = UUID.randomUUID().toString();
validSessions.put(token, new User(("" + result.getInt("ID")), user));
// TODO: Send session token to interface
} else {
// TODO: Send wrong password notification
}
} catch (SQLException e) {
// TODO: Send internal error notification
e.printStackTrace();
}
}
/**
* Tries to register a new user. Returns true if the registration was successful, false otherwise.
* It could fail because of duplicate user names or internal errors.
*
* @param ws The web socket which wants to register a new user
* @param user The user name
* @param pw The password
*/
public static void register(WebSocket ws, String user, String pw) {
try {
Connection con = SQLite.getConnection();
PreparedStatement queryStatement = con.prepareStatement("SELECT * FROM Users WHERE Username = ?;");
queryStatement.setString(1, user);
ResultSet result = queryStatement.executeQuery();
// Check if there is already a user with that name
if (!result.next()) {
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO Users VALUES (?, ?)");
insertStatement.setString(1, user);
insertStatement.setString(2, pw);
insertStatement.executeUpdate();
// TODO: Send registration successful notification
} else {
// TODO: Send name already taken notification
}
} catch (SQLException e) {
// TODO: Send internal error notification
e.printStackTrace();
}
}
/**
* Tries to delete the given user. Only works in combination with a valid session for that user.
* Do NOT call this function without checking if the user has a valid session.
*
* @param ws The web socket which wants to delete a user
* @param userID The user ID of the user to delete
* @param token A valid session token for the given user
*/
public static void delete(WebSocket ws, String userID, String token) {
if (isValidSession(token, userID)) {
try {
Connection con = SQLite.getConnection();
PreparedStatement deleteStatement = con.prepareStatement("DELETE * FROM Users WHERE ID = ?;");
deleteStatement.setString(1, userID);
deleteStatement.executeUpdate();
// TODO: Send account successfully deleted notification
} catch (SQLException e) {
// TODO: Send internal error notification
e.printStackTrace();
}
}
}
/**
* Performs a logout on the given user by removing it's session from the list of valid sessions.
*
* @param user the user to logout
* @return true if the logout was successful, false if the given user was not logged in
*/
private static boolean logout(String user) {
boolean isLoggedIn = false;
for (Map.Entry<String, User> curEntry : validSessions.entrySet()) {
if (curEntry.getValue().getName().equals(user)) {
validSessions.remove(curEntry.getKey());
isLoggedIn = true;
}
}
return isLoggedIn;
}
/**
* Returns whether or not the given session token is valid in combination with the given user.
*
* @param token the session token to check
* @param userID the ID of the user
* @return if the token is valid
*/
public static boolean isValidSession(String token, String userID) {
User user = validSessions.get(token);
return user != null && user.getUserID().equals(userID);
}
}
| Small jdoc fixes
| src/main/java/ch/ethz/geco/bass/server/auth/UserManager.java | Small jdoc fixes |
|
Java | mit | d5f48482c347dad2d7ebc50951c1e9de7cb4a0d8 | 0 | elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicAPI | package com.elmakers.mine.bukkit.api.event;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
public class MagicMobDeathEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final EntityDeathEvent deathEvent;
private final EntityData entityData;
private final MageController controller;
private Mage mage;
private Player player;
public MagicMobDeathEvent(MageController controller, EntityData entityData, EntityDeathEvent deathEvent) {
this.controller = controller;
this.entityData = entityData;
this.deathEvent = deathEvent;
LivingEntity killed = deathEvent.getEntity();
EntityDamageEvent damageEvent = killed.getLastDamageCause();
if (damageEvent instanceof EntityDamageByEntityEvent)
{
EntityDamageByEntityEvent damageByEvent = (EntityDamageByEntityEvent)damageEvent;
Entity damagingEntity = damageByEvent.getDamager();
if (damagingEntity instanceof Projectile) {
Projectile projectile = (Projectile)damagingEntity;
damagingEntity = (LivingEntity)projectile.getShooter();
}
if (damagingEntity != null && damagingEntity instanceof Player)
{
player = (Player)damagingEntity;
mage = controller.getRegisteredMage(player.getUniqueId().toString());
}
}
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public EntityDeathEvent getDeathEvent() {
return deathEvent;
}
public EntityData getEntityData() {
return entityData;
}
public MageController getController() {
return controller;
}
public Mage getMage() {
return mage;
}
public Player getPlayer() {
return player;
}
}
| src/main/java/com/elmakers/mine/bukkit/api/event/MagicMobDeathEvent.java | package com.elmakers.mine.bukkit.api.event;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDeathEvent;
public class MagicMobDeathEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private EntityDeathEvent deathEvent;
private EntityData entityData;
public MagicMobDeathEvent(EntityData entityData, EntityDeathEvent deathEvent) {
this.entityData =entityData;
this.deathEvent = deathEvent;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public EntityDeathEvent getDeathEvent() {
return deathEvent;
}
public EntityData getEntityData() {
return entityData;
}
}
| Fixes and improvements to Magic Mob death event, add killer info
| src/main/java/com/elmakers/mine/bukkit/api/event/MagicMobDeathEvent.java | Fixes and improvements to Magic Mob death event, add killer info |
|
Java | mit | 394aca0e3ffb4ab3f5c01818d6ab155c9eb35639 | 0 | ome450901/SimpleRatingBar | package com.willy.ratingbar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.FloatRange;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
/**
* Created by willy on 2017/5/5.
*/
public class BaseRatingBar extends LinearLayout implements SimpleRatingBar {
public interface OnRatingChangeListener {
void onRatingChange(BaseRatingBar ratingBar, float rating);
}
public static final String TAG = "SimpleRatingBar";
private static final int MAX_CLICK_DISTANCE = 5;
private static final int MAX_CLICK_DURATION = 200;
private final DecimalFormat mDecimalFormat;
private int mNumStars;
private int mPadding = 0;
private int mStarWidth;
private int mStarHeight;
private float mRating = -1;
private float mStepSize = 1f;
private float mPreviousRating = 0;
private boolean mIsTouchable = true;
private boolean mClearRatingEnabled = true;
private float mStartX;
private float mStartY;
private Drawable mEmptyDrawable;
private Drawable mFilledDrawable;
private OnRatingChangeListener mOnRatingChangeListener;
protected List<PartialView> mPartialViews;
public BaseRatingBar(Context context) {
this(context, null);
}
/* Call by xml layout */
public BaseRatingBar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* @param context context
* @param attrs attributes from XML => app:mainText="mainText"
* @param defStyleAttr attributes from default style (Application theme or activity theme)
*/
public BaseRatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBarAttributes);
float rating = typedArray.getFloat(R.styleable.RatingBarAttributes_rating, mRating);
mNumStars = typedArray.getInt(R.styleable.RatingBarAttributes_numStars, mNumStars);
mPadding = typedArray.getDimensionPixelSize(R.styleable.RatingBarAttributes_starPadding, mPadding);
mStarWidth = typedArray.getDimensionPixelSize(R.styleable.RatingBarAttributes_starWidth, 0);
mStarHeight = typedArray.getDimensionPixelSize(R.styleable.RatingBarAttributes_starHeight, 0);
mStepSize = typedArray.getFloat(R.styleable.RatingBarAttributes_stepSize, mStepSize);
mEmptyDrawable = typedArray.hasValue(R.styleable.RatingBarAttributes_drawableEmpty) ? ContextCompat.getDrawable(context, typedArray.getResourceId(R.styleable.RatingBarAttributes_drawableEmpty, View.NO_ID)) : null;
mFilledDrawable = typedArray.hasValue(R.styleable.RatingBarAttributes_drawableFilled) ? ContextCompat.getDrawable(context, typedArray.getResourceId(R.styleable.RatingBarAttributes_drawableFilled, View.NO_ID)) : null;
mIsTouchable = typedArray.getBoolean(R.styleable.RatingBarAttributes_touchable, mIsTouchable);
mClearRatingEnabled = typedArray.getBoolean(R.styleable.RatingBarAttributes_clearRatingEnabled, mClearRatingEnabled);
typedArray.recycle();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
mDecimalFormat = new DecimalFormat("#.##", symbols);
verifyParamsValue();
initRatingView();
setRating(rating);
}
private void verifyParamsValue() {
if (mNumStars <= 0) {
mNumStars = 5;
}
if (mPadding < 0) {
mPadding = 0;
}
if (mEmptyDrawable == null) {
mEmptyDrawable = ContextCompat.getDrawable(getContext(), R.drawable.empty);
}
if (mFilledDrawable == null) {
mFilledDrawable = ContextCompat.getDrawable(getContext(), R.drawable.filled);
}
if (mStepSize > 1.0f) {
mStepSize = 1.0f;
} else if (mStepSize < 0.1f) {
mStepSize = 0.1f;
}
}
private void initRatingView() {
mPartialViews = new ArrayList<>();
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
mStarWidth == 0 ? LayoutParams.WRAP_CONTENT : mStarWidth,
mStarHeight == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : mStarHeight);
for (int i = 1; i <= mNumStars; i++) {
PartialView partialView = getPartialView(i, mFilledDrawable, mEmptyDrawable);
mPartialViews.add(partialView);
addView(partialView, params);
}
}
private PartialView getPartialView(final int ratingViewId, Drawable filledDrawable, Drawable emptyDrawable) {
PartialView partialView = new PartialView(getContext());
// partialView.setId(ratingViewId);
partialView.setTag(ratingViewId);
partialView.setPadding(mPadding, mPadding, mPadding, mPadding);
partialView.setFilledDrawable(filledDrawable);
partialView.setEmptyDrawable(emptyDrawable);
return partialView;
}
/**
* Retain this method to let other RatingBar can custom their decrease animation.
*/
protected void emptyRatingBar() {
fillRatingBar(0);
}
/**
* Use {maxIntOfRating} because if the rating is 3.5
* the view which id is 3 also need to be filled.
*/
protected void fillRatingBar(final float rating) {
for (PartialView partialView : mPartialViews) {
int ratingViewId = (int) partialView.getTag();
double maxIntOfRating = Math.ceil(rating);
if (ratingViewId > maxIntOfRating) {
partialView.setEmpty();
continue;
}
if (ratingViewId == maxIntOfRating) {
partialView.setPartialFilled(rating);
} else {
partialView.setFilled();
}
}
}
@Override
public void setNumStars(int numStars) {
if (numStars <= 0) {
return;
}
mPartialViews.clear();
removeAllViews();
mNumStars = numStars;
initRatingView();
}
@Override
public int getNumStars() {
return mNumStars;
}
@Override
public void setRating(float rating) {
if (rating > mNumStars) {
rating = mNumStars;
}
if (rating < 0) {
rating = 0;
}
if (mRating == rating) {
return;
}
mRating = rating;
if (mOnRatingChangeListener != null) {
mOnRatingChangeListener.onRatingChange(this, mRating);
}
fillRatingBar(rating);
}
@Override
public float getRating() {
return mRating;
}
@Override
public void setStarPadding(int ratingPadding) {
if (ratingPadding < 0) {
return;
}
mPadding = ratingPadding;
for (PartialView partialView : mPartialViews) {
partialView.setPadding(mPadding, mPadding, mPadding, mPadding);
}
}
@Override
public int getStarPadding() {
return mPadding;
}
@Override
public void setEmptyDrawableRes(@DrawableRes int res) {
setEmptyDrawable(ContextCompat.getDrawable(getContext(), res));
}
@Override
public void setFilledDrawableRes(@DrawableRes int res) {
setFilledDrawable(ContextCompat.getDrawable(getContext(), res));
}
@Override
public void setEmptyDrawable(Drawable drawable) {
mEmptyDrawable = drawable;
for (PartialView partialView : mPartialViews) {
partialView.setEmptyDrawable(drawable);
}
}
@Override
public void setFilledDrawable(Drawable drawable) {
mFilledDrawable = drawable;
for (PartialView partialView : mPartialViews) {
partialView.setFilledDrawable(drawable);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isTouchable()) {
return false;
}
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartX = eventX;
mStartY = eventY;
mPreviousRating = mRating;
// Avoid rating changes two times when is a click event.
// handleMoveEvent(eventX);
break;
case MotionEvent.ACTION_MOVE:
handleMoveEvent(eventX);
break;
case MotionEvent.ACTION_UP:
if (!isClickEvent(mStartX, mStartY, event)) {
return false;
}
handleClickEvent(eventX);
}
return true;
}
private void handleMoveEvent(float eventX) {
for (PartialView partialView : mPartialViews) {
if (eventX < partialView.getWidth() / 10f) {
setRating(0);
return;
}
if (!isPositionInRatingView(eventX, partialView)) {
continue;
}
float rating = calculateRating(eventX, partialView);
if (mRating != rating) {
setRating(rating);
}
}
}
private float calculateRating(float eventX, PartialView partialView) {
float ratioOfView = Float.parseFloat(mDecimalFormat.format((eventX - partialView.getLeft()) / partialView.getWidth()));
float steps = Math.round(ratioOfView / mStepSize) * mStepSize;
return Float.parseFloat(mDecimalFormat.format((int) partialView.getTag() - (1 - steps)));
}
private void handleClickEvent(float eventX) {
for (PartialView partialView : mPartialViews) {
if (!isPositionInRatingView(eventX, partialView)) {
continue;
}
float rating = mStepSize == 1 ? (int) partialView.getTag() : calculateRating(eventX, partialView);
if (mPreviousRating == rating && isClearRatingEnabled()) {
setRating(0);
} else {
setRating(rating);
}
break;
}
}
private boolean isPositionInRatingView(float eventX, View ratingView) {
return eventX > ratingView.getLeft() && eventX < ratingView.getRight();
}
private boolean isClickEvent(float startX, float startY, MotionEvent event) {
float duration = event.getEventTime() - event.getDownTime();
if (duration > MAX_CLICK_DURATION) {
return false;
}
float differenceX = Math.abs(startX - event.getX());
float differenceY = Math.abs(startY - event.getY());
return !(differenceX > MAX_CLICK_DISTANCE || differenceY > MAX_CLICK_DISTANCE);
}
public void setOnRatingChangeListener(OnRatingChangeListener onRatingChangeListener) {
mOnRatingChangeListener = onRatingChangeListener;
}
public boolean isTouchable() {
return mIsTouchable;
}
public void setTouchable(boolean touchable) {
this.mIsTouchable = touchable;
}
public void setClearRatingEnabled(boolean enabled) {
this.mClearRatingEnabled = enabled;
}
public boolean isClearRatingEnabled() {
return mClearRatingEnabled;
}
public float getStepSize() {
return mStepSize;
}
public void setStepSize(@FloatRange(from = 0.1, to = 1.0) float stepSize) {
this.mStepSize = stepSize;
}
} | library/src/main/java/com/willy/ratingbar/BaseRatingBar.java | package com.willy.ratingbar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.FloatRange;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by willy on 2017/5/5.
*/
public class BaseRatingBar extends LinearLayout implements SimpleRatingBar {
public interface OnRatingChangeListener {
void onRatingChange(BaseRatingBar ratingBar, float rating);
}
public static final String TAG = "SimpleRatingBar";
private static final int MAX_CLICK_DISTANCE = 5;
private static final int MAX_CLICK_DURATION = 200;
private final DecimalFormat mDecimalFormat;
private int mNumStars;
private int mPadding = 0;
private int mStarWidth;
private int mStarHeight;
private float mRating = -1;
private float mStepSize = 1f;
private float mPreviousRating = 0;
private boolean mIsTouchable = true;
private boolean mClearRatingEnabled = true;
private float mStartX;
private float mStartY;
private Drawable mEmptyDrawable;
private Drawable mFilledDrawable;
private OnRatingChangeListener mOnRatingChangeListener;
protected List<PartialView> mPartialViews;
public BaseRatingBar(Context context) {
this(context, null);
}
/* Call by xml layout */
public BaseRatingBar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* @param context context
* @param attrs attributes from XML => app:mainText="mainText"
* @param defStyleAttr attributes from default style (Application theme or activity theme)
*/
public BaseRatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatingBarAttributes);
float rating = typedArray.getFloat(R.styleable.RatingBarAttributes_rating, mRating);
mNumStars = typedArray.getInt(R.styleable.RatingBarAttributes_numStars, mNumStars);
mPadding = typedArray.getDimensionPixelSize(R.styleable.RatingBarAttributes_starPadding, mPadding);
mStarWidth = typedArray.getDimensionPixelSize(R.styleable.RatingBarAttributes_starWidth, 0);
mStarHeight = typedArray.getDimensionPixelSize(R.styleable.RatingBarAttributes_starHeight, 0);
mStepSize = typedArray.getFloat(R.styleable.RatingBarAttributes_stepSize, mStepSize);
mEmptyDrawable = typedArray.hasValue(R.styleable.RatingBarAttributes_drawableEmpty) ? ContextCompat.getDrawable(context, typedArray.getResourceId(R.styleable.RatingBarAttributes_drawableEmpty, View.NO_ID)) : null;
mFilledDrawable = typedArray.hasValue(R.styleable.RatingBarAttributes_drawableFilled) ? ContextCompat.getDrawable(context, typedArray.getResourceId(R.styleable.RatingBarAttributes_drawableFilled, View.NO_ID)) : null;
mIsTouchable = typedArray.getBoolean(R.styleable.RatingBarAttributes_touchable, mIsTouchable);
mClearRatingEnabled = typedArray.getBoolean(R.styleable.RatingBarAttributes_clearRatingEnabled, mClearRatingEnabled);
typedArray.recycle();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
mDecimalFormat = new DecimalFormat("#.##", symbols);
verifyParamsValue();
initRatingView();
setRating(rating);
}
private void verifyParamsValue() {
if (mNumStars <= 0) {
mNumStars = 5;
}
if (mPadding < 0) {
mPadding = 0;
}
if (mEmptyDrawable == null) {
mEmptyDrawable = ContextCompat.getDrawable(getContext(), R.drawable.empty);
}
if (mFilledDrawable == null) {
mFilledDrawable = ContextCompat.getDrawable(getContext(), R.drawable.filled);
}
if (mStepSize > 1.0f) {
mStepSize = 1.0f;
} else if (mStepSize < 0.1f) {
mStepSize = 0.1f;
}
}
private void initRatingView() {
mPartialViews = new ArrayList<>();
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
mStarWidth == 0 ? LayoutParams.WRAP_CONTENT : mStarWidth,
mStarHeight == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : mStarHeight);
for (int i = 1; i <= mNumStars; i++) {
PartialView partialView = getPartialView(i, mFilledDrawable, mEmptyDrawable);
mPartialViews.add(partialView);
addView(partialView, params);
}
}
private PartialView getPartialView(final int ratingViewId, Drawable filledDrawable, Drawable emptyDrawable) {
PartialView partialView = new PartialView(getContext());
// partialView.setId(ratingViewId);
partialView.setTag(ratingViewId);
partialView.setPadding(mPadding, mPadding, mPadding, mPadding);
partialView.setFilledDrawable(filledDrawable);
partialView.setEmptyDrawable(emptyDrawable);
return partialView;
}
/**
* Retain this method to let other RatingBar can custom their decrease animation.
*/
protected void emptyRatingBar() {
fillRatingBar(0);
}
/**
* Use {maxIntOfRating} because if the rating is 3.5
* the view which id is 3 also need to be filled.
*/
protected void fillRatingBar(final float rating) {
for (PartialView partialView : mPartialViews) {
int ratingViewId = (int) partialView.getTag();
double maxIntOfRating = Math.ceil(rating);
if (ratingViewId > maxIntOfRating) {
partialView.setEmpty();
continue;
}
if (ratingViewId == maxIntOfRating) {
partialView.setPartialFilled(rating);
} else {
partialView.setFilled();
}
}
}
@Override
public void setNumStars(int numStars) {
if (numStars <= 0) {
return;
}
mPartialViews.clear();
removeAllViews();
mNumStars = numStars;
initRatingView();
}
@Override
public int getNumStars() {
return mNumStars;
}
@Override
public void setRating(float rating) {
if (rating > mNumStars) {
rating = mNumStars;
}
if (rating < 0) {
rating = 0;
}
if (mRating == rating) {
return;
}
mRating = rating;
if (mOnRatingChangeListener != null) {
mOnRatingChangeListener.onRatingChange(this, mRating);
}
fillRatingBar(rating);
}
@Override
public float getRating() {
return mRating;
}
@Override
public void setStarPadding(int ratingPadding) {
if (ratingPadding < 0) {
return;
}
mPadding = ratingPadding;
for (PartialView partialView : mPartialViews) {
partialView.setPadding(mPadding, mPadding, mPadding, mPadding);
}
}
@Override
public int getStarPadding() {
return mPadding;
}
@Override
public void setEmptyDrawableRes(@DrawableRes int res) {
setEmptyDrawable(ContextCompat.getDrawable(getContext(), res));
}
@Override
public void setFilledDrawableRes(@DrawableRes int res) {
setFilledDrawable(ContextCompat.getDrawable(getContext(), res));
}
@Override
public void setEmptyDrawable(Drawable drawable) {
mEmptyDrawable = drawable;
for (PartialView partialView : mPartialViews) {
partialView.setEmptyDrawable(drawable);
}
}
@Override
public void setFilledDrawable(Drawable drawable) {
mFilledDrawable = drawable;
for (PartialView partialView : mPartialViews) {
partialView.setFilledDrawable(drawable);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isTouchable()) {
return false;
}
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartX = eventX;
mStartY = eventY;
mPreviousRating = mRating;
// Avoid rating changes two times when is a click event.
// handleMoveEvent(eventX);
break;
case MotionEvent.ACTION_MOVE:
handleMoveEvent(eventX);
break;
case MotionEvent.ACTION_UP:
if (!isClickEvent(mStartX, mStartY, event)) {
return false;
}
handleClickEvent(eventX);
}
return true;
}
private void handleMoveEvent(float eventX) {
for (PartialView partialView : mPartialViews) {
if (eventX < partialView.getWidth() / 10f) {
setRating(0);
return;
}
if (!isPositionInRatingView(eventX, partialView)) {
continue;
}
float rating = calculateRating(eventX, partialView);
if (mRating != rating) {
setRating(rating);
}
}
}
private float calculateRating(float eventX, PartialView partialView) {
float ratioOfView = Float.parseFloat(mDecimalFormat.format((eventX - partialView.getLeft()) / partialView.getWidth()));
float steps = Math.round(ratioOfView / mStepSize) * mStepSize;
return Float.parseFloat(mDecimalFormat.format((int) partialView.getTag() - (1 - steps)));
}
private void handleClickEvent(float eventX) {
for (PartialView partialView : mPartialViews) {
if (!isPositionInRatingView(eventX, partialView)) {
continue;
}
float rating = mStepSize == 1 ? (int) partialView.getTag() : calculateRating(eventX, partialView);
if (mPreviousRating == rating && isClearRatingEnabled()) {
setRating(0);
} else {
setRating(rating);
}
break;
}
}
private boolean isPositionInRatingView(float eventX, View ratingView) {
return eventX > ratingView.getLeft() && eventX < ratingView.getRight();
}
private boolean isClickEvent(float startX, float startY, MotionEvent event) {
float duration = event.getEventTime() - event.getDownTime();
if (duration > MAX_CLICK_DURATION) {
return false;
}
float differenceX = Math.abs(startX - event.getX());
float differenceY = Math.abs(startY - event.getY());
return !(differenceX > MAX_CLICK_DISTANCE || differenceY > MAX_CLICK_DISTANCE);
}
public void setOnRatingChangeListener(OnRatingChangeListener onRatingChangeListener) {
mOnRatingChangeListener = onRatingChangeListener;
}
public boolean isTouchable() {
return mIsTouchable;
}
public void setTouchable(boolean touchable) {
this.mIsTouchable = touchable;
}
public void setClearRatingEnabled(boolean enabled) {
this.mClearRatingEnabled = enabled;
}
public boolean isClearRatingEnabled() {
return mClearRatingEnabled;
}
public float getStepSize() {
return mStepSize;
}
public void setStepSize(@FloatRange(from = 0.1, to = 1.0) float stepSize) {
this.mStepSize = stepSize;
}
} | Fix conflit
| library/src/main/java/com/willy/ratingbar/BaseRatingBar.java | Fix conflit |
|
Java | epl-1.0 | 3e102a0d5534e0e9d4ee53e34d7e95e9b6fb2b4d | 0 | css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio | package org.csstudio.sns.passwordprovider;
import javax.crypto.spec.PBEKeySpec;
import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.security.storage.provider.IPreferencesContainer;
import org.eclipse.equinox.security.storage.provider.PasswordProvider;
/** PasswordProvider for
* extension point org.eclipse.equinox.security.secureStorage.
* Generates a password without requiring user input
* @author Xihui Chen
*/
public class SNSPasswordProvider extends PasswordProvider {
@Override
public PBEKeySpec getPassword(IPreferencesContainer container,
int passwordType) {
//the master password cannot include spaces
String installLoc = Platform.getInstallLocation().getURL().toString().replaceAll("\\s", "");
return new PBEKeySpec(installLoc.toCharArray());
}
}
| products/SNS/plugins/org.csstudio.sns.passwordprovider/src/org/csstudio/sns/passwordprovider/SNSPasswordProvider.java | package org.csstudio.sns.passwordprovider;
import javax.crypto.spec.PBEKeySpec;
import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.security.storage.provider.IPreferencesContainer;
import org.eclipse.equinox.security.storage.provider.PasswordProvider;
/** PasswordProvider for
* extension point org.eclipse.equinox.security.secureStorage.
* Generates a password without requiring user input
* @author Xihui Chen
*/
public class SNSPasswordProvider extends PasswordProvider {
@Override
public PBEKeySpec getPassword(IPreferencesContainer container,
int passwordType) {
String installLoc = Platform.getInstallLocation().getURL().toString();
return new PBEKeySpec(installLoc.toCharArray());
}
}
| change master password so it won't include spaces
| products/SNS/plugins/org.csstudio.sns.passwordprovider/src/org/csstudio/sns/passwordprovider/SNSPasswordProvider.java | change master password so it won't include spaces |
|
Java | epl-1.0 | de87b24e2e924a7c7a05d2c17b3771fa43130e5c | 0 | aryantaheri/controller,aryantaheri/controller,aryantaheri/controller | package org.opendaylight.controller.samples.differentiatedforwarding.openstack.performance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.opendaylight.controller.samples.differentiatedforwarding.openstack.ReportManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SubExp {
private static Logger log = LoggerFactory.getLogger(SubExp.class);
int netNum;
int insNum;
int classRange[];
boolean runClassExpConcurrently = false;
boolean runInstanceExpConcurrently = false;
String subExpName = "";
String expDir = "";
public SubExp(int[] classRange, int netNum, int insNum, boolean runClassExpConcurrently, boolean runInstanceExpConcurrently, String expDir) {
this.netNum = netNum;
this.insNum = insNum;
this.classRange = classRange;
this.runClassExpConcurrently = runClassExpConcurrently;
this.runInstanceExpConcurrently = runInstanceExpConcurrently;
this.expDir = expDir;
this.subExpName = "classes"+Arrays.toString(classRange)+"[con="+runClassExpConcurrently+"]"
+"-nets"+netNum+"-instances"+insNum+"[con="+runInstanceExpConcurrently+"]";
log.info("executing SubExp {}", subExpName);
System.out.println(Arrays.toString(classRange)+":"+netNum+":"+insNum);
}
// class -> network -> instance
public void exec() {
List<BwExpReport> bwExpReports;
String outputFile = ReportManager.getReportName(expDir + "/" + subExpName);
if (runClassExpConcurrently) {
bwExpReports = execConcurrently();
} else {
bwExpReports = execSequential();
}
ReportManager.writeReport(bwExpReports, outputFile, true);
ReportManager.writeReportObjects(bwExpReports, outputFile+".obj");
}
private List<BwExpReport> execConcurrently() {
log.info("execConcurrent: Parallel execution of sub experiments");
List<BwExp> bwExps = new ArrayList<>();
List<BwExpReport> bwExpReports = new ArrayList<>();
List<Future<BwExpReport>> futureBwExpReports = new ArrayList<>();
ExecutorService executorService = Executors.newCachedThreadPool();
int classNum = classRange.length;
if (classNum > netNum){
log.warn("Number of requested classes {} is more than requested networks {}. Reducing number of classes", Arrays.toString(classRange), netNum);
classNum = netNum;
}
// Create BwExp classes
for (int classId = 1; classId <= classNum; classId++) {
int classNetNum = netNum / classNum;
for (int net = 1; net <= classNetNum; net++) {
int netInsNum = insNum / netNum;
System.out.println("class:" + classRange[classId - 1] + " network:" + net + " netInsNum:" + netInsNum);
BwExp bwExp = new BwExp(classId, net, netInsNum, runClassExpConcurrently, runInstanceExpConcurrently);
bwExps.add(bwExp);
}
}
// Submit BwExp classes
for (BwExp bwExp : bwExps) {
Future<BwExpReport> futureBwExpReport = executorService.submit(bwExp);
futureBwExpReports.add(futureBwExpReport);
}
// Get BwExp reports
for (Future<BwExpReport> futureBwExpReport : futureBwExpReports) {
BwExpReport bwExpReport = null;
try {
bwExpReport = futureBwExpReport.get();
bwExpReports.add(bwExpReport);
} catch (Exception e) {
log.error("execConcurrent: ", e);
}
}
// Clean up
for (BwExp bwExp : bwExps) {
bwExp.cleanUp();
}
executorService.shutdown();
return bwExpReports;
}
private List<BwExpReport> execSequential() {
log.info("execSequential: Sequential execution of sub experiments");
List<BwExpReport> bwExpReports = new ArrayList<>();
int classNum = classRange.length;
if (classNum > netNum){
log.warn("Number of requested classes {} is more than requested networks {}. Reducing number of classes", Arrays.toString(classRange), netNum);
classNum = netNum;
}
for (int classId = 1; classId <= classNum; classId++) {
int classNetNum = netNum / classNum;
for (int net = 1; net <= classNetNum; net++) {
int netInsNum = insNum / netNum;
BwExp bwExp = null;
try {
System.out.println("class:" + classRange[classId - 1] + " network:" + net + " netInsNum:" + netInsNum);
bwExp = new BwExp(classId, net, netInsNum, runClassExpConcurrently, runInstanceExpConcurrently);
BwExpReport bwExpReport = bwExp.call();
bwExpReports.add(bwExpReport);
} catch (Exception e) {
log.error("exec", e);
} finally {
if (bwExp != null) bwExp.cleanUp();
}
}
}
return bwExpReports;
}
public String getSubExpName() {
return subExpName;
}
}
| opendaylight/samples/differentiatedforwarding/src/main/java/org/opendaylight/controller/samples/differentiatedforwarding/openstack/performance/SubExp.java | package org.opendaylight.controller.samples.differentiatedforwarding.openstack.performance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.opendaylight.controller.samples.differentiatedforwarding.openstack.ReportManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SubExp {
private static Logger log = LoggerFactory.getLogger(SubExp.class);
int netNum;
int insNum;
int classRange[];
boolean runClassExpConcurrently = false;
boolean runInstanceExpConcurrently = false;
String reportFilePrefix = "";
public SubExp(int[] classRange, int netNum, int insNum, boolean runClassExpConcurrently, boolean runInstanceExpConcurrently) {
this.netNum = netNum;
this.insNum = insNum;
this.classRange = classRange;
this.runClassExpConcurrently = runClassExpConcurrently;
this.runInstanceExpConcurrently = runInstanceExpConcurrently;
this.reportFilePrefix = "/tmp/"+"classes"+Arrays.toString(classRange)+"[con="+runClassExpConcurrently+"]"
+"-nets"+netNum+"-instances"+insNum+"[con="+runInstanceExpConcurrently+"]";
System.out.println(Arrays.toString(classRange)+":"+netNum+":"+insNum);
}
// class -> network -> instance
public void exec() {
List<BwExpReport> bwExpReports;
String outputFile = ReportManager.getReportName(reportFilePrefix);
if (runClassExpConcurrently) {
bwExpReports = execConcurrently();
} else {
bwExpReports = execSequential();
}
ReportManager.writeReport(bwExpReports, outputFile, true);
}
private List<BwExpReport> execConcurrently() {
log.info("execConcurrent: Parallel execution of sub experiments");
List<BwExp> bwExps = new ArrayList<>();
List<BwExpReport> bwExpReports = new ArrayList<>();
List<Future<BwExpReport>> futureBwExpReports = new ArrayList<>();
ExecutorService executorService = Executors.newCachedThreadPool();
int classNum = classRange.length;
if (classNum > netNum){
log.warn("Number of requested classes {} is more than requested networks {}. Reducing number of classes", Arrays.toString(classRange), netNum);
classNum = netNum;
}
// Create BwExp classes
for (int classId = 1; classId <= classNum; classId++) {
int classNetNum = netNum / classNum;
for (int net = 1; net <= classNetNum; net++) {
int netInsNum = insNum / netNum;
System.out.println("class:" + classRange[classId - 1] + " network:" + net + " netInsNum:" + netInsNum);
BwExp bwExp = new BwExp(classId, net, netInsNum, runClassExpConcurrently, runInstanceExpConcurrently);
bwExps.add(bwExp);
}
}
// Submit BwExp classes
for (BwExp bwExp : bwExps) {
Future<BwExpReport> futureBwExpReport = executorService.submit(bwExp);
futureBwExpReports.add(futureBwExpReport);
}
// Get BwExp reports
for (Future<BwExpReport> futureBwExpReport : futureBwExpReports) {
BwExpReport bwExpReport = null;
try {
bwExpReport = futureBwExpReport.get();
bwExpReports.add(bwExpReport);
} catch (Exception e) {
log.error("execConcurrent: ", e);
}
}
executorService.shutdown();
return bwExpReports;
}
private List<BwExpReport> execSequential() {
log.info("execSequential: Sequential execution of sub experiments");
List<BwExpReport> bwExpReports = new ArrayList<>();
int classNum = classRange.length;
if (classNum > netNum){
log.warn("Number of requested classes {} is more than requested networks {}. Reducing number of classes", Arrays.toString(classRange), netNum);
classNum = netNum;
}
for (int classId = 1; classId <= classNum; classId++) {
int classNetNum = netNum / classNum;
for (int net = 1; net <= classNetNum; net++) {
int netInsNum = insNum / netNum;
try {
System.out.println("class:" + classRange[classId - 1] + " network:" + net + " netInsNum:" + netInsNum);
BwExpReport bwExpReport = new BwExp(classId, net, netInsNum, runClassExpConcurrently, runInstanceExpConcurrently).call();
bwExpReports.add(bwExpReport);
} catch (Exception e) {
log.error("exec", e);
}
}
}
return bwExpReports;
}
}
| Dir support for report files
| opendaylight/samples/differentiatedforwarding/src/main/java/org/opendaylight/controller/samples/differentiatedforwarding/openstack/performance/SubExp.java | Dir support for report files |
|
Java | agpl-3.0 | 2a3176fe5ecd8d717dc61b63187dadbc4532d99e | 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 | 243faad6-2e60-11e5-9284-b827eb9e62be | hello.java | 243a294e-2e60-11e5-9284-b827eb9e62be | 243faad6-2e60-11e5-9284-b827eb9e62be | hello.java | 243faad6-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 5466e45ee5434f810e90ed9d4d2ef75da832454c | 0 | halober/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine | package org.ovirt.engine.api.extensions.aaa;
import java.util.List;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.ExtUUID;
/**
* Authorization related constants.
*/
public class Authz {
/**
* Context keys.
*/
public static class ContextKeys {
/**
* Available namespaces within provider.
* Query can be done within the context of namespace, to avoid
* scanning entire network. At least one namespace must be available.
*/
public static final ExtKey AVAILABLE_NAMESPACES = new ExtKey("AAA_AUTHZ_AVAILABLE_NAMESPACES", List/*<String>*/.class, "6dffa34c-955f-486a-bd35-0a272b45a711");
/**
* Maximum query filter size.
* Limit the number of entries within {@link InvokeKeys#QUERY_FILTER}.
* No more than this may be provided.
*/
public static final ExtKey QUERY_MAX_FILTER_SIZE = new ExtKey("AAA_AUTHZ_QUERY_MAX_FILTER_SIZE", Integer.class, "2eb1f541-0f65-44a1-a6e3-014e247595f5");
}
/**
* Invoke keys.
*/
public static class InvokeKeys {
/**
* Page size for queries.
* This is only a hint, result may be at smaller page size
* or higher.
*/
public static final ExtKey PAGE_SIZE = new ExtKey("AAA_AUTHZ_PAGE_SIZE", Integer.class, "03197cd2-2d0f-4636-bd88-f65c4a543efe");
/**
* Resolve groups.
* Resolve groups recursively within query.
* */
public static final ExtKey RESOLVE_GROUPS_RECURSIVE = new ExtKey("AAA_AUTHZ_RESOLVE_GROUPS_RECURSIVE", Boolean.class, "f766a48d-cd3f-4c71-ad18-7c4bc9965ebe");
/** Principal record. */
public static final ExtKey PRINCIPAL_RECORD = new ExtKey("AAA_AUTHZ_PRINCIPAL_RECORD", ExtMap.class, "ebc0d5ca-f1ea-402c-86ae-a8ecbdadd6b5");
/**
* AuthResult of operation.
* @see Status
*/
public static final ExtKey STATUS = new ExtKey("AAA_AUTHZ_STATUS", Integer.class, "566f0ba5-8329-4de1-952a-7a81e4bedd3e");
/**
* Namespace to use.
* @see ContextKeys#AVAILABLE_NAMESPACES
*/
public static final ExtKey NAMESPACE = new ExtKey("AAA_AUTHZ_NAMESPACE", String.class, "7e12d802-86ff-4162-baaa-d6f6fe73201e");
/**
* Query filter.
* @see QueryFilterRecord
*/
public static final ExtKey QUERY_FILTER = new ExtKey("AAA_AUTHZ_QUERY_FILTER", ExtMap.class, "93086835-fef1-4d69-8173-a45d738b932a");
/**
* Query filter entity.
* @see QueryEntity
*/
public static final ExtKey QUERY_ENTITY = new ExtKey("AAA_AUTHZ_QUERY_ENTITY", ExtUUID.class, "d0a55f21-b604-43c4-84a0-2bf459b32fa8");
/**
* Query opaque.
* Returned by query open, must be provided as input to query execute.
*/
public static final ExtKey QUERY_OPAQUE = new ExtKey("AAA_AUTHZ_QUERY_OPAQUE", Object.class, "3e2491e9-2b2d-4108-ad4c-8048e2308f3e");
/**
* Query result.
* Execute query until no results.
* Output is List of {@link ExtMap}.
* Actual content depends on the query.
*/
public static final ExtKey QUERY_RESULT = new ExtKey("AAA_AUTHZ_QUERY_RESULT", List/*<ExtMap>*/.class, "0cde6caf-b851-41cb-8de2-cd34327d7249");
}
/**
* Invoke commands.
*/
public static class InvokeCommands {
/**
* Fetch principal record.
* Used for user login.
*
* <p>
* Input:
* <ul>
* <li>{@link Authn.InvokeKeys#AUTH_RECORD}[M] - authentication record.</li>
* <li>{@link InvokeKeys#RESOLVE_GROUPS_RECURSIVE}[M] - resolve groups recursively.</li>
* </ul>
* </p>
*
* <p>
* Output:
* <ul>
* <li>{@link InvokeKeys#PRINCIPAL_RECORD}</li>
* </ul>
* </p>
*
* @see Authn.AuthRecord
*/
public static final ExtUUID FETCH_PRINCIPAL_RECORD = new ExtUUID("AAA_AUTHZ_FETCH_PRINCIPAL_RECORD", "5a5bf9bb-9336-4376-a823-26efe1ba26df");
/**
* Query records.
*
* <p>
* Input:
* <ul>
* <li>{@link InvokeKeys#NAMESPACE}[M]</li>
* <li>{@link InvokeKeys#QUERY_ENTITY}[M]</li>
* <li>{@link InvokeKeys#QUERY_FILTER}[M]</li>
* <li>{@link InvokeKeys#RESOLVE_GROUPS_RECURSIVE}[M] - resolve groups recursively.</li>
* </ul>
* </p>
*
* <p>
* Output:
* <ul>
* <li>{@link InvokeKeys#QUERY_OPAQUE}</li>
* </ul>
* </p>
*
* <p>
* Search execute output based on entity.
* </p>
*/
public static final ExtUUID QUERY_OPEN = new ExtUUID("AAA_AUTHZ_QUERY_OPEN", "8879cfd1-17f8-477b-a057-c0fa849dc97f");
/**
* Execute query.
*
* <p>
* Input:
* <ul>
* <li>{@link InvokeKeys#PAGE_SIZE}[O]</li>
* <li>{@link InvokeKeys#QUERY_OPAQUE}[M]</li>
* </ul>
* </p>
*
* <p>
* Output:
* <ul>
* <li>{@link InvokeKeys#QUERY_RESULT} - Actual content depends on the query.</li>
* </ul>
* </p>
*/
public static final ExtUUID QUERY_EXECUTE = new ExtUUID("AAA_AUTHZ_QUERY_EXECUTE", "b572eb07-11b6-4337-89e3-d1a4e0dafe41");
/**
* Close query.
*
* <p>
* Input:
* <ul>
* <li>{@link InvokeKeys#QUERY_OPAQUE}[M]</li>
* </ul>
* </p>
*/
public static final ExtUUID QUERY_CLOSE = new ExtUUID("AAA_AUTHZ_QUERY_CLOSE", "3e049bc0-055e-4789-a4e3-0ef51bfe6685");
}
/**
* Principal record.
*/
public static class PrincipalRecord {
/** Principal unique (within provider) id. */
public static final ExtKey ID = new ExtKey("AAA_AUTHZ_PRINCIPAL_ID", String.class, "4f9440bc-9303-4d95-b317-b827515c782f");
/** Principal name */
public static final ExtKey NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_NAME", String.class, "a0df5bcc-6ead-40a2-8565-2f5cc8773bdd");
/** Display name. */
public static final ExtKey DISPLAY_NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_DISPLAY_NAME", String.class, "1687a9e2-d951-4ee6-9409-36bca8e83ed1");
/** Email. */
public static final ExtKey EMAIL = new ExtKey("AAA_AUTHZ_PRINCIPAL_EMAIL", String.class, "47367f40-71ca-472f-81b6-e11a0e0b75ed");
/** First name. */
public static final ExtKey FIRST_NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_FIRST_NAME", String.class, "654c2738-581b-45d4-a486-362d891d2db2");
/** Last name. */
public static final ExtKey LAST_NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_LAST_NAME", String.class, "d1479cd7-a19e-4bd8-a639-1e9db7f398d8");
/** Department. */
public static final ExtKey DEPARTMENT = new ExtKey("AAA_AUTHZ_PRINCIPAL_DEPARTMENT", String.class, "636e84bc-1e3a-4537-9407-7c6c3024fb60");
/** Title. */
public static final ExtKey TITLE = new ExtKey("AAA_AUTHZ_PRINCIPAL_TITLE", String.class, "506d3833-5c86-495c-af4c-0de2ef2da4ed");
/**
* Groups.
* List of {@link GroupRecord}.
* @see GroupRecord
*/
public static final ExtKey GROUPS = new ExtKey("AAA_AUTHZ_PRINCIPAL_GROUPS", List/*<GroupRecord>*/.class, "738ec045-aade-478f-90f9-13f4aa229a54");
/**
* Roles.
* List of {@link RoleRecord}.
* @see RoleRecord
*/
public static final ExtKey ROLES = new ExtKey("AAA_AUTHZ_PRINCIPAL_ROLES", List/*<RoleRecord>*/.class, "739b5ecc-6776-408d-b332-53e0adb4a753");
}
/**
* Group record.
*/
public static class GroupRecord {
/** Group unique (within provider) id. */
public static final ExtKey ID = new ExtKey("AAA_AUTHZ_GROUP_ID", String.class, "4615d4d3-a1b7-43cc-bc8d-c8a24a2ffd5a");
/** Group name. */
public static final ExtKey NAME = new ExtKey("AAA_AUTHZ_GROUP_NAME", String.class, "0eebe54f-b429-44f3-aa80-4704cbb16835");
/** Display name. */
public static final ExtKey DISPLAY_NAME = new ExtKey("AAA_AUTHZ_GROUP_DISPLAY_NAME", String.class, "cc2c8f75-bfac-453b-9184-c6ee18d62ef5");
/**
* Groups.
* List of {@link GroupRecord}.
* @see GroupRecord
*/
public static final ExtKey GROUPS = new ExtKey("AAA_AUTHZ_GROUP_GROUPS", List/*<GroupRecord>*/.class, "c4f34760-084b-4f29-b9cf-e77bb539ec18");
/**
* Roles.
* List of {@link RoleRecord}.
* @see RoleRecord
*/
public static final ExtKey ROLES = new ExtKey("AAA_AUTHZ_GROUP_ROLES", List/*<RoleRecord>*/.class, "20bf622b-07a8-4e8b-825e-70633618db07");
}
/**
* Role record.
*/
public static class RoleRecord {
/** Group unique (within provider) id. */
public static final ExtKey ID = new ExtKey("AAA_AUTHZ_ROLE_ID", String.class, "fbd391cc-29b6-41a5-af42-6ef8c4ed8652");
/** Group name. */
public static final ExtKey NAME = new ExtKey("AAA_AUTHZ_ROLE_NAME", String.class, "2b41f95e-7880-49e4-bfda-51da0ea0ba1a");
/** Display name. */
public static final ExtKey DISPLAY_NAME = new ExtKey("AAA_AUTHZ_ROLE_DISPLAY_NAME", String.class, "6383c483-e262-4157-a7cd-4720663efd1e");
}
/**
* Query filter record.
* Either nested filter list or field filter.
* <p>
* Example:
* <pre>{@code
* Filter = {
* OPERATOR: QueryFilterOperator.AND,
* FILTER: [
* {
* OPERATOR: QueryFilterOperator.EQ,
* KEY: PrincipalRecord.NAME,
* PrincipalRecord.NAME: "name1*",
* },
* {
* OPERATOR: QueryFilterOperator.NOT,
* FILTER: [
* {
* OPERATOR: QueryFilterOperator.EQ,
* KEY: PrincipalRecord.DEPARTMENT,
* PrincipalRecord.DEPARTMENT: "dept1",
* },
* ],
* },
* ],
* }
* }</pre>
* </p>
*/
public static class QueryFilterRecord {
/**
* Operator.
* <p>
* This operator is applied as if value within filter is at
* the right of the expression.
* </p>
* <p>
* For nested filter list the operator is used between fields.
* Permitted operators are boolean operators:
* {@link QueryFilterOperator#NOT}, {@link QueryFilterOperator#AND} and
* {@link QueryFilterOperator#OR}.
* </p>
* <p>
* For field filter relational operators are allowed.
* </p>
* @see QueryFilterOperator
*/
public static final ExtKey OPERATOR = new ExtKey("AAA_AUTHZ_QUERY_FILTER_OPERATOR", Integer.class, "c8588111-25a3-40e9-bf82-44acd3d0049d");
/**
* Nested filter.
* List of QueryFilterRecord.
* Either {@link #FILTER} or {@link #KEY} should be available.
* @see QueryFilterRecord
*/
public static final ExtKey FILTER = new ExtKey("AAA_AUTHZ_QUERY_FILTER_FILTER", List/*<QueryFilterRecord>*/.class, "a84d8b7a-0436-46bc-a49a-4dfda94e3a51");
/**
* Key to filter.
* This key with appropriate value must exist within this record.
* Either {@link #FILTER} or {@link #KEY} should be available.
*/
public static final ExtKey KEY = new ExtKey("AAA_AUTHZ_QUERY_FILTER_OPERATOR_KEY", ExtKey.class, "2be62864-6a4c-4a1b-80f0-bed68d9eb529");
}
/**
* Query entities.
*/
public static class QueryEntity {
/**
* Principal.
* Input and output are {@link PrincipalRecord}
*/
public static final ExtUUID PRINCIPAL = new ExtUUID("AAA_AUTHZ_QUERY_ENTITY_PRINCIPAL", "1695cd36-4656-474f-b7bc-4466e12634e4");
/**
* Group.
* Input and output are {@link GroupRecord}
*/
public static final ExtUUID GROUP = new ExtUUID("AAA_AUTHZ_QUERY_ENTITY_GROUP", "f91d029b-9140-459e-b452-db75d3d994a2");
}
/**
* Query filter boolean operator.
* Filter field value is at right side of expression.
*/
public static class QueryFilterOperator {
/**
* Equals.
* '*' wildcard may be placed at suffix of value to match any.
*/
public static final int EQ = 0;
/** Less or equals to. */
public static final int LE = 1;
/** Greater or equals to. */
public static final int GE = 2;
/** Not. */
public static final int NOT = 100;
/** And. */
public static final int AND = 101;
/** Or. */
public static final int OR = 102;
}
/**
* Status.
* Additional information for failure states.
*/
public static class Status {
/** Success. */
public static final int SUCCESS = 0;
/** General error. */
public static final int GENERAL_ERROR = 1;
/** Configuration is invalid. */
public static final int CONFIGURATION_INVALID = 2;
/** Request timeout. */
public static final int TIMED_OUT = 3;
}
}
| backend/manager/modules/extensions-api-root/extensions-api/src/main/java/org/ovirt/engine/api/extensions/aaa/Authz.java | package org.ovirt.engine.api.extensions.aaa;
import java.util.List;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.ExtUUID;
/**
* Authorization related constants.
*/
public class Authz {
/**
* Context keys.
*/
public static class ContextKeys {
/**
* Available namespaces within provider.
* Query can be done within the context of namespace, to avoid
* scanning entire network. At least one namespace must be available.
*/
public static final ExtKey AVAILABLE_NAMESPACES = new ExtKey("AAA_AUTHZ_AVAILABLE_NAMESPACES", List/*<String>*/.class, "6dffa34c-955f-486a-bd35-0a272b45a711");
/**
* Maximum query filter size.
* Limit the number of entries within {@link InvokeKeys#QUERY_FILTER}.
* No more than this may be provided.
*/
public static final ExtKey QUERY_MAX_FILTER_SIZE = new ExtKey("AAA_AUTHZ_QUERY_MAX_FILTER_SIZE", Integer.class, "2eb1f541-0f65-44a1-a6e3-014e247595f5");
}
/**
* Invoke keys.
*/
public static class InvokeKeys {
/**
* Page size for queries.
* This is only a hint, result may be at smaller page size
* or higher.
*/
public static final ExtKey PAGE_SIZE = new ExtKey("AAA_AUTHZ_PAGE_SIZE", Integer.class, "03197cd2-2d0f-4636-bd88-f65c4a543efe");
/**
* Resolve groups.
* Resolve groups recursively within query.
* */
public static final ExtKey RESOLVE_GROUPS_RECURSIVE = new ExtKey("AAA_AUTHZ_RESOLVE_GROUPS_RECURSIVE", Boolean.class, "f766a48d-cd3f-4c71-ad18-7c4bc9965ebe");
/** Principal record. */
public static final ExtKey PRINCIPAL_RECORD = new ExtKey("AAA_AUTHZ_PRINCIPAL_RECORD", ExtMap.class, "ebc0d5ca-f1ea-402c-86ae-a8ecbdadd6b5");
/**
* AuthResult of operation.
* @see Status
*/
public static final ExtKey STATUS = new ExtKey("AAA_AUTHZ_STATUS", Integer.class, "566f0ba5-8329-4de1-952a-7a81e4bedd3e");
/**
* Namespace to use.
* @see ContextKeys#AVAILABLE_NAMESPACES
*/
public static final ExtKey NAMESPACE = new ExtKey("AAA_AUTHZ_NAMESPACE", String.class, "7e12d802-86ff-4162-baaa-d6f6fe73201e");
/**
* Query filter.
* @see QueryFilterRecord
*/
public static final ExtKey QUERY_FILTER = new ExtKey("AAA_AUTHZ_QUERY_FILTER", ExtMap.class, "93086835-fef1-4d69-8173-a45d738b932a");
/**
* Query filter entity.
* @see QueryEntity
*/
public static final ExtKey QUERY_ENTITY = new ExtKey("AAA_AUTHZ_QUERY_ENTITY", ExtUUID.class, "d0a55f21-b604-43c4-84a0-2bf459b32fa8");
/**
* Query opaque.
* Returned by query open, must be provided as input to query execute.
*/
public static final ExtKey QUERY_OPAQUE = new ExtKey("AAA_AUTHZ_QUERY_OPAQUE", Object.class, "3e2491e9-2b2d-4108-ad4c-8048e2308f3e");
/**
* Query result.
* Execute query until no results.
* Output is List of {@link ExtMap}.
* Actual content depends on the query.
*/
public static final ExtKey QUERY_RESULT = new ExtKey("AAA_AUTHZ_QUERY_RESULT", List/*<ExtMap>*/.class, "0cde6caf-b851-41cb-8de2-cd34327d7249");
}
/**
* Invoke commands.
*/
public static class InvokeCommands {
/**
* Fetch principal record.
* Used for user login.
*
* <p>
* Input:
* <ul>
* <li>{@link Authn.InvokeKeys#AUTH_RECORD}[M] - authentication record.</li>
* <li>{@link InvokeKeys#RESOLVE_GROUPS_RECURSIVE}[M] - resolve groups recursively.</li>
* </ul>
* </p>
*
* <p>
* Output:
* <ul>
* <li>{@link InvokeKeys#PRINCIPAL_RECORD}</li>
* </ul>
* </p>
*
* @see Authn.AuthRecord
*/
public static final ExtUUID FETCH_PRINCIPAL_RECORD = new ExtUUID("AAA_AUTHZ_FETCH_PRINCIPAL_RECORD", "5a5bf9bb-9336-4376-a823-26efe1ba26df");
/**
* Query records.
*
* <p>
* Input:
* <ul>
* <li>{@link InvokeKeys#NAMESPACE}[M]</li>
* <li>{@link InvokeKeys#QUERY_ENTITY}[M]</li>
* <li>{@link InvokeKeys#QUERY_FILTER}[M]</li>
* <li>{@link InvokeKeys#RESOLVE_GROUPS_RECURSIVE}[M] - resolve groups recursively.</li>
* </ul>
* </p>
*
* <p>
* Output:
* <ul>
* <li>{@link InvokeKeys#QUERY_OPAQUE}</li>
* </ul>
* </p>
*
* <p>
* Search execute output based on entity.
* </p>
*/
public static final ExtUUID QUERY_OPEN = new ExtUUID("AAA_AUTHZ_QUERY_OPEN", "8879cfd1-17f8-477b-a057-c0fa849dc97f");
/**
* Execute query.
*
* <p>
* Input:
* <ul>
* <li>{@link InvokeKeys#PAGE_SIZE}[O]</li>
* <li>{@link InvokeKeys#QUERY_OPAQUE}[M]</li>
* </ul>
* </p>
*
* <p>
* Output:
* <ul>
* <li>{@link InvokeKeys#QUERY_RESULT} - Actual content depends on the query.</li>
* </ul>
* </p>
*/
public static final ExtUUID QUERY_EXECUTE = new ExtUUID("AAA_AUTHZ_QUERY_EXECUTE", "b572eb07-11b6-4337-89e3-d1a4e0dafe41");
/**
* Close query.
*
* <p>
* Input:
* <ul>
* <li>{@link InvokeKeys#QUERY_OPAQUE}[M]</li>
* </ul>
* </p>
*/
public static final ExtUUID QUERY_CLOSE = new ExtUUID("AAA_AUTHZ_QUERY_CLOSE", "3e049bc0-055e-4789-a4e3-0ef51bfe6685");
}
/**
* Principal record.
*/
public static class PrincipalRecord {
/** Principal unique (within provider) id. */
public static final ExtKey ID = new ExtKey("AAA_AUTHZ_PRINCIPAL_ID", String.class, "4f9440bc-9303-4d95-b317-b827515c782f");
/** Principal name */
public static final ExtKey NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_NAME", String.class, "a0df5bcc-6ead-40a2-8565-2f5cc8773bdd");
/** Display name. */
public static final ExtKey DISPLAY_NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_DISPLAY_NAME", String.class, "1687a9e2-d951-4ee6-9409-36bca8e83ed1");
/** Email. */
public static final ExtKey EMAIL = new ExtKey("AAA_AUTHZ_PRINCIPAL_EMAIL", String.class, "47367f40-71ca-472f-81b6-e11a0e0b75ed");
/** First name. */
public static final ExtKey FIRST_NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_FIRST_NAME", String.class, "654c2738-581b-45d4-a486-362d891d2db2");
/** Last name. */
public static final ExtKey LAST_NAME = new ExtKey("AAA_AUTHZ_PRINCIPAL_LAST_NAME", String.class, "d1479cd7-a19e-4bd8-a639-1e9db7f398d8");
/** Department. */
public static final ExtKey DEPARTMENT = new ExtKey("AAA_AUTHZ_PRINCIPAL_DEPARTMENT", String.class, "636e84bc-1e3a-4537-9407-7c6c3024fb60");
/** Title. */
public static final ExtKey TITLE = new ExtKey("AAA_AUTHZ_PRINCIPAL_TITLE", String.class, "506d3833-5c86-495c-af4c-0de2ef2da4ed");
/**
* Groups.
* List of {@link GroupRecord}.
* @see GroupRecord
*/
public static final ExtKey GROUPS = new ExtKey("AAA_AUTHZ_PRINCIPAL_GROUPS", List/*<GroupRecord>*/.class, "738ec045-aade-478f-90f9-13f4aa229a54");
/**
* Roles.
* List of {@link RoleRecord}.
* @see RoleRecord
*/
public static final ExtKey ROLES = new ExtKey("AAA_AUTHZ_PRINCIPAL_ROLES", List/*<RoleRecord>*/.class, "739b5ecc-6776-408d-b332-53e0adb4a753");
}
/**
* Group record.
*/
public static class GroupRecord {
/** Group unique (within provider) id. */
public static final ExtKey ID = new ExtKey("AAA_AUTHZ_GROUP_ID", String.class, "4615d4d3-a1b7-43cc-bc8d-c8a24a2ffd5a");
/** Group name. */
public static final ExtKey NAME = new ExtKey("AAA_AUTHZ_GROUP_NAME", String.class, "0eebe54f-b429-44f3-aa80-4704cbb16835");
/** Display name. */
public static final ExtKey DISPLAY_NAME = new ExtKey("AAA_AUTHZ_GROUP_DISPLAY_NAME", String.class, "cc2c8f75-bfac-453b-9184-c6ee18d62ef5");
/**
* Groups.
* List of {@link GroupRecord}.
* @see GroupRecord
*/
public static final ExtKey GROUPS = new ExtKey("AAA_AUTHZ_GROUP_GROUPS", List/*<GroupRecord>*/.class, "c4f34760-084b-4f29-b9cf-e77bb539ec18");
/**
* Roles.
* List of {@link RoleRecord}.
* @see RoleRecord
*/
public static final ExtKey ROLES = new ExtKey("AAA_AUTHZ_GROUP_ROLES", List/*<RoleRecord>*/.class, "20bf622b-07a8-4e8b-825e-70633618db07");
}
/**
* Role record.
*/
public static class RoleRecord {
/** Group unique (within provider) id. */
public static final ExtKey ID = new ExtKey("AAA_AUTHZ_ROLE_ID", String.class, "fbd391cc-29b6-41a5-af42-6ef8c4ed8652");
/** Group name. */
public static final ExtKey NAME = new ExtKey("AAA_AUTHZ_ROLE_NAME", String.class, "2b41f95e-7880-49e4-bfda-51da0ea0ba1a");
/** Display name. */
public static final ExtKey DISPLAY_NAME = new ExtKey("AAA_AUTHZ_ROLE_DISPLAY_NAME", String.class, "6383c483-e262-4157-a7cd-4720663efd1e");
}
/**
* Query filter record.
* Either nested filter list or field filter.
* <p>
* Example:
* <pre>{@code
* Filter = {
* OPERATOR: QueryFilterOperator.AND,
* FILTER: [
* {
* OPERATOR: QueryFilterOperator.EQ,
* KEY: PrincipalRecord.NAME,
* PrincipalRecord.NAME: "name1*",
* },
* {
* OPERATOR: QueryFilterOperator.NOT,
* FILTER: [
* {
* OPERATOR: QueryFilterOperator.EQ,
* KEY: PrincipalRecord.DEPARTMENT,
* PrincipalRecord.DEPARTMENT: "dept1",
* },
* ],
* },
* ],
* }
* }</pre>
* </p>
*/
public static class QueryFilterRecord {
/**
* Operator.
* <p>
* This operator is applied as if value within filter is at
* the right of the expression.
* </p>
* <p>
* For nested filter list the operator is used between fields.
* Permitted operators are boolean operators:
* {@link QueryFilterOperator#NOT}, {@link QueryFilterOperator#AND} and
* {@link QueryFilterOperator#OR}.
* </p>
* <p>
* For field filter relational operators are allowed.
* </p>
* @see QueryFilterOperator
*/
public static final ExtKey OPERATOR = new ExtKey("AAA_AUTHZ_QUERY_FILTER_OPERATOR", Integer.class, "c8588111-25a3-40e9-bf82-44acd3d0049d");
/**
* Nested filter.
* List of QueryFilterRecord.
* Either {@link #FILTER} or {@link #KEY} should be available.
* @see QueryFilterRecord
*/
public static final ExtKey FILTER = new ExtKey("AAA_AUTHZ_QUERY_FILTER_FILTER", List/*<QueryFilterRecord>*/.class, "a84d8b7a-0436-46bc-a49a-4dfda94e3a51");
/**
* Key to filter.
* This key with appropriate value must exist within this record.
* Either {@link #FILTER} or {@link #KEY} should be available.
*/
public static final ExtKey KEY = new ExtKey("AAA_AUTHZ_QUERY_FILTER_OPERATOR_KEY", ExtKey.class, "2be62864-6a4c-4a1b-80f0-bed68d9eb529");
}
/**
* Query entities.
*/
public static class QueryEntity {
/**
* Principal.
* Input and output are {@link PrincipalRecord}
*/
public static final ExtUUID PRINCIPAL = new ExtUUID("AAA_AUTHZ_QUERY_ENTITY_PRINCIPAL", "1695cd36-4656-474f-b7bc-4466e12634e4");
/**
* Group.
* Input and output are {@link GroupRecord}
*/
public static final ExtUUID GROUP = new ExtUUID("AAA_AUTHZ_QUERY_ENTITY_GROUP", "f91d029b-9140-459e-b452-db75d3d994a2");
}
/**
* Query filter boolean operator.
* Filter field value is at right side of expression.
*/
public static class QueryFilterOperator {
/**
* Equals.
* '*' wildcard may be placed at suffix of value to match any.
*/
public static int EQ = 0;
/** Less or equals to. */
public static int LE = 1;
/** Greater or equals to. */
public static int GE = 2;
/** Not. */
public static int NOT = 100;
/** And. */
public static int AND = 101;
/** Or. */
public static int OR = 102;
}
/**
* Status.
* Additional information for failure states.
*/
public static class Status {
/** Success. */
public static final int SUCCESS = 0;
/** General error. */
public static final int GENERAL_ERROR = 1;
/** Configuration is invalid. */
public static final int CONFIGURATION_INVALID = 2;
/** Request timeout. */
public static final int TIMED_OUT = 3;
}
}
| extapi: aaa: add missing final to constants
Topic: AAA
Change-Id: I1a352a876c2236aecdb13dc7c06b48edb8ed3e8d
Signed-off-by: Alon Bar-Lev <[email protected]>
| backend/manager/modules/extensions-api-root/extensions-api/src/main/java/org/ovirt/engine/api/extensions/aaa/Authz.java | extapi: aaa: add missing final to constants |
|
Java | apache-2.0 | bfb4bdaa47d8aa3688f2c3cf37bd456e1dad776a | 0 | Alluxio/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,bf8086/alluxio,calvinjia/tachyon,jswudi/alluxio,bf8086/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,wwjiang007/alluxio,jsimsa/alluxio,ShailShah/alluxio,riversand963/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,Reidddddd/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,aaudiber/alluxio,calvinjia/tachyon,jsimsa/alluxio,aaudiber/alluxio,uronce-cc/alluxio,jsimsa/alluxio,aaudiber/alluxio,apc999/alluxio,ChangerYoung/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,apc999/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,uronce-cc/alluxio,PasaLab/tachyon,Alluxio/alluxio,bf8086/alluxio,Alluxio/alluxio,ShailShah/alluxio,madanadit/alluxio,bf8086/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,Alluxio/alluxio,PasaLab/tachyon,calvinjia/tachyon,WilliamZapata/alluxio,Reidddddd/mo-alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,jswudi/alluxio,calvinjia/tachyon,wwjiang007/alluxio,maobaolong/alluxio,aaudiber/alluxio,madanadit/alluxio,wwjiang007/alluxio,maobaolong/alluxio,calvinjia/tachyon,apc999/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,riversand963/alluxio,Reidddddd/alluxio,Alluxio/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,apc999/alluxio,madanadit/alluxio,maobaolong/alluxio,wwjiang007/alluxio,PasaLab/tachyon,ChangerYoung/alluxio,Reidddddd/alluxio,maobaolong/alluxio,PasaLab/tachyon,uronce-cc/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,jsimsa/alluxio,bf8086/alluxio,Alluxio/alluxio,madanadit/alluxio,Reidddddd/mo-alluxio,Reidddddd/mo-alluxio,yuluo-ding/alluxio,madanadit/alluxio,maobaolong/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,jsimsa/alluxio,Alluxio/alluxio,jswudi/alluxio,calvinjia/tachyon,Reidddddd/alluxio,maboelhassan/alluxio,aaudiber/alluxio,riversand963/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,bf8086/alluxio,aaudiber/alluxio,PasaLab/tachyon,aaudiber/alluxio,bf8086/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,ShailShah/alluxio,bf8086/alluxio,riversand963/alluxio,jsimsa/alluxio,wwjiang007/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,maobaolong/alluxio,jswudi/alluxio,apc999/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,WilliamZapata/alluxio,Reidddddd/alluxio,calvinjia/tachyon,riversand963/alluxio,ShailShah/alluxio,madanadit/alluxio,maboelhassan/alluxio,yuluo-ding/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,jswudi/alluxio,maobaolong/alluxio,jswudi/alluxio | /*
* Licensed to the University of California, Berkeley 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 tachyon.examples;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tachyon.Constants;
import tachyon.TachyonURI;
import tachyon.client.file.FileInStream;
import tachyon.client.file.TachyonFile;
import tachyon.client.file.TachyonFileSystem;
import tachyon.client.file.TachyonFileSystem.TachyonFileSystemFactory;
import tachyon.client.file.options.OutStreamOptions;
import tachyon.exception.TachyonException;
import tachyon.thrift.FileInfo;
/**
* An example to show to how use Tachyon's API
*/
public class BasicCheckpoint implements Callable<Boolean> {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final TachyonURI mLocation;
private final String mFileFolder;
private final int mNumFiles;
public BasicCheckpoint(TachyonURI tachyonURI, String fileFolder, int numFiles) {
mLocation = tachyonURI;
mFileFolder = fileFolder;
mNumFiles = numFiles;
}
@Override
public Boolean call() throws Exception {
TachyonFileSystem tachyonClient = TachyonFileSystemFactory.get();
writeFile(tachyonClient);
return readFile(tachyonClient);
}
private boolean readFile(TachyonFileSystem tachyonClient) throws IOException, TachyonException {
boolean pass = true;
for (int i = 0; i < mNumFiles; i ++) {
TachyonURI filePath = new TachyonURI(mFileFolder + "/part-" + i);
LOG.debug("Reading data from {}", filePath);
TachyonFile file = tachyonClient.open(filePath);
FileInStream is = tachyonClient.getInStream(file);
FileInfo info = tachyonClient.getInfo(file);
ByteBuffer buf = ByteBuffer.allocate((int) info.getBlockSizeBytes());
is.read(buf.array());
buf.order(ByteOrder.nativeOrder());
for (int k = 0; k < mNumFiles; k ++) {
pass = pass && (buf.getInt() == k);
}
is.close();
}
return pass;
}
private void writeFile(TachyonFileSystem tachyonClient) throws IOException, TachyonException {
for (int i = 0; i < mNumFiles; i ++) {
ByteBuffer buf = ByteBuffer.allocate(80);
buf.order(ByteOrder.nativeOrder());
for (int k = 0; k < mNumFiles; k ++) {
buf.putInt(k);
}
buf.flip();
TachyonURI filePath = new TachyonURI(mFileFolder + "/part-" + i);
LOG.debug("Writing data to {}", filePath);
OutputStream os = tachyonClient.getOutStream(filePath);
os.write(buf.array());
os.close();
}
}
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.out.println("java -cp " + Constants.TACHYON_JAR
+ " tachyon.examples.BasicCheckpoint <TachyonMasterAddress> <FileFolder> <Files>");
System.exit(-1);
}
Utils.runExample(new BasicCheckpoint(new TachyonURI(args[0]), args[1], Integer
.parseInt(args[2])));
}
}
| examples/src/main/java/tachyon/examples/BasicCheckpoint.java | /*
* Licensed to the University of California, Berkeley 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 tachyon.examples;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tachyon.Constants;
import tachyon.TachyonURI;
import tachyon.client.file.FileInStream;
import tachyon.client.file.TachyonFile;
import tachyon.client.file.TachyonFileSystem;
import tachyon.client.file.TachyonFileSystem.TachyonFileSystemFactory;
import tachyon.client.file.options.OutStreamOptions;
import tachyon.exception.TachyonException;
import tachyon.thrift.FileInfo;
/**
* An example to show to how use Tachyon's API
*/
public class BasicCheckpoint implements Callable<Boolean> {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
private final TachyonURI mLocation;
private final String mFileFolder;
private final int mNumFiles;
public BasicCheckpoint(TachyonURI tachyonURI, String fileFolder, int numFiles) {
mLocation = tachyonURI;
mFileFolder = fileFolder;
mNumFiles = numFiles;
}
@Override
public Boolean call() throws Exception {
TachyonFileSystem tachyonClient = TachyonFileSystemFactory.get();
writeFile(tachyonClient);
return readFile(tachyonClient);
}
private boolean readFile(TachyonFileSystem tachyonClient) throws IOException, TachyonException {
boolean pass = true;
for (int i = 0; i < mNumFiles; i ++) {
TachyonURI filePath = new TachyonURI(mFileFolder + "/part-" + i);
LOG.debug("Reading data from {}", filePath);
TachyonFile file = tachyonClient.open(filePath);
FileInStream is = tachyonClient.getInStream(file);
FileInfo info = tachyonClient.getInfo(file);
ByteBuffer buf = ByteBuffer.allocate((int) info.getBlockSizeBytes());
is.read(buf.array());
buf.order(ByteOrder.nativeOrder());
for (int k = 0; k < mNumFiles; k ++) {
pass = pass && (buf.getInt() == k);
}
is.close();
}
return pass;
}
private void writeFile(TachyonFileSystem tachyonClient) throws IOException, TachyonException {
for (int i = 0; i < mNumFiles; i ++) {
ByteBuffer buf = ByteBuffer.allocate(80);
buf.order(ByteOrder.nativeOrder());
for (int k = 0; k < mNumFiles; k ++) {
buf.putInt(k);
}
buf.flip();
TachyonURI filePath = new TachyonURI(mFileFolder + "/part-" + i);
LOG.debug("Writing data to {}", filePath);
OutputStream os = tachyonClient.getOutStream(filePath, OutStreamOptions.defaults());
os.write(buf.array());
os.close();
}
}
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.out.println("java -cp " + Constants.TACHYON_JAR
+ " tachyon.examples.BasicCheckpoint <TachyonMasterAddress> <FileFolder> <Files>");
System.exit(-1);
}
Utils.runExample(new BasicCheckpoint(new TachyonURI(args[0]), args[1], Integer
.parseInt(args[2])));
}
}
| Simplify getoutstream call.
| examples/src/main/java/tachyon/examples/BasicCheckpoint.java | Simplify getoutstream call. |
|
Java | apache-2.0 | adfe3445d9e51a0f068a15fae661fa47fe7cf860 | 0 | nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa | /*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2022 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.basjes.parse.useragent;
import nl.basjes.parse.useragent.AgentField.ImmutableAgentField;
import nl.basjes.parse.useragent.AgentField.MutableAgentField;
import nl.basjes.parse.useragent.analyze.Matcher;
import nl.basjes.parse.useragent.parser.UserAgentBaseListener;
import nl.basjes.parse.useragent.utils.DefaultANTLRErrorListener;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.dfa.DFA;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
public interface UserAgent extends Serializable {
String getUserAgentString();
AgentField get(String fieldName);
String getValue(String fieldName);
Long getConfidence(String fieldName);
boolean hasSyntaxError();
boolean hasAmbiguity();
int getAmbiguityCount();
List<String> getAvailableFieldNamesSorted();
default List<String> getCleanedAvailableFieldNamesSorted() {
List<String> fieldNames = new ArrayList<>();
for (String fieldName : getAvailableFieldNamesSorted()) {
if (!STANDARD_FIELDS.contains(fieldName)) {
if (get(fieldName).isDefaultValue()) {
// Skip the "non standard" fields that do not have a relevant value.
continue;
}
}
fieldNames.add(fieldName);
}
return fieldNames;
}
String DEVICE_CLASS = "DeviceClass";
String DEVICE_NAME = "DeviceName";
String DEVICE_BRAND = "DeviceBrand";
String DEVICE_CPU = "DeviceCpu";
String DEVICE_CPU_BITS = "DeviceCpuBits";
String DEVICE_FIRMWARE_VERSION = "DeviceFirmwareVersion";
String DEVICE_VERSION = "DeviceVersion";
String OPERATING_SYSTEM_CLASS = "OperatingSystemClass";
String OPERATING_SYSTEM_NAME = "OperatingSystemName";
String OPERATING_SYSTEM_VERSION = "OperatingSystemVersion";
String OPERATING_SYSTEM_VERSION_MAJOR = "OperatingSystemVersionMajor";
String OPERATING_SYSTEM_NAME_VERSION = "OperatingSystemNameVersion";
String OPERATING_SYSTEM_NAME_VERSION_MAJOR = "OperatingSystemNameVersionMajor";
String OPERATING_SYSTEM_VERSION_BUILD = "OperatingSystemVersionBuild";
String LAYOUT_ENGINE_CLASS = "LayoutEngineClass";
String LAYOUT_ENGINE_NAME = "LayoutEngineName";
String LAYOUT_ENGINE_VERSION = "LayoutEngineVersion";
String LAYOUT_ENGINE_VERSION_MAJOR = "LayoutEngineVersionMajor";
String LAYOUT_ENGINE_NAME_VERSION = "LayoutEngineNameVersion";
String LAYOUT_ENGINE_NAME_VERSION_MAJOR = "LayoutEngineNameVersionMajor";
String LAYOUT_ENGINE_BUILD = "LayoutEngineBuild";
String AGENT_CLASS = "AgentClass";
String AGENT_NAME = "AgentName";
String AGENT_VERSION = "AgentVersion";
String AGENT_VERSION_MAJOR = "AgentVersionMajor";
String AGENT_NAME_VERSION = "AgentNameVersion";
String AGENT_NAME_VERSION_MAJOR = "AgentNameVersionMajor";
String AGENT_BUILD = "AgentBuild";
String AGENT_LANGUAGE = "AgentLanguage";
String AGENT_LANGUAGE_CODE = "AgentLanguageCode";
String AGENT_INFORMATION_EMAIL = "AgentInformationEmail";
String AGENT_INFORMATION_URL = "AgentInformationUrl";
String AGENT_SECURITY = "AgentSecurity";
String AGENT_UUID = "AgentUuid";
String WEBVIEW_APP_NAME = "WebviewAppName";
String WEBVIEW_APP_VERSION = "WebviewAppVersion";
String WEBVIEW_APP_VERSION_MAJOR = "WebviewAppVersionMajor";
String WEBVIEW_APP_NAME_VERSION = "WebviewAppNameVersion";
String WEBVIEW_APP_NAME_VERSION_MAJOR = "WebviewAppNameVersionMajor";
String FACEBOOK_CARRIER = "FacebookCarrier";
String FACEBOOK_DEVICE_CLASS = "FacebookDeviceClass";
String FACEBOOK_DEVICE_NAME = "FacebookDeviceName";
String FACEBOOK_DEVICE_VERSION = "FacebookDeviceVersion";
String FACEBOOK_F_B_O_P = "FacebookFBOP";
String FACEBOOK_F_B_S_S = "FacebookFBSS";
String FACEBOOK_OPERATING_SYSTEM_NAME = "FacebookOperatingSystemName";
String FACEBOOK_OPERATING_SYSTEM_VERSION = "FacebookOperatingSystemVersion";
String ANONYMIZED = "Anonymized";
String HACKER_ATTACK_VECTOR = "HackerAttackVector";
String HACKER_TOOLKIT = "HackerToolkit";
String KOBO_AFFILIATE = "KoboAffiliate";
String KOBO_PLATFORM_ID = "KoboPlatformId";
String IE_COMPATIBILITY_VERSION = "IECompatibilityVersion";
String IE_COMPATIBILITY_VERSION_MAJOR = "IECompatibilityVersionMajor";
String IE_COMPATIBILITY_NAME_VERSION = "IECompatibilityNameVersion";
String IE_COMPATIBILITY_NAME_VERSION_MAJOR = "IECompatibilityNameVersionMajor";
String SYNTAX_ERROR = "__SyntaxError__";
String USERAGENT_FIELDNAME = "Useragent";
String NETWORK_TYPE = "NetworkType";
String SET_ALL_FIELDS = "__Set_ALL_Fields__";
String NULL_VALUE = "<<<null>>>";
String UNKNOWN_VALUE = "Unknown";
String UNKNOWN_VERSION = "??";
String UNKNOWN_NAME_VERSION = "Unknown ??";
List<String> STANDARD_FIELDS = Collections.unmodifiableList(Arrays.asList(
DEVICE_CLASS,
DEVICE_BRAND,
DEVICE_NAME,
OPERATING_SYSTEM_CLASS,
OPERATING_SYSTEM_NAME,
OPERATING_SYSTEM_VERSION,
OPERATING_SYSTEM_VERSION_MAJOR,
OPERATING_SYSTEM_NAME_VERSION,
OPERATING_SYSTEM_NAME_VERSION_MAJOR,
LAYOUT_ENGINE_CLASS,
LAYOUT_ENGINE_NAME,
LAYOUT_ENGINE_VERSION,
LAYOUT_ENGINE_VERSION_MAJOR,
LAYOUT_ENGINE_NAME_VERSION,
LAYOUT_ENGINE_NAME_VERSION_MAJOR,
AGENT_CLASS,
AGENT_NAME,
AGENT_VERSION,
AGENT_VERSION_MAJOR,
AGENT_NAME_VERSION,
AGENT_NAME_VERSION_MAJOR
));
// We manually sort the list of fields to ensure the output is consistent.
// Any unspecified fieldnames will be appended to the end.
List<String> PRE_SORTED_FIELDS_LIST = Collections.unmodifiableList(Arrays.asList(
DEVICE_CLASS,
DEVICE_NAME,
DEVICE_BRAND,
DEVICE_CPU,
DEVICE_CPU_BITS,
DEVICE_FIRMWARE_VERSION,
DEVICE_VERSION,
OPERATING_SYSTEM_CLASS,
OPERATING_SYSTEM_NAME,
OPERATING_SYSTEM_VERSION,
OPERATING_SYSTEM_VERSION_MAJOR,
OPERATING_SYSTEM_NAME_VERSION,
OPERATING_SYSTEM_NAME_VERSION_MAJOR,
OPERATING_SYSTEM_VERSION_BUILD,
LAYOUT_ENGINE_CLASS,
LAYOUT_ENGINE_NAME,
LAYOUT_ENGINE_VERSION,
LAYOUT_ENGINE_VERSION_MAJOR,
LAYOUT_ENGINE_NAME_VERSION,
LAYOUT_ENGINE_NAME_VERSION_MAJOR,
LAYOUT_ENGINE_BUILD,
AGENT_CLASS,
AGENT_NAME,
AGENT_VERSION,
AGENT_VERSION_MAJOR,
AGENT_NAME_VERSION,
AGENT_NAME_VERSION_MAJOR,
AGENT_BUILD,
AGENT_LANGUAGE,
AGENT_LANGUAGE_CODE,
AGENT_INFORMATION_EMAIL,
AGENT_INFORMATION_URL,
AGENT_SECURITY,
AGENT_UUID,
WEBVIEW_APP_NAME,
WEBVIEW_APP_VERSION,
WEBVIEW_APP_VERSION_MAJOR,
WEBVIEW_APP_NAME_VERSION,
WEBVIEW_APP_NAME_VERSION_MAJOR,
FACEBOOK_CARRIER,
FACEBOOK_DEVICE_CLASS,
FACEBOOK_DEVICE_NAME,
FACEBOOK_DEVICE_VERSION,
FACEBOOK_F_B_O_P,
FACEBOOK_F_B_S_S,
FACEBOOK_OPERATING_SYSTEM_NAME,
FACEBOOK_OPERATING_SYSTEM_VERSION,
ANONYMIZED,
HACKER_ATTACK_VECTOR,
HACKER_TOOLKIT,
KOBO_AFFILIATE,
KOBO_PLATFORM_ID,
IE_COMPATIBILITY_VERSION,
IE_COMPATIBILITY_VERSION_MAJOR,
IE_COMPATIBILITY_NAME_VERSION,
IE_COMPATIBILITY_NAME_VERSION_MAJOR,
SYNTAX_ERROR
));
default String escapeYaml(String input) {
if (input == null) {
return NULL_VALUE;
}
return input.replace("'", "''");
}
default String toYamlTestCase() {
return toYamlTestCase(false, getCleanedAvailableFieldNamesSorted(), null);
}
default String toYamlTestCase(List<String> fieldNames) {
return toYamlTestCase(false, fieldNames, null);
}
default String toYamlTestCase(boolean showConfidence) {
return toYamlTestCase(showConfidence, getCleanedAvailableFieldNamesSorted(), null);
}
default String toYamlTestCase(boolean showConfidence, Map<String, String> comments) {
return toYamlTestCase(showConfidence, getCleanedAvailableFieldNamesSorted(), comments);
}
default String toYamlTestCase(boolean showConfidence, List<String> fieldNames) {
return toYamlTestCase(showConfidence, fieldNames, null);
}
default String toYamlTestCase(boolean showConfidence, List<String> fieldNames, Map<String, String> comments) {
StringBuilder sb = new StringBuilder(10240);
sb.append("\n");
sb.append("- test:\n");
sb.append(" input:\n");
sb.append(" user_agent_string: '").append(escapeYaml(getUserAgentString())).append("'\n");
sb.append(" expected:\n");
int maxNameLength = 30;
int maxValueLength = 0;
for (String fieldName : fieldNames) {
maxNameLength = Math.max(maxNameLength, fieldName.length());
}
for (String fieldName : fieldNames) {
String value = escapeYaml(getValue(fieldName));
if (value != null) {
maxValueLength = Math.max(maxValueLength, value.length());
}
}
for (String fieldName : fieldNames) {
AgentField field = get(fieldName);
sb.append(" ").append(fieldName);
for (int l = fieldName.length(); l < maxNameLength + 6; l++) {
sb.append(' ');
}
String value = escapeYaml(field.getValue());
sb.append(": '").append(value).append('\'');
if (showConfidence || comments != null) {
int l = value.length();
for (; l < maxValueLength + 5; l++) {
sb.append(' ');
}
sb.append("# ");
if (showConfidence) {
sb.append(String.format("%8d", getConfidence(fieldName)));
if (field.isDefaultValue()) {
sb.append(" [Default]");
}
}
if (comments != null) {
String comment = comments.get(fieldName);
if (comment != null) {
if (!field.isDefaultValue()) {
sb.append(" ");
}
sb.append(" | ").append(comment);
}
}
}
sb.append('\n');
}
return sb.toString();
}
default Map<String, String> toMap() {
List<String> fields = new ArrayList<>();
fields.add(USERAGENT_FIELDNAME);
fields.addAll(getAvailableFieldNamesSorted());
return toMap(fields);
}
default Map<String, String> toMap(String... fieldNames) {
return toMap(Arrays.asList(fieldNames));
}
default Map<String, String> toMap(List<String> fieldNames) {
Map<String, String> result = new TreeMap<>();
for (String fieldName : fieldNames) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
result.put(USERAGENT_FIELDNAME, getUserAgentString());
} else {
AgentField field = get(fieldName);
result.put(fieldName, field.getValue());
}
}
return result;
}
default String toJson() {
List<String> fields = new ArrayList<>();
fields.add(USERAGENT_FIELDNAME);
fields.addAll(getAvailableFieldNamesSorted());
return toJson(fields);
}
default String toJson(String... fieldNames) {
return toJson(Arrays.asList(fieldNames));
}
default String toJson(List<String> fieldNames) {
StringBuilder sb = new StringBuilder(10240);
sb.append("{");
boolean addSeparator = false;
for (String fieldName : fieldNames) {
if (addSeparator) {
sb.append(',');
} else {
addSeparator = true;
}
if (USERAGENT_FIELDNAME.equals(fieldName)) {
sb
.append("\"Useragent\"")
.append(':')
.append('"').append(StringEscapeUtils.escapeJson(getUserAgentString())).append('"');
} else {
AgentField field = get(fieldName);
sb
.append('"').append(StringEscapeUtils.escapeJson(fieldName)).append('"')
.append(':')
.append('"').append(StringEscapeUtils.escapeJson(field.getValue())).append('"');
}
}
sb.append("}");
return sb.toString();
}
default String toXML() {
List<String> fields = new ArrayList<>();
fields.add(USERAGENT_FIELDNAME);
fields.addAll(getAvailableFieldNamesSorted());
return toXML(fields);
}
default String toXML(String... fieldNames) {
return toXML(Arrays.asList(fieldNames));
}
default String toXML(List<String> fieldNames) {
StringBuilder sb =
new StringBuilder(10240)
.append("<Yauaa>");
for (String fieldName : fieldNames) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
sb
.append("<Useragent>")
.append(StringEscapeUtils.escapeXml10(getUserAgentString()))
.append("</Useragent>");
} else {
AgentField field = get(fieldName);
sb
.append('<').append(StringEscapeUtils.escapeXml10(fieldName)).append('>')
.append(StringEscapeUtils.escapeXml10(field.getValue()))
.append("</").append(StringEscapeUtils.escapeXml10(fieldName)).append('>');
}
}
sb.append("</Yauaa>");
return sb.toString();
}
default String toString(String... fieldNames) {
return toString(Arrays.asList(fieldNames));
}
default String toString(List<String> fieldNames) {
String uaFieldName = "user_agent_string";
int maxLength = uaFieldName.length();
for (String fieldName : fieldNames) {
maxLength = Math.max(maxLength, fieldName.length());
}
StringBuilder sb = new StringBuilder(" - ").append(uaFieldName);
for (int l = uaFieldName.length(); l < maxLength + 2; l++) {
sb.append(' ');
}
sb.append(": '").append(escapeYaml(getUserAgentString())).append("'\n");
for (String fieldName : fieldNames) {
if (!USERAGENT_FIELDNAME.equals(fieldName)) {
AgentField field = get(fieldName);
if (field != null) {
sb.append(" ").append(fieldName);
for (int l = fieldName.length(); l < maxLength + 2; l++) {
sb.append(' ');
}
sb.append(": '").append(escapeYaml(field.getValue())).append('\'');
sb.append('\n');
}
}
}
return sb.toString();
}
default String toJavaTestCase() {
return toJavaTestCase(getCleanedAvailableFieldNamesSorted());
}
default String toJavaTestCase(List<String> fieldNames) {
StringBuilder sb = new StringBuilder();
int maxValueLength = 0;
for (String fieldName : fieldNames) {
maxValueLength = Math.max(maxValueLength, StringEscapeUtils.escapeJava(getValue(fieldName)).length());
}
for (String fieldName : fieldNames) {
if (!USERAGENT_FIELDNAME.equals(fieldName)) {
AgentField field = get(fieldName);
if (field != null) {
String value = StringEscapeUtils.escapeJava(getValue(fieldName));
sb.append(" assertEquals(\"").append(value).append("\", ");
for (int l = value.length(); l < maxValueLength + 2; l++) {
sb.append(' ');
}
sb.append("userAgent.getValue(\"").append(StringEscapeUtils.escapeJava(fieldName)).append("\"));");
sb.append('\n');
}
}
}
return sb.toString();
}
default boolean uaEquals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserAgent)) {
return false;
}
UserAgent agent = (UserAgent) o;
if (!Objects.equals(getUserAgentString(), agent.getUserAgentString())) {
return false;
}
List<String> fieldNamesSorted1 = getAvailableFieldNamesSorted();
List<String> fieldNamesSorted2 = agent.getAvailableFieldNamesSorted();
if (!Objects.equals(fieldNamesSorted1, fieldNamesSorted2)) {
return false;
}
for (String fieldName: fieldNamesSorted1) {
if (!Objects.equals(get(fieldName), agent.get(fieldName))) {
return false;
}
}
return true;
}
default int uaHashCode() {
int result = Objects.hash(getUserAgentString());
for (String fieldName: getAvailableFieldNamesSorted()) {
result = 31 * result + get(fieldName).hashCode();
}
return result;
}
class MutableUserAgent extends UserAgentBaseListener implements UserAgent, Serializable, DefaultANTLRErrorListener {
private static final Logger LOG = LogManager.getLogger(UserAgent.class);
private static String getDefaultValueForField(String fieldName) {
if (fieldName.equals(SYNTAX_ERROR)) {
return "false";
}
if (fieldName.contains("NameVersion")) {
return UNKNOWN_NAME_VERSION;
}
if (fieldName.contains("Version")) {
return UNKNOWN_VERSION;
}
return UNKNOWN_VALUE;
}
private Set<String> wantedFieldNames = null;
private boolean hasSyntaxError;
private boolean hasAmbiguity;
private int ambiguityCount;
public void destroy() {
wantedFieldNames = null;
}
public boolean hasSyntaxError() {
return hasSyntaxError;
}
public boolean hasAmbiguity() {
return hasAmbiguity;
}
public int getAmbiguityCount() {
return ambiguityCount;
}
@Override
public void syntaxError(
Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line,
int charPositionInLine,
String msg,
RecognitionException e) {
if (debug) {
LOG.error("Syntax error");
LOG.error("Source : {}", userAgentString);
LOG.error("Message: {}", msg);
}
hasSyntaxError = true;
MutableAgentField syntaxError = new MutableAgentField("false");
syntaxError.setValue("true", 1);
allFields.put(SYNTAX_ERROR, syntaxError);
}
@Override
public void reportAmbiguity(
Parser recognizer,
DFA dfa,
int startIndex,
int stopIndex,
boolean exact,
BitSet ambigAlts,
ATNConfigSet configs) {
hasAmbiguity = true;
ambiguityCount++;
}
// The original input value
private String userAgentString = null;
private boolean debug = false;
public boolean isDebug() {
return debug;
}
public void setDebug(boolean newDebug) {
this.debug = newDebug;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
return uaEquals(o);
}
@Override
public int hashCode() {
return uaHashCode();
}
private final Map<String, MutableAgentField> allFields = new HashMap<>();
private void setWantedFieldNames(Collection<String> newWantedFieldNames) {
if (newWantedFieldNames != null) {
if (!newWantedFieldNames.isEmpty()) {
wantedFieldNames = new LinkedHashSet<>(newWantedFieldNames);
for (String wantedFieldName : wantedFieldNames) {
set(wantedFieldName, "Nothing", -2);
}
}
}
}
public MutableUserAgent() {
}
public MutableUserAgent(Collection<String> wantedFieldNames) {
setWantedFieldNames(wantedFieldNames);
}
public MutableUserAgent(String userAgentString) {
// wantedFieldNames == null; --> Assume we want all fields.
setUserAgentString(userAgentString);
}
public MutableUserAgent(String userAgentString, Collection<String> wantedFieldNames) {
setWantedFieldNames(wantedFieldNames);
setUserAgentString(userAgentString);
}
public void setUserAgentString(String newUserAgentString) {
this.userAgentString = newUserAgentString;
reset();
}
public String getUserAgentString() {
return userAgentString;
}
public void reset() {
hasSyntaxError = false;
hasAmbiguity = false;
ambiguityCount = 0;
for (MutableAgentField field : allFields.values()) {
field.reset();
}
}
public static boolean isSystemField(String fieldname) {
switch (fieldname) {
case SET_ALL_FIELDS:
case SYNTAX_ERROR:
case USERAGENT_FIELDNAME:
return true;
default:
return false;
}
}
public void processSetAll() {
MutableAgentField setAllField = allFields.get(SET_ALL_FIELDS);
if (setAllField == null) {
return;
}
String value;
if (setAllField.isDefaultValue()) {
value = NULL_VALUE;
} else {
value = setAllField.getValue();
}
long confidence = setAllField.confidence;
for (Map.Entry<String, MutableAgentField> fieldEntry : allFields.entrySet()) {
if (!isSystemField(fieldEntry.getKey())) {
fieldEntry.getValue().setValue(value, confidence);
}
}
}
public void set(String attribute, String value, long confidence) {
MutableAgentField field = allFields.get(attribute);
if (field == null) {
field = new MutableAgentField(getDefaultValueForField(attribute));
}
boolean wasEmpty = confidence == -1;
boolean updated = field.setValue(value, confidence);
if (debug && !wasEmpty) {
if (updated) {
LOG.info("USE {} ({}) = {}", attribute, confidence, value);
} else {
LOG.info("SKIP {} ({}) = {}", attribute, confidence, value);
}
}
allFields.put(attribute, field);
}
public void setForced(String attribute, String value, long confidence) {
MutableAgentField field = allFields.get(attribute);
if (field == null) {
field = new MutableAgentField(getDefaultValueForField(attribute));
}
boolean wasEmpty = confidence == -1;
field.setValueForced(value, confidence);
if (debug && !wasEmpty) {
LOG.info("USE {} ({}) = {}", attribute, confidence, value);
}
allFields.put(attribute, field);
}
// The appliedMatcher parameter is needed for development and debugging.
public void set(MutableUserAgent newValuesUserAgent, Matcher appliedMatcher) { // NOSONAR: Unused parameter
for (String fieldName : newValuesUserAgent.allFields.keySet()) {
MutableAgentField field = newValuesUserAgent.allFields.get(fieldName);
set(fieldName, field.value, field.confidence);
}
}
void setImmediateForTesting(String fieldName, MutableAgentField agentField) {
allFields.put(fieldName, agentField);
}
public AgentField get(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
MutableAgentField agentField = new MutableAgentField(userAgentString);
agentField.setValue(userAgentString, 0L);
return agentField;
} else {
return allFields
.computeIfAbsent(
fieldName,
f -> new MutableAgentField(getDefaultValueForField(fieldName)));
}
}
public String getValue(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return userAgentString;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return getDefaultValueForField(fieldName);
}
return field.getValue();
}
public Long getConfidence(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return 0L;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return -1L;
}
return field.getConfidence();
}
@Override
public List<String> getAvailableFieldNamesSorted() {
List<String> fieldNames = new ArrayList<>(allFields.size() + 10);
if (wantedFieldNames == null) {
fieldNames.addAll(STANDARD_FIELDS);
allFields.forEach((fieldName, field) -> {
if (!fieldNames.contains(fieldName)) {
fieldNames.add(fieldName);
}
});
} else {
fieldNames.addAll(wantedFieldNames);
}
// This is not a field; this is a special operator.
fieldNames.remove(SET_ALL_FIELDS);
List<String> result = PRE_SORTED_FIELDS_LIST
.stream()
.filter(fieldNames::remove)
.collect(Collectors.toList());
Collections.sort(fieldNames);
result.addAll(fieldNames);
return result;
}
@Override
public String toString() {
return toString(getAvailableFieldNamesSorted());
}
}
class ImmutableUserAgent implements UserAgent {
private final String userAgentString;
private final ImmutableAgentField userAgentStringField;
private final Map<String, ImmutableAgentField> allFields;
private final List<String> availableFieldNamesSorted;
private List<String> cleanedAvailableFieldNamesSorted;
private final boolean hasSyntaxError;
private final boolean hasAmbiguity;
private final int ambiguityCount;
public ImmutableUserAgent(MutableUserAgent userAgent) {
userAgentString = userAgent.userAgentString;
hasSyntaxError = userAgent.hasSyntaxError;
hasAmbiguity = userAgent.hasAmbiguity;
ambiguityCount = userAgent.ambiguityCount;
userAgentStringField = new ImmutableAgentField(userAgentString, 0L, false, userAgentString);
Map<String, ImmutableAgentField> preparingAllFields = new LinkedHashMap<>(userAgent.allFields.size());
for (String fieldName: userAgent.getAvailableFieldNamesSorted()) {
preparingAllFields.put(fieldName, new ImmutableAgentField((MutableAgentField) userAgent.get(fieldName)));
}
allFields = Collections.unmodifiableMap(preparingAllFields);
availableFieldNamesSorted = Collections.unmodifiableList(userAgent.getAvailableFieldNamesSorted());
}
@Override
public String getUserAgentString() {
return userAgentString;
}
public AgentField get(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return userAgentStringField;
} else {
ImmutableAgentField agentField = allFields.get(fieldName);
if (agentField == null) {
agentField = new ImmutableAgentField(MutableUserAgent.getDefaultValueForField(fieldName),
-1,
true,
MutableUserAgent.getDefaultValueForField(fieldName));
}
return agentField;
}
}
public String getValue(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return userAgentString;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return MutableUserAgent.getDefaultValueForField(fieldName);
}
return field.getValue();
}
public Long getConfidence(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return 0L;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return -1L;
}
return field.getConfidence();
}
public boolean hasSyntaxError() {
return hasSyntaxError;
}
public boolean hasAmbiguity() {
return hasAmbiguity;
}
public int getAmbiguityCount() {
return ambiguityCount;
}
@Override
public List<String> getAvailableFieldNamesSorted() {
return availableFieldNamesSorted;
}
@Override
public List<String> getCleanedAvailableFieldNamesSorted() {
if (cleanedAvailableFieldNamesSorted == null) {
cleanedAvailableFieldNamesSorted =
Collections.unmodifiableList(UserAgent.super.getCleanedAvailableFieldNamesSorted());
}
return cleanedAvailableFieldNamesSorted;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
return uaEquals(o);
}
@Override
public int hashCode() {
return uaHashCode();
}
@Override
public String toString() {
return toString(getAvailableFieldNamesSorted());
}
}
}
| analyzer/src/main/java/nl/basjes/parse/useragent/UserAgent.java | /*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2022 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.basjes.parse.useragent;
import nl.basjes.parse.useragent.AgentField.ImmutableAgentField;
import nl.basjes.parse.useragent.AgentField.MutableAgentField;
import nl.basjes.parse.useragent.analyze.Matcher;
import nl.basjes.parse.useragent.parser.UserAgentBaseListener;
import nl.basjes.parse.useragent.utils.DefaultANTLRErrorListener;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.dfa.DFA;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
public interface UserAgent extends Serializable {
String getUserAgentString();
AgentField get(String fieldName);
String getValue(String fieldName);
Long getConfidence(String fieldName);
boolean hasSyntaxError();
boolean hasAmbiguity();
int getAmbiguityCount();
List<String> getAvailableFieldNamesSorted();
default List<String> getCleanedAvailableFieldNamesSorted() {
List<String> fieldNames = new ArrayList<>();
for (String fieldName : getAvailableFieldNamesSorted()) {
if (!STANDARD_FIELDS.contains(fieldName)) {
if (get(fieldName).isDefaultValue()) {
// Skip the "non standard" fields that do not have a relevant value.
continue;
}
}
fieldNames.add(fieldName);
}
return fieldNames;
}
String DEVICE_CLASS = "DeviceClass";
String DEVICE_NAME = "DeviceName";
String DEVICE_BRAND = "DeviceBrand";
String DEVICE_CPU = "DeviceCpu";
String DEVICE_CPU_BITS = "DeviceCpuBits";
String DEVICE_FIRMWARE_VERSION = "DeviceFirmwareVersion";
String DEVICE_VERSION = "DeviceVersion";
String OPERATING_SYSTEM_CLASS = "OperatingSystemClass";
String OPERATING_SYSTEM_NAME = "OperatingSystemName";
String OPERATING_SYSTEM_VERSION = "OperatingSystemVersion";
String OPERATING_SYSTEM_VERSION_MAJOR = "OperatingSystemVersionMajor";
String OPERATING_SYSTEM_NAME_VERSION = "OperatingSystemNameVersion";
String OPERATING_SYSTEM_NAME_VERSION_MAJOR = "OperatingSystemNameVersionMajor";
String OPERATING_SYSTEM_VERSION_BUILD = "OperatingSystemVersionBuild";
String LAYOUT_ENGINE_CLASS = "LayoutEngineClass";
String LAYOUT_ENGINE_NAME = "LayoutEngineName";
String LAYOUT_ENGINE_VERSION = "LayoutEngineVersion";
String LAYOUT_ENGINE_VERSION_MAJOR = "LayoutEngineVersionMajor";
String LAYOUT_ENGINE_NAME_VERSION = "LayoutEngineNameVersion";
String LAYOUT_ENGINE_NAME_VERSION_MAJOR = "LayoutEngineNameVersionMajor";
String LAYOUT_ENGINE_BUILD = "LayoutEngineBuild";
String AGENT_CLASS = "AgentClass";
String AGENT_NAME = "AgentName";
String AGENT_VERSION = "AgentVersion";
String AGENT_VERSION_MAJOR = "AgentVersionMajor";
String AGENT_NAME_VERSION = "AgentNameVersion";
String AGENT_NAME_VERSION_MAJOR = "AgentNameVersionMajor";
String AGENT_BUILD = "AgentBuild";
String AGENT_LANGUAGE = "AgentLanguage";
String AGENT_LANGUAGE_CODE = "AgentLanguageCode";
String AGENT_INFORMATION_EMAIL = "AgentInformationEmail";
String AGENT_INFORMATION_URL = "AgentInformationUrl";
String AGENT_SECURITY = "AgentSecurity";
String AGENT_UUID = "AgentUuid";
String WEBVIEW_APP_NAME = "WebviewAppName";
String WEBVIEW_APP_VERSION = "WebviewAppVersion";
String WEBVIEW_APP_VERSION_MAJOR = "WebviewAppVersionMajor";
String WEBVIEW_APP_NAME_VERSION = "WebviewAppNameVersion";
String WEBVIEW_APP_NAME_VERSION_MAJOR = "WebviewAppNameVersionMajor";
String FACEBOOK_CARRIER = "FacebookCarrier";
String FACEBOOK_DEVICE_CLASS = "FacebookDeviceClass";
String FACEBOOK_DEVICE_NAME = "FacebookDeviceName";
String FACEBOOK_DEVICE_VERSION = "FacebookDeviceVersion";
String FACEBOOK_F_B_O_P = "FacebookFBOP";
String FACEBOOK_F_B_S_S = "FacebookFBSS";
String FACEBOOK_OPERATING_SYSTEM_NAME = "FacebookOperatingSystemName";
String FACEBOOK_OPERATING_SYSTEM_VERSION = "FacebookOperatingSystemVersion";
String ANONYMIZED = "Anonymized";
String HACKER_ATTACK_VECTOR = "HackerAttackVector";
String HACKER_TOOLKIT = "HackerToolkit";
String KOBO_AFFILIATE = "KoboAffiliate";
String KOBO_PLATFORM_ID = "KoboPlatformId";
String IE_COMPATIBILITY_VERSION = "IECompatibilityVersion";
String IE_COMPATIBILITY_VERSION_MAJOR = "IECompatibilityVersionMajor";
String IE_COMPATIBILITY_NAME_VERSION = "IECompatibilityNameVersion";
String IE_COMPATIBILITY_NAME_VERSION_MAJOR = "IECompatibilityNameVersionMajor";
String SYNTAX_ERROR = "__SyntaxError__";
String USERAGENT_FIELDNAME = "Useragent";
String NETWORK_TYPE = "NetworkType";
String SET_ALL_FIELDS = "__Set_ALL_Fields__";
String NULL_VALUE = "<<<null>>>";
String UNKNOWN_VALUE = "Unknown";
String UNKNOWN_VERSION = "??";
String UNKNOWN_NAME_VERSION = "Unknown ??";
List<String> STANDARD_FIELDS = Collections.unmodifiableList(Arrays.asList(
DEVICE_CLASS,
DEVICE_BRAND,
DEVICE_NAME,
OPERATING_SYSTEM_CLASS,
OPERATING_SYSTEM_NAME,
OPERATING_SYSTEM_VERSION,
OPERATING_SYSTEM_VERSION_MAJOR,
OPERATING_SYSTEM_NAME_VERSION,
OPERATING_SYSTEM_NAME_VERSION_MAJOR,
LAYOUT_ENGINE_CLASS,
LAYOUT_ENGINE_NAME,
LAYOUT_ENGINE_VERSION,
LAYOUT_ENGINE_VERSION_MAJOR,
LAYOUT_ENGINE_NAME_VERSION,
LAYOUT_ENGINE_NAME_VERSION_MAJOR,
AGENT_CLASS,
AGENT_NAME,
AGENT_VERSION,
AGENT_VERSION_MAJOR,
AGENT_NAME_VERSION,
AGENT_NAME_VERSION_MAJOR
));
// We manually sort the list of fields to ensure the output is consistent.
// Any unspecified fieldnames will be appended to the end.
List<String> PRE_SORTED_FIELDS_LIST = Collections.unmodifiableList(Arrays.asList(
DEVICE_CLASS,
DEVICE_NAME,
DEVICE_BRAND,
DEVICE_CPU,
DEVICE_CPU_BITS,
DEVICE_FIRMWARE_VERSION,
DEVICE_VERSION,
OPERATING_SYSTEM_CLASS,
OPERATING_SYSTEM_NAME,
OPERATING_SYSTEM_VERSION,
OPERATING_SYSTEM_VERSION_MAJOR,
OPERATING_SYSTEM_NAME_VERSION,
OPERATING_SYSTEM_NAME_VERSION_MAJOR,
OPERATING_SYSTEM_VERSION_BUILD,
LAYOUT_ENGINE_CLASS,
LAYOUT_ENGINE_NAME,
LAYOUT_ENGINE_VERSION,
LAYOUT_ENGINE_VERSION_MAJOR,
LAYOUT_ENGINE_NAME_VERSION,
LAYOUT_ENGINE_NAME_VERSION_MAJOR,
LAYOUT_ENGINE_BUILD,
AGENT_CLASS,
AGENT_NAME,
AGENT_VERSION,
AGENT_VERSION_MAJOR,
AGENT_NAME_VERSION,
AGENT_NAME_VERSION_MAJOR,
AGENT_BUILD,
AGENT_LANGUAGE,
AGENT_LANGUAGE_CODE,
AGENT_INFORMATION_EMAIL,
AGENT_INFORMATION_URL,
AGENT_SECURITY,
AGENT_UUID,
WEBVIEW_APP_NAME,
WEBVIEW_APP_VERSION,
WEBVIEW_APP_VERSION_MAJOR,
WEBVIEW_APP_NAME_VERSION,
WEBVIEW_APP_NAME_VERSION_MAJOR,
FACEBOOK_CARRIER,
FACEBOOK_DEVICE_CLASS,
FACEBOOK_DEVICE_NAME,
FACEBOOK_DEVICE_VERSION,
FACEBOOK_F_B_O_P,
FACEBOOK_F_B_S_S,
FACEBOOK_OPERATING_SYSTEM_NAME,
FACEBOOK_OPERATING_SYSTEM_VERSION,
ANONYMIZED,
HACKER_ATTACK_VECTOR,
HACKER_TOOLKIT,
KOBO_AFFILIATE,
KOBO_PLATFORM_ID,
IE_COMPATIBILITY_VERSION,
IE_COMPATIBILITY_VERSION_MAJOR,
IE_COMPATIBILITY_NAME_VERSION,
IE_COMPATIBILITY_NAME_VERSION_MAJOR,
SYNTAX_ERROR
));
default String escapeYaml(String input) {
if (input == null) {
return NULL_VALUE;
}
return input.replace("'", "''");
}
default String toYamlTestCase() {
return toYamlTestCase(false, getAvailableFieldNamesSorted(), null);
}
default String toYamlTestCase(List<String> fieldNames) {
return toYamlTestCase(false, fieldNames, null);
}
default String toYamlTestCase(boolean showConfidence) {
return toYamlTestCase(showConfidence, getAvailableFieldNamesSorted(), null);
}
default String toYamlTestCase(boolean showConfidence, Map<String, String> comments) {
return toYamlTestCase(showConfidence, getAvailableFieldNamesSorted(), comments);
}
default String toYamlTestCase(boolean showConfidence, List<String> fieldNames) {
return toYamlTestCase(showConfidence, fieldNames, null);
}
default String toYamlTestCase(boolean showConfidence, List<String> fieldNames, Map<String, String> comments) {
StringBuilder sb = new StringBuilder(10240);
sb.append("\n");
sb.append("- test:\n");
sb.append(" input:\n");
sb.append(" user_agent_string: '").append(escapeYaml(getUserAgentString())).append("'\n");
sb.append(" expected:\n");
int maxNameLength = 30;
int maxValueLength = 0;
for (String fieldName : fieldNames) {
maxNameLength = Math.max(maxNameLength, fieldName.length());
}
for (String fieldName : fieldNames) {
String value = escapeYaml(getValue(fieldName));
if (value != null) {
maxValueLength = Math.max(maxValueLength, value.length());
}
}
for (String fieldName : fieldNames) {
AgentField field = get(fieldName);
sb.append(" ").append(fieldName);
for (int l = fieldName.length(); l < maxNameLength + 6; l++) {
sb.append(' ');
}
String value = escapeYaml(field.getValue());
sb.append(": '").append(value).append('\'');
if (showConfidence || comments != null) {
int l = value.length();
for (; l < maxValueLength + 5; l++) {
sb.append(' ');
}
sb.append("# ");
if (showConfidence) {
sb.append(String.format("%8d", getConfidence(fieldName)));
if (field.isDefaultValue()) {
sb.append(" [Default]");
}
}
if (comments != null) {
String comment = comments.get(fieldName);
if (comment != null) {
if (!field.isDefaultValue()) {
sb.append(" ");
}
sb.append(" | ").append(comment);
}
}
}
sb.append('\n');
}
return sb.toString();
}
default Map<String, String> toMap() {
List<String> fields = new ArrayList<>();
fields.add(USERAGENT_FIELDNAME);
fields.addAll(getAvailableFieldNamesSorted());
return toMap(fields);
}
default Map<String, String> toMap(String... fieldNames) {
return toMap(Arrays.asList(fieldNames));
}
default Map<String, String> toMap(List<String> fieldNames) {
Map<String, String> result = new TreeMap<>();
for (String fieldName : fieldNames) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
result.put(USERAGENT_FIELDNAME, getUserAgentString());
} else {
AgentField field = get(fieldName);
result.put(fieldName, field.getValue());
}
}
return result;
}
default String toJson() {
List<String> fields = new ArrayList<>();
fields.add(USERAGENT_FIELDNAME);
fields.addAll(getAvailableFieldNamesSorted());
return toJson(fields);
}
default String toJson(String... fieldNames) {
return toJson(Arrays.asList(fieldNames));
}
default String toJson(List<String> fieldNames) {
StringBuilder sb = new StringBuilder(10240);
sb.append("{");
boolean addSeparator = false;
for (String fieldName : fieldNames) {
if (addSeparator) {
sb.append(',');
} else {
addSeparator = true;
}
if (USERAGENT_FIELDNAME.equals(fieldName)) {
sb
.append("\"Useragent\"")
.append(':')
.append('"').append(StringEscapeUtils.escapeJson(getUserAgentString())).append('"');
} else {
AgentField field = get(fieldName);
sb
.append('"').append(StringEscapeUtils.escapeJson(fieldName)).append('"')
.append(':')
.append('"').append(StringEscapeUtils.escapeJson(field.getValue())).append('"');
}
}
sb.append("}");
return sb.toString();
}
default String toXML() {
List<String> fields = new ArrayList<>();
fields.add(USERAGENT_FIELDNAME);
fields.addAll(getAvailableFieldNamesSorted());
return toXML(fields);
}
default String toXML(String... fieldNames) {
return toXML(Arrays.asList(fieldNames));
}
default String toXML(List<String> fieldNames) {
StringBuilder sb =
new StringBuilder(10240)
.append("<Yauaa>");
for (String fieldName : fieldNames) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
sb
.append("<Useragent>")
.append(StringEscapeUtils.escapeXml10(getUserAgentString()))
.append("</Useragent>");
} else {
AgentField field = get(fieldName);
sb
.append('<').append(StringEscapeUtils.escapeXml10(fieldName)).append('>')
.append(StringEscapeUtils.escapeXml10(field.getValue()))
.append("</").append(StringEscapeUtils.escapeXml10(fieldName)).append('>');
}
}
sb.append("</Yauaa>");
return sb.toString();
}
default String toString(String... fieldNames) {
return toString(Arrays.asList(fieldNames));
}
default String toString(List<String> fieldNames) {
String uaFieldName = "user_agent_string";
int maxLength = uaFieldName.length();
for (String fieldName : fieldNames) {
maxLength = Math.max(maxLength, fieldName.length());
}
StringBuilder sb = new StringBuilder(" - ").append(uaFieldName);
for (int l = uaFieldName.length(); l < maxLength + 2; l++) {
sb.append(' ');
}
sb.append(": '").append(escapeYaml(getUserAgentString())).append("'\n");
for (String fieldName : fieldNames) {
if (!USERAGENT_FIELDNAME.equals(fieldName)) {
AgentField field = get(fieldName);
if (field != null) {
sb.append(" ").append(fieldName);
for (int l = fieldName.length(); l < maxLength + 2; l++) {
sb.append(' ');
}
sb.append(": '").append(escapeYaml(field.getValue())).append('\'');
sb.append('\n');
}
}
}
return sb.toString();
}
default boolean uaEquals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserAgent)) {
return false;
}
UserAgent agent = (UserAgent) o;
if (!Objects.equals(getUserAgentString(), agent.getUserAgentString())) {
return false;
}
List<String> fieldNamesSorted1 = getAvailableFieldNamesSorted();
List<String> fieldNamesSorted2 = agent.getAvailableFieldNamesSorted();
if (!Objects.equals(fieldNamesSorted1, fieldNamesSorted2)) {
return false;
}
for (String fieldName: fieldNamesSorted1) {
if (!Objects.equals(get(fieldName), agent.get(fieldName))) {
return false;
}
}
return true;
}
default int uaHashCode() {
int result = Objects.hash(getUserAgentString());
for (String fieldName: getAvailableFieldNamesSorted()) {
result = 31 * result + get(fieldName).hashCode();
}
return result;
}
class MutableUserAgent extends UserAgentBaseListener implements UserAgent, Serializable, DefaultANTLRErrorListener {
private static final Logger LOG = LogManager.getLogger(UserAgent.class);
private static String getDefaultValueForField(String fieldName) {
if (fieldName.equals(SYNTAX_ERROR)) {
return "false";
}
if (fieldName.contains("NameVersion")) {
return UNKNOWN_NAME_VERSION;
}
if (fieldName.contains("Version")) {
return UNKNOWN_VERSION;
}
return UNKNOWN_VALUE;
}
private Set<String> wantedFieldNames = null;
private boolean hasSyntaxError;
private boolean hasAmbiguity;
private int ambiguityCount;
public void destroy() {
wantedFieldNames = null;
}
public boolean hasSyntaxError() {
return hasSyntaxError;
}
public boolean hasAmbiguity() {
return hasAmbiguity;
}
public int getAmbiguityCount() {
return ambiguityCount;
}
@Override
public void syntaxError(
Recognizer<?, ?> recognizer,
Object offendingSymbol,
int line,
int charPositionInLine,
String msg,
RecognitionException e) {
if (debug) {
LOG.error("Syntax error");
LOG.error("Source : {}", userAgentString);
LOG.error("Message: {}", msg);
}
hasSyntaxError = true;
MutableAgentField syntaxError = new MutableAgentField("false");
syntaxError.setValue("true", 1);
allFields.put(SYNTAX_ERROR, syntaxError);
}
@Override
public void reportAmbiguity(
Parser recognizer,
DFA dfa,
int startIndex,
int stopIndex,
boolean exact,
BitSet ambigAlts,
ATNConfigSet configs) {
hasAmbiguity = true;
ambiguityCount++;
}
// The original input value
private String userAgentString = null;
private boolean debug = false;
public boolean isDebug() {
return debug;
}
public void setDebug(boolean newDebug) {
this.debug = newDebug;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
return uaEquals(o);
}
@Override
public int hashCode() {
return uaHashCode();
}
private final Map<String, MutableAgentField> allFields = new HashMap<>();
private void setWantedFieldNames(Collection<String> newWantedFieldNames) {
if (newWantedFieldNames != null) {
if (!newWantedFieldNames.isEmpty()) {
wantedFieldNames = new LinkedHashSet<>(newWantedFieldNames);
for (String wantedFieldName : wantedFieldNames) {
set(wantedFieldName, "Nothing", -2);
}
}
}
}
public MutableUserAgent() {
}
public MutableUserAgent(Collection<String> wantedFieldNames) {
setWantedFieldNames(wantedFieldNames);
}
public MutableUserAgent(String userAgentString) {
// wantedFieldNames == null; --> Assume we want all fields.
setUserAgentString(userAgentString);
}
public MutableUserAgent(String userAgentString, Collection<String> wantedFieldNames) {
setWantedFieldNames(wantedFieldNames);
setUserAgentString(userAgentString);
}
public void setUserAgentString(String newUserAgentString) {
this.userAgentString = newUserAgentString;
reset();
}
public String getUserAgentString() {
return userAgentString;
}
public void reset() {
hasSyntaxError = false;
hasAmbiguity = false;
ambiguityCount = 0;
for (MutableAgentField field : allFields.values()) {
field.reset();
}
}
public static boolean isSystemField(String fieldname) {
switch (fieldname) {
case SET_ALL_FIELDS:
case SYNTAX_ERROR:
case USERAGENT_FIELDNAME:
return true;
default:
return false;
}
}
public void processSetAll() {
MutableAgentField setAllField = allFields.get(SET_ALL_FIELDS);
if (setAllField == null) {
return;
}
String value;
if (setAllField.isDefaultValue()) {
value = NULL_VALUE;
} else {
value = setAllField.getValue();
}
long confidence = setAllField.confidence;
for (Map.Entry<String, MutableAgentField> fieldEntry : allFields.entrySet()) {
if (!isSystemField(fieldEntry.getKey())) {
fieldEntry.getValue().setValue(value, confidence);
}
}
}
public void set(String attribute, String value, long confidence) {
MutableAgentField field = allFields.get(attribute);
if (field == null) {
field = new MutableAgentField(getDefaultValueForField(attribute));
}
boolean wasEmpty = confidence == -1;
boolean updated = field.setValue(value, confidence);
if (debug && !wasEmpty) {
if (updated) {
LOG.info("USE {} ({}) = {}", attribute, confidence, value);
} else {
LOG.info("SKIP {} ({}) = {}", attribute, confidence, value);
}
}
allFields.put(attribute, field);
}
public void setForced(String attribute, String value, long confidence) {
MutableAgentField field = allFields.get(attribute);
if (field == null) {
field = new MutableAgentField(getDefaultValueForField(attribute));
}
boolean wasEmpty = confidence == -1;
field.setValueForced(value, confidence);
if (debug && !wasEmpty) {
LOG.info("USE {} ({}) = {}", attribute, confidence, value);
}
allFields.put(attribute, field);
}
// The appliedMatcher parameter is needed for development and debugging.
public void set(MutableUserAgent newValuesUserAgent, Matcher appliedMatcher) { // NOSONAR: Unused parameter
for (String fieldName : newValuesUserAgent.allFields.keySet()) {
MutableAgentField field = newValuesUserAgent.allFields.get(fieldName);
set(fieldName, field.value, field.confidence);
}
}
void setImmediateForTesting(String fieldName, MutableAgentField agentField) {
allFields.put(fieldName, agentField);
}
public AgentField get(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
MutableAgentField agentField = new MutableAgentField(userAgentString);
agentField.setValue(userAgentString, 0L);
return agentField;
} else {
return allFields
.computeIfAbsent(
fieldName,
f -> new MutableAgentField(getDefaultValueForField(fieldName)));
}
}
public String getValue(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return userAgentString;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return getDefaultValueForField(fieldName);
}
return field.getValue();
}
public Long getConfidence(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return 0L;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return -1L;
}
return field.getConfidence();
}
@Override
public List<String> getAvailableFieldNamesSorted() {
List<String> fieldNames = new ArrayList<>(allFields.size() + 10);
if (wantedFieldNames == null) {
fieldNames.addAll(STANDARD_FIELDS);
allFields.forEach((fieldName, field) -> {
if (!fieldNames.contains(fieldName)) {
fieldNames.add(fieldName);
}
});
} else {
fieldNames.addAll(wantedFieldNames);
}
// This is not a field; this is a special operator.
fieldNames.remove(SET_ALL_FIELDS);
List<String> result = PRE_SORTED_FIELDS_LIST
.stream()
.filter(fieldNames::remove)
.collect(Collectors.toList());
Collections.sort(fieldNames);
result.addAll(fieldNames);
return result;
}
@Override
public String toString() {
return toString(getAvailableFieldNamesSorted());
}
}
class ImmutableUserAgent implements UserAgent {
private final String userAgentString;
private final ImmutableAgentField userAgentStringField;
private final Map<String, ImmutableAgentField> allFields;
private final List<String> availableFieldNamesSorted;
private List<String> cleanedAvailableFieldNamesSorted;
private final boolean hasSyntaxError;
private final boolean hasAmbiguity;
private final int ambiguityCount;
public ImmutableUserAgent(MutableUserAgent userAgent) {
userAgentString = userAgent.userAgentString;
hasSyntaxError = userAgent.hasSyntaxError;
hasAmbiguity = userAgent.hasAmbiguity;
ambiguityCount = userAgent.ambiguityCount;
userAgentStringField = new ImmutableAgentField(userAgentString, 0L, false, userAgentString);
Map<String, ImmutableAgentField> preparingAllFields = new LinkedHashMap<>(userAgent.allFields.size());
for (String fieldName: userAgent.getAvailableFieldNamesSorted()) {
preparingAllFields.put(fieldName, new ImmutableAgentField((MutableAgentField) userAgent.get(fieldName)));
}
allFields = Collections.unmodifiableMap(preparingAllFields);
availableFieldNamesSorted = Collections.unmodifiableList(userAgent.getAvailableFieldNamesSorted());
}
@Override
public String getUserAgentString() {
return userAgentString;
}
public AgentField get(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return userAgentStringField;
} else {
ImmutableAgentField agentField = allFields.get(fieldName);
if (agentField == null) {
agentField = new ImmutableAgentField(MutableUserAgent.getDefaultValueForField(fieldName),
-1,
true,
MutableUserAgent.getDefaultValueForField(fieldName));
}
return agentField;
}
}
public String getValue(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return userAgentString;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return MutableUserAgent.getDefaultValueForField(fieldName);
}
return field.getValue();
}
public Long getConfidence(String fieldName) {
if (USERAGENT_FIELDNAME.equals(fieldName)) {
return 0L;
}
AgentField field = allFields.get(fieldName);
if (field == null) {
return -1L;
}
return field.getConfidence();
}
public boolean hasSyntaxError() {
return hasSyntaxError;
}
public boolean hasAmbiguity() {
return hasAmbiguity;
}
public int getAmbiguityCount() {
return ambiguityCount;
}
@Override
public List<String> getAvailableFieldNamesSorted() {
return availableFieldNamesSorted;
}
@Override
public List<String> getCleanedAvailableFieldNamesSorted() {
if (cleanedAvailableFieldNamesSorted == null) {
cleanedAvailableFieldNamesSorted =
Collections.unmodifiableList(UserAgent.super.getCleanedAvailableFieldNamesSorted());
}
return cleanedAvailableFieldNamesSorted;
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object o) {
return uaEquals(o);
}
@Override
public int hashCode() {
return uaHashCode();
}
@Override
public String toString() {
return toString(getAvailableFieldNamesSorted());
}
}
}
| feat: Improved the extraction of testcases
| analyzer/src/main/java/nl/basjes/parse/useragent/UserAgent.java | feat: Improved the extraction of testcases |
|
Java | apache-2.0 | f7811484bdd28d0e3354a4b930c3a6d066a097de | 0 | sk413025/carcv,oskopek/carcv,oskopek/carcv,sk413025/carcv,sk413025/carcv,sk413025/carcv,oskopek/carcv,oskopek/carcv,sk413025/carcv,oskopek/carcv,sk413025/carcv,oskopek/carcv | /**
*
*/
package org.carcv.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* @author oskopek
*
*/
@Entity
//@Table(name = "entry")
public class Entry implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6502456443004564945L;
private long id;
private CarData data;
private MediaObject preview;
/**
* For EJB
*/
public Entry() {
// Hibernate stub
}
/**
* @param data
* @param preview
*/
public Entry(CarData data, MediaObject preview) {
this.data = data;
this.preview = preview;
}
/**
* @return the id
*/
@Id
@GeneratedValue
@NotNull
//@Column(name = "id")
public long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the data
*/
@OneToOne
@NotNull
//@Column(name="data")
public CarData getData() {
return data;
}
/**
* @param data
* the data to set
*/
public void setData(CarData data) {
this.data = data;
}
/**
* @return the preview
*/
@OneToOne
@NotNull
//@Column(name="preview")
public MediaObject getPreview() {
return preview;
}
/**
* @param preview
* the preview to set
*/
public void setPreview(MediaObject preview) {
this.preview = preview;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Entry [id=" + id + ", data=" + data + ", preview=" + preview
+ "]";
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(data).append(preview).toHashCode();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Entry)) {
return false;
}
Entry other = (Entry) obj;
return new EqualsBuilder().append(data, other.data)
.append(preview, other.preview).isEquals();
}
}
| src/main/java/org/carcv/model/Entry.java | /**
*
*/
package org.carcv.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* @author oskopek
*
*/
@Entity
//@Table(name = "entry")
public class Entry implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6502456443004564945L;
private long id;
private CarData data;
private MediaObject preview;
/**
* For EJB
*/
public Entry() {
// Hibernate stub
}
/**
* @param data
* @param preview
*/
public Entry(CarData data, MediaObject preview) {
this.data = data;
this.preview = preview;
}
/**
* @return the id
*/
@Id
@GeneratedValue
@NotNull
//@Column(name = "id")
public long getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the data
*/
@OneToOne
@NotNull
//@Column(name="data")
public CarData getData() {
return data;
}
/**
* @param data
* the data to set
*/
public void setData(CarData data) {
this.data = data;
}
/**
* @return the preview
*/
@OneToOne
@NotNull
//@Column(name="preview")
public MediaObject getPreview() {
return preview;
}
/**
* @param preview
* the preview to set
*/
public void setPreview(MediaObject preview) {
this.preview = preview;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Entry [id=" + id + "data=" + data + ", preview=" + preview
+ "]";
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(data).append(preview).toHashCode();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Entry)) {
return false;
}
Entry other = (Entry) obj;
return new EqualsBuilder().append(data, other.data)
.append(preview, other.preview).isEquals();
}
}
| Small error in toString of Entry | src/main/java/org/carcv/model/Entry.java | Small error in toString of Entry |
|
Java | apache-2.0 | 9736dfd0c9551dd60b8f99f0b21c9b60f95c8950 | 0 | boulzordev/android_external_okhttp,OneRom/external_okhttp,AOSPB/external_okhttp,Infinitive-OS/platform_external_okhttp,OneRom/external_okhttp,TeamExodus/external_okhttp,boulzordev/android_external_okhttp,PAC-ROM/android_external_okhttp,w3nd1go/android_external_okhttp,CyanogenMod/android_external_okhttp,OneRom/external_okhttp,TeamExodus/external_okhttp,boulzordev/android_external_okhttp,AOSPB/external_okhttp,CyanogenMod/android_external_okhttp,w3nd1go/android_external_okhttp,AOSP-YU/platform_external_okhttp,CyanogenMod/android_external_okhttp,SlimRoms/android_external_okhttp,AOSPB/external_okhttp,YUPlayGodDev/platform_external_okhttp,geekboxzone/mmallow_external_okhttp,TeamExodus/external_okhttp,AOSP-YU/platform_external_okhttp,PAC-ROM/android_external_okhttp,Infinitive-OS/platform_external_okhttp,AOSP-CAF/platform_external_okhttp,AOSP-CAF/platform_external_okhttp,YUPlayGodDev/platform_external_okhttp,AOSP-CAF/platform_external_okhttp,PAC-ROM/android_external_okhttp,YUPlayGodDev/platform_external_okhttp,geekboxzone/mmallow_external_okhttp,w3nd1go/android_external_okhttp,geekboxzone/mmallow_external_okhttp,Infinitive-OS/platform_external_okhttp,AOSP-YU/platform_external_okhttp | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import com.squareup.okhttp.internal.Platform;
import com.squareup.okhttp.internal.Util;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP
* requests that share the same {@link com.squareup.okhttp.Address} may share a
* {@link com.squareup.okhttp.Connection}. This class implements the policy of
* which connections to keep open for future use.
*
* <p>The {@link #getDefault() system-wide default} uses system properties for
* tuning parameters:
* <ul>
* <li>{@code http.keepAlive} true if HTTP and SPDY connections should be
* pooled at all. Default is true.
* <li>{@code http.maxConnections} maximum number of idle connections to
* each to keep in the pool. Default is 5.
* <li>{@code http.keepAliveDuration} Time in milliseconds to keep the
* connection alive in the pool before closing it. Default is 5 minutes.
* This property isn't used by {@code HttpURLConnection}.
* </ul>
*
* <p>The default instance <i>doesn't</i> adjust its configuration as system
* properties are changed. This assumes that the applications that set these
* parameters do so before making HTTP connections, and that this class is
* initialized lazily.
*/
public class ConnectionPool {
private static final int MAX_CONNECTIONS_TO_CLEANUP = 2;
private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min
private static final ConnectionPool systemDefault;
static {
String keepAlive = System.getProperty("http.keepAlive");
String keepAliveDuration = System.getProperty("http.keepAliveDuration");
String maxIdleConnections = System.getProperty("http.maxConnections");
long keepAliveDurationMs = keepAliveDuration != null ? Long.parseLong(keepAliveDuration)
: DEFAULT_KEEP_ALIVE_DURATION_MS;
if (keepAlive != null && !Boolean.parseBoolean(keepAlive)) {
systemDefault = new ConnectionPool(0, keepAliveDurationMs);
} else if (maxIdleConnections != null) {
systemDefault = new ConnectionPool(Integer.parseInt(maxIdleConnections), keepAliveDurationMs);
} else {
systemDefault = new ConnectionPool(5, keepAliveDurationMs);
}
}
/** The maximum number of idle connections for each address. */
private final int maxIdleConnections;
private final long keepAliveDurationNs;
private final LinkedList<Connection> connections = new LinkedList<Connection>();
/** We use a single background thread to cleanup expired connections. */
private final ExecutorService executorService = new ThreadPoolExecutor(0, 1,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
Util.threadFactory("OkHttp ConnectionPool", true));
private enum CleanMode {
/**
* Connection clean up is driven by usage of the pool. Each usage of the pool can schedule a
* clean up. A pool left in this state and unused may contain idle connections indefinitely.
*/
NORMAL,
/**
* Entered when a pool has been orphaned and is not expected to receive more usage, except for
* references held by existing connections. See {@link #enterDrainMode()}.
* A thread runs periodically to close idle connections in the pool until the pool is empty and
* then the state moves to {@link #DRAINED}.
*/
DRAINING,
/**
* The pool is empty and no clean-up is taking place. Connections may still be added to the
* pool due to latent references to the pool, in which case the pool re-enters
* {@link #DRAINING}. If the pool is DRAINED and no longer referenced it is safe to be garbage
* collected.
*/
DRAINED
}
/** The current mode for cleaning connections in the pool */
private CleanMode cleanMode = CleanMode.NORMAL;
// A scheduled drainModeRunnable keeps a reference to the enclosing ConnectionPool,
// preventing the ConnectionPool from being garbage collected before all held connections have
// been explicitly closed. If this was not the case any open connections in the pool would trigger
// StrictMode violations in Android when they were garbage collected. http://b/18369687
private final Runnable drainModeRunnable = new Runnable() {
@Override public void run() {
// Close any connections we can.
connectionsCleanupRunnable.run();
synchronized (ConnectionPool.this) {
// See whether we should continue checking the connection pool.
if (connections.size() > 0) {
// Pause to avoid checking too regularly, which would drain the battery on mobile
// devices. The wait() surrenders the pool monitor and will not block other calls.
try {
// Use the keep alive duration as a rough indicator of a good check interval.
long keepAliveDurationMillis = keepAliveDurationNs / (1000 * 1000);
ConnectionPool.this.wait(keepAliveDurationMillis);
} catch (InterruptedException e) {
// Ignored.
}
// Reschedule "this" to perform another clean-up.
executorService.execute(this);
} else {
cleanMode = CleanMode.DRAINED;
}
}
}
};
private final Runnable connectionsCleanupRunnable = new Runnable() {
@Override public void run() {
List<Connection> expiredConnections = new ArrayList<Connection>(MAX_CONNECTIONS_TO_CLEANUP);
int idleConnectionCount = 0;
synchronized (ConnectionPool.this) {
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious(); ) {
Connection connection = i.previous();
if (!connection.isAlive() || connection.isExpired(keepAliveDurationNs)) {
i.remove();
expiredConnections.add(connection);
if (expiredConnections.size() == MAX_CONNECTIONS_TO_CLEANUP) break;
} else if (connection.isIdle()) {
idleConnectionCount++;
}
}
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious() && idleConnectionCount > maxIdleConnections; ) {
Connection connection = i.previous();
if (connection.isIdle()) {
expiredConnections.add(connection);
i.remove();
--idleConnectionCount;
}
}
}
for (Connection expiredConnection : expiredConnections) {
Util.closeQuietly(expiredConnection);
}
}
};
public ConnectionPool(int maxIdleConnections, long keepAliveDurationMs) {
this.maxIdleConnections = maxIdleConnections;
this.keepAliveDurationNs = keepAliveDurationMs * 1000 * 1000;
}
/**
* Returns a snapshot of the connections in this pool, ordered from newest to
* oldest. Waits for the cleanup callable to run if it is currently scheduled.
* Only use in tests.
*/
List<Connection> getConnections() {
waitForCleanupCallableToRun();
synchronized (this) {
return new ArrayList<Connection>(connections);
}
}
/**
* Blocks until the executor service has processed all currently enqueued
* jobs.
*/
private void waitForCleanupCallableToRun() {
try {
executorService.submit(new Runnable() {
@Override public void run() {
}
}).get();
} catch (Exception e) {
throw new AssertionError();
}
}
public static ConnectionPool getDefault() {
return systemDefault;
}
/** Returns total number of connections in the pool. */
public synchronized int getConnectionCount() {
return connections.size();
}
/** Returns total number of spdy connections in the pool. */
public synchronized int getSpdyConnectionCount() {
int total = 0;
for (Connection connection : connections) {
if (connection.isSpdy()) total++;
}
return total;
}
/** Returns total number of http connections in the pool. */
public synchronized int getHttpConnectionCount() {
int total = 0;
for (Connection connection : connections) {
if (!connection.isSpdy()) total++;
}
return total;
}
/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
public synchronized Connection get(Address address) {
Connection foundConnection = null;
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious(); ) {
Connection connection = i.previous();
if (!connection.getRoute().getAddress().equals(address)
|| !connection.isAlive()
|| System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
continue;
}
i.remove();
if (!connection.isSpdy()) {
try {
Platform.get().tagSocket(connection.getSocket());
} catch (SocketException e) {
Util.closeQuietly(connection);
// When unable to tag, skip recycling and close
Platform.get().logW("Unable to tagSocket(): " + e);
continue;
}
}
foundConnection = connection;
break;
}
if (foundConnection != null && foundConnection.isSpdy()) {
connections.addFirst(foundConnection); // Add it back after iteration.
}
scheduleCleanupAsRequired();
return foundConnection;
}
/**
* Gives {@code connection} to the pool. The pool may store the connection,
* or close it, as its policy describes.
*
* <p>It is an error to use {@code connection} after calling this method.
*/
public void recycle(Connection connection) {
if (connection.isSpdy()) {
return;
}
if (!connection.clearOwner()) {
return; // This connection isn't eligible for reuse.
}
if (!connection.isAlive()) {
Util.closeQuietly(connection);
return;
}
try {
Platform.get().untagSocket(connection.getSocket());
} catch (SocketException e) {
// When unable to remove tagging, skip recycling and close.
Platform.get().logW("Unable to untagSocket(): " + e);
Util.closeQuietly(connection);
return;
}
synchronized (this) {
connections.addFirst(connection);
connection.incrementRecycleCount();
connection.resetIdleStartTime();
scheduleCleanupAsRequired();
}
}
/**
* Shares the SPDY connection with the pool. Callers to this method may
* continue to use {@code connection}.
*/
public void share(Connection connection) {
if (!connection.isSpdy()) throw new IllegalArgumentException();
if (connection.isAlive()) {
synchronized (this) {
connections.addFirst(connection);
scheduleCleanupAsRequired();
}
}
}
/** Close and remove all connections in the pool. */
public void evictAll() {
List<Connection> connections;
synchronized (this) {
connections = new ArrayList<Connection>(this.connections);
this.connections.clear();
}
for (int i = 0, size = connections.size(); i < size; i++) {
Util.closeQuietly(connections.get(i));
}
}
/**
* A less abrupt way of draining the pool than {@link #evictAll()}. For use when the pool
* may still be referenced by active shared connections which cannot safely be closed.
*/
public void enterDrainMode() {
synchronized(this) {
cleanMode = CleanMode.DRAINING;
executorService.execute(drainModeRunnable);
}
}
public boolean isDrained() {
synchronized(this) {
return cleanMode == CleanMode.DRAINED;
}
}
// Callers must synchronize on "this".
private void scheduleCleanupAsRequired() {
switch (cleanMode) {
case NORMAL:
executorService.execute(connectionsCleanupRunnable);
break;
case DRAINING:
// Do nothing -drainModeRunnable is already scheduled, and will reschedules itself as
// needed.
break;
case DRAINED:
// A new connection has potentially been offered up to a drained pool. Restart the drain.
cleanMode = CleanMode.DRAINING;
executorService.execute(drainModeRunnable);
break;
}
}
}
| okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.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 com.squareup.okhttp;
import com.squareup.okhttp.internal.Platform;
import com.squareup.okhttp.internal.Util;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP
* requests that share the same {@link com.squareup.okhttp.Address} may share a
* {@link com.squareup.okhttp.Connection}. This class implements the policy of
* which connections to keep open for future use.
*
* <p>The {@link #getDefault() system-wide default} uses system properties for
* tuning parameters:
* <ul>
* <li>{@code http.keepAlive} true if HTTP and SPDY connections should be
* pooled at all. Default is true.
* <li>{@code http.maxConnections} maximum number of idle connections to
* each to keep in the pool. Default is 5.
* <li>{@code http.keepAliveDuration} Time in milliseconds to keep the
* connection alive in the pool before closing it. Default is 5 minutes.
* This property isn't used by {@code HttpURLConnection}.
* </ul>
*
* <p>The default instance <i>doesn't</i> adjust its configuration as system
* properties are changed. This assumes that the applications that set these
* parameters do so before making HTTP connections, and that this class is
* initialized lazily.
*/
public class ConnectionPool {
private static final int MAX_CONNECTIONS_TO_CLEANUP = 2;
private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min
private static final ConnectionPool systemDefault;
static {
String keepAlive = System.getProperty("http.keepAlive");
String keepAliveDuration = System.getProperty("http.keepAliveDuration");
String maxIdleConnections = System.getProperty("http.maxConnections");
long keepAliveDurationMs = keepAliveDuration != null ? Long.parseLong(keepAliveDuration)
: DEFAULT_KEEP_ALIVE_DURATION_MS;
if (keepAlive != null && !Boolean.parseBoolean(keepAlive)) {
systemDefault = new ConnectionPool(0, keepAliveDurationMs);
} else if (maxIdleConnections != null) {
systemDefault = new ConnectionPool(Integer.parseInt(maxIdleConnections), keepAliveDurationMs);
} else {
systemDefault = new ConnectionPool(5, keepAliveDurationMs);
}
}
/** The maximum number of idle connections for each address. */
private final int maxIdleConnections;
private final long keepAliveDurationNs;
private final LinkedList<Connection> connections = new LinkedList<Connection>();
/** We use a single background thread to cleanup expired connections. */
private final ExecutorService executorService = new ThreadPoolExecutor(0, 1,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
Util.threadFactory("OkHttp ConnectionPool", true));
private enum CleanMode {
/**
* Connection clean up is driven by usage of the pool. Each usage of the pool can schedule a
* clean up. A pool left in this state and unused may contain idle connections indefinitely.
*/
NORMAL,
/**
* Entered when a pool as been orphaned and is not expected to receive more usage, except for
* references held by existing connections. See {@link #enterDrainMode()}.
* A thread runs periodically to close idle connections in the pool until the pool is empty and
* then the state moves to {@link #DRAINED}.
*/
DRAINING,
/**
* The pool is empty and no clean-up is taking place. Connections may still be added to the
* pool due to latent references to the pool, in which case the pool re-enters
* {@link #DRAINING}. If the pool is DRAINED and no longer referenced it is safe to be garbage
* collected.
*/
DRAINED
}
/** The current mode for cleaning connections in the pool */
private CleanMode cleanMode = CleanMode.NORMAL;
// A scheduled drainModeRunnable keeps a reference to the enclosing ConnectionPool,
// preventing the ConnectionPool from being garbage collected before all held connections have
// been explicitly closed. If this was not the case any open connections in the pool would trigger
// StrictMode violations in Android when they were garbage collected. http://b/18369687
private final Runnable drainModeRunnable = new Runnable() {
@Override public void run() {
// Close any connections we can.
connectionsCleanupRunnable.run();
synchronized (ConnectionPool.this) {
// See whether we should continue checking the connection pool.
if (connections.size() > 0) {
// Pause to avoid checking too regularly, which would drain the battery on mobile
// devices. The wait() surrenders the pool monitor and will not block other calls.
try {
// Use the keep alive duration as a rough indicator of a good check interval.
long keepAliveDurationMillis = keepAliveDurationNs / (1000 * 1000);
ConnectionPool.this.wait(keepAliveDurationMillis);
} catch (InterruptedException e) {
// Ignored.
}
// Reschedule "this" to perform another clean-up.
executorService.execute(this);
} else {
cleanMode = CleanMode.DRAINED;
}
}
}
};
private final Runnable connectionsCleanupRunnable = new Runnable() {
@Override public void run() {
List<Connection> expiredConnections = new ArrayList<Connection>(MAX_CONNECTIONS_TO_CLEANUP);
int idleConnectionCount = 0;
synchronized (ConnectionPool.this) {
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious(); ) {
Connection connection = i.previous();
if (!connection.isAlive() || connection.isExpired(keepAliveDurationNs)) {
i.remove();
expiredConnections.add(connection);
if (expiredConnections.size() == MAX_CONNECTIONS_TO_CLEANUP) break;
} else if (connection.isIdle()) {
idleConnectionCount++;
}
}
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious() && idleConnectionCount > maxIdleConnections; ) {
Connection connection = i.previous();
if (connection.isIdle()) {
expiredConnections.add(connection);
i.remove();
--idleConnectionCount;
}
}
}
for (Connection expiredConnection : expiredConnections) {
Util.closeQuietly(expiredConnection);
}
}
};
public ConnectionPool(int maxIdleConnections, long keepAliveDurationMs) {
this.maxIdleConnections = maxIdleConnections;
this.keepAliveDurationNs = keepAliveDurationMs * 1000 * 1000;
}
/**
* Returns a snapshot of the connections in this pool, ordered from newest to
* oldest. Waits for the cleanup callable to run if it is currently scheduled.
* Only use in tests.
*/
List<Connection> getConnections() {
waitForCleanupCallableToRun();
synchronized (this) {
return new ArrayList<Connection>(connections);
}
}
/**
* Blocks until the executor service has processed all currently enqueued
* jobs.
*/
private void waitForCleanupCallableToRun() {
try {
executorService.submit(new Runnable() {
@Override public void run() {
}
}).get();
} catch (Exception e) {
throw new AssertionError();
}
}
public static ConnectionPool getDefault() {
return systemDefault;
}
/** Returns total number of connections in the pool. */
public synchronized int getConnectionCount() {
return connections.size();
}
/** Returns total number of spdy connections in the pool. */
public synchronized int getSpdyConnectionCount() {
int total = 0;
for (Connection connection : connections) {
if (connection.isSpdy()) total++;
}
return total;
}
/** Returns total number of http connections in the pool. */
public synchronized int getHttpConnectionCount() {
int total = 0;
for (Connection connection : connections) {
if (!connection.isSpdy()) total++;
}
return total;
}
/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
public synchronized Connection get(Address address) {
Connection foundConnection = null;
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious(); ) {
Connection connection = i.previous();
if (!connection.getRoute().getAddress().equals(address)
|| !connection.isAlive()
|| System.nanoTime() - connection.getIdleStartTimeNs() >= keepAliveDurationNs) {
continue;
}
i.remove();
if (!connection.isSpdy()) {
try {
Platform.get().tagSocket(connection.getSocket());
} catch (SocketException e) {
Util.closeQuietly(connection);
// When unable to tag, skip recycling and close
Platform.get().logW("Unable to tagSocket(): " + e);
continue;
}
}
foundConnection = connection;
break;
}
if (foundConnection != null && foundConnection.isSpdy()) {
connections.addFirst(foundConnection); // Add it back after iteration.
}
scheduleCleanupAsRequired();
return foundConnection;
}
/**
* Gives {@code connection} to the pool. The pool may store the connection,
* or close it, as its policy describes.
*
* <p>It is an error to use {@code connection} after calling this method.
*/
public void recycle(Connection connection) {
if (connection.isSpdy()) {
return;
}
if (!connection.clearOwner()) {
return; // This connection isn't eligible for reuse.
}
if (!connection.isAlive()) {
Util.closeQuietly(connection);
return;
}
try {
Platform.get().untagSocket(connection.getSocket());
} catch (SocketException e) {
// When unable to remove tagging, skip recycling and close.
Platform.get().logW("Unable to untagSocket(): " + e);
Util.closeQuietly(connection);
return;
}
synchronized (this) {
connections.addFirst(connection);
connection.incrementRecycleCount();
connection.resetIdleStartTime();
scheduleCleanupAsRequired();
}
}
/**
* Shares the SPDY connection with the pool. Callers to this method may
* continue to use {@code connection}.
*/
public void share(Connection connection) {
if (!connection.isSpdy()) throw new IllegalArgumentException();
if (connection.isAlive()) {
synchronized (this) {
connections.addFirst(connection);
scheduleCleanupAsRequired();
}
}
}
/** Close and remove all connections in the pool. */
public void evictAll() {
List<Connection> connections;
synchronized (this) {
connections = new ArrayList<Connection>(this.connections);
this.connections.clear();
}
for (int i = 0, size = connections.size(); i < size; i++) {
Util.closeQuietly(connections.get(i));
}
}
/**
* A less abrupt way of draining the pool than {@link #evictAll()}. For use when the pool
* may still be referenced by active shared connections which cannot safely be closed.
*/
public void enterDrainMode() {
synchronized(this) {
cleanMode = CleanMode.DRAINING;
executorService.execute(drainModeRunnable);
}
}
public boolean isDrained() {
synchronized(this) {
return cleanMode == CleanMode.DRAINED;
}
}
// Callers must synchronize on "this" for the cleanMode check to be reliable.
private void scheduleCleanupAsRequired() {
switch (cleanMode) {
case NORMAL:
executorService.execute(connectionsCleanupRunnable);
break;
case DRAINING:
// Do nothing -drainModeRunnable is already scheduled, and will reschedules itself as
// needed.
break;
case DRAINED:
// A new connection has potentially been offered up to a drained pool. Restart the drain.
executorService.execute(drainModeRunnable);
break;
}
}
}
| am 6257f0c1: Fixes to ConnectionPool noticed during upstream review
* commit '6257f0c1c5e6e94d446051f856207782d7188c43':
Fixes to ConnectionPool noticed during upstream review
| okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java | am 6257f0c1: Fixes to ConnectionPool noticed during upstream review |
|
Java | apache-2.0 | a87596162e1809a878636c3c91d95d6ddb83d8d2 | 0 | xfournet/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,vladmm/intellij-community,apixandru/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,clumsy/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,da1z/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,holmes/intellij-community,fitermay/intellij-community,fnouama/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,asedunov/intellij-community,kool79/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,jagguli/intellij-community,fnouama/intellij-community,caot/intellij-community,blademainer/intellij-community,izonder/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ernestp/consulo,retomerz/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,samthor/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,asedunov/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,da1z/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,signed/intellij-community,allotria/intellij-community,hurricup/intellij-community,vladmm/intellij-community,kool79/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,supersven/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,asedunov/intellij-community,holmes/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,signed/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,vladmm/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,supersven/intellij-community,fitermay/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,joewalnes/idea-community,clumsy/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,robovm/robovm-studio,robovm/robovm-studio,ol-loginov/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,izonder/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,holmes/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ernestp/consulo,supersven/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,kdwink/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,diorcety/intellij-community,semonte/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,hurricup/intellij-community,samthor/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,kool79/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,semonte/intellij-community,caot/intellij-community,amith01994/intellij-community,fnouama/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,signed/intellij-community,apixandru/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ryano144/intellij-community,signed/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ibinti/intellij-community,xfournet/intellij-community,da1z/intellij-community,apixandru/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,joewalnes/idea-community,consulo/consulo,slisson/intellij-community,samthor/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,consulo/consulo,holmes/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,samthor/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,caot/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,jagguli/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,consulo/consulo,supersven/intellij-community,amith01994/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,xfournet/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,samthor/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,semonte/intellij-community,ibinti/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,samthor/intellij-community,adedayo/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,da1z/intellij-community,slisson/intellij-community,dslomov/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,asedunov/intellij-community,petteyg/intellij-community,holmes/intellij-community,caot/intellij-community,ryano144/intellij-community,semonte/intellij-community,allotria/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,supersven/intellij-community,caot/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,da1z/intellij-community,diorcety/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,apixandru/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,xfournet/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,dslomov/intellij-community,supersven/intellij-community,allotria/intellij-community,joewalnes/idea-community,vladmm/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,semonte/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,signed/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,allotria/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,holmes/intellij-community,hurricup/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,xfournet/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,apixandru/intellij-community,fitermay/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,semonte/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,fitermay/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ernestp/consulo,slisson/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,izonder/intellij-community,kdwink/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,joewalnes/idea-community,caot/intellij-community,suncycheng/intellij-community,caot/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,supersven/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,da1z/intellij-community,supersven/intellij-community,ibinti/intellij-community,adedayo/intellij-community,clumsy/intellij-community,robovm/robovm-studio,fitermay/intellij-community,hurricup/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,samthor/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,izonder/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,consulo/consulo,TangHao1987/intellij-community,adedayo/intellij-community,samthor/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,FHannes/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,signed/intellij-community,petteyg/intellij-community,diorcety/intellij-community,hurricup/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,signed/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,allotria/intellij-community,fitermay/intellij-community,allotria/intellij-community,adedayo/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ibinti/intellij-community,joewalnes/idea-community,apixandru/intellij-community,jagguli/intellij-community,kool79/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,izonder/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,slisson/intellij-community,youdonghai/intellij-community,allotria/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,signed/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,holmes/intellij-community,ibinti/intellij-community,slisson/intellij-community,semonte/intellij-community,kdwink/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,consulo/consulo,xfournet/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,kool79/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,allotria/intellij-community,amith01994/intellij-community,petteyg/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,signed/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,da1z/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.xml.util;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.impl.include.FileIncludeInfo;
import com.intellij.psi.impl.include.FileIncludeProvider;
import com.intellij.util.indexing.FileContent;
import com.intellij.util.xml.NanoXmlUtil;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
/**
* @author Dmitry Avdeev
*/
public class XIncludeProvider extends FileIncludeProvider {
@NotNull
@Override
public String getId() {
return "XInclude";
}
@Override
public boolean acceptFile(VirtualFile file) {
FileType fileType = file.getFileType();
return fileType == XmlFileType.INSTANCE && !ProjectUtil.isProjectOrWorkspaceFile(file, fileType);
}
@NotNull
@Override
public FileIncludeInfo[] getIncludeInfos(FileContent content) {
final ArrayList<FileIncludeInfo> infos = new ArrayList<FileIncludeInfo>();
NanoXmlUtil.parse(new ByteArrayInputStream(content.getContent()), new NanoXmlUtil.IXMLBuilderAdapter() {
boolean isXInclude;
@Override
public void startElement(String name, String nsPrefix, String nsURI, String systemID, int lineNr) throws Exception {
isXInclude = XmlUtil.XINCLUDE_URI.equals(nsURI) && "include".equals(name);
}
@Override
public void addAttribute(String key, String nsPrefix, String nsURI, String value, String type) throws Exception {
if (isXInclude && "href".equals(key)) {
infos.add(new FileIncludeInfo(value));
}
}
@Override
public void endElement(String name, String nsPrefix, String nsURI) throws Exception {
isXInclude = false;
}
});
return infos.toArray(new FileIncludeInfo[infos.size()]);
}
}
| xml/impl/src/com/intellij/xml/util/XIncludeProvider.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.xml.util;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.impl.include.FileIncludeInfo;
import com.intellij.psi.impl.include.FileIncludeProvider;
import com.intellij.util.indexing.FileContent;
import com.intellij.util.xml.NanoXmlUtil;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
/**
* @author Dmitry Avdeev
*/
public class XIncludeProvider extends FileIncludeProvider {
@NotNull
@Override
public String getId() {
return "XInclude";
}
@Override
public boolean acceptFile(VirtualFile file) {
return file.getFileType() == XmlFileType.INSTANCE;
}
@NotNull
@Override
public FileIncludeInfo[] getIncludeInfos(FileContent content) {
final ArrayList<FileIncludeInfo> infos = new ArrayList<FileIncludeInfo>();
NanoXmlUtil.parse(new ByteArrayInputStream(content.getContent()), new NanoXmlUtil.IXMLBuilderAdapter() {
boolean isXInclude;
@Override
public void startElement(String name, String nsPrefix, String nsURI, String systemID, int lineNr) throws Exception {
isXInclude = XmlUtil.XINCLUDE_URI.equals(nsURI) && "include".equals(name);
}
@Override
public void addAttribute(String key, String nsPrefix, String nsURI, String value, String type) throws Exception {
if (isXInclude && "href".equals(key)) {
infos.add(new FileIncludeInfo(value));
}
}
@Override
public void endElement(String name, String nsPrefix, String nsURI) throws Exception {
isXInclude = false;
}
});
return infos.toArray(new FileIncludeInfo[infos.size()]);
}
}
| project files skipped
| xml/impl/src/com/intellij/xml/util/XIncludeProvider.java | project files skipped |
|
Java | apache-2.0 | 2d31befdabb405abe513678f9341f0f3baf78b76 | 0 | huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,dmmiller612/deeplearning4j,dmmiller612/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,dmmiller612/deeplearning4j,dmmiller612/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j | package org.deeplearning4j.models.embeddings.learning.impl.elements;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.embeddings.learning.ElementsLearningAlgorithm;
import org.deeplearning4j.models.embeddings.loader.VectorsConfiguration;
import org.deeplearning4j.models.sequencevectors.interfaces.SequenceIterator;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.nd4j.linalg.api.ops.aggregates.Aggregate;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.util.DeviceLocalNDArray;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**
* Skip-Gram implementation for dl4j SequenceVectors
*
* @author [email protected]
*/
@Slf4j
public class SkipGram<T extends SequenceElement> implements ElementsLearningAlgorithm<T> {
protected VocabCache<T> vocabCache;
protected WeightLookupTable<T> lookupTable;
protected VectorsConfiguration configuration;
protected int window;
protected boolean useAdaGrad;
protected double negative;
protected double sampling;
protected int[] variableWindows;
protected int vectorLength;
protected DeviceLocalNDArray syn0, syn1, syn1Neg, table, expTable;
protected ThreadLocal<List<Aggregate>> batches = new ThreadLocal<>();
/**
* Dummy construction is required for reflection
*/
public SkipGram() {
}
/**
* Returns implementation code name
*
* @return
*/
@Override
public String getCodeName() {
return "SkipGram";
}
/**
* SkipGram initialization over given vocabulary and WeightLookupTable
*
* @param vocabCache
* @param lookupTable
* @param configuration
*/
@Override
public void configure(@NonNull VocabCache<T> vocabCache, @NonNull WeightLookupTable<T> lookupTable, @NonNull VectorsConfiguration configuration) {
this.vocabCache = vocabCache;
this.lookupTable = lookupTable;
this.configuration = configuration;
this.expTable = new DeviceLocalNDArray(Nd4j.create(((InMemoryLookupTable<T>) lookupTable).getExpTable()));
this.syn0 = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn0());
this.syn1 = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1());
this.syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
this.table = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getTable());
this.window = configuration.getWindow();
this.useAdaGrad = configuration.isUseAdaGrad();
this.negative = configuration.getNegative();
this.sampling = configuration.getSampling();
this.variableWindows = configuration.getVariableWindows();
this.vectorLength = configuration.getLayersSize();
}
/**
* SkipGram doesn't involves any pretraining
*
* @param iterator
*/
@Override
public void pretrain(SequenceIterator<T> iterator) {
// no-op
}
public Sequence<T> applySubsampling(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom) {
Sequence<T> result = new Sequence<>();
// subsampling implementation, if subsampling threshold met, just continue to next element
if (sampling > 0) {
result.setSequenceId(sequence.getSequenceId());
if (sequence.getSequenceLabels() != null) result.setSequenceLabels(sequence.getSequenceLabels());
if (sequence.getSequenceLabel() != null) result.setSequenceLabel(sequence.getSequenceLabel());
for (T element : sequence.getElements()) {
double numWords = vocabCache.totalWordOccurrences();
double ran = (Math.sqrt(element.getElementFrequency() / (sampling * numWords)) + 1) * (sampling * numWords) / element.getElementFrequency();
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
if (ran < (nextRandom.get() & 0xFFFF) / (double) 65536) {
continue;
}
result.addElement(element);
}
return result;
} else return sequence;
}
/**
* Learns sequence using SkipGram algorithm
*
* @param sequence
* @param nextRandom
* @param learningRate
*/
@Override
public double learnSequence(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom, double learningRate) {
Sequence<T> tempSequence = sequence;
if (sampling > 0) tempSequence = applySubsampling(sequence, nextRandom);
double score = 0.0;
int currentWindow = window;
if (variableWindows != null && variableWindows.length != 0) {
currentWindow = variableWindows[RandomUtils.nextInt(variableWindows.length)];
}
for(int i = 0; i < tempSequence.getElements().size(); i++) {
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
score = skipGram(i, tempSequence.getElements(), (int) nextRandom.get() % currentWindow ,nextRandom, learningRate, currentWindow);
}
if (batches.get().size() >= configuration.getBatchSize()){
Nd4j.getExecutioner().exec(batches.get());
batches.get().clear();
}
return score;
}
@Override
public void finish() {
if (batches.get().size() > 0){
Nd4j.getExecutioner().exec(batches.get());
batches.get().clear();
}
}
/**
* SkipGram has no reasons for early termination ever.
*
* @return
*/
@Override
public boolean isEarlyTerminationHit() {
return false;
}
private double skipGram(int i, List<T> sentence, int b, AtomicLong nextRandom, double alpha, int currentWindow) {
final T word = sentence.get(i);
if(word == null || sentence.isEmpty())
return 0.0;
double score = 0.0;
int cnt = 0;
int end = currentWindow * 2 + 1 - b;
for(int a = b; a < end; a++) {
if(a != currentWindow) {
int c = i - currentWindow + a;
if(c >= 0 && c < sentence.size()) {
T lastWord = sentence.get(c);
score = iterateSample(word,lastWord,nextRandom,alpha);
}
}
}
return score;
}
public double iterateSample(T w1, T lastWord, AtomicLong nextRandom,double alpha) {
if(w1 == null || lastWord == null || lastWord.getIndex() < 0 || w1.getIndex() == lastWord.getIndex() || w1.getLabel().equals("STOP") || lastWord.getLabel().equals("STOP") || w1.getLabel().equals("UNK") || lastWord.getLabel().equals("UNK"))
return 0.0;
double score = 0.0;
int [] idxSyn1 = null;
int [] codes = null;
if (configuration.isUseHierarchicSoftmax()) {
idxSyn1 = new int[w1.getCodeLength()];
codes = new int[w1.getCodeLength()];
for (int i = 0; i < w1.getCodeLength(); i++) {
int code = w1.getCodes().get(i);
int point = w1.getPoints().get(i);
if (point >= vocabCache.numWords() || point < 0)
throw new IllegalStateException("Illegal point " + point);
codes[i] = code;
idxSyn1[i] = point;
}
} else {
idxSyn1 = new int[0];
codes = new int[0];
}
int target = w1.getIndex();
//negative sampling
if(negative > 0) {
if (syn1Neg == null) {
((InMemoryLookupTable<T>) lookupTable).initNegative();
syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
}
}
if (batches.get() == null)
batches.set(new ArrayList<Aggregate>());
org.nd4j.linalg.api.ops.aggregates.impl.SkipGram sg = new org.nd4j.linalg.api.ops.aggregates.impl.SkipGram(syn0.get(), syn1.get(), syn1Neg.get(), expTable.get(), table.get(), lastWord.getIndex(), idxSyn1, codes, (int) negative, target, vectorLength, alpha, nextRandom.get(), vocabCache.numWords());
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
batches.get().add(sg);
return score;
}
}
| deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/learning/impl/elements/SkipGram.java | package org.deeplearning4j.models.embeddings.learning.impl.elements;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable;
import org.deeplearning4j.models.embeddings.learning.ElementsLearningAlgorithm;
import org.deeplearning4j.models.embeddings.loader.VectorsConfiguration;
import org.deeplearning4j.models.sequencevectors.interfaces.SequenceIterator;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.nd4j.linalg.api.ops.aggregates.Aggregate;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.util.DeviceLocalNDArray;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**
* Skip-Gram implementation for dl4j SequenceVectors
*
* @author [email protected]
*/
@Slf4j
public class SkipGram<T extends SequenceElement> implements ElementsLearningAlgorithm<T> {
protected VocabCache<T> vocabCache;
protected WeightLookupTable<T> lookupTable;
protected VectorsConfiguration configuration;
protected int window;
protected boolean useAdaGrad;
protected double negative;
protected double sampling;
protected int[] variableWindows;
protected int vectorLength;
protected DeviceLocalNDArray syn0, syn1, syn1Neg, table, expTable;
protected ThreadLocal<List<Aggregate>> batches = new ThreadLocal<>();
/**
* Dummy construction is required for reflection
*/
public SkipGram() {
}
/**
* Returns implementation code name
*
* @return
*/
@Override
public String getCodeName() {
return "SkipGram";
}
/**
* SkipGram initialization over given vocabulary and WeightLookupTable
*
* @param vocabCache
* @param lookupTable
* @param configuration
*/
@Override
public void configure(@NonNull VocabCache<T> vocabCache, @NonNull WeightLookupTable<T> lookupTable, @NonNull VectorsConfiguration configuration) {
this.vocabCache = vocabCache;
this.lookupTable = lookupTable;
this.configuration = configuration;
this.expTable = new DeviceLocalNDArray(Nd4j.create(((InMemoryLookupTable<T>) lookupTable).getExpTable()));
this.syn0 = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn0());
this.syn1 = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1());
this.syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
this.table = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getTable());
this.window = configuration.getWindow();
this.useAdaGrad = configuration.isUseAdaGrad();
this.negative = configuration.getNegative();
this.sampling = configuration.getSampling();
this.variableWindows = configuration.getVariableWindows();
this.vectorLength = configuration.getLayersSize();
}
/**
* SkipGram doesn't involves any pretraining
*
* @param iterator
*/
@Override
public void pretrain(SequenceIterator<T> iterator) {
// no-op
}
public Sequence<T> applySubsampling(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom) {
Sequence<T> result = new Sequence<>();
// subsampling implementation, if subsampling threshold met, just continue to next element
if (sampling > 0) {
result.setSequenceId(sequence.getSequenceId());
if (sequence.getSequenceLabels() != null) result.setSequenceLabels(sequence.getSequenceLabels());
if (sequence.getSequenceLabel() != null) result.setSequenceLabel(sequence.getSequenceLabel());
for (T element : sequence.getElements()) {
double numWords = vocabCache.totalWordOccurrences();
double ran = (Math.sqrt(element.getElementFrequency() / (sampling * numWords)) + 1) * (sampling * numWords) / element.getElementFrequency();
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
if (ran < (nextRandom.get() & 0xFFFF) / (double) 65536) {
continue;
}
result.addElement(element);
}
return result;
} else return sequence;
}
/**
* Learns sequence using SkipGram algorithm
*
* @param sequence
* @param nextRandom
* @param learningRate
*/
@Override
public double learnSequence(@NonNull Sequence<T> sequence, @NonNull AtomicLong nextRandom, double learningRate) {
Sequence<T> tempSequence = sequence;
if (sampling > 0) tempSequence = applySubsampling(sequence, nextRandom);
double score = 0.0;
int currentWindow = window;
if (variableWindows != null && variableWindows.length != 0) {
currentWindow = variableWindows[RandomUtils.nextInt(variableWindows.length)];
}
for(int i = 0; i < tempSequence.getElements().size(); i++) {
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
score = skipGram(i, tempSequence.getElements(), (int) nextRandom.get() % currentWindow ,nextRandom, learningRate, currentWindow);
}
if (batches.get().size() >= configuration.getBatchSize()){
Nd4j.getExecutioner().exec(batches.get());
batches.get().clear();
}
return score;
}
@Override
public void finish() {
if (batches.get().size() > 0){
Nd4j.getExecutioner().exec(batches.get());
batches.get().clear();
}
}
/**
* SkipGram has no reasons for early termination ever.
*
* @return
*/
@Override
public boolean isEarlyTerminationHit() {
return false;
}
private double skipGram(int i, List<T> sentence, int b, AtomicLong nextRandom, double alpha, int currentWindow) {
final T word = sentence.get(i);
if(word == null || sentence.isEmpty())
return 0.0;
double score = 0.0;
int cnt = 0;
int end = currentWindow * 2 + 1 - b;
for(int a = b; a < end; a++) {
if(a != currentWindow) {
int c = i - currentWindow + a;
if(c >= 0 && c < sentence.size()) {
T lastWord = sentence.get(c);
score = iterateSample(word,lastWord,nextRandom,alpha);
}
}
}
return score;
}
public double iterateSample(T w1, T w2,AtomicLong nextRandom,double alpha) {
if(w1 == null || w2 == null || w2.getIndex() < 0 || w1.getIndex() == w2.getIndex() || w1.getLabel().equals("STOP") || w2.getLabel().equals("STOP") || w1.getLabel().equals("UNK") || w2.getLabel().equals("UNK"))
return 0.0;
double score = 0.0;
int [] idxSyn1 = null;
int [] codes = null;
if (configuration.isUseHierarchicSoftmax()) {
idxSyn1 = new int[w1.getCodeLength()];
codes = new int[w1.getCodeLength()];
for (int i = 0; i < w1.getCodeLength(); i++) {
int code = w1.getCodes().get(i);
int point = w1.getPoints().get(i);
if (point >= vocabCache.numWords() || point < 0)
throw new IllegalStateException("Illegal point " + point);
codes[i] = code;
idxSyn1[i] = point;
}
} else {
idxSyn1 = new int[0];
codes = new int[0];
}
int target = w1.getIndex();
//negative sampling
if(negative > 0) {
if (syn1Neg == null) {
((InMemoryLookupTable<T>) lookupTable).initNegative();
syn1Neg = new DeviceLocalNDArray(((InMemoryLookupTable<T>) lookupTable).getSyn1Neg());
}
}
if (batches.get() == null)
batches.set(new ArrayList<Aggregate>());
org.nd4j.linalg.api.ops.aggregates.impl.SkipGram sg = new org.nd4j.linalg.api.ops.aggregates.impl.SkipGram(syn0.get(), syn1.get(), syn1Neg.get(), expTable.get(), table.get(), w2.getIndex(), idxSyn1, codes, (int) negative, target, vectorLength, alpha, nextRandom.get(), vocabCache.numWords());
nextRandom.set(Math.abs(nextRandom.get() * 25214903917L + 11));
batches.get().add(sg);
return score;
}
}
| new w2v integration p.4.01
Former-commit-id: 89a7077f9603dd742ae0c766d1a0aee1235e4c50 | deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/learning/impl/elements/SkipGram.java | new w2v integration p.4.01 |
|
Java | apache-2.0 | ecf01a111aec530d55ced295e444f66dee56f2ae | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import androidx.core.view.GestureDetectorCompat;
import me.devsaki.hentoid.R;
/**
* Zoned tap listener for the image viewer
*/
public class OnZoneTapListener implements View.OnTouchListener {
/**
* This view's dimensions are used to determine which zone a tap belongs to
*/
private final View view;
private final GestureDetectorCompat gestureDetector;
private final int pagerTapZoneWidth;
private Runnable onLeftZoneTapListener;
private Runnable onRightZoneTapListener;
private Runnable onMiddleZoneTapListener;
public OnZoneTapListener(View view) {
this.view = view;
Context context = view.getContext();
gestureDetector = new GestureDetectorCompat(context, new OnGestureListener());
pagerTapZoneWidth = context.getResources().getDimensionPixelSize(R.dimen.tap_zone_width);
}
public OnZoneTapListener setOnLeftZoneTapListener(Runnable onLeftZoneTapListener) {
this.onLeftZoneTapListener = onLeftZoneTapListener;
return this;
}
public OnZoneTapListener setOnRightZoneTapListener(Runnable onRightZoneTapListener) {
this.onRightZoneTapListener = onRightZoneTapListener;
return this;
}
public OnZoneTapListener setOnMiddleZoneTapListener(Runnable onMiddleZoneTapListener) {
this.onMiddleZoneTapListener = onMiddleZoneTapListener;
return this;
}
public boolean onSingleTapConfirmedAction(MotionEvent e) {
if (e.getX() < pagerTapZoneWidth && onLeftZoneTapListener != null) {
onLeftZoneTapListener.run();
} else if (e.getX() > view.getWidth() - pagerTapZoneWidth && onRightZoneTapListener != null) {
onRightZoneTapListener.run();
} else {
if (onMiddleZoneTapListener != null) onMiddleZoneTapListener.run();
else return false;
}
return true;
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class OnGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return onSingleTapConfirmedAction(e);
}
}
}
| app/src/main/java/me/devsaki/hentoid/widget/OnZoneTapListener.java | package me.devsaki.hentoid.widget;
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import androidx.core.view.GestureDetectorCompat;
import me.devsaki.hentoid.R;
/**
* Zoned tap listener for the image viewer
*/
public class OnZoneTapListener implements View.OnTouchListener {
/**
* This view's dimensions are used to determine which zone a tap belongs to
*/
private final View view;
private final GestureDetectorCompat gestureDetector;
private final int pagerTapZoneWidth;
private Runnable onLeftZoneTapListener;
private Runnable onRightZoneTapListener;
private Runnable onMiddleZoneTapListener;
public OnZoneTapListener(View view) {
this.view = view;
Context context = view.getContext();
gestureDetector = new GestureDetectorCompat(context, new OnGestureListener());
pagerTapZoneWidth = context.getResources().getDimensionPixelSize(R.dimen.tap_zone_width);
}
public OnZoneTapListener setOnLeftZoneTapListener(Runnable onLeftZoneTapListener) {
this.onLeftZoneTapListener = onLeftZoneTapListener;
return this;
}
public OnZoneTapListener setOnRightZoneTapListener(Runnable onRightZoneTapListener) {
this.onRightZoneTapListener = onRightZoneTapListener;
return this;
}
public OnZoneTapListener setOnMiddleZoneTapListener(Runnable onMiddleZoneTapListener) {
this.onMiddleZoneTapListener = onMiddleZoneTapListener;
return this;
}
public boolean onSingleTapConfirmedAction(MotionEvent e) {
if (e.getX() < pagerTapZoneWidth && onLeftZoneTapListener != null) {
onLeftZoneTapListener.run();
} else if (e.getX() > view.getWidth() - pagerTapZoneWidth && onRightZoneTapListener != null) {
onRightZoneTapListener.run();
} else {
if (onMiddleZoneTapListener != null) onMiddleZoneTapListener.run();
else return false;
}
return true;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class OnGestureListener extends GestureDetector.SimpleOnGestureListener { // TODO remove if it proves useless
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return onSingleTapConfirmedAction(e);
}
}
}
| Cleanup
| app/src/main/java/me/devsaki/hentoid/widget/OnZoneTapListener.java | Cleanup |
|
Java | apache-2.0 | 523ac934af466af36ac4a331f71d2ce46f82ed46 | 0 | cn-cerc/summer-mis,cn-cerc/summer-mis | package cn.cerc.mis.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import cn.cerc.core.ClassResource;
import cn.cerc.core.DataSet;
import cn.cerc.core.ISession;
import cn.cerc.core.Utils;
import cn.cerc.db.core.IHandle;
import cn.cerc.mis.SummerMIS;
public class CustomService implements IMultiplService, IRestful {
private static final Logger log = LoggerFactory.getLogger(CustomService.class);
private static final ClassResource res = new ClassResource(CustomService.class, SummerMIS.ID);
@Autowired
public ISystemTable systemTable;
protected DataSet dataIn = null; // request
protected DataSet dataOut = null; // response
protected String funcCode;
private String message = "";
private StringBuffer msg = null;
private String restPath;
private ISession session;
protected IHandle handle;
public CustomService init(CustomService owner, boolean refData) {
this.setHandle(owner);
if (refData) {
this.dataIn = owner.getDataIn();
this.dataOut = owner.getDataOut();
}
return this;
}
@Override
public IStatus execute(DataSet dataIn, DataSet dataOut) throws ServiceException {
this.setDataIn(dataIn);
this.setDataOut(dataOut);
if (this.funcCode == null) {
throw new RuntimeException("funcCode is null");
}
ServiceStatus ss = new ServiceStatus(false);
Class<?> self = this.getClass();
Method mt = null;
for (Method item : self.getMethods()) {
if (item.getName().equals(this.funcCode)) {
mt = item;
break;
}
}
if (mt == null) {
this.setMessage(
String.format(res.getString(1, "没有找到服务:%s.%s !"), this.getClass().getName(), this.funcCode));
ss.setMessage(this.getMessage());
ss.setResult(false);
return ss;
}
try {
long startTime = System.currentTimeMillis();
try {
// 执行具体的服务函数
if (mt.getParameterCount() == 0) {
ss.setResult((Boolean) mt.invoke(this));
ss.setMessage(this.getMessage());
return ss;
} else {
return (IStatus) mt.invoke(this, dataIn, dataOut);
}
} finally {
if (dataOut != null) {
dataOut.first();
}
long totalTime = System.currentTimeMillis() - startTime;
long timeout = 1000;
if (totalTime > timeout) {
String[] tmp = this.getClass().getName().split("\\.");
String service = tmp[tmp.length - 1] + "." + this.funcCode;
log.warn(String.format("corpNo:%s, userCode:%s, service:%s, tickCount:%s", getCorpNo(),
getUserCode(), service, totalTime));
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
Throwable err = e.getCause() != null ? e.getCause() : e;
String msg = err.getMessage() == null ? "error is null" : err.getMessage();
if ((err instanceof ServiceException)) {
this.setMessage(msg);
ss.setMessage(msg);
ss.setResult(false);
return ss;
} else {
log.error(msg, err);
this.setMessage(msg);
ss.setMessage(msg);
ss.setResult(false);
return ss;
}
}
}
@Override
public DataSet getDataIn() {
if (dataIn == null) {
dataIn = new DataSet();
}
return dataIn;
}
@Override
public DataSet getDataOut() {
if (dataOut == null) {
dataOut = new DataSet();
}
return dataOut;
}
// 需要返回的失败讯息, 且永远为 false !
public boolean fail(String text) {
this.setMessage(text);
return false;
}
@Deprecated
public StringBuffer getMsg() {
if (msg == null) {
msg = new StringBuffer(message);
}
return msg;
}
public String getMessage() {
return msg != null ? msg.toString() : message;
}
public void setMessage(String message) {
if (message == null || "".equals(message.trim())) {
return;
}
if (msg != null) {
this.msg.append(message);
} else {
this.message = message;
}
}
@Override
public String getJSON(DataSet dataOut) {
return String.format("[%s]", this.getDataOut().getJSON());
}
// 设置是否需要授权才能登入
@Override
public boolean checkSecurity(IHandle handle) {
ISession sess = handle.getSession();
return sess != null && sess.logon();
}
@Override
public String getFuncCode() {
return funcCode;
}
@Override
public void setFuncCode(String funcCode) {
this.funcCode = funcCode;
}
@Override
public String getCorpNo() {
if (handle != null)
return handle.getCorpNo();
else
return getSession().getCorpNo();
}
@Override
public String getUserCode() {
if (handle != null) {
return Utils.isNotEmpty(handle.getUserCode()) ? handle.getUserCode() : getSession().getUserCode();
} else {
return getSession().getUserCode();
}
}
@Override
public void setDataIn(DataSet dataIn) {
this.dataIn = dataIn;
}
@Override
public void setDataOut(DataSet dataOut) {
this.dataOut = dataOut;
}
@Override
public String getRestPath() {
return restPath;
}
@Override
public void setRestPath(String restPath) {
this.restPath = restPath;
}
@Override
public ISession getSession() {
return session;
}
@Override
public void setSession(ISession session) {
this.session = session;
if (handle == null)
handle = new Handle(session);
}
@Override
public void setHandle(IHandle handle) {
this.handle = handle;
if (handle != null) {
this.setSession(handle.getSession());
}
}
@Override
public IHandle getHandle() {
return this.handle;
}
}
| summer-mis/src/main/java/cn/cerc/mis/core/CustomService.java | package cn.cerc.mis.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import cn.cerc.core.ClassResource;
import cn.cerc.core.DataSet;
import cn.cerc.core.ISession;
import cn.cerc.db.core.IHandle;
import cn.cerc.mis.SummerMIS;
public class CustomService implements IMultiplService, IRestful {
private static final Logger log = LoggerFactory.getLogger(CustomService.class);
private static final ClassResource res = new ClassResource(CustomService.class, SummerMIS.ID);
@Autowired
public ISystemTable systemTable;
protected DataSet dataIn = null; // request
protected DataSet dataOut = null; // response
protected String funcCode;
private String message = "";
private StringBuffer msg = null;
private String restPath;
private ISession session;
protected IHandle handle;
public CustomService init(CustomService owner, boolean refData) {
this.setHandle(owner);
if (refData) {
this.dataIn = owner.getDataIn();
this.dataOut = owner.getDataOut();
}
return this;
}
@Override
public IStatus execute(DataSet dataIn, DataSet dataOut) throws ServiceException {
this.setDataIn(dataIn);
this.setDataOut(dataOut);
if (this.funcCode == null) {
throw new RuntimeException("funcCode is null");
}
ServiceStatus ss = new ServiceStatus(false);
Class<?> self = this.getClass();
Method mt = null;
for (Method item : self.getMethods()) {
if (item.getName().equals(this.funcCode)) {
mt = item;
break;
}
}
if (mt == null) {
this.setMessage(
String.format(res.getString(1, "没有找到服务:%s.%s !"), this.getClass().getName(), this.funcCode));
ss.setMessage(this.getMessage());
ss.setResult(false);
return ss;
}
try {
long startTime = System.currentTimeMillis();
try {
// 执行具体的服务函数
if (mt.getParameterCount() == 0) {
ss.setResult((Boolean) mt.invoke(this));
ss.setMessage(this.getMessage());
return ss;
} else {
return (IStatus) mt.invoke(this, dataIn, dataOut);
}
} finally {
if (dataOut != null) {
dataOut.first();
}
long totalTime = System.currentTimeMillis() - startTime;
long timeout = 1000;
if (totalTime > timeout) {
String[] tmp = this.getClass().getName().split("\\.");
String service = tmp[tmp.length - 1] + "." + this.funcCode;
log.warn(String.format("corpNo:%s, userCode:%s, service:%s, tickCount:%s", getCorpNo(),
getUserCode(), service, totalTime));
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
Throwable err = e.getCause() != null ? e.getCause() : e;
String msg = err.getMessage() == null ? "error is null" : err.getMessage();
if ((err instanceof ServiceException)) {
this.setMessage(msg);
ss.setMessage(msg);
ss.setResult(false);
return ss;
} else {
log.error(msg, err);
this.setMessage(msg);
ss.setMessage(msg);
ss.setResult(false);
return ss;
}
}
}
@Override
public DataSet getDataIn() {
if (dataIn == null) {
dataIn = new DataSet();
}
return dataIn;
}
@Override
public DataSet getDataOut() {
if (dataOut == null) {
dataOut = new DataSet();
}
return dataOut;
}
// 需要返回的失败讯息, 且永远为 false !
public boolean fail(String text) {
this.setMessage(text);
return false;
}
@Deprecated
public StringBuffer getMsg() {
if (msg == null) {
msg = new StringBuffer(message);
}
return msg;
}
public String getMessage() {
return msg != null ? msg.toString() : message;
}
public void setMessage(String message) {
if (message == null || "".equals(message.trim())) {
return;
}
if (msg != null) {
this.msg.append(message);
} else {
this.message = message;
}
}
@Override
public String getJSON(DataSet dataOut) {
return String.format("[%s]", this.getDataOut().getJSON());
}
// 设置是否需要授权才能登入
@Override
public boolean checkSecurity(IHandle handle) {
ISession sess = handle.getSession();
return sess != null && sess.logon();
}
@Override
public String getFuncCode() {
return funcCode;
}
@Override
public void setFuncCode(String funcCode) {
this.funcCode = funcCode;
}
@Override
public String getCorpNo() {
if (handle != null)
return handle.getCorpNo();
else
return getSession().getCorpNo();
}
@Override
public void setDataIn(DataSet dataIn) {
this.dataIn = dataIn;
}
@Override
public void setDataOut(DataSet dataOut) {
this.dataOut = dataOut;
}
@Override
public String getRestPath() {
return restPath;
}
@Override
public void setRestPath(String restPath) {
this.restPath = restPath;
}
@Override
public ISession getSession() {
return session;
}
@Override
public void setSession(ISession session) {
this.session = session;
if (handle == null)
handle = new Handle(session);
}
@Override
public void setHandle(IHandle handle) {
this.handle = handle;
if (handle != null) {
this.setSession(handle.getSession());
}
}
@Override
public IHandle getHandle() {
return this.handle;
}
}
| !4 CustomService增加getUserCode方法,优先从handle取值
| summer-mis/src/main/java/cn/cerc/mis/core/CustomService.java | !4 CustomService增加getUserCode方法,优先从handle取值 |
|
Java | apache-2.0 | 325775db9ccc185d06d2c1b95e9f9affb16bec20 | 0 | OmerMachluf/Mykeyboard,OmerMachluf/Mykeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard,AnySoftKeyboard/AnySoftKeyboard,AnySoftKeyboard/AnySoftKeyboard,AnySoftKeyboard/AnySoftKeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,AnySoftKeyboard/AnySoftKeyboard,AnySoftKeyboard/AnySoftKeyboard,OmerMachluf/Mykeyboard,OmerMachluf/Mykeyboard,OmerMachluf/Mykeyboard | package com.menny.android.anysoftkeyboard.dictionary;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.util.Log;
import com.menny.android.anysoftkeyboard.AnyKeyboardContextProvider;
import com.menny.android.anysoftkeyboard.AnySoftKeyboard;
import com.menny.android.anysoftkeyboard.AnySoftKeyboardConfiguration;
import com.menny.android.anysoftkeyboard.dictionary.ExternalDictionaryFactory.DictionaryBuilder;
public class DictionaryFactory
{
private static final String TAG = "ASK DictFctry";
private static UserDictionaryBase msUserDictionary = null;
private static final List<Dictionary> msDictionaries;
// Maps id to specific index in msDictionaries
private static final Map<String, Integer> msDictionariesById;
// Maps language to specific index in msDictionaries
private static final Map<String, Integer> msDictionariesByLanguage;
static
{
msDictionaries = new ArrayList<Dictionary>();
msDictionariesById = new HashMap<String, Integer>();
msDictionariesByLanguage = new HashMap<String, Integer>();
}
private static ContactsDictionary contactsDictionary;
private static AutoDictionary autoDictionary;
public synchronized static UserDictionaryBase createUserDictionary(AnyKeyboardContextProvider context)
{
if (msUserDictionary != null){
return msUserDictionary;
}
try
{
msUserDictionary = new AndroidUserDictionary(context);
msUserDictionary.loadDictionary();
}
catch(final Exception ex)
{
Log.w(TAG, "Failed to load 'AndroidUserDictionary' (could be that the platform does not support it). Will use fall-back dictionary. Error:"+ex.getMessage());
try {
msUserDictionary = new FallbackUserDictionary(context);
msUserDictionary.loadDictionary();
} catch (final Exception e) {
Log.e(TAG, "Failed to load failback user dictionary!");
e.printStackTrace();
}
}
return msUserDictionary;
}
public synchronized static ContactsDictionary createContactsDictionary(AnyKeyboardContextProvider context)
{
if(contactsDictionary != null){
return contactsDictionary;
}
try{
contactsDictionary = new ContactsDictionary(context);
contactsDictionary.loadDictionary();
}
catch(final Exception ex)
{
Log.w(TAG, "Failed to load 'ContactsDictionary'",ex);
}
return contactsDictionary;
}
public static boolean equals(String a, String b){
if(a == null && b == null){
return true;
}
if(a == null || b == null){
return false;
}
return a.equals(b);
}
public synchronized static AutoDictionary createAutoDictionary(AnyKeyboardContextProvider context, AnySoftKeyboard ime, String locale)
{
if(autoDictionary == null){
autoDictionary = new AutoDictionary(context, ime,locale);
return autoDictionary;
}
if(equals(autoDictionary.getLocale(),locale)){
return autoDictionary;
}
autoDictionary.close();
autoDictionary = new AutoDictionary(context, ime,locale);
return autoDictionary;
}
public synchronized static Dictionary getDictionaryByLanguage(final String language, AnyKeyboardContextProvider context){
return getDictionaryImpl(language, null, context);
}
public synchronized static Dictionary getDictionaryById(final String id, AnyKeyboardContextProvider context){
return getDictionaryImpl(null, id, context);
}
private synchronized static Dictionary getDictionaryImpl(final String language, final String id, AnyKeyboardContextProvider context)
{
final String languageFormat = language == null ? "(null)" : language;
final String idFormat = id == null ? "(null)" : id;
if (language != null && msDictionariesByLanguage.containsKey(language)) {
return msDictionaries.get(msDictionariesByLanguage.get(language));
}
if (id != null && msDictionariesById.containsKey(id)) {
return msDictionaries.get(msDictionariesById.get(id));
}
Dictionary dict = null;
try
{
if(id == null) {
if ((language == null) || (language.length() == 0 || ("none".equalsIgnoreCase(language)))) {
return null;
}
}
if(language == null) {
if ((id == null) || (id.length() == 0 || ("none".equalsIgnoreCase(id)))) {
return null;
}
}
if(id != null) {
dict = locateDictionaryByIdInFactory(id, context);
}
else if(language != null) {
dict = locateDictionaryByLanguageInFactory(language, context);
}
if (dict == null)
{
if (AnySoftKeyboardConfiguration.DEBUG)Log.d(TAG,
MessageFormat.format("Could not locate dictionary for language {0} and id {1}. Maybe it was not loaded yet (installed recently?)",
new Object[]{languageFormat, idFormat}));
ExternalDictionaryFactory.resetBuildersCache();
//trying again
if(id != null) {
dict = locateDictionaryByIdInFactory(id, context);
}
else if(language != null) {
dict = locateDictionaryByLanguageInFactory(language, context);
}
if (dict == null)
Log.w(TAG,
MessageFormat.format("Could not locate dictionary for language {0} and id {1}.",
new Object[]{languageFormat, idFormat}));
}
//checking again, cause it may have loaded the second try.
if (dict != null)
{
final Dictionary dictToLoad = dict;
final Thread loader = new Thread()
{
@Override
public void run()
{
try {
dictToLoad.loadDictionary();
} catch (final Exception e) {
Log.e(TAG, MessageFormat.format(
"Failed load dictionary for language {0} with id {1}! Will reset the map. Error:{2}",
new Object[]{languageFormat, idFormat, e.getMessage()}));
e.printStackTrace();
if(id != null) {
removeDictionaryById(id);
}else {
removeDictionaryByLanguage(language);
}
}
}
};
//a little less...
loader.setPriority(Thread.NORM_PRIORITY - 1);
loader.start();
if(id != null) {
addDictionaryById(id, dict);
}else {
addDictionaryByLanguage(language, dict);
}
}
}
catch(final Exception ex)
{
Log.e(TAG, "Failed to load main dictionary for: "+language);
ex.printStackTrace();
}
return dict;
}
private static Dictionary locateDictionaryByLanguageInFactory(final String language,
AnyKeyboardContextProvider context)
throws Exception {
Dictionary dict = null;
if (language == null)
return dict;
final ArrayList<DictionaryBuilder> allBuilders = ExternalDictionaryFactory.getAllBuilders(context.getApplicationContext());
for(DictionaryBuilder builder : allBuilders)
{
if (AnySoftKeyboardConfiguration.DEBUG){
Log.d(TAG, MessageFormat.format("Checking if builder ''{0}'' with locale ''{1}'' matches locale ''{2}''",
new Object[] {builder.getId(), builder.getLanguage(), language}));
}
if (builder.getLanguage().equalsIgnoreCase(language))
{
dict = builder.createDictionary();
break;
}
}
return dict;
}
private static Dictionary locateDictionaryByIdInFactory(final String id,
AnyKeyboardContextProvider context)
throws Exception {
Dictionary dict = null;
if (id == null)
return dict;
final ArrayList<DictionaryBuilder> allBuilders = ExternalDictionaryFactory.getAllBuilders(context.getApplicationContext());
for(DictionaryBuilder builder : allBuilders)
{
if (AnySoftKeyboardConfiguration.DEBUG){
Log.d(TAG, MessageFormat.format("Checking if builder ''{0}'' with locale ''{1}'' matches id ''{2}''",
new Object[] {builder.getId(), builder.getLanguage(), id}));
}
if (builder.getId().equalsIgnoreCase(id))
{
dict = builder.createDictionary();
break;
}
}
return dict;
}
public synchronized static void addDictionaryByLanguage(String language, Dictionary dictionary)
{
if(language == null || dictionary == null)
return;
// Add dictionary to msDictionaries, if necessary
int position = msDictionaries.indexOf(dictionary);
if(position < 0) {
msDictionaries.add(dictionary);
position = msDictionaries.size() - 1;
}
assert msDictionaries.get(position) == dictionary;
// Overwrite/Create language->dictionary mapping
msDictionariesByLanguage.put(language, position);
}
public synchronized static void addDictionaryById(String id, Dictionary dictionary)
{
if(id == null || dictionary == null)
return;
// Add dictionary to msDictionaries, if necessary
int position = msDictionaries.indexOf(dictionary);
if(position < 0) {
msDictionaries.add(dictionary);
position = msDictionaries.size() - 1;
}
assert msDictionaries.get(position) == dictionary;
// Overwrite/Create id->dictionary mapping
msDictionariesById.put(id, position);
}
public synchronized static void removeDictionaryByLanguage(String language)
{
if(language == null)
return;
if (msDictionariesByLanguage.containsKey(language))
{
final int index = msDictionariesByLanguage.get(language);
final Dictionary dict = msDictionaries.get(index);
dict.close();
msDictionaries.remove(index);
msDictionariesById.remove(language);
Collection<Integer> languageMappings = msDictionariesByLanguage.values();
// Note that changes in this collection are mapped back to the map which
// is what we want
languageMappings.remove(index);
}
}
public synchronized static void removeDictionaryById(String id)
{
if(id == null)
return;
if (msDictionariesById.containsKey(id))
{
final int index = msDictionariesById.get(id);
final Dictionary dict = msDictionaries.get(index);
dict.close();
msDictionaries.remove(index);
msDictionariesById.remove(id);
Collection<Integer> idMappings = msDictionariesById.values();
// Note that changes in this collection are mapped back to the map which
// is what we want
idMappings.remove(index);
}
}
public synchronized static void close() {
if (msUserDictionary != null) {
msUserDictionary.close();
}
for(final Dictionary dict : msDictionaries) {
dict.close();
}
msUserDictionary = null;
msDictionaries.clear();
msDictionariesById.clear();
msDictionariesByLanguage.clear();
if(contactsDictionary != null){
contactsDictionary.close();
}
}
public static void releaseAllDictionaries()
{
close();
}
public synchronized static void onLowMemory(Dictionary currentlyUsedDictionary) {
//I'll clear all dictionaries but the required.
Dictionary dictToKeep = null;
int index = msDictionaries.indexOf(currentlyUsedDictionary);
if(index >= 0) {
dictToKeep = msDictionaries.get(index);
}
String idMappingToDict = null;
String languageMappingToDict = null;
// We search first the id->dictionary mapping and
// then language->dictionary mapping.
{
Iterator<Entry<String, Integer>> idIterator = msDictionariesById.entrySet().iterator();
while(idIterator.hasNext()) {
Entry<String, Integer> value = idIterator.next();
if(value.getValue() == index) {
idMappingToDict = value.getKey();
break;
}
}
}
Iterator<Entry<String, Integer>> languageIterator = msDictionariesByLanguage.entrySet().iterator();
while(languageIterator.hasNext()) {
Entry<String, Integer> value = languageIterator.next();
if(value.getValue() == index) {
languageMappingToDict = value.getKey();
break;
}
}
assert idMappingToDict != null || languageMappingToDict != null;
msDictionaries.clear();
msDictionariesByLanguage.clear();
msDictionariesById.clear();
if (dictToKeep != null)
{
if(idMappingToDict != null){
addDictionaryById(idMappingToDict, currentlyUsedDictionary);
}
if(languageMappingToDict != null){
addDictionaryByLanguage(languageMappingToDict, currentlyUsedDictionary);
}
}
}
}
| src/com/menny/android/anysoftkeyboard/dictionary/DictionaryFactory.java | package com.menny.android.anysoftkeyboard.dictionary;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.util.Log;
import com.menny.android.anysoftkeyboard.AnyKeyboardContextProvider;
import com.menny.android.anysoftkeyboard.AnySoftKeyboard;
import com.menny.android.anysoftkeyboard.AnySoftKeyboardConfiguration;
import com.menny.android.anysoftkeyboard.dictionary.ExternalDictionaryFactory.DictionaryBuilder;
public class DictionaryFactory
{
private static final String TAG = "ASK DictFctry";
private static UserDictionaryBase msUserDictionary = null;
private static final List<Dictionary> msDictionaries;
// Maps id to specific index in msDictionaries
private static final Map<String, Integer> msDictionariesById;
// Maps language to specific index in msDictionaries
private static final Map<String, Integer> msDictionariesByLanguage;
static
{
msDictionaries = new ArrayList<Dictionary>();
msDictionariesById = new HashMap<String, Integer>();
msDictionariesByLanguage = new HashMap<String, Integer>();
}
private static ContactsDictionary contactsDictionary;
private static AutoDictionary autoDictionary;
public synchronized static UserDictionaryBase createUserDictionary(AnyKeyboardContextProvider context)
{
if (msUserDictionary != null){
return msUserDictionary;
}
try
{
msUserDictionary = new AndroidUserDictionary(context);
msUserDictionary.loadDictionary();
}
catch(final Exception ex)
{
Log.w(TAG, "Failed to load 'AndroidUserDictionary' (could be that the platform does not support it). Will use fall-back dictionary. Error:"+ex.getMessage());
try {
msUserDictionary = new FallbackUserDictionary(context);
msUserDictionary.loadDictionary();
} catch (final Exception e) {
Log.e(TAG, "Failed to load failback user dictionary!");
e.printStackTrace();
}
}
return msUserDictionary;
}
public synchronized static ContactsDictionary createContactsDictionary(AnyKeyboardContextProvider context)
{
if(contactsDictionary != null){
return contactsDictionary;
}
try{
contactsDictionary = new ContactsDictionary(context);
contactsDictionary.loadDictionary();
}
catch(final Exception ex)
{
Log.w(TAG, "Failed to load 'ContactsDictionary'",ex);
}
return contactsDictionary;
}
public synchronized static AutoDictionary createAutoDictionary(AnyKeyboardContextProvider context, AnySoftKeyboard ime, String locale)
{
if(autoDictionary == null){
autoDictionary = new AutoDictionary(context, ime,locale);
return autoDictionary;
}
if(autoDictionary.getLocale().equals(locale)){
return autoDictionary;
}
autoDictionary.close();
autoDictionary = new AutoDictionary(context, ime,locale);
return autoDictionary;
}
public synchronized static Dictionary getDictionaryByLanguage(final String language, AnyKeyboardContextProvider context){
return getDictionaryImpl(language, null, context);
}
public synchronized static Dictionary getDictionaryById(final String id, AnyKeyboardContextProvider context){
return getDictionaryImpl(null, id, context);
}
private synchronized static Dictionary getDictionaryImpl(final String language, final String id, AnyKeyboardContextProvider context)
{
final String languageFormat = language == null ? "(null)" : language;
final String idFormat = id == null ? "(null)" : id;
if (language != null && msDictionariesByLanguage.containsKey(language)) {
return msDictionaries.get(msDictionariesByLanguage.get(language));
}
if (id != null && msDictionariesById.containsKey(id)) {
return msDictionaries.get(msDictionariesById.get(id));
}
Dictionary dict = null;
try
{
if(id == null) {
if ((language == null) || (language.length() == 0 || ("none".equalsIgnoreCase(language)))) {
return null;
}
}
if(language == null) {
if ((id == null) || (id.length() == 0 || ("none".equalsIgnoreCase(id)))) {
return null;
}
}
if(id != null) {
dict = locateDictionaryByIdInFactory(id, context);
}
else if(language != null) {
dict = locateDictionaryByLanguageInFactory(language, context);
}
if (dict == null)
{
if (AnySoftKeyboardConfiguration.DEBUG)Log.d(TAG,
MessageFormat.format("Could not locate dictionary for language {0} and id {1}. Maybe it was not loaded yet (installed recently?)",
new Object[]{languageFormat, idFormat}));
ExternalDictionaryFactory.resetBuildersCache();
//trying again
if(id != null) {
dict = locateDictionaryByIdInFactory(id, context);
}
else if(language != null) {
dict = locateDictionaryByLanguageInFactory(language, context);
}
if (dict == null)
Log.w(TAG,
MessageFormat.format("Could not locate dictionary for language {0} and id {1}.",
new Object[]{languageFormat, idFormat}));
}
//checking again, cause it may have loaded the second try.
if (dict != null)
{
final Dictionary dictToLoad = dict;
final Thread loader = new Thread()
{
@Override
public void run()
{
try {
dictToLoad.loadDictionary();
} catch (final Exception e) {
Log.e(TAG, MessageFormat.format(
"Failed load dictionary for language {0} with id {1}! Will reset the map. Error:{2}",
new Object[]{languageFormat, idFormat, e.getMessage()}));
e.printStackTrace();
if(id != null) {
removeDictionaryById(id);
}else {
removeDictionaryByLanguage(language);
}
}
}
};
//a little less...
loader.setPriority(Thread.NORM_PRIORITY - 1);
loader.start();
if(id != null) {
addDictionaryById(id, dict);
}else {
addDictionaryByLanguage(language, dict);
}
}
}
catch(final Exception ex)
{
Log.e(TAG, "Failed to load main dictionary for: "+language);
ex.printStackTrace();
}
return dict;
}
private static Dictionary locateDictionaryByLanguageInFactory(final String language,
AnyKeyboardContextProvider context)
throws Exception {
Dictionary dict = null;
if (language == null)
return dict;
final ArrayList<DictionaryBuilder> allBuilders = ExternalDictionaryFactory.getAllBuilders(context.getApplicationContext());
for(DictionaryBuilder builder : allBuilders)
{
if (AnySoftKeyboardConfiguration.DEBUG){
Log.d(TAG, MessageFormat.format("Checking if builder ''{0}'' with locale ''{1}'' matches locale ''{2}''",
new Object[] {builder.getId(), builder.getLanguage(), language}));
}
if (builder.getLanguage().equalsIgnoreCase(language))
{
dict = builder.createDictionary();
break;
}
}
return dict;
}
private static Dictionary locateDictionaryByIdInFactory(final String id,
AnyKeyboardContextProvider context)
throws Exception {
Dictionary dict = null;
if (id == null)
return dict;
final ArrayList<DictionaryBuilder> allBuilders = ExternalDictionaryFactory.getAllBuilders(context.getApplicationContext());
for(DictionaryBuilder builder : allBuilders)
{
if (AnySoftKeyboardConfiguration.DEBUG){
Log.d(TAG, MessageFormat.format("Checking if builder ''{0}'' with locale ''{1}'' matches id ''{2}''",
new Object[] {builder.getId(), builder.getLanguage(), id}));
}
if (builder.getId().equalsIgnoreCase(id))
{
dict = builder.createDictionary();
break;
}
}
return dict;
}
public synchronized static void addDictionaryByLanguage(String language, Dictionary dictionary)
{
if(language == null || dictionary == null)
return;
// Add dictionary to msDictionaries, if necessary
int position = msDictionaries.indexOf(dictionary);
if(position < 0) {
msDictionaries.add(dictionary);
position = msDictionaries.size() - 1;
}
assert msDictionaries.get(position) == dictionary;
// Overwrite/Create language->dictionary mapping
msDictionariesByLanguage.put(language, position);
}
public synchronized static void addDictionaryById(String id, Dictionary dictionary)
{
if(id == null || dictionary == null)
return;
// Add dictionary to msDictionaries, if necessary
int position = msDictionaries.indexOf(dictionary);
if(position < 0) {
msDictionaries.add(dictionary);
position = msDictionaries.size() - 1;
}
assert msDictionaries.get(position) == dictionary;
// Overwrite/Create id->dictionary mapping
msDictionariesById.put(id, position);
}
public synchronized static void removeDictionaryByLanguage(String language)
{
if(language == null)
return;
if (msDictionariesByLanguage.containsKey(language))
{
final int index = msDictionariesByLanguage.get(language);
final Dictionary dict = msDictionaries.get(index);
dict.close();
msDictionaries.remove(index);
msDictionariesById.remove(language);
Collection<Integer> languageMappings = msDictionariesByLanguage.values();
// Note that changes in this collection are mapped back to the map which
// is what we want
languageMappings.remove(index);
}
}
public synchronized static void removeDictionaryById(String id)
{
if(id == null)
return;
if (msDictionariesById.containsKey(id))
{
final int index = msDictionariesById.get(id);
final Dictionary dict = msDictionaries.get(index);
dict.close();
msDictionaries.remove(index);
msDictionariesById.remove(id);
Collection<Integer> idMappings = msDictionariesById.values();
// Note that changes in this collection are mapped back to the map which
// is what we want
idMappings.remove(index);
}
}
public synchronized static void close() {
if (msUserDictionary != null) {
msUserDictionary.close();
}
for(final Dictionary dict : msDictionaries) {
dict.close();
}
msUserDictionary = null;
msDictionaries.clear();
msDictionariesById.clear();
msDictionariesByLanguage.clear();
if(contactsDictionary != null){
contactsDictionary.close();
}
}
public static void releaseAllDictionaries()
{
close();
}
public synchronized static void onLowMemory(Dictionary currentlyUsedDictionary) {
//I'll clear all dictionaries but the required.
Dictionary dictToKeep = null;
int index = msDictionaries.indexOf(currentlyUsedDictionary);
if(index >= 0) {
dictToKeep = msDictionaries.get(index);
}
String idMappingToDict = null;
String languageMappingToDict = null;
// We search first the id->dictionary mapping and
// then language->dictionary mapping.
{
Iterator<Entry<String, Integer>> idIterator = msDictionariesById.entrySet().iterator();
while(idIterator.hasNext()) {
Entry<String, Integer> value = idIterator.next();
if(value.getValue() == index) {
idMappingToDict = value.getKey();
break;
}
}
}
Iterator<Entry<String, Integer>> languageIterator = msDictionariesByLanguage.entrySet().iterator();
while(languageIterator.hasNext()) {
Entry<String, Integer> value = languageIterator.next();
if(value.getValue() == index) {
languageMappingToDict = value.getKey();
break;
}
}
assert idMappingToDict != null || languageMappingToDict != null;
msDictionaries.clear();
msDictionariesByLanguage.clear();
msDictionariesById.clear();
if (dictToKeep != null)
{
if(idMappingToDict != null){
addDictionaryById(idMappingToDict, currentlyUsedDictionary);
}
if(languageMappingToDict != null){
addDictionaryByLanguage(languageMappingToDict, currentlyUsedDictionary);
}
}
}
}
| avoid npe
| src/com/menny/android/anysoftkeyboard/dictionary/DictionaryFactory.java | avoid npe |
|
Java | apache-2.0 | 510e297f23acc581ac6cff3ec65ffd39dd274260 | 0 | SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server;
import io.spine.base.Environment;
import io.spine.server.delivery.Delivery;
import io.spine.server.delivery.UniformAcrossAllShards;
import io.spine.server.storage.StorageFactory;
import io.spine.server.storage.memory.InMemoryStorageFactory;
import io.spine.server.storage.system.SystemAwareStorageFactory;
import io.spine.server.storage.system.given.MemoizingStorageFactory;
import io.spine.server.transport.ChannelId;
import io.spine.server.transport.Publisher;
import io.spine.server.transport.Subscriber;
import io.spine.server.transport.TransportFactory;
import io.spine.server.transport.memory.InMemoryTransportFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.server.DeploymentDetector.APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE;
import static io.spine.server.DeploymentDetector.APP_ENGINE_ENVIRONMENT_PATH;
import static io.spine.server.DeploymentDetector.APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE;
import static io.spine.server.DeploymentType.APPENGINE_CLOUD;
import static io.spine.server.DeploymentType.APPENGINE_EMULATOR;
import static io.spine.server.DeploymentType.STANDALONE;
import static io.spine.testing.DisplayNames.HAVE_PARAMETERLESS_CTOR;
import static io.spine.testing.Tests.assertHasPrivateParameterlessCtor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@DisplayName("ServerEnvironment should")
class ServerEnvironmentTest {
private static final ServerEnvironment serverEnvironment = ServerEnvironment.instance();
@Test
@DisplayName(HAVE_PARAMETERLESS_CTOR)
void haveUtilityConstructor() {
assertHasPrivateParameterlessCtor(ServerEnvironment.class);
}
@Test
@DisplayName("allow to customize delivery mechanism")
void allowToCustomizeDeliveryStrategy() {
Delivery newDelivery = Delivery.newBuilder()
.setStrategy(UniformAcrossAllShards.forNumber(42))
.build();
ServerEnvironment environment = serverEnvironment;
Delivery defaultValue = environment.delivery();
environment.configureDelivery(newDelivery);
assertEquals(newDelivery, environment.delivery());
// Restore the default value.
environment.configureDelivery(defaultValue);
}
@Test
@DisplayName("tell when not running without any specific server environment")
void tellIfStandalone() {
// Tests are not run by AppEngine by default.
assertEquals(STANDALONE, serverEnvironment.deploymentType());
}
@Nested
@DisplayName("when running on App Engine cloud infrastructure")
class OnProdAppEngine extends WithAppEngineEnvironment {
OnProdAppEngine() {
super(APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE);
}
@Test
@DisplayName("obtain AppEngine environment GAE cloud infrastructure server environment")
void receivesCloudEnvironment() {
assertEquals(APPENGINE_CLOUD, serverEnvironment.deploymentType());
}
@Test
@DisplayName("cache the property value")
void cachesValue() {
assertEquals(APPENGINE_CLOUD, serverEnvironment.deploymentType());
setGaeEnvironment("Unrecognized Value");
assertEquals(APPENGINE_CLOUD, serverEnvironment.deploymentType());
}
}
@Nested
@DisplayName("when running on App Engine local server")
class OnDevAppEngine extends WithAppEngineEnvironment {
OnDevAppEngine() {
super(APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE);
}
@Test
@DisplayName("obtain AppEngine environment GAE local dev server environment")
void receivesEmulatorEnvironment() {
assertEquals(APPENGINE_EMULATOR, serverEnvironment.deploymentType());
}
}
@Nested
@DisplayName("when running with invalid App Engine environment property")
class InvalidGaeEnvironment extends WithAppEngineEnvironment {
InvalidGaeEnvironment() {
super("InvalidGaeEnvironment");
}
@Test
@DisplayName("receive STANDALONE deployment type")
void receivesStandalone() {
assertEquals(STANDALONE, serverEnvironment.deploymentType());
}
}
@Nested
@DisplayName("configure production `StorageFactory`")
class StorageFactoryConfig {
private final Environment environment = Environment.instance();
private final ServerEnvironment serverEnvironment = ServerEnvironment.instance();
@BeforeEach
void turnToProduction() {
// Ensure the server environment is clear.
serverEnvironment.reset();
environment.setToProduction();
}
@AfterEach
void backToTests() {
environment.setToTests();
serverEnvironment.reset();
}
@Test
@DisplayName("throwing an `IllegalStateException` if not configured in the Production mode")
void throwsIfNotConfigured() {
assertThrows(IllegalStateException.class, serverEnvironment::storageFactory);
}
@Test
@DisplayName("return configured `StorageFactory` when asked in Production")
void productionFactory() {
StorageFactory factory = InMemoryStorageFactory.newInstance();
serverEnvironment.useStorageFactory(factory)
.forProduction();
assertThat(((SystemAwareStorageFactory) serverEnvironment.storageFactory()).delegate())
.isEqualTo(factory);
}
@Test
@DisplayName("return `InMemoryStorageFactory` under Tests")
void testsFactory() {
environment.setToTests();
StorageFactory factory = serverEnvironment.storageFactory();
assertThat(factory)
.isInstanceOf(SystemAwareStorageFactory.class);
SystemAwareStorageFactory systemAware = (SystemAwareStorageFactory) factory;
assertThat(systemAware.delegate()).isInstanceOf(InMemoryStorageFactory.class);
}
}
@Nested
@DisplayName("configure `StorageFactory` for tests")
class TestStorageFactoryConfig {
@AfterEach
void resetEnvironment() {
serverEnvironment.reset();
}
@Test
@DisplayName("returning it when explicitly set")
void getSet() {
StorageFactory factory = new MemoizingStorageFactory();
serverEnvironment.useStorageFactory(factory)
.forTests();
assertThat(((SystemAwareStorageFactory) serverEnvironment.storageFactory()).delegate())
.isEqualTo(factory);
}
}
@Nested
@DisplayName("configure `TransportFactory` in production")
class TransportFactoryConfig {
private final Environment environment = Environment.instance();
@BeforeEach
void turnToProduction() {
// Ensure the instance is clear.
serverEnvironment.reset();
environment.setToProduction();
}
@AfterEach
void backToTests() {
environment.setToTests();
serverEnvironment.reset();
}
@Test
@DisplayName("throw an `IllegalStateException` if not configured")
void throwsIfNotConfigured() {
assertThrows(IllegalStateException.class, serverEnvironment::transportFactory);
}
@Test
@DisplayName("return configured instance in Production")
void productionValue() {
TransportFactory factory = new StubTransportFactory();
serverEnvironment.useTransportFactory(factory)
.forProduction();
assertThat(serverEnvironment.transportFactory())
.isEqualTo(factory);
}
}
@Nested
@DisplayName("configure `TransportFactory` for tests")
class TestTransportFactoryConfig {
@AfterEach
void resetEnvironment() {
serverEnvironment.reset();
}
@Test
@DisplayName("returning one when explicitly set")
void setExplicitly() {
TransportFactory factory = new StubTransportFactory();
serverEnvironment.useTransportFactory(factory)
.forTests();
assertThat(serverEnvironment.transportFactory()).isEqualTo(factory);
}
@Test
@DisplayName("returning an `InMemoryTransportFactory` when not set")
void notSet() {
Environment.instance()
.setToTests();
assertThat(serverEnvironment.transportFactory())
.isInstanceOf(InMemoryTransportFactory.class);
}
}
@Nested
@DisplayName("while closing resources")
class TestClosesResources {
private InMemoryTransportFactory transportFactory;
private MemoizingStorageFactory storageFactory;
@BeforeEach
void setup() {
transportFactory = InMemoryTransportFactory.newInstance();
storageFactory = new MemoizingStorageFactory();
}
@AfterEach
void resetEnvironment() {
serverEnvironment.reset();
}
@Test
@DisplayName("close the production transport and storage factories")
void testCloses() throws Exception {
ServerEnvironment serverEnv = ServerEnvironment.instance();
serverEnv.useTransportFactory(transportFactory)
.forProduction();
serverEnv.useStorageFactory(storageFactory)
.forProduction();
serverEnv.close();
assertThat(transportFactory.isOpen()).isFalse();
assertThat(storageFactory.isClosed()).isTrue();
}
@Test
@DisplayName("leave the testing transport and storage factories open")
void testDoesNotClose() throws Exception {
ServerEnvironment serverEnv = ServerEnvironment.instance();
serverEnv.useTransportFactory(transportFactory)
.forTests();
serverEnv.useStorageFactory(storageFactory)
.forTests();
serverEnv.close();
assertThat(transportFactory.isOpen()).isTrue();
assertThat(storageFactory.isClosed()).isFalse();
}
}
@SuppressWarnings({
"AccessOfSystemProperties" /* Testing the configuration loaded from System properties. */,
"AbstractClassWithoutAbstractMethods" /* A test base with setUp and tearDown. */
})
abstract class WithAppEngineEnvironment {
private final String targetEnvironment;
private String initialValue;
WithAppEngineEnvironment(String targetEnvironment) {
this.targetEnvironment = targetEnvironment;
}
@BeforeEach
void setUp() {
initialValue = System.getProperty(APP_ENGINE_ENVIRONMENT_PATH);
setGaeEnvironment(targetEnvironment);
serverEnvironment.reset();
}
@AfterEach
void tearDown() {
if (initialValue == null) {
System.clearProperty(APP_ENGINE_ENVIRONMENT_PATH);
} else {
setGaeEnvironment(initialValue);
}
serverEnvironment.reset();
}
void setGaeEnvironment(String value) {
System.setProperty(APP_ENGINE_ENVIRONMENT_PATH, value);
}
}
/**
* Stub implementation of {@code TransportFactory} which delegates all the calls
* to {@code InMemoryTransportFactory}.
*/
private static class StubTransportFactory implements TransportFactory {
private final TransportFactory delegate = InMemoryTransportFactory.newInstance();
@Override
public Publisher createPublisher(ChannelId id) {
return delegate.createPublisher(id);
}
@Override
public Subscriber createSubscriber(ChannelId id) {
return delegate.createSubscriber(id);
}
@Override
public boolean isOpen() {
return delegate.isOpen();
}
@Override
public void close() throws Exception {
delegate.close();
}
}
}
| server/src/test/java/io/spine/server/ServerEnvironmentTest.java | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server;
import io.spine.base.Environment;
import io.spine.server.delivery.Delivery;
import io.spine.server.delivery.UniformAcrossAllShards;
import io.spine.server.storage.StorageFactory;
import io.spine.server.storage.memory.InMemoryStorageFactory;
import io.spine.server.storage.system.SystemAwareStorageFactory;
import io.spine.server.storage.system.given.MemoizingStorageFactory;
import io.spine.server.transport.ChannelId;
import io.spine.server.transport.Publisher;
import io.spine.server.transport.Subscriber;
import io.spine.server.transport.TransportFactory;
import io.spine.server.transport.memory.InMemoryTransportFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.server.DeploymentDetector.APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE;
import static io.spine.server.DeploymentDetector.APP_ENGINE_ENVIRONMENT_PATH;
import static io.spine.server.DeploymentDetector.APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE;
import static io.spine.server.DeploymentType.APPENGINE_CLOUD;
import static io.spine.server.DeploymentType.APPENGINE_EMULATOR;
import static io.spine.server.DeploymentType.STANDALONE;
import static io.spine.testing.DisplayNames.HAVE_PARAMETERLESS_CTOR;
import static io.spine.testing.Tests.assertHasPrivateParameterlessCtor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@DisplayName("ServerEnvironment should")
class ServerEnvironmentTest {
private static final ServerEnvironment serverEnvironment = ServerEnvironment.instance();
@Test
@DisplayName(HAVE_PARAMETERLESS_CTOR)
void haveUtilityConstructor() {
assertHasPrivateParameterlessCtor(ServerEnvironment.class);
}
@Test
@DisplayName("allow to customize delivery mechanism")
void allowToCustomizeDeliveryStrategy() {
Delivery newDelivery = Delivery.newBuilder()
.setStrategy(UniformAcrossAllShards.forNumber(42))
.build();
ServerEnvironment environment = serverEnvironment;
Delivery defaultValue = environment.delivery();
environment.configureDelivery(newDelivery);
assertEquals(newDelivery, environment.delivery());
// Restore the default value.
environment.configureDelivery(defaultValue);
}
@Test
@DisplayName("tell when not running without any specific server environment")
void tellIfStandalone() {
// Tests are not run by AppEngine by default.
assertEquals(STANDALONE, serverEnvironment.deploymentType());
}
@Nested
@DisplayName("when running on App Engine cloud infrastructure")
class OnProdAppEngine extends WithAppEngineEnvironment {
OnProdAppEngine() {
super(APP_ENGINE_ENVIRONMENT_PRODUCTION_VALUE);
}
@Test
@DisplayName("obtain AppEngine environment GAE cloud infrastructure server environment")
void receivesCloudEnvironment() {
assertEquals(APPENGINE_CLOUD, serverEnvironment.deploymentType());
}
@Test
@DisplayName("cache the property value")
void cachesValue() {
assertEquals(APPENGINE_CLOUD, serverEnvironment.deploymentType());
setGaeEnvironment("Unrecognized Value");
assertEquals(APPENGINE_CLOUD, serverEnvironment.deploymentType());
}
}
@Nested
@DisplayName("when running on App Engine local server")
class OnDevAppEngine extends WithAppEngineEnvironment {
OnDevAppEngine() {
super(APP_ENGINE_ENVIRONMENT_DEVELOPMENT_VALUE);
}
@Test
@DisplayName("obtain AppEngine environment GAE local dev server environment")
void receivesEmulatorEnvironment() {
assertEquals(APPENGINE_EMULATOR, serverEnvironment.deploymentType());
}
}
@Nested
@DisplayName("when running with invalid App Engine environment property")
class InvalidGaeEnvironment extends WithAppEngineEnvironment {
InvalidGaeEnvironment() {
super("InvalidGaeEnvironment");
}
@Test
@DisplayName("receive STANDALONE deployment type")
void receivesStandalone() {
assertEquals(STANDALONE, serverEnvironment.deploymentType());
}
}
@Nested
@DisplayName("configure production `StorageFactory`")
class StorageFactoryConfig {
private final Environment environment = Environment.instance();
private final ServerEnvironment serverEnvironment = ServerEnvironment.instance();
@BeforeEach
void turnToProduction() {
// Ensure the server environment is clear.
serverEnvironment.reset();
environment.setToProduction();
}
@AfterEach
void backToTests() {
environment.setToTests();
serverEnvironment.reset();
}
@Test
@DisplayName("throwing an `IllegalStateException` if not configured in the Production mode")
void throwsIfNotConfigured() {
assertThrows(IllegalStateException.class, serverEnvironment::storageFactory);
}
@Test
@DisplayName("return configured `StorageFactory` when asked in Production")
void productionFactory() {
StorageFactory factory = InMemoryStorageFactory.newInstance();
serverEnvironment.useStorageFactory(factory)
.forProduction();
assertThat(((SystemAwareStorageFactory) serverEnvironment.storageFactory()).delegate())
.isEqualTo(factory);
}
@Test
@DisplayName("return `InMemoryStorageFactory` under Tests")
void testsFactory() {
environment.setToTests();
StorageFactory factory = serverEnvironment.storageFactory();
assertThat(factory)
.isInstanceOf(SystemAwareStorageFactory.class);
SystemAwareStorageFactory systemAware = (SystemAwareStorageFactory) factory;
assertThat(systemAware.delegate()).isInstanceOf(InMemoryStorageFactory.class);
}
}
@Nested
@DisplayName("configure `StorageFactory` for tests")
class TestStorageFactoryConfig {
@AfterEach
void resetEnvironment() {
serverEnvironment.reset();
}
@Test
@DisplayName("returning it when explicitly set")
void getSet() {
StorageFactory factory = new MemoizingStorageFactory();
serverEnvironment.useStorageFactory(factory)
.forTests();
assertThat(((SystemAwareStorageFactory) serverEnvironment.storageFactory()).delegate())
.isEqualTo(factory);
}
}
@Nested
@DisplayName("configure `TransportFactory` in production")
class TransportFactoryConfig {
private final Environment environment = Environment.instance();
@BeforeEach
void turnToProduction() {
// Ensure the instance is clear.
serverEnvironment.reset();
environment.setToProduction();
}
@AfterEach
void backToTests() {
environment.setToTests();
serverEnvironment.reset();
}
@Test
@DisplayName("throw an `IllegalStateException` if not configured")
void throwsIfNotConfigured() {
assertThrows(IllegalStateException.class, serverEnvironment::transportFactory);
}
@Test
@DisplayName("return configured instance in Production")
void productionValue() {
TransportFactory factory = new StubTransportFactory();
serverEnvironment.useTransportFactory(factory)
.forProduction();
assertThat(serverEnvironment.transportFactory())
.isEqualTo(factory);
}
}
@Nested
@DisplayName("configure `TransportFactory` for tests")
class TestTransportFactoryConfig {
@AfterEach
void resetEnvironment() {
serverEnvironment.reset();
}
@Test
@DisplayName("returning one when explicitly set")
void setExplicitly() {
TransportFactory factory = new StubTransportFactory();
serverEnvironment.useTransportFactory(factory)
.forTests();
assertThat(serverEnvironment.transportFactory()).isEqualTo(factory);
}
@Test
@DisplayName("returning an `InMemoryTransportFactory` when not set")
void notSet() {
Environment.instance()
.setToTests();
assertThat(serverEnvironment.transportFactory())
.isInstanceOf(InMemoryTransportFactory.class);
}
}
@Nested
@DisplayName("close the resources")
class TestClosesResources {
private InMemoryTransportFactory transportFactory;
private MemoizingStorageFactory storageFactory;
@BeforeEach
void setup() {
transportFactory = InMemoryTransportFactory.newInstance();
storageFactory = new MemoizingStorageFactory();
}
@AfterEach
void resetEnvironment() {
serverEnvironment.reset();
}
@Test
@DisplayName("close the transport and the storage factories")
void testCloses() throws Exception {
ServerEnvironment serverEnv = ServerEnvironment.instance();
serverEnv.useTransportFactory(transportFactory)
.forProduction();
serverEnv.useStorageFactory(storageFactory)
.forProduction();
serverEnv.close();
assertThat(transportFactory.isOpen()).isFalse();
assertThat(storageFactory.isClosed()).isTrue();
}
}
@SuppressWarnings({
"AccessOfSystemProperties" /* Testing the configuration loaded from System properties. */,
"AbstractClassWithoutAbstractMethods" /* A test base with setUp and tearDown. */
})
abstract class WithAppEngineEnvironment {
private final String targetEnvironment;
private String initialValue;
WithAppEngineEnvironment(String targetEnvironment) {
this.targetEnvironment = targetEnvironment;
}
@BeforeEach
void setUp() {
initialValue = System.getProperty(APP_ENGINE_ENVIRONMENT_PATH);
setGaeEnvironment(targetEnvironment);
serverEnvironment.reset();
}
@AfterEach
void tearDown() {
if (initialValue == null) {
System.clearProperty(APP_ENGINE_ENVIRONMENT_PATH);
} else {
setGaeEnvironment(initialValue);
}
serverEnvironment.reset();
}
void setGaeEnvironment(String value) {
System.setProperty(APP_ENGINE_ENVIRONMENT_PATH, value);
}
}
/**
* Stub implementation of {@code TransportFactory} which delegates all the calls
* to {@code InMemoryTransportFactory}.
*/
private static class StubTransportFactory implements TransportFactory {
private final TransportFactory delegate = InMemoryTransportFactory.newInstance();
@Override
public Publisher createPublisher(ChannelId id) {
return delegate.createPublisher(id);
}
@Override
public Subscriber createSubscriber(ChannelId id) {
return delegate.createSubscriber(id);
}
@Override
public boolean isOpen() {
return delegate.isOpen();
}
@Override
public void close() throws Exception {
delegate.close();
}
}
}
| Test whether the testing resources are closed on `ServerEnvironment#close`.
| server/src/test/java/io/spine/server/ServerEnvironmentTest.java | Test whether the testing resources are closed on `ServerEnvironment#close`. |
|
Java | apache-2.0 | 7685b9219dab1e483fc21f7cb13b5c03c966b999 | 0 | Esri/geoportal-server,Esri/geoportal-server,Esri/geoportal-server,Esri/geoportal-server,Esri/geoportal-server | /* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.gpt.server.csw.provider30;
import com.esri.gpt.framework.util.Val;
import com.esri.gpt.framework.xml.DomUtil;
import com.esri.gpt.server.csw.components.CswConstants;
import com.esri.gpt.server.csw.components.CswNamespaces;
import com.esri.gpt.server.csw.components.ICqlParser;
import com.esri.gpt.server.csw.components.IFilterParser;
import com.esri.gpt.server.csw.components.IOperationProvider;
import com.esri.gpt.server.csw.components.IProviderFactory;
import com.esri.gpt.server.csw.components.IQueryEvaluator;
import com.esri.gpt.server.csw.components.IResponseGenerator;
import com.esri.gpt.server.csw.components.ISortByParser;
import com.esri.gpt.server.csw.components.ISupportedValues;
import com.esri.gpt.server.csw.components.OperationContext;
import com.esri.gpt.server.csw.components.OwsException;
import com.esri.gpt.server.csw.components.ParseHelper;
import com.esri.gpt.server.csw.components.QueryOptions;
import com.esri.gpt.server.csw.components.ServiceProperties;
import com.esri.gpt.server.csw.components.SupportedValues;
import com.esri.gpt.server.csw.components.ValidationHelper;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Provides the CSW GetRecords operation.
*/
public class GetRecordsProvider implements IOperationProvider {
/** class variables ========================================================= */
/** The Logger. */
private static Logger LOGGER = Logger.getLogger(GetRecordsProvider.class.getName());
/** constructors ============================================================ */
/** Default constructor */
public GetRecordsProvider() {
super();
}
/** methods ================================================================= */
/**
* Builds an ogc:Filter node from HTTP GET parameters.
* @param namespace the namespace parameter values
* @param constraintFilter the constraint parameter value
* @throws Exception if a processing exception occurs
*/
protected Node buildFilterNode(String[] namespace, String constraintFilter) throws Exception {
// TODO GetRecordsDomBuilder had a different pattern??
// parse namespaces
// pattern: namespace=xmlns(ogc=http://www.opengis.net/ogc),xmlns(gml=http://www.opengis.net/gml)...
StringBuilder nsBuffer = new StringBuilder();
boolean hasCswUri = false;
boolean hasCswPfx = false;
String cswPfx = "";
if (namespace != null) {
for (String ns: namespace) {
ns = Val.chkStr(ns);
String nsPfx = null;
String nsUri = null;
if (ns.toLowerCase().startsWith("xmlns(")) {
ns = ns.substring(6);
if (ns.toLowerCase().endsWith(")")) {
ns = ns.substring(0,ns.length() - 1);
}
ns = Val.chkStr(ns);
if (ns.length() > 0) {
String[] pair = ns.split("=");
if (pair.length == 1) {
nsUri = Val.chkStr(pair[0]);
} else if (pair.length == 2) {
nsPfx = Val.chkStr(pair[0]);
nsUri = Val.chkStr(pair[1]);
}
}
}
if ((nsUri == null) || (nsUri.length() == 0)) {
String msg = "The namespace must follow the following pattern:";
msg += " xmlns(pfx1=uri1),xmlns(pfx2=uri2),...";
throw new OwsException(OwsException.OWSCODE_InvalidParameterValue,"namespace",msg);
} else {
if (nsUri.equals("http://www.opengis.net/cat/csw/")) {
hasCswUri = true;
if ((nsPfx != null) && (nsPfx.length() > 0)) {
hasCswPfx = true;
cswPfx = nsPfx;
}
}
nsUri = Val.escapeXml(nsUri);
if ((nsPfx == null) || (nsPfx.length() == 0)) {
nsBuffer.append(" xmlns=\"").append(nsUri).append("\"");
} else {
nsBuffer.append(" xmlns:").append(nsPfx).append("=\"").append(nsUri).append("\"");
}
}
}
}
// use ogc as the default namespace if no namespace parameter was supplied
if (nsBuffer.length() == 0) {
nsBuffer.append(" xmlns=\"http://www.opengis.net/ogc\"");
}
// build the constraint XML
StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
if (hasCswUri && hasCswPfx) {
cswPfx = cswPfx+":";
} else if (hasCswUri) {
cswPfx = "";
} else {
cswPfx = "csw:";
nsBuffer.append(" xmlns:csw=\"http://www.opengis.net/cat/csw/3.0\"");
}
sbXml.append("\r\n<").append(cswPfx).append("Constraint");
if (nsBuffer.length() > 0) {
sbXml.append(" ").append(nsBuffer);
}
sbXml.append(">");
sbXml.append("\r\n").append(constraintFilter);
sbXml.append("\r\n</").append(cswPfx).append("Constraint>");
// make the dom, find the ogc:Filter node
try {
Document dom = DomUtil.makeDomFromString(sbXml.toString(),true);
CswNamespaces ns = CswNamespaces.CSW_30;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(ns.makeNamespaceContext());
Node ndFilter = null;
Node ndConstraint = (Node)xpath.evaluate("csw:Constraint",dom,XPathConstants.NODE);
if (ndConstraint != null) {
ndFilter = (Node)xpath.evaluate("ogc:Filter",ndConstraint,XPathConstants.NODE);;
}
if (ndFilter == null) {
String msg = "The supplied constraint was not a valid ogc:Filter.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,"constraint",msg);
} else {
return ndFilter;
}
} catch (SAXException e) {
String msg = "The supplied namespace/constraint pairs were not well-formed xml: ";
msg += " "+e.toString();
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,"constraint",msg);
}
}
/**
* Builds an ogc:SortBy node from HTTP GET parameters.
* @param sortBy the sortBy parameter values
* @throws Exception if a processing exception occurs
*/
protected Node buildSortByNode(String[] sortBy) throws Exception {
// parse sort by parameters
// pattern: sortby=property1:A,property2:D...
if (sortBy != null) {
StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sbXml.append("\r\n<ogc:SortBy xmlns:ogc=\"http://www.opengis.net/ogc\">");
boolean hadProperty = false;
for (String param: sortBy) {
param = Val.chkStr(param);
String name = null;
String dir = null;
if (param.toLowerCase().endsWith(":a")) {
name = Val.chkStr(param.substring(0,param.length() - 2));
dir= "ASC";
} else if (param.toLowerCase().endsWith(":d")) {
name = Val.chkStr(param.substring(0,param.length() - 2));
dir = "DESC";
} else {
name = Val.chkStr(param);
}
if ((name == null) || (name.length() == 0)) {
// we'll ignore this condition without an exception
} else {
hadProperty = true;
sbXml.append("\r\n<ogc:SortProperty>");
sbXml.append("\r\n<ogc:PropertyName>").append(Val.escapeXml(name)).append("</ogc:PropertyName>");
if (dir != null) {
sbXml.append("\r\n<ogc:SortOrder>").append(Val.escapeXml(dir)).append("</ogc:SortOrder>");
}
sbXml.append("\r\n</ogc:SortProperty>");
}
}
sbXml.append("\r\n</ogc:SortBy>");
if (hadProperty) {
Document dom = DomUtil.makeDomFromString(sbXml.toString(),true);
NodeList nl = dom.getChildNodes();
for (int i=0; i<nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE){
return nl.item(i);
}
}
}
}
return null;
}
/**
* Executes a parsed operation request.
* @param context the operation context
* @throws Exception if a processing exception occurs
*/
public void execute(OperationContext context) throws Exception {
// initialize
LOGGER.finer("Executing csw:GetRecords request...");
IProviderFactory factory = context.getProviderFactory();
QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
// evaluate the query
IQueryEvaluator evaluator = factory.makeQueryEvaluator(context);
if (evaluator == null) {
String msg = "IProviderFactory.makeQueryEvaluator: instantiation failed.";
LOGGER.log(Level.SEVERE,msg);
throw new OwsException(msg);
} if (!qOptions.getIDs().isEmpty()) {
evaluator.evaluateIdQuery(context,qOptions.getIDs().toArray(new String[0]));
} else {
evaluator.evaluateQuery(context);
}
// generate the response
IResponseGenerator generator = factory.makeResponseGenerator(context);
if (generator == null) {
String msg = "IProviderFactory.makeResponseGenerator: instantiation failed.";
LOGGER.log(Level.SEVERE,msg);
throw new OwsException(msg);
} else {
generator.generateResponse(context);
}
}
/**
* Handles a URL based request (HTTP GET).
* @param context the operation context
* @param request the HTTP request
* @throws Exception if a processing exception occurs
*/
public void handleGet(OperationContext context, HttpServletRequest request)
throws Exception {
// initialize
LOGGER.finer("Handling csw:GetRecords request URL...");
QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
ServiceProperties svcProps = context.getServiceProperties();
ParseHelper pHelper = new ParseHelper();
ValidationHelper vHelper = new ValidationHelper();
String locator;
String[] parsed;
ISupportedValues supported;
IProviderFactory factory = context.getProviderFactory();
CswNamespaces ns = CswNamespaces.CSW_30;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(ns.makeNamespaceContext());
// service and version are parsed by the parent RequestHandler
// TODO typeNames requestId distributedSearch hopCount responseHandler
// TODO resultype validate is not applicable for a GET request?
// output format
locator = "outputFormat";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputFormat);
context.getOperationResponse().setOutputFormat(
vHelper.validateValue(supported,locator,parsed,false));
// output schema
locator = "outputSchema";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputSchema);
qOptions.setOutputSchema(vHelper.validateValue(supported,locator,parsed,false));
// record ids
locator = "recordIds";
parsed = pHelper.getParameterValues(request,locator,",");
qOptions.setIDs(vHelper.validateValues(locator,parsed,false));
// start and max records
parsed = pHelper.getParameterValues(request,"startPosition");
if ((parsed != null) && (parsed.length) > 0) {
qOptions.setStartRecord(Math.max(Val.chkInt(parsed[0],1),1));
}
parsed = pHelper.getParameterValues(request,"maxRecords");
if ((parsed != null) && (parsed.length) > 0) {
qOptions.setMaxRecords(Val.chkInt(parsed[0],10));
}
// result type
locator = "resultType";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ResultType);
qOptions.setResultType(vHelper.validateValue(supported,locator,parsed,false));
if (qOptions.getResultType() == null) {
qOptions.setResultType(CswConstants.ResultType_Results);
}
// query type names
locator = "typeNames";
parsed = pHelper.getParameterValues(request,locator);
qOptions.setQueryTypeNames(vHelper.validateValues(locator,parsed,false));
// response element set type
locator = "ElementSetName";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementSetType);
qOptions.setElementSetType(vHelper.validateValue(supported,locator,parsed,false));
// response element names
if (qOptions.getElementSetType() == null) {
// TODO supported ElementNames this for GetRecordById as well?
locator = "ElementName";
parsed = pHelper.getParameterValues(request,locator,",");
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementName);
qOptions.setElementNames(vHelper.validateValues(supported,locator,parsed,false));
}
// constraint language
locator = "constraintLanguage";
parsed = pHelper.getParameterValues(request,locator);
supported = new SupportedValues("CQL_TEXT,FILTER",",");
String constraintLanguage = vHelper.validateValue(supported,locator,parsed,false);
// constraint version
locator = "constraint_language_version";
parsed = pHelper.getParameterValues(request,locator);
String constraintVersion = vHelper.validateValue(locator,parsed,false);
qOptions.setQueryConstraintVersion(constraintVersion);
// constraint text
locator = "constraint";
parsed = pHelper.getParameterValues(request,locator);
String constraint = vHelper.validateValue(locator,parsed,false);
// csw:CqlText
if ((constraintLanguage != null) && constraintLanguage.equalsIgnoreCase("CQL_TEXT")) {
String cql = Val.chkStr(constraint);
qOptions.setQueryConstraintCql(cql);
ICqlParser parser = factory.makeCqlParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeCqlParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseCql(context,cql);
}
}
// ogc:Filter
if ((constraintLanguage == null) || constraintLanguage.equalsIgnoreCase("FILTER")) {
Node ndFilter = null;
IFilterParser parser = factory.makeFilterParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeFilterParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
}
String constraintFilter = Val.chkStr(constraint);
if (constraintFilter.length() > 0) {
String[] namespace = pHelper.getParameterValues(request,"namespace",",");
ndFilter = this.buildFilterNode(namespace,constraintFilter);
parser.parseFilter(context,ndFilter,xpath);
}
}
// ogc:SortBy
locator = "sortBy";
String[] sortBy = pHelper.getParameterValues(request,"sortBy",",");
if (sortBy != null) {
Node ndSortBy = this.buildSortByNode(sortBy);
if (ndSortBy != null) {
ISortByParser parser = factory.makeSortByParser(context);
if (parser == null) {
String msg = "IProviderFactory.makeSortByParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseSortBy(context,ndSortBy,xpath);
}
}
}
// execute the request
this.execute(context);
}
/**
* Handles an XML based request (normally HTTP POST).
* @param context the operation context
* @param root the root node
* @param xpath an XPath to enable queries (properly configured with name spaces)
* @throws Exception if a processing exception occurs
*/
public void handleXML(OperationContext context, Node root, XPath xpath)
throws Exception {
// initialize
LOGGER.finer("Handling csw:GetRecords request XML...");
QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
ServiceProperties svcProps = context.getServiceProperties();
ParseHelper pHelper = new ParseHelper();
ValidationHelper vHelper = new ValidationHelper();
String locator;
String[] parsed;
ISupportedValues supported;
IProviderFactory factory = context.getProviderFactory();
// service and version are parsed by the parent RequestHandler
// TODO requestId
// output format
locator = "@outputFormat";
parsed = pHelper.getParameterValues(root,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputFormat);
context.getOperationResponse().setOutputFormat(
vHelper.validateValue(supported,locator,parsed,false));
// output schema
locator = "@outputSchema";
parsed = pHelper.getParameterValues(root,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputSchema);
qOptions.setOutputSchema(vHelper.validateValue(supported,locator,parsed,false));
// start and max records
qOptions.setStartRecord(Math.max(Val.chkInt(xpath.evaluate("@startPosition",root),1),1));
qOptions.setMaxRecords(Val.chkInt(xpath.evaluate("@maxRecords",root),10));
// result type
locator = "@resultType";
parsed = pHelper.getParameterValues(root,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ResultType);
qOptions.setResultType(vHelper.validateValue(supported,locator,parsed,false));
if (qOptions.getResultType() == null) {
qOptions.setResultType(CswConstants.ResultType_Results);
}
// find the query node
locator = "csw:Query";
Node ndQuery = (Node)xpath.evaluate(locator,root,XPathConstants.NODE);
if (ndQuery != null) {
// query type names
locator = "csw:Query/@typeNames";
parsed = pHelper.getParameterValues(root,xpath,"@typeNames");
qOptions.setQueryTypeNames(vHelper.validateValues(locator,parsed,false));
// response element set type
locator = "csw:ElementSetName";
parsed = pHelper.getParameterValues(ndQuery,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementSetType);
qOptions.setElementSetType(vHelper.validateValue(supported,locator,parsed,false));
// response element set type names
String elementSetType = qOptions.getElementSetType();
if (elementSetType != null) {
locator = "csw:ElementSetName/@typeNames";
parsed = pHelper.getParameterValues(ndQuery,xpath,locator);
qOptions.setElementSetTypeNames(vHelper.validateValues(locator,parsed,false));
}
// response element names
if (elementSetType == null) {
// TODO supported ElementNames
locator = "csw:ElementName";
parsed = pHelper.getParameterValues(ndQuery,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementName);
qOptions.setElementNames(vHelper.validateValues(supported,locator,parsed,false));
}
// find the constraint node
Node ndConstraint = (Node)xpath.evaluate("csw:Constraint",ndQuery,XPathConstants.NODE);
if (ndConstraint != null) {
// constraint version
String constraintVersion = xpath.evaluate("@version",ndConstraint);
qOptions.setQueryConstraintVersion(constraintVersion);
// csw:CqlText
locator = "csw:CqlText";
Node ndCql = (Node)xpath.evaluate(locator,ndConstraint,XPathConstants.NODE);
if (ndCql != null) {
String cql = Val.chkStr(ndCql.getTextContent());
qOptions.setQueryConstraintCql(cql);
ICqlParser parser = factory.makeCqlParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeCqlParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseCql(context,cql);
}
} else {
// ogc:Filter
locator = "ogc:Filter";
Node ndFilter = (Node)xpath.evaluate(locator,ndConstraint,XPathConstants.NODE);
if (ndFilter != null) {
IFilterParser parser = factory.makeFilterParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeFilterParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseFilter(context,ndFilter,xpath);
}
} else {
String msg = "An OGC filter for the CSW constraint is required.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
}
}
}
// ogc:SortBy
locator = "ogc:SortBy";
Node ndSortBy = (Node)xpath.evaluate(locator,ndQuery,XPathConstants.NODE);
if (ndSortBy != null) {
ISortByParser parser = factory.makeSortByParser(context);
if (parser == null) {
String msg = "IProviderFactory.makeSortByParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseSortBy(context,ndSortBy,xpath);
}
}
}
// execute the request
this.execute(context);
}
}
| geoportal/src/com/esri/gpt/server/csw/provider30/GetRecordsProvider.java | /* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.esri.gpt.server.csw.provider30;
import com.esri.gpt.framework.util.Val;
import com.esri.gpt.framework.xml.DomUtil;
import com.esri.gpt.server.csw.components.CswConstants;
import com.esri.gpt.server.csw.components.CswNamespaces;
import com.esri.gpt.server.csw.components.ICqlParser;
import com.esri.gpt.server.csw.components.IFilterParser;
import com.esri.gpt.server.csw.components.IOperationProvider;
import com.esri.gpt.server.csw.components.IProviderFactory;
import com.esri.gpt.server.csw.components.IQueryEvaluator;
import com.esri.gpt.server.csw.components.IResponseGenerator;
import com.esri.gpt.server.csw.components.ISortByParser;
import com.esri.gpt.server.csw.components.ISupportedValues;
import com.esri.gpt.server.csw.components.OperationContext;
import com.esri.gpt.server.csw.components.OwsException;
import com.esri.gpt.server.csw.components.ParseHelper;
import com.esri.gpt.server.csw.components.QueryOptions;
import com.esri.gpt.server.csw.components.ServiceProperties;
import com.esri.gpt.server.csw.components.SupportedValues;
import com.esri.gpt.server.csw.components.ValidationHelper;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Provides the CSW GetRecords operation.
*/
public class GetRecordsProvider implements IOperationProvider {
/** class variables ========================================================= */
/** The Logger. */
private static Logger LOGGER = Logger.getLogger(GetRecordsProvider.class.getName());
/** constructors ============================================================ */
/** Default constructor */
public GetRecordsProvider() {
super();
}
/** methods ================================================================= */
/**
* Builds an ogc:Filter node from HTTP GET parameters.
* @param namespace the namespace parameter values
* @param constraintFilter the constraint parameter value
* @throws Exception if a processing exception occurs
*/
protected Node buildFilterNode(String[] namespace, String constraintFilter) throws Exception {
// TODO GetRecordsDomBuilder had a different pattern??
// parse namespaces
// pattern: namespace=xmlns(ogc=http://www.opengis.net/ogc),xmlns(gml=http://www.opengis.net/gml)...
StringBuilder nsBuffer = new StringBuilder();
boolean hasCswUri = false;
boolean hasCswPfx = false;
String cswPfx = "";
if (namespace != null) {
for (String ns: namespace) {
ns = Val.chkStr(ns);
String nsPfx = null;
String nsUri = null;
if (ns.toLowerCase().startsWith("xmlns(")) {
ns = ns.substring(6);
if (ns.toLowerCase().endsWith(")")) {
ns = ns.substring(0,ns.length() - 1);
}
ns = Val.chkStr(ns);
if (ns.length() > 0) {
String[] pair = ns.split("=");
if (pair.length == 1) {
nsUri = Val.chkStr(pair[0]);
} else if (pair.length == 2) {
nsPfx = Val.chkStr(pair[0]);
nsUri = Val.chkStr(pair[1]);
}
}
}
if ((nsUri == null) || (nsUri.length() == 0)) {
String msg = "The namespace must follow the following pattern:";
msg += " xmlns(pfx1=uri1),xmlns(pfx2=uri2),...";
throw new OwsException(OwsException.OWSCODE_InvalidParameterValue,"namespace",msg);
} else {
if (nsUri.equals("http://www.opengis.net/cat/csw/")) {
hasCswUri = true;
if ((nsPfx != null) && (nsPfx.length() > 0)) {
hasCswPfx = true;
cswPfx = nsPfx;
}
}
nsUri = Val.escapeXml(nsUri);
if ((nsPfx == null) || (nsPfx.length() == 0)) {
nsBuffer.append(" xmlns=\"").append(nsUri).append("\"");
} else {
nsBuffer.append(" xmlns:").append(nsPfx).append("=\"").append(nsUri).append("\"");
}
}
}
}
// use ogc as the default namespace if no namespace parameter was supplied
if (nsBuffer.length() == 0) {
nsBuffer.append(" xmlns=\"http://www.opengis.net/ogc\"");
}
// build the constraint XML
StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
if (hasCswUri && hasCswPfx) {
cswPfx = cswPfx+":";
} else if (hasCswUri) {
cswPfx = "";
} else {
cswPfx = "csw:";
nsBuffer.append(" xmlns:csw=\"http://www.opengis.net/cat/csw/3.0\"");
}
sbXml.append("\r\n<").append(cswPfx).append("Constraint");
if (nsBuffer.length() > 0) {
sbXml.append(" ").append(nsBuffer);
}
sbXml.append(">");
sbXml.append("\r\n").append(constraintFilter);
sbXml.append("\r\n</").append(cswPfx).append("Constraint>");
// make the dom, find the ogc:Filter node
try {
Document dom = DomUtil.makeDomFromString(sbXml.toString(),true);
CswNamespaces ns = CswNamespaces.CSW_30;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(ns.makeNamespaceContext());
Node ndFilter = null;
Node ndConstraint = (Node)xpath.evaluate("csw:Constraint",dom,XPathConstants.NODE);
if (ndConstraint != null) {
ndFilter = (Node)xpath.evaluate("ogc:Filter",ndConstraint,XPathConstants.NODE);;
}
if (ndFilter == null) {
String msg = "The supplied constraint was not a valid ogc:Filter.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,"constraint",msg);
} else {
return ndFilter;
}
} catch (SAXException e) {
String msg = "The supplied namespace/constraint pairs were not well-formed xml: ";
msg += " "+e.toString();
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,"constraint",msg);
}
}
/**
* Builds an ogc:SortBy node from HTTP GET parameters.
* @param sortBy the sortBy parameter values
* @throws Exception if a processing exception occurs
*/
protected Node buildSortByNode(String[] sortBy) throws Exception {
// parse sort by parameters
// pattern: sortby=property1:A,property2:D...
if (sortBy != null) {
StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sbXml.append("\r\n<ogc:SortBy xmlns:ogc=\"http://www.opengis.net/ogc\">");
boolean hadProperty = false;
for (String param: sortBy) {
param = Val.chkStr(param);
String name = null;
String dir = null;
if (param.toLowerCase().endsWith(":a")) {
name = Val.chkStr(param.substring(0,param.length() - 2));
dir= "ASC";
} else if (param.toLowerCase().endsWith(":d")) {
name = Val.chkStr(param.substring(0,param.length() - 2));
dir = "DESC";
} else {
name = Val.chkStr(param);
}
if ((name == null) || (name.length() == 0)) {
// we'll ignore this condition without an exception
} else {
hadProperty = true;
sbXml.append("\r\n<ogc:SortProperty>");
sbXml.append("\r\n<ogc:PropertyName>").append(Val.escapeXml(name)).append("</ogc:PropertyName>");
if (dir != null) {
sbXml.append("\r\n<ogc:SortOrder>").append(Val.escapeXml(dir)).append("</ogc:SortOrder>");
}
sbXml.append("\r\n</ogc:SortProperty>");
}
}
sbXml.append("\r\n</ogc:SortBy>");
if (hadProperty) {
Document dom = DomUtil.makeDomFromString(sbXml.toString(),true);
NodeList nl = dom.getChildNodes();
for (int i=0; i<nl.getLength(); i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE){
return nl.item(i);
}
}
}
}
return null;
}
/**
* Executes a parsed operation request.
* @param context the operation context
* @throws Exception if a processing exception occurs
*/
public void execute(OperationContext context) throws Exception {
// initialize
LOGGER.finer("Executing csw:GetRecords request...");
IProviderFactory factory = context.getProviderFactory();
// evaluate the query
IQueryEvaluator evaluator = factory.makeQueryEvaluator(context);
if (evaluator == null) {
String msg = "IProviderFactory.makeQueryEvaluator: instantiation failed.";
LOGGER.log(Level.SEVERE,msg);
throw new OwsException(msg);
} else {
evaluator.evaluateQuery(context);
}
// generate the response
IResponseGenerator generator = factory.makeResponseGenerator(context);
if (generator == null) {
String msg = "IProviderFactory.makeResponseGenerator: instantiation failed.";
LOGGER.log(Level.SEVERE,msg);
throw new OwsException(msg);
} else {
generator.generateResponse(context);
}
}
/**
* Handles a URL based request (HTTP GET).
* @param context the operation context
* @param request the HTTP request
* @throws Exception if a processing exception occurs
*/
public void handleGet(OperationContext context, HttpServletRequest request)
throws Exception {
// initialize
LOGGER.finer("Handling csw:GetRecords request URL...");
QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
ServiceProperties svcProps = context.getServiceProperties();
ParseHelper pHelper = new ParseHelper();
ValidationHelper vHelper = new ValidationHelper();
String locator;
String[] parsed;
ISupportedValues supported;
IProviderFactory factory = context.getProviderFactory();
CswNamespaces ns = CswNamespaces.CSW_30;
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(ns.makeNamespaceContext());
// service and version are parsed by the parent RequestHandler
// TODO typeNames requestId distributedSearch hopCount responseHandler
// TODO resultype validate is not applicable for a GET request?
// output format
locator = "outputFormat";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputFormat);
context.getOperationResponse().setOutputFormat(
vHelper.validateValue(supported,locator,parsed,false));
// output schema
locator = "outputSchema";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputSchema);
qOptions.setOutputSchema(vHelper.validateValue(supported,locator,parsed,false));
// start and max records
parsed = pHelper.getParameterValues(request,"startPosition");
if ((parsed != null) && (parsed.length) > 0) {
qOptions.setStartRecord(Math.max(Val.chkInt(parsed[0],1),1));
}
parsed = pHelper.getParameterValues(request,"maxRecords");
if ((parsed != null) && (parsed.length) > 0) {
qOptions.setMaxRecords(Val.chkInt(parsed[0],10));
}
// result type
locator = "resultType";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ResultType);
qOptions.setResultType(vHelper.validateValue(supported,locator,parsed,false));
if (qOptions.getResultType() == null) {
qOptions.setResultType(CswConstants.ResultType_Results);
}
// query type names
locator = "typeNames";
parsed = pHelper.getParameterValues(request,locator);
qOptions.setQueryTypeNames(vHelper.validateValues(locator,parsed,false));
// response element set type
locator = "ElementSetName";
parsed = pHelper.getParameterValues(request,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementSetType);
qOptions.setElementSetType(vHelper.validateValue(supported,locator,parsed,false));
// response element names
if (qOptions.getElementSetType() == null) {
// TODO supported ElementNames this for GetRecordById as well?
locator = "ElementName";
parsed = pHelper.getParameterValues(request,locator,",");
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementName);
qOptions.setElementNames(vHelper.validateValues(supported,locator,parsed,false));
}
// constraint language
locator = "constraintLanguage";
parsed = pHelper.getParameterValues(request,locator);
supported = new SupportedValues("CQL_TEXT,FILTER",",");
String constraintLanguage = vHelper.validateValue(supported,locator,parsed,false);
// constraint version
locator = "constraint_language_version";
parsed = pHelper.getParameterValues(request,locator);
String constraintVersion = vHelper.validateValue(locator,parsed,false);
qOptions.setQueryConstraintVersion(constraintVersion);
// constraint text
locator = "constraint";
parsed = pHelper.getParameterValues(request,locator);
String constraint = vHelper.validateValue(locator,parsed,false);
// csw:CqlText
if ((constraintLanguage != null) && constraintLanguage.equalsIgnoreCase("CQL_TEXT")) {
String cql = Val.chkStr(constraint);
qOptions.setQueryConstraintCql(cql);
ICqlParser parser = factory.makeCqlParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeCqlParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseCql(context,cql);
}
}
// ogc:Filter
if ((constraintLanguage == null) || constraintLanguage.equalsIgnoreCase("FILTER")) {
Node ndFilter = null;
IFilterParser parser = factory.makeFilterParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeFilterParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
}
String constraintFilter = Val.chkStr(constraint);
if (constraintFilter.length() > 0) {
String[] namespace = pHelper.getParameterValues(request,"namespace",",");
ndFilter = this.buildFilterNode(namespace,constraintFilter);
parser.parseFilter(context,ndFilter,xpath);
}
}
// ogc:SortBy
locator = "sortBy";
String[] sortBy = pHelper.getParameterValues(request,"sortBy",",");
if (sortBy != null) {
Node ndSortBy = this.buildSortByNode(sortBy);
if (ndSortBy != null) {
ISortByParser parser = factory.makeSortByParser(context);
if (parser == null) {
String msg = "IProviderFactory.makeSortByParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseSortBy(context,ndSortBy,xpath);
}
}
}
// execute the request
this.execute(context);
}
/**
* Handles an XML based request (normally HTTP POST).
* @param context the operation context
* @param root the root node
* @param xpath an XPath to enable queries (properly configured with name spaces)
* @throws Exception if a processing exception occurs
*/
public void handleXML(OperationContext context, Node root, XPath xpath)
throws Exception {
// initialize
LOGGER.finer("Handling csw:GetRecords request XML...");
QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
ServiceProperties svcProps = context.getServiceProperties();
ParseHelper pHelper = new ParseHelper();
ValidationHelper vHelper = new ValidationHelper();
String locator;
String[] parsed;
ISupportedValues supported;
IProviderFactory factory = context.getProviderFactory();
// service and version are parsed by the parent RequestHandler
// TODO requestId
// output format
locator = "@outputFormat";
parsed = pHelper.getParameterValues(root,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputFormat);
context.getOperationResponse().setOutputFormat(
vHelper.validateValue(supported,locator,parsed,false));
// output schema
locator = "@outputSchema";
parsed = pHelper.getParameterValues(root,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputSchema);
qOptions.setOutputSchema(vHelper.validateValue(supported,locator,parsed,false));
// start and max records
qOptions.setStartRecord(Math.max(Val.chkInt(xpath.evaluate("@startPosition",root),1),1));
qOptions.setMaxRecords(Val.chkInt(xpath.evaluate("@maxRecords",root),10));
// result type
locator = "@resultType";
parsed = pHelper.getParameterValues(root,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ResultType);
qOptions.setResultType(vHelper.validateValue(supported,locator,parsed,false));
if (qOptions.getResultType() == null) {
qOptions.setResultType(CswConstants.ResultType_Results);
}
// find the query node
locator = "csw:Query";
Node ndQuery = (Node)xpath.evaluate(locator,root,XPathConstants.NODE);
if (ndQuery != null) {
// query type names
locator = "csw:Query/@typeNames";
parsed = pHelper.getParameterValues(root,xpath,"@typeNames");
qOptions.setQueryTypeNames(vHelper.validateValues(locator,parsed,false));
// response element set type
locator = "csw:ElementSetName";
parsed = pHelper.getParameterValues(ndQuery,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementSetType);
qOptions.setElementSetType(vHelper.validateValue(supported,locator,parsed,false));
// response element set type names
String elementSetType = qOptions.getElementSetType();
if (elementSetType != null) {
locator = "csw:ElementSetName/@typeNames";
parsed = pHelper.getParameterValues(ndQuery,xpath,locator);
qOptions.setElementSetTypeNames(vHelper.validateValues(locator,parsed,false));
}
// response element names
if (elementSetType == null) {
// TODO supported ElementNames
locator = "csw:ElementName";
parsed = pHelper.getParameterValues(ndQuery,xpath,locator);
supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementName);
qOptions.setElementNames(vHelper.validateValues(supported,locator,parsed,false));
}
// find the constraint node
Node ndConstraint = (Node)xpath.evaluate("csw:Constraint",ndQuery,XPathConstants.NODE);
if (ndConstraint != null) {
// constraint version
String constraintVersion = xpath.evaluate("@version",ndConstraint);
qOptions.setQueryConstraintVersion(constraintVersion);
// csw:CqlText
locator = "csw:CqlText";
Node ndCql = (Node)xpath.evaluate(locator,ndConstraint,XPathConstants.NODE);
if (ndCql != null) {
String cql = Val.chkStr(ndCql.getTextContent());
qOptions.setQueryConstraintCql(cql);
ICqlParser parser = factory.makeCqlParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeCqlParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseCql(context,cql);
}
} else {
// ogc:Filter
locator = "ogc:Filter";
Node ndFilter = (Node)xpath.evaluate(locator,ndConstraint,XPathConstants.NODE);
if (ndFilter != null) {
IFilterParser parser = factory.makeFilterParser(context,constraintVersion);
if (parser == null) {
String msg = "IProviderFactory.makeFilterParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseFilter(context,ndFilter,xpath);
}
} else {
String msg = "An OGC filter for the CSW constraint is required.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
}
}
}
// ogc:SortBy
locator = "ogc:SortBy";
Node ndSortBy = (Node)xpath.evaluate(locator,ndQuery,XPathConstants.NODE);
if (ndSortBy != null) {
ISortByParser parser = factory.makeSortByParser(context);
if (parser == null) {
String msg = "IProviderFactory.makeSortByParser: instantiation failed.";
throw new OwsException(OwsException.OWSCODE_NoApplicableCode,locator,msg);
} else {
parser.parseSortBy(context,ndSortBy,xpath);
}
}
}
// execute the request
this.execute(context);
}
}
| CSW3.0: GetReordsProvider accepts recordIds | geoportal/src/com/esri/gpt/server/csw/provider30/GetRecordsProvider.java | CSW3.0: GetReordsProvider accepts recordIds |
|
Java | apache-2.0 | c287f250391f15349e9fc821f971a7529be435b4 | 0 | michael-rapp/AndroidAdapters | /*
* AndroidAdapters Copyright 2014 Michael Rapp
*
* This program 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 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 Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package de.mrapp.android.adapter.datastructure.item;
import static de.mrapp.android.adapter.util.Condition.ensureNotNull;
import java.util.Comparator;
/**
* A comparator, which allows to compare two items by comparing their data.
*
*
* @param <DataType>
* The type of the item's data
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public class ItemComparator<DataType> implements Comparator<Item<DataType>> {
/**
* The comparator, which is used to compare the items' data.
*/
private final Comparator<DataType> comparator;
/**
* Creates a new comparator, which allows to compare two items by comparing
* their data.
*
* @param comparator
* The comparator, which should be used to compare the items'
* data, as an instance of the type {@link Comparator}. The
* comparator may not be null
*/
public ItemComparator(final Comparator<DataType> comparator) {
ensureNotNull(comparator, "The comparator may not be null");
this.comparator = comparator;
}
@Override
public final int compare(final Item<DataType> lhs, final Item<DataType> rhs) {
return comparator.compare(lhs.getData(), rhs.getData());
}
} | src/de/mrapp/android/adapter/datastructure/item/ItemComparator.java | /*
* AndroidAdapters Copyright 2014 Michael Rapp
*
* This program 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 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 Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package de.mrapp.android.adapter.datastructure.item;
import static de.mrapp.android.adapter.util.Condition.ensureNotNull;
import java.util.Comparator;
/**
* A comparator, which allows to compare two items by comparing their data.
*
* @author Michael Rapp
*
* @param <DataType>
* The type of the item's data
*/
public class ItemComparator<DataType> implements Comparator<Item<DataType>> {
/**
* The comparator, which is used to compare the items' data.
*/
private final Comparator<DataType> comparator;
/**
* Creates a new comparator, which allows to compare two items by comparing
* their data.
*
* @param comparator
* The comparator, which should be used to compare the items'
* data, as an instance of the type {@link Comparator}. The
* comparator may not be null
*/
public ItemComparator(final Comparator<DataType> comparator) {
ensureNotNull(comparator, "The comparator may not be null");
this.comparator = comparator;
}
@Override
public final int compare(final Item<DataType> lhs, final Item<DataType> rhs) {
return comparator.compare(lhs.getData(), rhs.getData());
}
} | Added @since annotation.
| src/de/mrapp/android/adapter/datastructure/item/ItemComparator.java | Added @since annotation. |
|
Java | apache-2.0 | 1f95cf896110afb750300a4efc9965a9f82f02a4 | 0 | wwjiang007/alluxio,wwjiang007/alluxio,apc999/alluxio,wwjiang007/alluxio,PasaLab/tachyon,madanadit/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,calvinjia/tachyon,calvinjia/tachyon,Alluxio/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,Alluxio/alluxio,maboelhassan/alluxio,Alluxio/alluxio,madanadit/alluxio,maobaolong/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,aaudiber/alluxio,riversand963/alluxio,bf8086/alluxio,apc999/alluxio,jswudi/alluxio,maboelhassan/alluxio,maobaolong/alluxio,riversand963/alluxio,bf8086/alluxio,maobaolong/alluxio,Reidddddd/alluxio,apc999/alluxio,riversand963/alluxio,apc999/alluxio,maobaolong/alluxio,PasaLab/tachyon,maobaolong/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,madanadit/alluxio,jswudi/alluxio,apc999/alluxio,PasaLab/tachyon,maboelhassan/alluxio,jswudi/alluxio,Alluxio/alluxio,bf8086/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,jswudi/alluxio,aaudiber/alluxio,calvinjia/tachyon,maboelhassan/alluxio,calvinjia/tachyon,Alluxio/alluxio,bf8086/alluxio,wwjiang007/alluxio,calvinjia/tachyon,madanadit/alluxio,maobaolong/alluxio,jswudi/alluxio,aaudiber/alluxio,aaudiber/alluxio,wwjiang007/alluxio,aaudiber/alluxio,Alluxio/alluxio,maobaolong/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,calvinjia/tachyon,Alluxio/alluxio,aaudiber/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,PasaLab/tachyon,calvinjia/tachyon,calvinjia/tachyon,maobaolong/alluxio,bf8086/alluxio,Reidddddd/alluxio,jswudi/alluxio,bf8086/alluxio,maboelhassan/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,riversand963/alluxio,Reidddddd/alluxio,riversand963/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,riversand963/alluxio,wwjiang007/alluxio,aaudiber/alluxio,madanadit/alluxio,maobaolong/alluxio,madanadit/alluxio,wwjiang007/alluxio,apc999/alluxio,bf8086/alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.hadoop;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.any;
import alluxio.AlluxioURI;
import alluxio.ConfigurationRule;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.client.file.FileSystemContext;
import alluxio.client.file.FileSystemMasterClient;
import alluxio.client.file.URIStatus;
import alluxio.exception.status.UnavailableException;
import alluxio.wire.FileInfo;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.Subject;
/**
* Unit tests for {@link AbstractFileSystem}.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({FileSystemContext.class, FileSystemMasterClient.class, UserGroupInformation.class})
/*
* [ALLUXIO-1384] Tell PowerMock to defer the loading of javax.security classes to the system
* classloader in order to avoid linkage error when running this test with CDH.
* See https://code.google.com/p/powermock/wiki/FAQ.
*/
@PowerMockIgnore("javax.security.*")
/**
* Tests for {@link AbstractFileSystem}.
*/
public class AbstractFileSystemTest {
private static final Logger LOG = LoggerFactory.getLogger(AbstractFileSystemTest.class);
private FileSystemContext mMockFileSystemContext;
private FileSystemContext mMockFileSystemContextCustomized;
private FileSystemMasterClient mMockFileSystemMasterClient;
@Rule
public ExpectedException mExpectedException = ExpectedException.none();
/**
* Sets up the configuration before a test runs.
*/
@Before
public void before() throws Exception {
mockFileSystemContextAndMasterClient();
mockUserGroupInformation("");
if (HadoopClientTestUtils.isHadoop1x()) {
LOG.debug("Running Alluxio FS tests against hadoop 1x");
} else if (HadoopClientTestUtils.isHadoop2x()) {
LOG.debug("Running Alluxio FS tests against hadoop 2x");
} else {
LOG.warn("Running Alluxio FS tests against untargeted Hadoop version: "
+ HadoopClientTestUtils.getHadoopVersion());
}
}
@After
public void after() {
HadoopClientTestUtils.resetClient();
}
/**
* Ensures that Hadoop loads {@link FaultTolerantFileSystem} when configured.
*/
@Test
public void hadoopShouldLoadFaultTolerantFileSystemWhenConfigured() throws Exception {
URI uri = URI.create(Constants.HEADER_FT + "localhost:19998/tmp/path.txt");
try (Closeable c = new ConfigurationRule(ImmutableMap.of(
PropertyKey.MASTER_HOSTNAME, uri.getHost(),
PropertyKey.MASTER_RPC_PORT, Integer.toString(uri.getPort()),
PropertyKey.ZOOKEEPER_ENABLED, "true")).toResource()) {
final org.apache.hadoop.fs.FileSystem fs =
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
assertTrue(fs instanceof FaultTolerantFileSystem);
}
}
/**
* Hadoop should be able to load uris like alluxio-ft:///path/to/file.
*/
@Test
public void loadFaultTolerantSystemWhenUsingNoAuthority() throws Exception {
URI uri = URI.create(Constants.HEADER_FT + "/tmp/path.txt");
try (Closeable c = new ConfigurationRule(PropertyKey.ZOOKEEPER_ENABLED, "true").toResource()) {
final org.apache.hadoop.fs.FileSystem fs =
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
assertTrue(fs instanceof FaultTolerantFileSystem);
}
}
/**
* Tests that using an alluxio-ft:/// URI is still possible after using an alluxio://host:port/
* URI.
*/
@Test
public void loadRegularThenFaultTolerant() throws Exception {
try (Closeable c = new ConfigurationRule(ImmutableMap.of(
PropertyKey.ZOOKEEPER_ENABLED, "true",
PropertyKey.ZOOKEEPER_ADDRESS, "host:2")).toResource()) {
org.apache.hadoop.fs.FileSystem.get(URI.create(Constants.HEADER + "host:1/"), getConf());
org.apache.hadoop.fs.FileSystem fs =
org.apache.hadoop.fs.FileSystem.get(URI.create(Constants.HEADER_FT + "/"), getConf());
assertTrue(fs instanceof FaultTolerantFileSystem);
}
}
/**
* Ensures that Hadoop loads the Alluxio file system when configured.
*/
@Test
public void hadoopShouldLoadFileSystemWhenConfigured() throws Exception {
org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "localhost:19998/tmp/path.txt");
try (Closeable c = new ConfigurationRule(ImmutableMap.of(
PropertyKey.MASTER_HOSTNAME, uri.getHost(),
PropertyKey.MASTER_RPC_PORT, Integer.toString(uri.getPort()),
PropertyKey.ZOOKEEPER_ENABLED, "false")).toResource()) {
final org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.get(uri, conf);
assertTrue(fs instanceof FileSystem);
}
}
/**
* Tests that initializing the {@link AbstractFileSystem} will reinitialize the file system
* context.
*/
@Test
public void resetContext() throws Exception {
// Change to otherhost:410
URI uri = URI.create(Constants.HEADER + "otherhost:410/");
org.apache.hadoop.fs.FileSystem fileSystem =
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
verify(mMockFileSystemContext).reset();
}
/**
* Verifies that the initialize method is only called once even when there are many concurrent
* initializers during the initialization phase.
*/
@Test
public void concurrentInitialize() throws Exception {
List<Thread> threads = new ArrayList<>();
final org.apache.hadoop.conf.Configuration conf = getConf();
when(mMockFileSystemContext.getMasterAddress())
.thenReturn(new InetSocketAddress("randomhost", 410));
for (int i = 0; i < 100; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
URI uri = URI.create(Constants.HEADER + "randomhost:410/");
try {
org.apache.hadoop.fs.FileSystem.get(uri, conf);
} catch (IOException e) {
fail();
}
}
});
threads.add(t);
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
}
/**
* Tests that failing to connect to Alluxio master causes initialization failure.
*/
@Test
public void initializeFailToConnect() throws Exception {
doThrow(new UnavailableException("test")).when(mMockFileSystemMasterClient).connect();
URI uri = URI.create(Constants.HEADER + "randomhost:400/");
mExpectedException.expect(UnavailableException.class);
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
}
/**
* Tests that after initialization, reinitialize with a different URI should fail.
*/
@Test
public void reinitializeWithDifferentURI() throws Exception {
final org.apache.hadoop.conf.Configuration conf = getConf();
String originalURI = "host1:1";
URI uri = URI.create(Constants.HEADER + originalURI);
org.apache.hadoop.fs.FileSystem.get(uri, conf);
when(mMockFileSystemContext.getMasterAddress())
.thenReturn(new InetSocketAddress("host1", 1));
String[] newURIs = new String[]{"host2:1", "host1:2", "host2:2"};
for (String newURI : newURIs) {
// mExpectedException.expect(IOException.class);
// mExpectedException.expectMessage(ExceptionMessage.DIFFERENT_MASTER_ADDRESS
// .getMessage(newURI, originalURI));
uri = URI.create(Constants.HEADER + newURI);
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// The above code should not throw an exception.
// TODO(cc): Remove or bring this check back.
// Assert.fail("Initialization should throw an exception.");
}
}
/**
* Tests that the {@link AbstractFileSystem#listStatus(Path)} method uses
* {@link URIStatus#getLastModificationTimeMs()} correctly.
*/
@Test
public void listStatus() throws Exception {
FileInfo fileInfo1 = new FileInfo()
.setLastModificationTimeMs(111L)
.setFolder(false)
.setOwner("user1")
.setGroup("group1")
.setMode(00755);
FileInfo fileInfo2 = new FileInfo()
.setLastModificationTimeMs(222L)
.setFolder(true)
.setOwner("user2")
.setGroup("group2")
.setMode(00644);
Path path = new Path("/dir");
alluxio.client.file.FileSystem alluxioFs =
mock(alluxio.client.file.FileSystem.class);
when(alluxioFs.listStatus(new AlluxioURI(HadoopUtils.getPathWithoutScheme(path))))
.thenReturn(Lists.newArrayList(new URIStatus(fileInfo1), new URIStatus(fileInfo2)));
FileSystem alluxioHadoopFs = new FileSystem(alluxioFs);
FileStatus[] fileStatuses = alluxioHadoopFs.listStatus(path);
assertFileInfoEqualsFileStatus(fileInfo1, fileStatuses[0]);
assertFileInfoEqualsFileStatus(fileInfo2, fileStatuses[1]);
alluxioHadoopFs.close();
}
/**
* Tests that the {@link AbstractFileSystem#listStatus(Path)} method throws
* FileNotFound Exception.
*/
@Test
public void listStatusFileNotFound() throws Exception {
FileInfo fileInfo1 = new FileInfo()
.setLastModificationTimeMs(111L)
.setFolder(false)
.setOwner("user1")
.setGroup("group1")
.setMode(00755);
FileInfo fileInfo2 = new FileInfo()
.setLastModificationTimeMs(222L)
.setFolder(true)
.setOwner("user2")
.setGroup("group2")
.setMode(00644);
try {
Path path = new Path("/dummyDir");
alluxio.client.file.FileSystem alluxioFs =
mock(alluxio.client.file.FileSystem.class);
when(alluxioFs.listStatus(new AlluxioURI(HadoopUtils.getPathWithoutScheme(path))))
.thenReturn(Lists.newArrayList(new URIStatus(fileInfo1), new URIStatus(fileInfo2)));
} catch (FileNotFoundException fnf) {
Assert.assertTrue(true);
}
}
@Test
public void getStatus() throws Exception {
FileInfo fileInfo = new FileInfo()
.setLastModificationTimeMs(111L)
.setFolder(false)
.setOwner("user1")
.setGroup("group1")
.setMode(00755);
Path path = new Path("/dir");
alluxio.client.file.FileSystem alluxioFs =
mock(alluxio.client.file.FileSystem.class);
when(alluxioFs.getStatus(new AlluxioURI(HadoopUtils.getPathWithoutScheme(path))))
.thenReturn(new URIStatus(fileInfo));
FileSystem alluxioHadoopFs = new FileSystem(alluxioFs);
FileStatus fileStatus = alluxioHadoopFs.getFileStatus(path);
assertFileInfoEqualsFileStatus(fileInfo, fileStatus);
}
@Test
public void initializeWithCustomizedUgi() throws Exception {
mockUserGroupInformation("testuser");
final org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "host:1");
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// FileSystem.get would have thrown an exception if the initialization failed.
}
@Test
public void initializeWithFullPrincipalUgi() throws Exception {
mockUserGroupInformation("[email protected]");
final org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "host:1");
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// FileSystem.get would have thrown an exception if the initialization failed.
}
private org.apache.hadoop.conf.Configuration getConf() throws Exception {
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
if (HadoopClientTestUtils.isHadoop1x()) {
conf.set("fs." + Constants.SCHEME + ".impl", FileSystem.class.getName());
conf.set("fs." + Constants.SCHEME_FT + ".impl", FaultTolerantFileSystem.class.getName());
}
return conf;
}
private void mockFileSystemContextAndMasterClient() throws Exception {
mMockFileSystemContext = PowerMockito.mock(FileSystemContext.class);
mMockFileSystemContextCustomized = PowerMockito.mock(FileSystemContext.class);
PowerMockito.mockStatic(FileSystemContext.class);
Whitebox.setInternalState(FileSystemContext.class, "INSTANCE", mMockFileSystemContext);
PowerMockito.when(FileSystemContext.create(any(Subject.class)))
.thenReturn(mMockFileSystemContextCustomized);
mMockFileSystemMasterClient = mock(FileSystemMasterClient.class);
when(mMockFileSystemContext.acquireMasterClient())
.thenReturn(mMockFileSystemMasterClient);
when(mMockFileSystemContextCustomized.acquireMasterClient())
.thenReturn(mMockFileSystemMasterClient);
doNothing().when(mMockFileSystemMasterClient).connect();
when(mMockFileSystemContext.getMasterAddress())
.thenReturn(new InetSocketAddress("defaultHost", 1));
}
private void mockUserGroupInformation(String username) throws IOException {
// need to mock out since FileSystem.get calls UGI, which some times has issues on some systems
PowerMockito.mockStatic(UserGroupInformation.class);
final UserGroupInformation ugi = mock(UserGroupInformation.class);
when(UserGroupInformation.getCurrentUser()).thenReturn(ugi);
when(ugi.getUserName()).thenReturn(username);
when(ugi.getShortUserName()).thenReturn(username.split("@")[0]);
}
private void assertFileInfoEqualsFileStatus(FileInfo info, FileStatus status) {
assertEquals(info.getOwner(), status.getOwner());
assertEquals(info.getGroup(), status.getGroup());
assertEquals(info.getMode(), status.getPermission().toShort());
assertEquals(info.getLastModificationTimeMs(), status.getModificationTime());
assertEquals(info.isFolder(), status.isDir());
}
}
| core/client/hdfs/src/test/java/alluxio/hadoop/AbstractFileSystemTest.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.hadoop;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.any;
import alluxio.AlluxioURI;
import alluxio.ConfigurationRule;
import alluxio.Constants;
import alluxio.PropertyKey;
import alluxio.client.file.FileSystemContext;
import alluxio.client.file.FileSystemMasterClient;
import alluxio.client.file.URIStatus;
import alluxio.exception.status.UnavailableException;
import alluxio.wire.FileInfo;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.Subject;
/**
* Unit tests for {@link AbstractFileSystem}.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({FileSystemContext.class, FileSystemMasterClient.class, UserGroupInformation.class})
/*
* [ALLUXIO-1384] Tell PowerMock to defer the loading of javax.security classes to the system
* classloader in order to avoid linkage error when running this test with CDH.
* See https://code.google.com/p/powermock/wiki/FAQ.
*/
@PowerMockIgnore("javax.security.*")
/**
* Tests for {@link AbstractFileSystem}.
*/
public class AbstractFileSystemTest {
private static final Logger LOG = LoggerFactory.getLogger(AbstractFileSystemTest.class);
private FileSystemContext mMockFileSystemContext;
private FileSystemContext mMockFileSystemContextCustomized;
private FileSystemMasterClient mMockFileSystemMasterClient;
@Rule
public ExpectedException mExpectedException = ExpectedException.none();
/**
* Sets up the configuration before a test runs.
*/
@Before
public void before() throws Exception {
mockFileSystemContextAndMasterClient();
mockUserGroupInformation("");
if (HadoopClientTestUtils.isHadoop1x()) {
LOG.debug("Running Alluxio FS tests against hadoop 1x");
} else if (HadoopClientTestUtils.isHadoop2x()) {
LOG.debug("Running Alluxio FS tests against hadoop 2x");
} else {
LOG.warn("Running Alluxio FS tests against untargeted Hadoop version: "
+ HadoopClientTestUtils.getHadoopVersion());
}
}
@After
public void after() {
HadoopClientTestUtils.resetClient();
}
/**
* Ensures that Hadoop loads {@link FaultTolerantFileSystem} when configured.
*/
@Test
public void hadoopShouldLoadFaultTolerantFileSystemWhenConfigured() throws Exception {
URI uri = URI.create(Constants.HEADER_FT + "localhost:19998/tmp/path.txt");
try (Closeable c = new ConfigurationRule(ImmutableMap.of(
PropertyKey.MASTER_HOSTNAME, uri.getHost(),
PropertyKey.MASTER_RPC_PORT, Integer.toString(uri.getPort()),
PropertyKey.ZOOKEEPER_ENABLED, "true")).toResource()) {
final org.apache.hadoop.fs.FileSystem fs =
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
assertTrue(fs instanceof FaultTolerantFileSystem);
}
}
/**
* Hadoop should be able to load uris like alluxio-ft:///path/to/file.
*/
@Test
public void loadFaultTolerantSystemWhenUsingNoAuthority() throws Exception {
URI uri = URI.create(Constants.HEADER_FT + "/tmp/path.txt");
try (Closeable c = new ConfigurationRule(PropertyKey.ZOOKEEPER_ENABLED, "true").toResource()) {
final org.apache.hadoop.fs.FileSystem fs =
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
assertTrue(fs instanceof FaultTolerantFileSystem);
}
}
/**
* Tests that using an alluxio-ft:/// URI is still possible after using an alluxio://host:port/
* URI.
*/
@Test
public void loadRegularThenFaultTolerant() throws Exception {
try (Closeable c = new ConfigurationRule(ImmutableMap.of(
PropertyKey.ZOOKEEPER_ENABLED, "true",
PropertyKey.ZOOKEEPER_ADDRESS, "host:2")).toResource()) {
org.apache.hadoop.fs.FileSystem.get(URI.create(Constants.HEADER + "host:1/"), getConf());
org.apache.hadoop.fs.FileSystem fs =
org.apache.hadoop.fs.FileSystem.get(URI.create(Constants.HEADER_FT + "/"), getConf());
assertTrue(fs instanceof FaultTolerantFileSystem);
}
}
/**
* Ensures that Hadoop loads the Alluxio file system when configured.
*/
@Test
public void hadoopShouldLoadFileSystemWhenConfigured() throws Exception {
org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "localhost:19998/tmp/path.txt");
try (Closeable c = new ConfigurationRule(ImmutableMap.of(
PropertyKey.MASTER_HOSTNAME, uri.getHost(),
PropertyKey.MASTER_RPC_PORT, Integer.toString(uri.getPort()),
PropertyKey.ZOOKEEPER_ENABLED, "false")).toResource()) {
final org.apache.hadoop.fs.FileSystem fs = org.apache.hadoop.fs.FileSystem.get(uri, conf);
assertTrue(fs instanceof FileSystem);
}
}
/**
* Tests that initializing the {@link AbstractFileSystem} will reinitialize the file system
* context.
*/
@Test
public void resetContext() throws Exception {
// Change to otherhost:410
URI uri = URI.create(Constants.HEADER + "otherhost:410/");
org.apache.hadoop.fs.FileSystem fileSystem =
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
verify(mMockFileSystemContext).reset();
}
/**
* Verifies that the initialize method is only called once even when there are many concurrent
* initializers during the initialization phase.
*/
@Test
public void concurrentInitialize() throws Exception {
List<Thread> threads = new ArrayList<>();
final org.apache.hadoop.conf.Configuration conf = getConf();
when(mMockFileSystemContext.getMasterAddress())
.thenReturn(new InetSocketAddress("randomhost", 410));
for (int i = 0; i < 100; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
URI uri = URI.create(Constants.HEADER + "randomhost:410/");
try {
org.apache.hadoop.fs.FileSystem.get(uri, conf);
} catch (IOException e) {
fail();
}
}
});
threads.add(t);
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
}
/**
* Tests that failing to connect to Alluxio master causes initialization failure.
*/
@Test
public void initializeFailToConnect() throws Exception {
doThrow(new UnavailableException("test")).when(mMockFileSystemMasterClient).connect();
URI uri = URI.create(Constants.HEADER + "randomhost:400/");
mExpectedException.expect(UnavailableException.class);
org.apache.hadoop.fs.FileSystem.get(uri, getConf());
}
/**
* Tests that after initialization, reinitialize with a different URI should fail.
*/
@Test
public void reinitializeWithDifferentURI() throws Exception {
final org.apache.hadoop.conf.Configuration conf = getConf();
String originalURI = "host1:1";
URI uri = URI.create(Constants.HEADER + originalURI);
org.apache.hadoop.fs.FileSystem.get(uri, conf);
when(mMockFileSystemContext.getMasterAddress())
.thenReturn(new InetSocketAddress("host1", 1));
String[] newURIs = new String[]{"host2:1", "host1:2", "host2:2"};
for (String newURI : newURIs) {
// mExpectedException.expect(IOException.class);
// mExpectedException.expectMessage(ExceptionMessage.DIFFERENT_MASTER_ADDRESS
// .getMessage(newURI, originalURI));
uri = URI.create(Constants.HEADER + newURI);
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// The above code should not throw an exception.
// TODO(cc): Remove or bring this check back.
// Assert.fail("Initialization should throw an exception.");
}
}
/**
* Tests that the {@link AbstractFileSystem#listStatus(Path)} method uses
* {@link URIStatus#getLastModificationTimeMs()} correctly.
*/
@Test
public void listStatus() throws Exception {
FileInfo fileInfo1 = new FileInfo()
.setLastModificationTimeMs(111L)
.setFolder(false)
.setOwner("user1")
.setGroup("group1")
.setMode(00755);
FileInfo fileInfo2 = new FileInfo()
.setLastModificationTimeMs(222L)
.setFolder(true)
.setOwner("user2")
.setGroup("group2")
.setMode(00644);
Path path = new Path("/dir");
alluxio.client.file.FileSystem alluxioFs =
mock(alluxio.client.file.FileSystem.class);
when(alluxioFs.listStatus(new AlluxioURI(HadoopUtils.getPathWithoutScheme(path))))
.thenReturn(Lists.newArrayList(new URIStatus(fileInfo1), new URIStatus(fileInfo2)));
FileSystem alluxioHadoopFs = new FileSystem(alluxioFs);
FileStatus[] fileStatuses = alluxioHadoopFs.listStatus(path);
assertFileInfoEqualsFileStatus(fileInfo1, fileStatuses[0]);
assertFileInfoEqualsFileStatus(fileInfo2, fileStatuses[1]);
alluxioHadoopFs.close();
}
/**
* Tests that the {@link AbstractFileSystem#listStatus(Path)} method throws
* FileNotFound Exception.
*/
@Test
public void listStatusFileNotFound() throws Exception {
FileInfo fileInfo1 = new FileInfo()
.setLastModificationTimeMs(111L)
.setFolder(false)
.setOwner("user1")
.setGroup("group1")
.setMode(00755);
FileInfo fileInfo2 = new FileInfo()
.setLastModificationTimeMs(222L)
.setFolder(true)
.setOwner("user2")
.setGroup("group2")
.setMode(00644);
FileSystem alluxioHadoopFs = null;
try {
Path path = new Path("/dummyDir");
alluxio.client.file.FileSystem alluxioFs =
mock(alluxio.client.file.FileSystem.class);
when(alluxioFs.listStatus(new AlluxioURI(HadoopUtils.getPathWithoutScheme(path))))
.thenReturn(Lists.newArrayList(new URIStatus(fileInfo1), new URIStatus(fileInfo2)));
alluxioHadoopFs = new FileSystem(alluxioFs);
FileStatus[] fileStatuses = alluxioHadoopFs.listStatus(path);
} catch (FileNotFoundException fnf) {
Assert.assertTrue(true);
} finally {
if (null != alluxioHadoopFs) {
alluxioHadoopFs.close();
}
}
}
@Test
public void getStatus() throws Exception {
FileInfo fileInfo = new FileInfo()
.setLastModificationTimeMs(111L)
.setFolder(false)
.setOwner("user1")
.setGroup("group1")
.setMode(00755);
Path path = new Path("/dir");
alluxio.client.file.FileSystem alluxioFs =
mock(alluxio.client.file.FileSystem.class);
when(alluxioFs.getStatus(new AlluxioURI(HadoopUtils.getPathWithoutScheme(path))))
.thenReturn(new URIStatus(fileInfo));
FileSystem alluxioHadoopFs = new FileSystem(alluxioFs);
FileStatus fileStatus = alluxioHadoopFs.getFileStatus(path);
assertFileInfoEqualsFileStatus(fileInfo, fileStatus);
}
@Test
public void initializeWithCustomizedUgi() throws Exception {
mockUserGroupInformation("testuser");
final org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "host:1");
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// FileSystem.get would have thrown an exception if the initialization failed.
}
@Test
public void initializeWithFullPrincipalUgi() throws Exception {
mockUserGroupInformation("[email protected]");
final org.apache.hadoop.conf.Configuration conf = getConf();
URI uri = URI.create(Constants.HEADER + "host:1");
org.apache.hadoop.fs.FileSystem.get(uri, conf);
// FileSystem.get would have thrown an exception if the initialization failed.
}
private org.apache.hadoop.conf.Configuration getConf() throws Exception {
org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
if (HadoopClientTestUtils.isHadoop1x()) {
conf.set("fs." + Constants.SCHEME + ".impl", FileSystem.class.getName());
conf.set("fs." + Constants.SCHEME_FT + ".impl", FaultTolerantFileSystem.class.getName());
}
return conf;
}
private void mockFileSystemContextAndMasterClient() throws Exception {
mMockFileSystemContext = PowerMockito.mock(FileSystemContext.class);
mMockFileSystemContextCustomized = PowerMockito.mock(FileSystemContext.class);
PowerMockito.mockStatic(FileSystemContext.class);
Whitebox.setInternalState(FileSystemContext.class, "INSTANCE", mMockFileSystemContext);
PowerMockito.when(FileSystemContext.create(any(Subject.class)))
.thenReturn(mMockFileSystemContextCustomized);
mMockFileSystemMasterClient = mock(FileSystemMasterClient.class);
when(mMockFileSystemContext.acquireMasterClient())
.thenReturn(mMockFileSystemMasterClient);
when(mMockFileSystemContextCustomized.acquireMasterClient())
.thenReturn(mMockFileSystemMasterClient);
doNothing().when(mMockFileSystemMasterClient).connect();
when(mMockFileSystemContext.getMasterAddress())
.thenReturn(new InetSocketAddress("defaultHost", 1));
}
private void mockUserGroupInformation(String username) throws IOException {
// need to mock out since FileSystem.get calls UGI, which some times has issues on some systems
PowerMockito.mockStatic(UserGroupInformation.class);
final UserGroupInformation ugi = mock(UserGroupInformation.class);
when(UserGroupInformation.getCurrentUser()).thenReturn(ugi);
when(ugi.getUserName()).thenReturn(username);
when(ugi.getShortUserName()).thenReturn(username.split("@")[0]);
}
private void assertFileInfoEqualsFileStatus(FileInfo info, FileStatus status) {
assertEquals(info.getOwner(), status.getOwner());
assertEquals(info.getGroup(), status.getGroup());
assertEquals(info.getMode(), status.getPermission().toShort());
assertEquals(info.getLastModificationTimeMs(), status.getModificationTime());
assertEquals(info.isFolder(), status.isDir());
}
}
| [ALLUXIO-2036] Add a unit test to validate AbstractFileSystem#ListStatus exceptions
| core/client/hdfs/src/test/java/alluxio/hadoop/AbstractFileSystemTest.java | [ALLUXIO-2036] Add a unit test to validate AbstractFileSystem#ListStatus exceptions |
|
Java | apache-2.0 | db12fbd293a70449b851728eb7a46d6279db5023 | 0 | chrisvest/stormpot,chrisvest/stormpot | package stormpot.benchmark;
import java.util.Random;
public abstract class Benchmark {
private static final Random rnd = new Random();
private static final int SIZE = 10;
private static final long TRIAL_TIME_MILLIS = 500L;
private static final long OBJ_TTL_MILLIS = 5 * 60 * 100;
protected static Bench[] buildPoolList() {
return new Bench[] {
new QueuePoolBench(),
new QueuePoolWithClockTtlBench(),
new CmnsStackPoolBench(),
new CmnsGenericObjPoolBench()};
}
protected static void prime(Bench[] pools, int size, long objTtlMillis)
throws Exception {
for (Bench pool : pools) {
pool.primeWithSize(size, objTtlMillis);
}
}
protected static void shuffle(Bench[] pools) {
for (int i = 0; i < pools.length; i++) {
int index = i + rnd.nextInt(pools.length - i);
Bench tmp = pools[index];
pools[index] = pools[i];
pools[i] = tmp;
}
}
public static long runCycles(Bench bench, int cycles) throws Exception {
long start;
long end = 0;
for (int i = 0; i < cycles; i++) {
start = Clock.currentTimeMillis();
bench.claimAndRelease();
end = Clock.currentTimeMillis();
bench.recordTime(end - start);
}
return end;
}
protected abstract String getBenchmarkName();
protected abstract void benchmark(Bench bench, long trialTimeMillis) throws Exception;
public void run() {
Clock.start();
System.out.println(getBenchmarkName());
try {
runBenchmark();
} catch (Exception e) {
e.printStackTrace();
}
}
private void runBenchmark() throws Exception {
Bench[] pools = buildPoolList();
prime(pools, SIZE, OBJ_TTL_MILLIS);
warmup(pools);
trial(pools);
}
private void warmup(Bench[] pools) throws Exception {
System.out.println("Warming up pools...");
for (Bench pool : pools) {
warmup(pool, 1);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 13);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 1);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 1);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 4);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 1);
}
System.out.println("Warmup done.");
}
protected void warmup(Bench bench, int steps) throws Exception {
System.out.println(
"Warming up " + bench.getName() + " with " + steps + "K steps.");
for (int i = 0; i < steps; i++) {
for (int j = 0; j < 1000; j++) {
prepareAndRunBenchmark(bench, 1);
}
System.out.printf("%02d/%s.", i + 1, steps);
}
System.out.println("\ndone.");
}
protected void trial(Bench[] pools) throws Exception {
for (int i = 0; i < 10; i++) {
shuffle(pools);
for (Bench pool : pools) {
trial(pool);
}
}
}
private void trial(Bench bench) throws Exception {
Thread.sleep(10);
prepareAndRunBenchmark(bench, TRIAL_TIME_MILLIS);
bench.report();
}
protected void prepareAndRunBenchmark(Bench bench, long trialTimeMillis)
throws Exception {
beforeBenchmark(bench, trialTimeMillis);
benchmark(bench, trialTimeMillis);
}
protected void beforeBenchmark(Bench bench, long trialTimeMillis) {
bench.reset();
}
}
| stormpot-benchmark/src/main/java/stormpot/benchmark/Benchmark.java | package stormpot.benchmark;
import java.util.Random;
public abstract class Benchmark {
private static final Random rnd = new Random();
private static final int SIZE = 10;
private static final long TRIAL_TIME_MILLIS = 500L;
private static final long OBJ_TTL_MILLIS = 5 * 60 * 100;
protected static Bench[] buildPoolList() {
return new Bench[] {
new QueuePoolBench(),
new QueuePoolWithClockTtlBench(),
new CmnsStackPoolBench(),
new CmnsGenericObjPoolBench()};
}
protected static void prime(Bench[] pools, int size, long objTtlMillis)
throws Exception {
for (Bench pool : pools) {
pool.primeWithSize(size, objTtlMillis);
}
}
protected static void shuffle(Bench[] pools) {
for (int i = 0; i < pools.length; i++) {
int index = i + rnd.nextInt(pools.length - i);
Bench tmp = pools[index];
pools[index] = pools[i];
pools[i] = tmp;
}
}
public static long runCycles(Bench bench, int cycles) throws Exception {
long start;
long end = 0;
for (int i = 0; i < cycles; i++) {
start = Clock.currentTimeMillis();
bench.claimAndRelease();
end = Clock.currentTimeMillis();
bench.recordTime(end - start);
}
return end;
}
protected abstract String getBenchmarkName();
protected abstract void benchmark(Bench bench, long trialTimeMillis) throws Exception;
public void run() {
Clock.start();
System.out.println(getBenchmarkName());
try {
runBenchmark();
} catch (Exception e) {
e.printStackTrace();
}
}
private void runBenchmark() throws Exception {
Bench[] pools = buildPoolList();
prime(pools, SIZE, OBJ_TTL_MILLIS);
warmup(pools);
trial(pools);
}
private void warmup(Bench[] pools) throws Exception {
System.out.println("Warming up pools...");
for (Bench pool : pools) {
warmup(pool, 1);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 11);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 1);
}
shuffle(pools);
for (Bench pool : pools) {
warmup(pool, 1);
}
System.out.println("Warmup done.");
}
protected int[] warmupSteps() {
return new int[] {1, 11, 1, 1};
}
protected void warmup(Bench bench, int steps) throws Exception {
System.out.println(
"Warming up " + bench.getName() + " with " + steps + "K steps.");
for (int i = 0; i < steps; i++) {
for (int j = 0; j < 1000; j++) {
prepareAndRunBenchmark(bench, 1);
}
System.out.printf("%02d/%s.", i + 1, steps);
}
System.out.println("\ndone.");
}
protected void trial(Bench[] pools) throws Exception {
for (int i = 0; i < 10; i++) {
shuffle(pools);
for (Bench pool : pools) {
trial(pool);
}
}
}
private void trial(Bench bench) throws Exception {
Thread.sleep(10);
prepareAndRunBenchmark(bench, TRIAL_TIME_MILLIS);
bench.report();
}
protected void prepareAndRunBenchmark(Bench bench, long trialTimeMillis)
throws Exception {
beforeBenchmark(bench, trialTimeMillis);
benchmark(bench, trialTimeMillis);
}
protected void beforeBenchmark(Bench bench, long trialTimeMillis) {
bench.reset();
}
}
| try to improve the warmup for the MT benchmark -- still not perfect...
| stormpot-benchmark/src/main/java/stormpot/benchmark/Benchmark.java | try to improve the warmup for the MT benchmark -- still not perfect... |
|
Java | apache-2.0 | 47ea048c2360661798538932d235b731705aa5d1 | 0 | jasperhoogland/jautomata | package net.jhoogland.jautomata;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Map.Entry;
import net.jhoogland.jautomata.io.CharacterFormat;
import net.jhoogland.jautomata.io.AcceptorIO;
import net.jhoogland.jautomata.io.TransducerIO;
import net.jhoogland.jautomata.operations.AcceptorIntersection;
import net.jhoogland.jautomata.operations.Operations;
import net.jhoogland.jautomata.operations.SingleInitialStateOperation;
import net.jhoogland.jautomata.operations.Union;
import net.jhoogland.jautomata.queues.DefaultQueueFactory;
import net.jhoogland.jautomata.queues.KTropicalQueueFactory;
import net.jhoogland.jautomata.semirings.BestPathWeights;
import net.jhoogland.jautomata.semirings.BooleanSemiring;
import net.jhoogland.jautomata.semirings.KTropicalSemiring;
import net.jhoogland.jautomata.semirings.RealSemiring;
import net.jhoogland.jautomata.semirings.Semiring;
import static net.jhoogland.jautomata.operations.Operations.concat;
import static net.jhoogland.jautomata.operations.Operations.union;
/**
*
* This class contains static methods for computing properties of automata
* and creating various types of automata.
*
* @author Jasper Hoogland
*
*/
public class Automata
{
public static void main(String[] args) throws IOException
{
SinglePathAutomaton<Character, Double> a1 = createSinglePathAutomaton(new RealSemiring(), "a");
SinglePathAutomaton<Character, Double> a2 = createSinglePathAutomaton(new RealSemiring(), "b");
Automaton<Character, Double> complex = Operations.epsilonRemoval(Operations.singleInitialState(Operations.weightedClosure(Operations.weightedUnion(a1, a2), 0.6)));
List<Path<Character, Double>> ps = bestStrings(complex, 5);
for (Path<Character, Double> p : ps)
System.out.println(p.weight + ": " + toString(p.label));
}
/**
*
* @return
* a {@link Collection} containing all states of the specified automaton.
*
*/
public static <L, K> Collection<Object> states(Automaton<L, K> automaton)
{
ArrayList<Object> states = new ArrayList<Object>();
Set<Object> processed = new HashSet<Object>();
Comparator<Object> order = automaton.topologicalOrder();
Queue<Object> front = order == null ? new LinkedList<Object>() : new PriorityQueue<Object>(11, order);
front.addAll(automaton.initialStates());
processed.addAll(front);
while (! front.isEmpty())
{
Object state = front.poll();
states.add(state);
for (Object transition : automaton.transitionsOut(state))
{
Object next = automaton.nextState(transition);
if (! processed.contains(next))
{
front.add(next);
processed.add(next);
}
}
}
return states;
}
/**
*
* @return
* a {@link Collection} containing all transitions of the specified automaton.
*
*/
public static <L, K> Collection<Object> transitions(Automaton<L, K> automaton)
{
ArrayList<Object> transitions = new ArrayList<Object>();
Set<Object> processed = new HashSet<Object>();
Comparator<Object> order = automaton.topologicalOrder();
Queue<Object> front = order == null ? new LinkedList<Object>() : new PriorityQueue<Object>(11, order);
front.addAll(automaton.initialStates());
processed.addAll(front);
while (! front.isEmpty())
{
Object state = front.poll();
for (Object transition : automaton.transitionsOut(state))
{
transitions.add(transition);
Object next = automaton.nextState(transition);
if (! processed.contains(next))
{
front.add(next);
processed.add(next);
}
}
}
return transitions;
}
/**
*
* @return
* true if and only if the specified state is an initial state of the specified automaton
*
*/
public static <L, K> boolean isInitialState(Automaton<L, K> automaton, Object state)
{
return ! automaton.semiring().zero().equals(automaton.initialWeight(state));
}
/**
*
* @return
* true if and only if the specified state is an final state of the specified automaton
*
*/
public static <L, K> boolean isFinalState(Automaton<L, K> automaton, Object state)
{
return ! automaton.semiring().zero().equals(automaton.finalWeight(state));
}
/**
*
* @return
* the label of the specified path
*
*/
public static <L, K> List<L> pathLabel(Iterable<Object> path, Automaton<L, K> automaton)
{
ArrayList<L> pathLabel = new ArrayList<L>();
for (Object transition : path)
{
L label = automaton.label(transition);
if (label != null) pathLabel.add(label);
}
return pathLabel;
}
public static <L, K> SinglePathAutomaton<L, K> emptyStringAutomaton(Semiring<K> semiring)
{
return createSinglePathAutomaton(semiring, new ArrayList<L>(0));
}
public static <L, K> SinglePathAutomaton<L, K> createSinglePathAutomaton(Semiring<K> semiring, List<L> list)
{
return new SinglePathAutomaton<L, K>(semiring, list);
}
public static <K> SinglePathAutomaton<Character, K> createSinglePathAutomaton(Semiring<K> semiring, String str)
{
return createSinglePathAutomaton(semiring, toCharacterList(str));
}
public static <K> K stringWeight(Automaton<Character, K> automaton, String str)
{
return stringWeight(automaton, toCharacterList(str));
}
public static <L, K> K stringWeight(Automaton<L, K> automaton, List<L> string)
{
SingleSourceShortestDistances<K> sssd = new SingleSourceShortestDistances<K>(new DefaultQueueFactory<K>(), new ExactConvergence<K>());
return stringWeight(automaton, sssd, string);
}
public static <S, T, L, K> K stringWeight(Automaton<L, K> automaton, SingleSourceShortestDistances<K> sssd, List<L> string)
{
SinglePathAutomaton<L, K> stringAutomaton = new SinglePathAutomaton<L, K>(automaton.semiring(), string);
AcceptorIntersection<L, K> intersection = new AcceptorIntersection<L, K>(automaton, stringAutomaton);
return shortestCompleteDistances(intersection, sssd);
}
public static <L, K> List<Path<L, Double>> shortestPaths(Automaton<L, K> automaton, int numPaths, SingleSourceShortestDistances<BestPathWeights> sssd)
{
Automaton<L, BestPathWeights> kT = Operations.toKTropicalSemiring(automaton, numPaths);
BestPathWeights w = shortestCompleteDistances(kT, sssd);
ArrayList<Path<L, Double>> paths = new ArrayList<Path<L, Double>>();
for (int i = 0; i < w.pathWeights.length; i++) if (w.pathWeights[i].weight != Double.POSITIVE_INFINITY)
{
Path<L, Double> path = (Path<L, Double>) w.pathWeights[i].path((net.jhoogland.jautomata.Automaton<L, Double>) automaton);
path.weight = Math.exp(-path.weight);
paths.add(path);
}
return paths;
}
public static <L, K> List<Path<L, Double>> shortestPaths(Automaton<L, K> automaton, int numPaths)
{
SingleSourceShortestDistances<BestPathWeights> sssd = new SingleSourceShortestDistances<BestPathWeights>(new KTropicalQueueFactory(), new ExactConvergence<BestPathWeights>());
return shortestPaths(automaton, numPaths, sssd);
}
public static <L, K> List<Path<L, Double>> bestStrings(Automaton<L, K> automaton, int numPaths, SingleSourceShortestDistances<BestPathWeights> sssd)
{
Automaton<L, K> det = Operations.determinizeER(automaton);
return shortestPaths(det, numPaths, sssd);
}
public static <L, K> List<Path<L, Double>> bestStrings(Automaton<L, K> automaton, int numPaths)
{
Automaton<L, K> det = Operations.determinizeER(automaton);
return shortestPaths(det, numPaths);
}
public static <L, K> Map<Object, K> shortestDistancesFromInitialStates(Automaton<L, K> automaton, SingleSourceShortestDistancesInterface<K> sssd)
{
SingleInitialStateOperation<L, K> sisAutomaton = new SingleInitialStateOperation<L, K>(automaton);
Map<Object, K> sisMap = sssd.computeShortestDistances(sisAutomaton, sisAutomaton.initialState());
HashMap<Object, K> sdMap = new HashMap<Object, K>();
for (Entry<Object, K> e : sisMap.entrySet())
{
SingleInitialStateOperation<L, K>.SISState s = (SingleInitialStateOperation<L, K>.SISState) e.getKey();
if (s.operandState != null)
sdMap.put(s.operandState, e.getValue());
}
return sdMap;
}
public static <L, K> Map<Object, K> shortestDistancesToFinalStates(Automaton<L, K> automaton, SingleSourceShortestDistancesInterface<K> sssd)
{
Automaton<L, K> rev = Operations.reverse((ReverselyAccessibleAutomaton<L, K>) automaton);
SingleInitialStateOperation<L, K> sisAutomaton = new SingleInitialStateOperation<L, K>(rev);
Map<Object, K> sisMap = sssd.computeShortestDistances(sisAutomaton, sisAutomaton.initialState());
HashMap<Object, K> sdMap = new HashMap<Object, K>();
for (Entry<Object, K> e : sisMap.entrySet())
{
SingleInitialStateOperation<L, K>.SISState s = (SingleInitialStateOperation<L, K>.SISState) e.getKey();
if (s.operandState != null)
sdMap.put(s.operandState, e.getValue());
}
return sdMap;
}
public static <L, K> K shortestCompleteDistances(Automaton<L, K> automaton, SingleSourceShortestDistances<K> shortestDistanceAlgorithm)
{
Semiring<K> sr = automaton.semiring();
Map<Object, K> shortestDistances = shortestDistancesFromInitialStates(automaton, shortestDistanceAlgorithm);
K weight = sr.zero();
for (Entry<Object, K> e : shortestDistances.entrySet()) if (isFinalState(automaton, e.getKey()))
{
weight = sr.add(weight, sr.multiply(e.getValue(), automaton.finalWeight(e.getKey())));
}
return weight;
}
public static List<Character> toCharacterList(String str)
{
List<Character> characterList = new ArrayList<Character>(str.length());
for (int i = 0; i < str.length(); i++)
characterList.add(str.charAt(i));
return characterList;
}
public static String toString(List<Character> characterList)
{
String str = "";
for (Character c : characterList)
if (c != null)
str += c;
return str;
}
}
| jautomata/src/main/java/net/jhoogland/jautomata/Automata.java | package net.jhoogland.jautomata;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Map.Entry;
import net.jhoogland.jautomata.io.CharacterFormat;
import net.jhoogland.jautomata.io.AcceptorIO;
import net.jhoogland.jautomata.io.TransducerIO;
import net.jhoogland.jautomata.operations.AcceptorIntersection;
import net.jhoogland.jautomata.operations.Operations;
import net.jhoogland.jautomata.operations.SingleInitialStateOperation;
import net.jhoogland.jautomata.operations.Union;
import net.jhoogland.jautomata.queues.DefaultQueueFactory;
import net.jhoogland.jautomata.queues.KTropicalQueueFactory;
import net.jhoogland.jautomata.semirings.BestPathWeights;
import net.jhoogland.jautomata.semirings.BooleanSemiring;
import net.jhoogland.jautomata.semirings.KTropicalSemiring;
import net.jhoogland.jautomata.semirings.RealSemiring;
import net.jhoogland.jautomata.semirings.Semiring;
import static net.jhoogland.jautomata.operations.Operations.concat;
import static net.jhoogland.jautomata.operations.Operations.union;
/**
*
* This class contains static methods for computing properties of automata
* and creating various types of automata.
*
* @author Jasper Hoogland
*
*/
public class Automata
{
public static void main(String[] args) throws IOException
{
SinglePathAutomaton<Character, Double> a1 = createSinglePathAutomaton(new RealSemiring(), "a");
SinglePathAutomaton<Character, Double> a2 = createSinglePathAutomaton(new RealSemiring(), "b");
// for (Object state : states(a1))
// System.out.println(state);
// SingleSourceShortestDistances<Boolean> sssp = new SingleSourceShortestDistances<Boolean>(new DefaultQueueFactory<Boolean>(), new ExactConvergence<Boolean>());
// System.out.println(sssp.computeShortestDistances(automaton, 0));
// System.out.println(shortestCompleteDistances(automaton, sssp));
Automaton<Character, Double> complex = Operations.epsilonRemoval(Operations.singleInitialState(Operations.weightedClosure(Operations.weightedUnion(a1, a2), 0.6)));
File f = new File("C:\\Users\\Jasper\\Documents\\ta.txt");
File f2 = new File("C:\\Users\\Jasper\\Documents\\ta2.txt");
// Automaton<Character, Double> complex = IO.loadWeightedAcceptor(f, "att");
PrintWriter writer = new PrintWriter(f2);
AcceptorIO.write(complex, writer);
InputStream is = Automata.class.getResourceAsStream("indonesian-prefix-1.txt");
Transducer<Character, Character, Boolean> ip1 = TransducerIO.readUnweighted(new InputStreamReader(is, "UTF-8"));
Transducer<Character, Character, Boolean> pfMe = Transducers.outputTransducer(Automata.createSinglePathAutomaton(new BooleanSemiring(), "me"));
Transducer<Character, Character, Boolean> meWords = Transducers.concat(pfMe, ip1);
Automaton<Character, Boolean> r = Transducers.apply(meWords, "s");
List<Path<Character, Double>> ps = bestStrings(r, 5);
for (Path<Character, Double> p : ps)
System.out.println(p.weight + ": " + toString(p.label));
}
/**
*
* @return
* a {@link Collection} containing all states of the specified automaton.
*
*/
public static <L, K> Collection<Object> states(Automaton<L, K> automaton)
{
ArrayList<Object> states = new ArrayList<Object>();
Set<Object> processed = new HashSet<Object>();
Comparator<Object> order = automaton.topologicalOrder();
Queue<Object> front = order == null ? new LinkedList<Object>() : new PriorityQueue<Object>(11, order);
front.addAll(automaton.initialStates());
processed.addAll(front);
while (! front.isEmpty())
{
Object state = front.poll();
states.add(state);
for (Object transition : automaton.transitionsOut(state))
{
Object next = automaton.nextState(transition);
if (! processed.contains(next))
{
front.add(next);
processed.add(next);
}
}
}
return states;
}
/**
*
* @return
* a {@link Collection} containing all transitions of the specified automaton.
*
*/
public static <L, K> Collection<Object> transitions(Automaton<L, K> automaton)
{
ArrayList<Object> transitions = new ArrayList<Object>();
Set<Object> processed = new HashSet<Object>();
Comparator<Object> order = automaton.topologicalOrder();
Queue<Object> front = order == null ? new LinkedList<Object>() : new PriorityQueue<Object>(11, order);
front.addAll(automaton.initialStates());
processed.addAll(front);
while (! front.isEmpty())
{
Object state = front.poll();
for (Object transition : automaton.transitionsOut(state))
{
transitions.add(transition);
Object next = automaton.nextState(transition);
if (! processed.contains(next))
{
front.add(next);
processed.add(next);
}
}
}
return transitions;
}
/**
*
* @return
* true if and only if the specified state is an initial state of the specified automaton
*
*/
public static <L, K> boolean isInitialState(Automaton<L, K> automaton, Object state)
{
return ! automaton.semiring().zero().equals(automaton.initialWeight(state));
}
/**
*
* @return
* true if and only if the specified state is an final state of the specified automaton
*
*/
public static <L, K> boolean isFinalState(Automaton<L, K> automaton, Object state)
{
return ! automaton.semiring().zero().equals(automaton.finalWeight(state));
}
/**
*
* @return
* the label of the specified path
*
*/
public static <L, K> List<L> pathLabel(Iterable<Object> path, Automaton<L, K> automaton)
{
ArrayList<L> pathLabel = new ArrayList<L>();
for (Object transition : path)
{
L label = automaton.label(transition);
if (label != null) pathLabel.add(label);
}
return pathLabel;
}
public static <L, K> SinglePathAutomaton<L, K> emptyStringAutomaton(Semiring<K> semiring)
{
return createSinglePathAutomaton(semiring, new ArrayList<L>(0));
}
public static <L, K> SinglePathAutomaton<L, K> createSinglePathAutomaton(Semiring<K> semiring, List<L> list)
{
return new SinglePathAutomaton<L, K>(semiring, list);
}
public static <K> SinglePathAutomaton<Character, K> createSinglePathAutomaton(Semiring<K> semiring, String str)
{
return createSinglePathAutomaton(semiring, toCharacterList(str));
}
public static <K> K stringWeight(Automaton<Character, K> automaton, String str)
{
return stringWeight(automaton, toCharacterList(str));
}
public static <L, K> K stringWeight(Automaton<L, K> automaton, List<L> string)
{
SingleSourceShortestDistances<K> sssd = new SingleSourceShortestDistances<K>(new DefaultQueueFactory<K>(), new ExactConvergence<K>());
return stringWeight(automaton, sssd, string);
}
public static <S, T, L, K> K stringWeight(Automaton<L, K> automaton, SingleSourceShortestDistances<K> sssd, List<L> string)
{
SinglePathAutomaton<L, K> stringAutomaton = new SinglePathAutomaton<L, K>(automaton.semiring(), string);
AcceptorIntersection<L, K> intersection = new AcceptorIntersection<L, K>(automaton, stringAutomaton);
return shortestCompleteDistances(intersection, sssd);
}
public static <L, K> List<Path<L, Double>> shortestPaths(Automaton<L, K> automaton, int numPaths, SingleSourceShortestDistances<BestPathWeights> sssd)
{
Automaton<L, BestPathWeights> kT = Operations.toKTropicalSemiring(automaton, numPaths);
BestPathWeights w = shortestCompleteDistances(kT, sssd);
ArrayList<Path<L, Double>> paths = new ArrayList<Path<L, Double>>();
for (int i = 0; i < w.pathWeights.length; i++) if (w.pathWeights[i].weight != Double.POSITIVE_INFINITY)
{
Path<L, Double> path = (Path<L, Double>) w.pathWeights[i].path((net.jhoogland.jautomata.Automaton<L, Double>) automaton);
path.weight = Math.exp(-path.weight);
paths.add(path);
}
return paths;
}
public static <L, K> List<Path<L, Double>> shortestPaths(Automaton<L, K> automaton, int numPaths)
{
SingleSourceShortestDistances<BestPathWeights> sssd = new SingleSourceShortestDistances<BestPathWeights>(new KTropicalQueueFactory(), new ExactConvergence<BestPathWeights>());
return shortestPaths(automaton, numPaths, sssd);
}
public static <L, K> List<Path<L, Double>> bestStrings(Automaton<L, K> automaton, int numPaths, SingleSourceShortestDistances<BestPathWeights> sssd)
{
Automaton<L, K> det = Operations.determinizeER(automaton);
return shortestPaths(det, numPaths, sssd);
}
public static <L, K> List<Path<L, Double>> bestStrings(Automaton<L, K> automaton, int numPaths)
{
Automaton<L, K> det = Operations.determinizeER(automaton);
return shortestPaths(det, numPaths);
}
public static <L, K> Map<Object, K> shortestDistancesFromInitialStates(Automaton<L, K> automaton, SingleSourceShortestDistancesInterface<K> sssd)
{
SingleInitialStateOperation<L, K> sisAutomaton = new SingleInitialStateOperation<L, K>(automaton);
Map<Object, K> sisMap = sssd.computeShortestDistances(sisAutomaton, sisAutomaton.initialState());
HashMap<Object, K> sdMap = new HashMap<Object, K>();
for (Entry<Object, K> e : sisMap.entrySet())
{
SingleInitialStateOperation<L, K>.SISState s = (SingleInitialStateOperation<L, K>.SISState) e.getKey();
if (s.operandState != null)
sdMap.put(s.operandState, e.getValue());
}
return sdMap;
}
public static <L, K> Map<Object, K> shortestDistancesToFinalStates(Automaton<L, K> automaton, SingleSourceShortestDistancesInterface<K> sssd)
{
Automaton<L, K> rev = Operations.reverse((ReverselyAccessibleAutomaton<L, K>) automaton);
SingleInitialStateOperation<L, K> sisAutomaton = new SingleInitialStateOperation<L, K>(rev);
Map<Object, K> sisMap = sssd.computeShortestDistances(sisAutomaton, sisAutomaton.initialState());
HashMap<Object, K> sdMap = new HashMap<Object, K>();
for (Entry<Object, K> e : sisMap.entrySet())
{
SingleInitialStateOperation<L, K>.SISState s = (SingleInitialStateOperation<L, K>.SISState) e.getKey();
if (s.operandState != null)
sdMap.put(s.operandState, e.getValue());
}
return sdMap;
}
public static <L, K> K shortestCompleteDistances(Automaton<L, K> automaton, SingleSourceShortestDistances<K> shortestDistanceAlgorithm)
{
Semiring<K> sr = automaton.semiring();
Map<Object, K> shortestDistances = shortestDistancesFromInitialStates(automaton, shortestDistanceAlgorithm);
K weight = sr.zero();
for (Entry<Object, K> e : shortestDistances.entrySet()) if (isFinalState(automaton, e.getKey()))
{
weight = sr.add(weight, sr.multiply(e.getValue(), automaton.finalWeight(e.getKey())));
}
return weight;
}
public static List<Character> toCharacterList(String str)
{
List<Character> characterList = new ArrayList<Character>(str.length());
for (int i = 0; i < str.length(); i++)
characterList.add(str.charAt(i));
return characterList;
}
public static String toString(List<Character> characterList)
{
String str = "";
for (Character c : characterList)
if (c != null)
str += c;
return str;
}
}
| Test code changed. | jautomata/src/main/java/net/jhoogland/jautomata/Automata.java | Test code changed. |
|
Java | bsd-3-clause | 5e0fa6459c9638114451409539482bbb1e06bc7b | 0 | bsmr-java/jmonkeyengine,danteinforno/jmonkeyengine,g-rocket/jmonkeyengine,davidB/jmonkeyengine,bsmr-java/jmonkeyengine,tr0k/jmonkeyengine,rbottema/jmonkeyengine,bertleft/jmonkeyengine,atomixnmc/jmonkeyengine,InShadow/jmonkeyengine,skapi1992/jmonkeyengine,wrvangeest/jmonkeyengine,tr0k/jmonkeyengine,aaronang/jmonkeyengine,nickschot/jmonkeyengine,olafmaas/jmonkeyengine,yetanotherindie/jMonkey-Engine,skapi1992/jmonkeyengine,mbenson/jmonkeyengine,bertleft/jmonkeyengine,atomixnmc/jmonkeyengine,OpenGrabeso/jmonkeyengine,olafmaas/jmonkeyengine,zzuegg/jmonkeyengine,rbottema/jmonkeyengine,d235j/jmonkeyengine,GreenCubes/jmonkeyengine,Georgeto/jmonkeyengine,weilichuang/jmonkeyengine,weilichuang/jmonkeyengine,phr00t/jmonkeyengine,aaronang/jmonkeyengine,davidB/jmonkeyengine,mbenson/jmonkeyengine,shurun19851206/jMonkeyEngine,Georgeto/jmonkeyengine,mbenson/jmonkeyengine,amit2103/jmonkeyengine,g-rocket/jmonkeyengine,davidB/jmonkeyengine,delftsre/jmonkeyengine,mbenson/jmonkeyengine,nickschot/jmonkeyengine,atomixnmc/jmonkeyengine,davidB/jmonkeyengine,aaronang/jmonkeyengine,Georgeto/jmonkeyengine,InShadow/jmonkeyengine,shurun19851206/jMonkeyEngine,olafmaas/jmonkeyengine,zzuegg/jmonkeyengine,danteinforno/jmonkeyengine,g-rocket/jmonkeyengine,Georgeto/jmonkeyengine,InShadow/jmonkeyengine,davidB/jmonkeyengine,amit2103/jmonkeyengine,bertleft/jmonkeyengine,olafmaas/jmonkeyengine,bertleft/jmonkeyengine,OpenGrabeso/jmonkeyengine,OpenGrabeso/jmonkeyengine,sandervdo/jmonkeyengine,shurun19851206/jMonkeyEngine,yetanotherindie/jMonkey-Engine,nickschot/jmonkeyengine,rbottema/jmonkeyengine,wrvangeest/jmonkeyengine,weilichuang/jmonkeyengine,nickschot/jmonkeyengine,zzuegg/jmonkeyengine,tr0k/jmonkeyengine,GreenCubes/jmonkeyengine,phr00t/jmonkeyengine,d235j/jmonkeyengine,amit2103/jmonkeyengine,davidB/jmonkeyengine,bsmr-java/jmonkeyengine,jMonkeyEngine/jmonkeyengine,delftsre/jmonkeyengine,amit2103/jmonkeyengine,d235j/jmonkeyengine,tr0k/jmonkeyengine,danteinforno/jmonkeyengine,jMonkeyEngine/jmonkeyengine,phr00t/jmonkeyengine,wrvangeest/jmonkeyengine,rbottema/jmonkeyengine,amit2103/jmonkeyengine,Georgeto/jmonkeyengine,wrvangeest/jmonkeyengine,sandervdo/jmonkeyengine,weilichuang/jmonkeyengine,yetanotherindie/jMonkey-Engine,atomixnmc/jmonkeyengine,yetanotherindie/jMonkey-Engine,d235j/jmonkeyengine,amit2103/jmonkeyengine,shurun19851206/jMonkeyEngine,Georgeto/jmonkeyengine,sandervdo/jmonkeyengine,yetanotherindie/jMonkey-Engine,aaronang/jmonkeyengine,zzuegg/jmonkeyengine,OpenGrabeso/jmonkeyengine,GreenCubes/jmonkeyengine,phr00t/jmonkeyengine,g-rocket/jmonkeyengine,jMonkeyEngine/jmonkeyengine,OpenGrabeso/jmonkeyengine,skapi1992/jmonkeyengine,InShadow/jmonkeyengine,atomixnmc/jmonkeyengine,d235j/jmonkeyengine,mbenson/jmonkeyengine,shurun19851206/jMonkeyEngine,shurun19851206/jMonkeyEngine,GreenCubes/jmonkeyengine,danteinforno/jmonkeyengine,mbenson/jmonkeyengine,d235j/jmonkeyengine,danteinforno/jmonkeyengine,atomixnmc/jmonkeyengine,g-rocket/jmonkeyengine,jMonkeyEngine/jmonkeyengine,g-rocket/jmonkeyengine,weilichuang/jmonkeyengine,sandervdo/jmonkeyengine,weilichuang/jmonkeyengine,danteinforno/jmonkeyengine,delftsre/jmonkeyengine,bsmr-java/jmonkeyengine,yetanotherindie/jMonkey-Engine,delftsre/jmonkeyengine,OpenGrabeso/jmonkeyengine,skapi1992/jmonkeyengine | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* 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 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.scene.plugins;
import com.jme3.asset.*;
import com.jme3.material.Material;
import com.jme3.material.MaterialList;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.Mesh.Mode;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.mesh.IndexBuffer;
import com.jme3.scene.mesh.IndexIntBuffer;
import com.jme3.scene.mesh.IndexShortBuffer;
import com.jme3.util.BufferUtils;
import com.jme3.util.IntMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Reads OBJ format models.
*/
public final class OBJLoader implements AssetLoader {
private static final Logger logger = Logger.getLogger(OBJLoader.class.getName());
protected final ArrayList<Vector3f> verts = new ArrayList<Vector3f>();
protected final ArrayList<Vector2f> texCoords = new ArrayList<Vector2f>();
protected final ArrayList<Vector3f> norms = new ArrayList<Vector3f>();
protected final ArrayList<Face> faces = new ArrayList<Face>();
protected final HashMap<String, ArrayList<Face>> matFaces = new HashMap<String, ArrayList<Face>>();
protected String currentMatName;
protected String currentObjectName;
protected final HashMap<Vertex, Integer> vertIndexMap = new HashMap<Vertex, Integer>(100);
protected final IntMap<Vertex> indexVertMap = new IntMap<Vertex>(100);
protected int curIndex = 0;
protected int objectIndex = 0;
protected int geomIndex = 0;
protected Scanner scan;
protected ModelKey key;
protected AssetManager assetManager;
protected MaterialList matList;
protected String objName;
protected Node objNode;
protected static class Vertex {
Vector3f v;
Vector2f vt;
Vector3f vn;
int index;
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Vertex other = (Vertex) obj;
if (this.v != other.v && (this.v == null || !this.v.equals(other.v))) {
return false;
}
if (this.vt != other.vt && (this.vt == null || !this.vt.equals(other.vt))) {
return false;
}
if (this.vn != other.vn && (this.vn == null || !this.vn.equals(other.vn))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 53 * hash + (this.v != null ? this.v.hashCode() : 0);
hash = 53 * hash + (this.vt != null ? this.vt.hashCode() : 0);
hash = 53 * hash + (this.vn != null ? this.vn.hashCode() : 0);
return hash;
}
}
protected static class Face {
Vertex[] verticies;
}
protected class ObjectGroup {
final String objectName;
public ObjectGroup(String objectName){
this.objectName = objectName;
}
public Spatial createGeometry(){
Node groupNode = new Node(objectName);
if (objectName == null) {
groupNode.setName("Model");
}
// if (matFaces.size() > 0){
// for (Entry<String, ArrayList<Face>> entry : matFaces.entrySet()){
// ArrayList<Face> materialFaces = entry.getValue();
// if (materialFaces.size() > 0){
// Geometry geom = createGeometry(materialFaces, entry.getKey());
// objNode.attachChild(geom);
// }
// }
// }else if (faces.size() > 0){
// // generate final geometry
// Geometry geom = createGeometry(faces, null);
// objNode.attachChild(geom);
// }
return groupNode;
}
}
public void reset(){
verts.clear();
texCoords.clear();
norms.clear();
faces.clear();
matFaces.clear();
vertIndexMap.clear();
indexVertMap.clear();
currentMatName = null;
matList = null;
curIndex = 0;
geomIndex = 0;
scan = null;
}
protected void findVertexIndex(Vertex vert){
Integer index = vertIndexMap.get(vert);
if (index != null){
vert.index = index.intValue();
}else{
vert.index = curIndex++;
vertIndexMap.put(vert, vert.index);
indexVertMap.put(vert.index, vert);
}
}
protected Face[] quadToTriangle(Face f){
assert f.verticies.length == 4;
Face[] t = new Face[]{ new Face(), new Face() };
t[0].verticies = new Vertex[3];
t[1].verticies = new Vertex[3];
Vertex v0 = f.verticies[0];
Vertex v1 = f.verticies[1];
Vertex v2 = f.verticies[2];
Vertex v3 = f.verticies[3];
// find the pair of verticies that is closest to each over
// v0 and v2
// OR
// v1 and v3
float d1 = v0.v.distanceSquared(v2.v);
float d2 = v1.v.distanceSquared(v3.v);
if (d1 < d2){
// put an edge in v0, v2
t[0].verticies[0] = v0;
t[0].verticies[1] = v1;
t[0].verticies[2] = v3;
t[1].verticies[0] = v1;
t[1].verticies[1] = v2;
t[1].verticies[2] = v3;
}else{
// put an edge in v1, v3
t[0].verticies[0] = v0;
t[0].verticies[1] = v1;
t[0].verticies[2] = v2;
t[1].verticies[0] = v0;
t[1].verticies[1] = v2;
t[1].verticies[2] = v3;
}
return t;
}
private ArrayList<Vertex> vertList = new ArrayList<Vertex>();
protected void readFace(){
Face f = new Face();
vertList.clear();
String line = scan.nextLine().trim();
String[] verticies = line.split("\\s+");
for (String vertex : verticies){
int v = 0;
int vt = 0;
int vn = 0;
String[] split = vertex.split("/");
if (split.length == 1){
v = Integer.parseInt(split[0].trim());
}else if (split.length == 2){
v = Integer.parseInt(split[0].trim());
vt = Integer.parseInt(split[1].trim());
}else if (split.length == 3 && !split[1].equals("")){
v = Integer.parseInt(split[0].trim());
vt = Integer.parseInt(split[1].trim());
vn = Integer.parseInt(split[2].trim());
}else if (split.length == 3){
v = Integer.parseInt(split[0].trim());
vn = Integer.parseInt(split[2].trim());
}
if (v < 0) {
v = verts.size() + v + 1;
}
if (vt < 0) {
vt = texCoords.size() + vt + 1;
}
if (vn < 0) {
vn = norms.size() + vn + 1;
}
Vertex vx = new Vertex();
vx.v = verts.get(v - 1);
if (vt > 0)
vx.vt = texCoords.get(vt - 1);
if (vn > 0)
vx.vn = norms.get(vn - 1);
vertList.add(vx);
}
if (vertList.size() > 4 || vertList.size() <= 2) {
logger.warning("Edge or polygon detected in OBJ. Ignored.");
return;
}
f.verticies = new Vertex[vertList.size()];
for (int i = 0; i < vertList.size(); i++){
f.verticies[i] = vertList.get(i);
}
if (matList != null && matFaces.containsKey(currentMatName)){
matFaces.get(currentMatName).add(f);
}else{
faces.add(f); // faces that belong to the default material
}
}
protected Vector3f readVector3(){
Vector3f v = new Vector3f();
v.set(Float.parseFloat(scan.next()),
Float.parseFloat(scan.next()),
Float.parseFloat(scan.next()));
return v;
}
protected Vector2f readVector2(){
Vector2f v = new Vector2f();
String line = scan.nextLine().trim();
String[] split = line.split("\\s+");
v.setX( Float.parseFloat(split[0].trim()) );
v.setY( Float.parseFloat(split[1].trim()) );
// v.setX(scan.nextFloat());
// if (scan.hasNextFloat()){
// v.setY(scan.nextFloat());
// if (scan.hasNextFloat()){
// scan.nextFloat(); // ignore
// }
// }
return v;
}
protected void loadMtlLib(String name) throws IOException{
if (!name.toLowerCase().endsWith(".mtl"))
throw new IOException("Expected .mtl file! Got: " + name);
// NOTE: Cut off any relative/absolute paths
name = new File(name).getName();
AssetKey mtlKey = new AssetKey(key.getFolder() + name);
try {
matList = (MaterialList) assetManager.loadAsset(mtlKey);
} catch (AssetNotFoundException ex){
logger.log(Level.WARNING, "Cannot locate {0} for model {1}", new Object[]{name, key});
}
if (matList != null){
// create face lists for every material
for (String matName : matList.keySet()){
matFaces.put(matName, new ArrayList<Face>());
}
}
}
protected boolean nextStatement(){
try {
scan.skip(".*\r{0,1}\n");
return true;
} catch (NoSuchElementException ex){
// EOF
return false;
}
}
protected boolean readLine() throws IOException{
if (!scan.hasNext()){
return false;
}
String cmd = scan.next();
if (cmd.startsWith("#")){
// skip entire comment until next line
return nextStatement();
}else if (cmd.equals("v")){
// vertex position
verts.add(readVector3());
}else if (cmd.equals("vn")){
// vertex normal
norms.add(readVector3());
}else if (cmd.equals("vt")){
// texture coordinate
texCoords.add(readVector2());
}else if (cmd.equals("f")){
// face, can be triangle, quad, or polygon (unsupported)
readFace();
}else if (cmd.equals("usemtl")){
// use material from MTL lib for the following faces
currentMatName = scan.next();
// if (!matList.containsKey(currentMatName))
// throw new IOException("Cannot locate material " + currentMatName + " in MTL file!");
}else if (cmd.equals("mtllib")){
// specify MTL lib to use for this OBJ file
String mtllib = scan.nextLine().trim();
loadMtlLib(mtllib);
}else if (cmd.equals("s") || cmd.equals("g")){
return nextStatement();
}else{
// skip entire command until next line
logger.log(Level.WARNING, "Unknown statement in OBJ! {0}", cmd);
return nextStatement();
}
return true;
}
protected Geometry createGeometry(ArrayList<Face> faceList, String matName) throws IOException{
if (faceList.isEmpty())
throw new IOException("No geometry data to generate mesh");
// Create mesh from the faces
Mesh mesh = constructMesh(faceList);
Geometry geom = new Geometry(objName + "-geom-" + (geomIndex++), mesh);
Material material = null;
if (matName != null && matList != null){
// Get material from material list
material = matList.get(matName);
}
if (material == null){
// create default material
material = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
material.setFloat("Shininess", 64);
}
geom.setMaterial(material);
if (material.isTransparent())
geom.setQueueBucket(Bucket.Transparent);
else
geom.setQueueBucket(Bucket.Opaque);
if (material.getMaterialDef().getName().contains("Lighting")
&& mesh.getFloatBuffer(Type.Normal) == null){
logger.log(Level.WARNING, "OBJ mesh {0} doesn't contain normals! "
+ "It might not display correctly", geom.getName());
}
return geom;
}
protected Mesh constructMesh(ArrayList<Face> faceList){
Mesh m = new Mesh();
m.setMode(Mode.Triangles);
boolean hasTexCoord = false;
boolean hasNormals = false;
ArrayList<Face> newFaces = new ArrayList<Face>(faceList.size());
for (int i = 0; i < faceList.size(); i++){
Face f = faceList.get(i);
for (Vertex v : f.verticies){
findVertexIndex(v);
if (!hasTexCoord && v.vt != null)
hasTexCoord = true;
if (!hasNormals && v.vn != null)
hasNormals = true;
}
if (f.verticies.length == 4){
Face[] t = quadToTriangle(f);
newFaces.add(t[0]);
newFaces.add(t[1]);
}else{
newFaces.add(f);
}
}
FloatBuffer posBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 3);
FloatBuffer normBuf = null;
FloatBuffer tcBuf = null;
if (hasNormals){
normBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 3);
m.setBuffer(VertexBuffer.Type.Normal, 3, normBuf);
}
if (hasTexCoord){
tcBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 2);
m.setBuffer(VertexBuffer.Type.TexCoord, 2, tcBuf);
}
IndexBuffer indexBuf = null;
if (vertIndexMap.size() >= 65536){
// too many verticies: use intbuffer instead of shortbuffer
IntBuffer ib = BufferUtils.createIntBuffer(newFaces.size() * 3);
m.setBuffer(VertexBuffer.Type.Index, 3, ib);
indexBuf = new IndexIntBuffer(ib);
}else{
ShortBuffer sb = BufferUtils.createShortBuffer(newFaces.size() * 3);
m.setBuffer(VertexBuffer.Type.Index, 3, sb);
indexBuf = new IndexShortBuffer(sb);
}
int numFaces = newFaces.size();
for (int i = 0; i < numFaces; i++){
Face f = newFaces.get(i);
if (f.verticies.length != 3)
continue;
Vertex v0 = f.verticies[0];
Vertex v1 = f.verticies[1];
Vertex v2 = f.verticies[2];
posBuf.position(v0.index * 3);
posBuf.put(v0.v.x).put(v0.v.y).put(v0.v.z);
posBuf.position(v1.index * 3);
posBuf.put(v1.v.x).put(v1.v.y).put(v1.v.z);
posBuf.position(v2.index * 3);
posBuf.put(v2.v.x).put(v2.v.y).put(v2.v.z);
if (normBuf != null){
if (v0.vn != null){
normBuf.position(v0.index * 3);
normBuf.put(v0.vn.x).put(v0.vn.y).put(v0.vn.z);
normBuf.position(v1.index * 3);
normBuf.put(v1.vn.x).put(v1.vn.y).put(v1.vn.z);
normBuf.position(v2.index * 3);
normBuf.put(v2.vn.x).put(v2.vn.y).put(v2.vn.z);
}
}
if (tcBuf != null){
if (v0.vt != null){
tcBuf.position(v0.index * 2);
tcBuf.put(v0.vt.x).put(v0.vt.y);
tcBuf.position(v1.index * 2);
tcBuf.put(v1.vt.x).put(v1.vt.y);
tcBuf.position(v2.index * 2);
tcBuf.put(v2.vt.x).put(v2.vt.y);
}
}
int index = i * 3; // current face * 3 = current index
indexBuf.put(index, v0.index);
indexBuf.put(index+1, v1.index);
indexBuf.put(index+2, v2.index);
}
m.setBuffer(VertexBuffer.Type.Position, 3, posBuf);
// index buffer and others were set on creation
m.setStatic();
m.updateBound();
m.updateCounts();
//m.setInterleaved();
// clear data generated face statements
// to prepare for next mesh
vertIndexMap.clear();
indexVertMap.clear();
curIndex = 0;
return m;
}
@SuppressWarnings("empty-statement")
public Object load(AssetInfo info) throws IOException{
reset();
key = (ModelKey) info.getKey();
assetManager = info.getManager();
objName = key.getName();
String folderName = key.getFolder();
String ext = key.getExtension();
objName = objName.substring(0, objName.length() - ext.length() - 1);
if (folderName != null && folderName.length() > 0){
objName = objName.substring(folderName.length());
}
objNode = new Node(objName + "-objnode");
if (!(info.getKey() instanceof ModelKey))
throw new IllegalArgumentException("Model assets must be loaded using a ModelKey");
InputStream in = null;
try {
in = info.openStream();
scan = new Scanner(in);
scan.useLocale(Locale.US);
while (readLine());
} finally {
if (in != null){
in.close();
}
}
if (matFaces.size() > 0){
for (Entry<String, ArrayList<Face>> entry : matFaces.entrySet()){
ArrayList<Face> materialFaces = entry.getValue();
if (materialFaces.size() > 0){
Geometry geom = createGeometry(materialFaces, entry.getKey());
objNode.attachChild(geom);
}
}
}else if (faces.size() > 0){
// generate final geometry
Geometry geom = createGeometry(faces, null);
objNode.attachChild(geom);
}
if (objNode.getQuantity() == 1)
// only 1 geometry, so no need to send node
return objNode.getChild(0);
else
return objNode;
}
}
| engine/src/core-plugins/com/jme3/scene/plugins/OBJLoader.java | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* 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 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.scene.plugins;
import com.jme3.asset.*;
import com.jme3.material.Material;
import com.jme3.material.MaterialList;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.Mesh.Mode;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.mesh.IndexBuffer;
import com.jme3.scene.mesh.IndexIntBuffer;
import com.jme3.scene.mesh.IndexShortBuffer;
import com.jme3.util.BufferUtils;
import com.jme3.util.IntMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Reads OBJ format models.
*/
public final class OBJLoader implements AssetLoader {
private static final Logger logger = Logger.getLogger(OBJLoader.class.getName());
protected final ArrayList<Vector3f> verts = new ArrayList<Vector3f>();
protected final ArrayList<Vector2f> texCoords = new ArrayList<Vector2f>();
protected final ArrayList<Vector3f> norms = new ArrayList<Vector3f>();
protected final ArrayList<Face> faces = new ArrayList<Face>();
protected final HashMap<String, ArrayList<Face>> matFaces = new HashMap<String, ArrayList<Face>>();
protected String currentMatName;
protected String currentObjectName;
protected final HashMap<Vertex, Integer> vertIndexMap = new HashMap<Vertex, Integer>(100);
protected final IntMap<Vertex> indexVertMap = new IntMap<Vertex>(100);
protected int curIndex = 0;
protected int objectIndex = 0;
protected int geomIndex = 0;
protected Scanner scan;
protected ModelKey key;
protected AssetManager assetManager;
protected MaterialList matList;
protected String objName;
protected Node objNode;
protected static class Vertex {
Vector3f v;
Vector2f vt;
Vector3f vn;
int index;
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Vertex other = (Vertex) obj;
if (this.v != other.v && (this.v == null || !this.v.equals(other.v))) {
return false;
}
if (this.vt != other.vt && (this.vt == null || !this.vt.equals(other.vt))) {
return false;
}
if (this.vn != other.vn && (this.vn == null || !this.vn.equals(other.vn))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 53 * hash + (this.v != null ? this.v.hashCode() : 0);
hash = 53 * hash + (this.vt != null ? this.vt.hashCode() : 0);
hash = 53 * hash + (this.vn != null ? this.vn.hashCode() : 0);
return hash;
}
}
protected static class Face {
Vertex[] verticies;
}
protected class ObjectGroup {
final String objectName;
public ObjectGroup(String objectName){
this.objectName = objectName;
}
public Spatial createGeometry(){
Node groupNode = new Node(objectName);
// if (matFaces.size() > 0){
// for (Entry<String, ArrayList<Face>> entry : matFaces.entrySet()){
// ArrayList<Face> materialFaces = entry.getValue();
// if (materialFaces.size() > 0){
// Geometry geom = createGeometry(materialFaces, entry.getKey());
// objNode.attachChild(geom);
// }
// }
// }else if (faces.size() > 0){
// // generate final geometry
// Geometry geom = createGeometry(faces, null);
// objNode.attachChild(geom);
// }
return groupNode;
}
}
public void reset(){
verts.clear();
texCoords.clear();
norms.clear();
faces.clear();
matFaces.clear();
vertIndexMap.clear();
indexVertMap.clear();
currentMatName = null;
matList = null;
curIndex = 0;
geomIndex = 0;
scan = null;
}
protected void findVertexIndex(Vertex vert){
Integer index = vertIndexMap.get(vert);
if (index != null){
vert.index = index.intValue();
}else{
vert.index = curIndex++;
vertIndexMap.put(vert, vert.index);
indexVertMap.put(vert.index, vert);
}
}
protected Face[] quadToTriangle(Face f){
assert f.verticies.length == 4;
Face[] t = new Face[]{ new Face(), new Face() };
t[0].verticies = new Vertex[3];
t[1].verticies = new Vertex[3];
Vertex v0 = f.verticies[0];
Vertex v1 = f.verticies[1];
Vertex v2 = f.verticies[2];
Vertex v3 = f.verticies[3];
// find the pair of verticies that is closest to each over
// v0 and v2
// OR
// v1 and v3
float d1 = v0.v.distanceSquared(v2.v);
float d2 = v1.v.distanceSquared(v3.v);
if (d1 < d2){
// put an edge in v0, v2
t[0].verticies[0] = v0;
t[0].verticies[1] = v1;
t[0].verticies[2] = v3;
t[1].verticies[0] = v1;
t[1].verticies[1] = v2;
t[1].verticies[2] = v3;
}else{
// put an edge in v1, v3
t[0].verticies[0] = v0;
t[0].verticies[1] = v1;
t[0].verticies[2] = v2;
t[1].verticies[0] = v0;
t[1].verticies[1] = v2;
t[1].verticies[2] = v3;
}
return t;
}
private ArrayList<Vertex> vertList = new ArrayList<Vertex>();
protected void readFace(){
Face f = new Face();
vertList.clear();
String line = scan.nextLine().trim();
String[] verticies = line.split("\\s+");
for (String vertex : verticies){
int v = 0;
int vt = 0;
int vn = 0;
String[] split = vertex.split("/");
if (split.length == 1){
v = Integer.parseInt(split[0].trim());
}else if (split.length == 2){
v = Integer.parseInt(split[0].trim());
vt = Integer.parseInt(split[1].trim());
}else if (split.length == 3 && !split[1].equals("")){
v = Integer.parseInt(split[0].trim());
vt = Integer.parseInt(split[1].trim());
vn = Integer.parseInt(split[2].trim());
}else if (split.length == 3){
v = Integer.parseInt(split[0].trim());
vn = Integer.parseInt(split[2].trim());
}
if (v < 0) {
v = verts.size() + v + 1;
}
if (vt < 0) {
vt = texCoords.size() + vt + 1;
}
if (vn < 0) {
vn = norms.size() + vn + 1;
}
Vertex vx = new Vertex();
vx.v = verts.get(v - 1);
if (vt > 0)
vx.vt = texCoords.get(vt - 1);
if (vn > 0)
vx.vn = norms.get(vn - 1);
vertList.add(vx);
}
if (vertList.size() > 4 || vertList.size() <= 2) {
logger.warning("Edge or polygon detected in OBJ. Ignored.");
return;
}
f.verticies = new Vertex[vertList.size()];
for (int i = 0; i < vertList.size(); i++){
f.verticies[i] = vertList.get(i);
}
if (matList != null && matFaces.containsKey(currentMatName)){
matFaces.get(currentMatName).add(f);
}else{
faces.add(f); // faces that belong to the default material
}
}
protected Vector3f readVector3(){
Vector3f v = new Vector3f();
v.set(Float.parseFloat(scan.next()),
Float.parseFloat(scan.next()),
Float.parseFloat(scan.next()));
return v;
}
protected Vector2f readVector2(){
Vector2f v = new Vector2f();
String line = scan.nextLine().trim();
String[] split = line.split("\\s+");
v.setX( Float.parseFloat(split[0].trim()) );
v.setY( Float.parseFloat(split[1].trim()) );
// v.setX(scan.nextFloat());
// if (scan.hasNextFloat()){
// v.setY(scan.nextFloat());
// if (scan.hasNextFloat()){
// scan.nextFloat(); // ignore
// }
// }
return v;
}
protected void loadMtlLib(String name) throws IOException{
if (!name.toLowerCase().endsWith(".mtl"))
throw new IOException("Expected .mtl file! Got: " + name);
// NOTE: Cut off any relative/absolute paths
name = new File(name).getName();
AssetKey mtlKey = new AssetKey(key.getFolder() + name);
try {
matList = (MaterialList) assetManager.loadAsset(mtlKey);
} catch (AssetNotFoundException ex){
logger.log(Level.WARNING, "Cannot locate {0} for model {1}", new Object[]{name, key});
}
if (matList != null){
// create face lists for every material
for (String matName : matList.keySet()){
matFaces.put(matName, new ArrayList<Face>());
}
}
}
protected boolean nextStatement(){
try {
scan.skip(".*\r{0,1}\n");
return true;
} catch (NoSuchElementException ex){
// EOF
return false;
}
}
protected boolean readLine() throws IOException{
if (!scan.hasNext()){
return false;
}
String cmd = scan.next();
if (cmd.startsWith("#")){
// skip entire comment until next line
return nextStatement();
}else if (cmd.equals("v")){
// vertex position
verts.add(readVector3());
}else if (cmd.equals("vn")){
// vertex normal
norms.add(readVector3());
}else if (cmd.equals("vt")){
// texture coordinate
texCoords.add(readVector2());
}else if (cmd.equals("f")){
// face, can be triangle, quad, or polygon (unsupported)
readFace();
}else if (cmd.equals("usemtl")){
// use material from MTL lib for the following faces
currentMatName = scan.next();
// if (!matList.containsKey(currentMatName))
// throw new IOException("Cannot locate material " + currentMatName + " in MTL file!");
}else if (cmd.equals("mtllib")){
// specify MTL lib to use for this OBJ file
String mtllib = scan.nextLine().trim();
loadMtlLib(mtllib);
}else if (cmd.equals("s") || cmd.equals("g")){
return nextStatement();
}else{
// skip entire command until next line
logger.log(Level.WARNING, "Unknown statement in OBJ! {0}", cmd);
return nextStatement();
}
return true;
}
protected Geometry createGeometry(ArrayList<Face> faceList, String matName) throws IOException{
if (faceList.isEmpty())
throw new IOException("No geometry data to generate mesh");
// Create mesh from the faces
Mesh mesh = constructMesh(faceList);
Geometry geom = new Geometry(objName + "-geom-" + (geomIndex++), mesh);
Material material = null;
if (matName != null && matList != null){
// Get material from material list
material = matList.get(matName);
}
if (material == null){
// create default material
material = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
material.setFloat("Shininess", 64);
}
geom.setMaterial(material);
if (material.isTransparent())
geom.setQueueBucket(Bucket.Transparent);
else
geom.setQueueBucket(Bucket.Opaque);
if (material.getMaterialDef().getName().contains("Lighting")
&& mesh.getFloatBuffer(Type.Normal) == null){
logger.log(Level.WARNING, "OBJ mesh {0} doesn't contain normals! "
+ "It might not display correctly", geom.getName());
}
return geom;
}
protected Mesh constructMesh(ArrayList<Face> faceList){
Mesh m = new Mesh();
m.setMode(Mode.Triangles);
boolean hasTexCoord = false;
boolean hasNormals = false;
ArrayList<Face> newFaces = new ArrayList<Face>(faceList.size());
for (int i = 0; i < faceList.size(); i++){
Face f = faceList.get(i);
for (Vertex v : f.verticies){
findVertexIndex(v);
if (!hasTexCoord && v.vt != null)
hasTexCoord = true;
if (!hasNormals && v.vn != null)
hasNormals = true;
}
if (f.verticies.length == 4){
Face[] t = quadToTriangle(f);
newFaces.add(t[0]);
newFaces.add(t[1]);
}else{
newFaces.add(f);
}
}
FloatBuffer posBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 3);
FloatBuffer normBuf = null;
FloatBuffer tcBuf = null;
if (hasNormals){
normBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 3);
m.setBuffer(VertexBuffer.Type.Normal, 3, normBuf);
}
if (hasTexCoord){
tcBuf = BufferUtils.createFloatBuffer(vertIndexMap.size() * 2);
m.setBuffer(VertexBuffer.Type.TexCoord, 2, tcBuf);
}
IndexBuffer indexBuf = null;
if (vertIndexMap.size() >= 65536){
// too many verticies: use intbuffer instead of shortbuffer
IntBuffer ib = BufferUtils.createIntBuffer(newFaces.size() * 3);
m.setBuffer(VertexBuffer.Type.Index, 3, ib);
indexBuf = new IndexIntBuffer(ib);
}else{
ShortBuffer sb = BufferUtils.createShortBuffer(newFaces.size() * 3);
m.setBuffer(VertexBuffer.Type.Index, 3, sb);
indexBuf = new IndexShortBuffer(sb);
}
int numFaces = newFaces.size();
for (int i = 0; i < numFaces; i++){
Face f = newFaces.get(i);
if (f.verticies.length != 3)
continue;
Vertex v0 = f.verticies[0];
Vertex v1 = f.verticies[1];
Vertex v2 = f.verticies[2];
posBuf.position(v0.index * 3);
posBuf.put(v0.v.x).put(v0.v.y).put(v0.v.z);
posBuf.position(v1.index * 3);
posBuf.put(v1.v.x).put(v1.v.y).put(v1.v.z);
posBuf.position(v2.index * 3);
posBuf.put(v2.v.x).put(v2.v.y).put(v2.v.z);
if (normBuf != null){
if (v0.vn != null){
normBuf.position(v0.index * 3);
normBuf.put(v0.vn.x).put(v0.vn.y).put(v0.vn.z);
normBuf.position(v1.index * 3);
normBuf.put(v1.vn.x).put(v1.vn.y).put(v1.vn.z);
normBuf.position(v2.index * 3);
normBuf.put(v2.vn.x).put(v2.vn.y).put(v2.vn.z);
}
}
if (tcBuf != null){
if (v0.vt != null){
tcBuf.position(v0.index * 2);
tcBuf.put(v0.vt.x).put(v0.vt.y);
tcBuf.position(v1.index * 2);
tcBuf.put(v1.vt.x).put(v1.vt.y);
tcBuf.position(v2.index * 2);
tcBuf.put(v2.vt.x).put(v2.vt.y);
}
}
int index = i * 3; // current face * 3 = current index
indexBuf.put(index, v0.index);
indexBuf.put(index+1, v1.index);
indexBuf.put(index+2, v2.index);
}
m.setBuffer(VertexBuffer.Type.Position, 3, posBuf);
// index buffer and others were set on creation
m.setStatic();
m.updateBound();
m.updateCounts();
//m.setInterleaved();
// clear data generated face statements
// to prepare for next mesh
vertIndexMap.clear();
indexVertMap.clear();
curIndex = 0;
return m;
}
@SuppressWarnings("empty-statement")
public Object load(AssetInfo info) throws IOException{
reset();
key = (ModelKey) info.getKey();
assetManager = info.getManager();
objName = key.getName();
String folderName = key.getFolder();
String ext = key.getExtension();
objName = objName.substring(0, objName.length() - ext.length() - 1);
if (folderName != null && folderName.length() > 0){
objName = objName.substring(folderName.length());
}
objNode = new Node(objName + "-objnode");
if (!(info.getKey() instanceof ModelKey))
throw new IllegalArgumentException("Model assets must be loaded using a ModelKey");
InputStream in = null;
try {
in = info.openStream();
scan = new Scanner(in);
scan.useLocale(Locale.US);
while (readLine());
} finally {
if (in != null){
in.close();
}
}
if (matFaces.size() > 0){
for (Entry<String, ArrayList<Face>> entry : matFaces.entrySet()){
ArrayList<Face> materialFaces = entry.getValue();
if (materialFaces.size() > 0){
Geometry geom = createGeometry(materialFaces, entry.getKey());
objNode.attachChild(geom);
}
}
}else if (faces.size() > 0){
// generate final geometry
Geometry geom = createGeometry(faces, null);
objNode.attachChild(geom);
}
if (objNode.getQuantity() == 1)
// only 1 geometry, so no need to send node
return objNode.getChild(0);
else
return objNode;
}
}
| - avoid null node names in obj importer
git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@10362 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| engine/src/core-plugins/com/jme3/scene/plugins/OBJLoader.java | - avoid null node names in obj importer |
|
Java | mit | e301549a8095293c3cd1d639bb71af7cbff9922e | 0 | concord-consortium/webstart-maven-plugin | package org.codehaus.mojo.webstart;
/*
* Copyright 2001-2005 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.
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.Vector;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang.SystemUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.resolver.filter.IncludesArtifactFilter;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.jar.JarSignMojo;
import org.apache.maven.plugin.jar.JarSignVerifyMojo;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.settings.Settings;
import org.apache.tools.ant.BuildException;
import org.codehaus.mojo.keytool.GenkeyMojo;
import org.codehaus.mojo.webstart.generator.Generator;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.cli.StreamFeeder;
import org.codehaus.plexus.util.cli.StreamPumper;
/**
* Packages a jnlp application.
* <p/>
* The plugin tries to not re-sign/re-pack if the dependent jar hasn't changed.
* As a consequence, if one modifies the pom jnlp config or a keystore, one should clean before rebuilding.
*
* @author <a href="[email protected]">Jerome Lacoste</a>
* @version $Id: JnlpMojo.java 1908 2006-06-06 13:48:13 +0000 (Tue, 06 Jun 2006) lacostej $
* @goal jnlp
* @phase package
* @requiresDependencyResolution runtime
* @requiresProject
* @inheritedByDefault true
* @todo refactor the common code with javadoc plugin
* @todo how to propagate the -X argument to enable verbose?
* @todo initialize the jnlp alias and dname.o from pom.artifactId and pom.organization.name
*/
public class JnlpMojo
extends AbstractMojo
{
/**
* These shouldn't be necessary, but just incase the main ones in
* maven change. They can be found in SnapshotTransform class
*/
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone( "UTC" );
private static final String UTC_TIMESTAMP_PATTERN = "yyyyMMdd.HHmmss";
/**
* Directory to create the resulting artifacts
*
* @parameter expression="${project.build.directory}/jnlp"
* @required
*/
protected File workDirectory;
/**
* The Zip archiver.
*
* @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#zip}"
* @required
*/
private ZipArchiver zipArchiver;
/**
* Project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* Xxx
*
* @parameter
*/
private JnlpConfig jnlp;
/**
* Xxx
*
* @parameter
*/
private Dependencies dependencies;
public static class Dependencies
{
private List includes;
private List excludes;
private List includeClassifiers;
private List excludeClassifiers;
public List getIncludes()
{
return includes;
}
public void setIncludes( List includes )
{
this.includes = includes;
}
public List getIncludeClassifiers() {
return includeClassifiers;
}
public void setIncludeClassifiers(List includeClassifiers) {
this.includeClassifiers = includeClassifiers;
}
public List getExcludes()
{
return excludes;
}
public void setExcludes( List excludes )
{
this.excludes = excludes;
}
public List getExcludeClassifiers() {
return excludeClassifiers;
}
public void setExcludeClassifiers(List excludeClassifiers) {
this.excludeClassifiers = excludeClassifiers;
}
}
/**
* Xxx
*
* @parameter
*/
private List artifactGroups;
/**
* Xxx
*
* @parameter
*/
private SignConfig sign;
/**
* Xxx
*
* @parameter default-value="false"
*/
// private boolean usejnlpservlet;
/**
* Xxx
*
* @parameter default-value="true"
*/
private boolean verifyjar;
/**
* Enables pack200. Requires SDK 5.0.
*
* @parameter default-value="false"
*/
private boolean pack200;
/**
* Xxx
*
* @parameter default-value="false"
*/
private boolean gzip;
/**
* Enable verbose.
*
* @parameter expression="${verbose}" default-value="false"
*/
private boolean verbose;
/**
* @parameter expression="${basedir}"
* @required
* @readonly
*/
private File basedir;
/**
* Artifact resolver, needed to download source jars for inclusion in classpath.
*
* @parameter expression="${component.org.apache.maven.artifact.resolver.ArtifactResolver}"
* @required
* @readonly
* @todo waiting for the component tag
*/
private ArtifactResolver artifactResolver;
/**
* Artifact factory, needed to download source jars for inclusion in classpath.
*
* @parameter expression="${component.org.apache.maven.artifact.factory.ArtifactFactory}"
* @required
* @readonly
* @todo waiting for the component tag
*/
private ArtifactFactory artifactFactory;
/**
* @parameter expression="${localRepository}"
* @required
* @readonly
*/
protected ArtifactRepository localRepository;
/**
* @parameter expression="${component.org.apache.maven.project.MavenProjectHelper}
*/
private MavenProjectHelper projectHelper;
/**
* The current user system settings for use in Maven. This is used for
* <br/>
* plugin manager API calls.
*
* @parameter expression="${settings}"
* @required
* @readonly
*/
private Settings settings;
/**
* The plugin manager instance used to resolve plugin descriptors.
*
* @component role="org.apache.maven.plugin.PluginManager"
*/
private PluginManager pluginManager;
private class CompositeFileFilter
implements FileFilter
{
private List fileFilters = new ArrayList();
CompositeFileFilter( FileFilter filter1, FileFilter filter2 )
{
fileFilters.add( filter1 );
fileFilters.add( filter2 );
}
public boolean accept( File pathname )
{
for ( int i = 0; i < fileFilters.size(); i++ )
{
if ( ! ( (FileFilter) fileFilters.get( i ) ).accept( pathname ) )
{
return false;
}
}
return true;
}
}
/**
* The maven-xbean-plugin can't handle anon inner classes
*
* @author scott
*
*/
private class ModifiedFileFilter
implements FileFilter
{
public boolean accept( File pathname )
{
boolean modified = pathname.lastModified() > getStartTime();
getLog().debug( "File: " + pathname.getName() + " modified: " + modified );
getLog().debug( "lastModified: " + pathname.lastModified() + " plugin start time " + getStartTime() );
return modified;
}
}
private FileFilter modifiedFileFilter = new ModifiedFileFilter();
/**
* @author scott
*
*/
private final class JarFileFilter implements FileFilter {
public boolean accept( File pathname )
{
return pathname.isFile() && pathname.getName().endsWith( ".jar" );
}
}
private FileFilter jarFileFilter = new JarFileFilter();
/**
* @author scott
*
*/
private final class Pack200FileFilter implements FileFilter {
public boolean accept( File pathname )
{
return pathname.isFile() &&
( pathname.getName().endsWith( ".jar.pack.gz" ) || pathname.getName().endsWith( ".jar.pack" ) );
}
}
private FileFilter pack200FileFilter = new Pack200FileFilter();
// the jars to sign and pack are selected if they are newer than the plugin start.
// as the plugin copies the new versions locally before signing/packing them
// we just need to see if the plugin copied a new version
// We achieve that by only filtering files modified after the plugin was started
// FIXME we may want to also resign/repack the jars if other files (the pom, the keystore config) have changed
// today one needs to clean...
private FileFilter updatedJarFileFilter = new CompositeFileFilter( jarFileFilter, modifiedFileFilter );
private FileFilter updatedPack200FileFilter = new CompositeFileFilter( pack200FileFilter, modifiedFileFilter );
/**
* the artifacts packaged in the webstart app. *
*/
private List packagedJnlpArtifacts = new ArrayList();
/**
* A map of groups of dependencies for the jnlp file.
* the key of each group is string which can be referenced in
*/
private Map jnlpArtifactGroups = new HashMap();
private ArrayList processedJnlpArtifacts = new ArrayList();
private Artifact artifactWithMainClass;
// initialized by execute
private long startTime;
private String jnlpBuildVersion;
private File temporaryDirectory;
private long getStartTime()
{
if ( startTime == 0 )
{
throw new IllegalStateException( "startTime not initialized" );
}
return startTime;
}
public void execute()
throws MojoExecutionException
{
checkInput();
if(jnlp == null) {
getLog().debug( "skipping project because no jnlp element was found");
return;
}
// interesting: copied files lastModified time stamp will be rounded.
// We have to be sure that the startTime is before that time...
// rounding to the second - 1 millis should be sufficient..
startTime = System.currentTimeMillis() - 1000;
File workDirectory = getWorkDirectory();
getLog().debug( "using work directory " + workDirectory );
//
// prepare layout
//
if ( !workDirectory.exists() && !workDirectory.mkdirs() )
{
throw new MojoExecutionException( "Failed to create: " + workDirectory.getAbsolutePath() );
}
try
{
File resourcesDir = getJnlp().getResources();
if ( resourcesDir == null )
{
resourcesDir = new File( project.getBasedir(), "src/main/jnlp" );
}
copyResources( resourcesDir, workDirectory );
artifactWithMainClass = null;
processDependencies();
buildArtifactGroups();
if ( artifactWithMainClass == null )
{
getLog().info( "skipping project because no main class: " +
jnlp.getMainClass() + " was found");
return;
/*
throw new MojoExecutionException(
"didn't find artifact with main class: " + jnlp.getMainClass() + ". Did you specify it? " );
*/
}
File jnlpDirectory = workDirectory;
if(jnlp.getGroupIdDirs()) {
// store the jnlp in the same layout as the jar files
// if groupIdDirs is true
jnlpDirectory =
getArtifactJnlpDirFile(getProject().getArtifact());
}
generateJnlpFile( jnlpDirectory );
if(jnlp.getCreateZip()) {
// package the zip. Note this is very simple. Look at the JarMojo which does more things.
// we should perhaps package as a war when inside a project with war packaging ?
File toFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".zip" );
if ( toFile.exists() )
{
getLog().debug( "deleting file " + toFile );
toFile.delete();
}
zipArchiver.addDirectory( workDirectory );
zipArchiver.setDestFile( toFile );
getLog().debug( "about to call createArchive" );
zipArchiver.createArchive();
// maven 2 version 2.0.1 method
projectHelper.attachArtifact( project, "zip", toFile );
}
}
catch ( MojoExecutionException e )
{
throw e;
}
catch ( Exception e )
{
throw new MojoExecutionException( "Failure to run the plugin: ", e );
/*
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter( sw, true );
e.printStackTrace( pw );
pw.flush();
sw.flush();
getLog().debug( "An error occurred during the task: " + sw.toString() );
*/
}
}
private void copyResources( File resourcesDir, File workDirectory )
throws IOException
{
if ( ! resourcesDir.exists() )
{
getLog().info( "No resources found in " + resourcesDir.getAbsolutePath() );
}
else
{
if ( ! resourcesDir.isDirectory() )
{
getLog().debug( "Not a directory: " + resourcesDir.getAbsolutePath() );
}
else
{
getLog().debug( "Copying resources from " + resourcesDir.getAbsolutePath() );
// hopefully available from FileUtils 1.0.5-SNAPSHOT
// FileUtils.copyDirectoryStructure( resourcesDir , workDirectory );
// this may needs to be parametrized somehow
String excludes = concat( DirectoryScanner.DEFAULTEXCLUDES, ", " );
copyDirectoryStructure( resourcesDir, workDirectory, "**", excludes );
}
}
}
private static String concat( String[] array, String delim )
{
StringBuffer buffer = new StringBuffer();
for ( int i = 0; i < array.length; i++ )
{
if ( i > 0 )
{
buffer.append( delim );
}
String s = array[i];
buffer.append( s ).append( delim );
}
return buffer.toString();
}
private void copyDirectoryStructure( File sourceDirectory, File destinationDirectory, String includes,
String excludes )
throws IOException
{
if ( ! sourceDirectory.exists() )
{
return;
}
List files = FileUtils.getFiles( sourceDirectory, includes, excludes );
for ( Iterator i = files.iterator(); i.hasNext(); )
{
File file = (File) i.next();
getLog().debug( "Copying " + file + " to " + destinationDirectory );
String path = file.getAbsolutePath().substring( sourceDirectory.getAbsolutePath().length() + 1 );
File destDir = new File( destinationDirectory, path );
getLog().debug( "Copying " + file + " to " + destDir );
if ( file.isDirectory() )
{
destDir.mkdirs();
}
else
{
FileUtils.copyFileToDirectory( file, destDir.getParentFile() );
}
}
}
private ArtifactFilter createArtifactFilter(Dependencies dependencies)
{
AndArtifactFilter filter = new AndArtifactFilter();
if ( dependencies == null) {
return filter;
}
if ( dependencies.getIncludes() != null && !dependencies.getIncludes().isEmpty() )
{
filter.add( new IncludesArtifactFilter( dependencies.getIncludes() ) );
}
if ( dependencies.getIncludeClassifiers() != null && !dependencies.getIncludeClassifiers().isEmpty() )
{
final List classifierList = dependencies.getIncludeClassifiers();
filter.add( new ArtifactFilter (){
public boolean include(Artifact artifact) {
if(!artifact.hasClassifier()) {
return false;
}
String classifer = artifact.getClassifier();
if (classifierList.contains(classifer)) {
return true;
}
return false;
};
});
}
if ( dependencies.getExcludeClassifiers() != null && !dependencies.getExcludeClassifiers().isEmpty() )
{
final List classifierList = dependencies.getExcludeClassifiers();
filter.add( new ArtifactFilter (){
public boolean include(Artifact artifact) {
String classifier = artifact.getClassifier();
// The artifact has no classifier so this excludes rule doesn't
// apply
if(classifier == null || classifier.length() == 0) {
return true;
}
// special pattern hack so excluding * can be handled
// if star is used then any artifact with a classifier is excluded
if(classifierList.contains("*")) {
return false;
}
if (classifierList.contains(classifier)) {
return false;
}
return true;
};
});
}
if ( dependencies.getExcludes() != null && !dependencies.getExcludes().isEmpty() )
{
filter.add( new ExcludesArtifactFilter( dependencies.getExcludes() ) );
}
return filter;
}
/**
* Iterate through all the top level and transitive dependencies declared in the project and
* collect all the runtime scope dependencies for inclusion in the .zip and signing.
*
* @throws IOException
* @throws MojoExecutionException
*/
private void processDependencies()
throws IOException, MojoExecutionException
{
processDependency( getProject().getArtifact(), packagedJnlpArtifacts );
ArtifactFilter filter = createArtifactFilter(dependencies);
Collection artifacts = getProject().getArtifacts();
for ( Iterator it = artifacts.iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
if ( filter.include( artifact ) )
{
processDependency( artifact , packagedJnlpArtifacts);
}
}
// Check if the temporaryDirectory is empty, if so delete it
File tmpDirectory = getTemporaryDirectory();
File [] tmpArtifactDirs = tmpDirectory.listFiles();
if(tmpArtifactDirs != null && tmpArtifactDirs.length != 0){
throw new MojoExecutionException("Left over files in : " + tmpDirectory);
}
tmpDirectory.delete();
}
private void processDependency( Artifact artifact , List artifactList)
throws IOException, MojoExecutionException
{
// TODO: scope handler
// skip provided and test scopes
if ( Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ) ||
Artifact.SCOPE_TEST.equals( artifact.getScope() ) )
{
return;
}
String type = artifact.getType();
// skip artifacts that are not jar or nar
// nar is how we handle native libraries
if ( !("jar".equals( type )) && !("nar".equals( type )))
{
getLog().debug( "Skipping artifact of type " + type + " for " +
getWorkDirectory().getName() );
return;
}
// FIXME when signed, we should update the manifest.
// see http://www.mail-archive.com/[email protected]/msg08081.html
// and maven1: maven-plugins/jnlp/src/main/org/apache/maven/jnlp/UpdateManifest.java
// or shouldn't we? See MOJO-7 comment end of October.
final File toCopy = artifact.getFile();
if ( toCopy == null )
{
getLog().error( "artifact with no file: " + artifact );
getLog().error( "artifact download url: " + artifact.getDownloadUrl() );
getLog().error( "artifact repository: " + artifact.getRepository() );
getLog().error( "artifact repository: " + artifact.getVersion() );
throw new IllegalStateException(
"artifact " + artifact + " has no matching file, why? Check the logs..." );
}
// check if this artifact has the main class in it
if ( artifactContainsClass( artifact, jnlp.getMainClass() ) )
{
if ( artifactWithMainClass == null )
{
artifactWithMainClass = artifact;
getLog().debug( "Found main jar. Artifact " + artifactWithMainClass +
" contains the main class: " + jnlp.getMainClass() );
}
else
{
getLog().warn( "artifact " + artifact + " also contains the main class: " +
jnlp.getMainClass() + ". IGNORED." );
}
}
// Add the artifact to the list even if it is not processed
artifactList.add( artifact );
String outputName = getArtifactJnlpName(artifact);
File targetDirectory = getArtifactJnlpDirFile(artifact);
// Check if this file needs to be updated in the targetDirectory
// currently this check is just based on the existance of a jar and if the
// modified time of the jar in the maven cache is newer or older than
// that in the targetDirectory. It would be better to use the version of the
// jar
if(!needsUpdating(toCopy, targetDirectory, outputName)){
getLog().info( "skipping " + artifact + " it has already been processed");
return;
}
// Instead of copying the file to its final location we make a temporary
// folder and put the jar there. This way if something fails we won't
// leave bad files in the final output folder
File tmpArtifactDirectory = getArtifactTemporaryDirFile(artifact);
File currentJar = new File(tmpArtifactDirectory, outputName);
FileUtils.copyFile( toCopy, currentJar);
//
// pack200 and jar signing
//
// This used to be conditional based on a sign config and
// a pack boolean. We now just try to do these things all the time
// there used to be some automatic keystore generation here but
// we aren't using it anymore
// http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html
// we need to pack then unpack the files before signing them
File packedJar = new File(currentJar.getAbsolutePath() + ".pack");
// There is no need to gz them if we are just going to uncompress them
// again. (gz isn't losy like pack is)
// We should handle the case where a jar cannot be packed.
String shortName = getArtifactFlatPath(artifact) + "/" + outputName;
boolean doPack200 = true;
// We should remove any previous signature information. Signatures on the file
// mess up verification of the signature, because there ends up being 2 signatures
// in the jar. The pack code does a signature verification before packing so
// to be safe we want to remove any signatures before we do any packing.
removeSignatures(currentJar, shortName);
getLog().info("packing : " + shortName);
try {
Pack200.packJar( currentJar, false );
} catch (BuildException e){
// it will throw an ant.BuildException if it can't pack the jar
// One example is with
// <groupId>com.ibm.icu</groupId>
// <artifactId>icu4j</artifactId>
// <version>2.6.1</version>
// That jar has some class that causes the packing code to die trying
// to read it in.
// Another time it will not be able to pack the jar if it has an invalid
// signature. That one we can fix by removing the signature
getLog().warn("Cannot pack: " + artifact, e);
doPack200 = false;
// It might have left a bad pack jar
if(packedJar.exists()){
packedJar.delete();
}
}
if(!doPack200){
// Packing is being skipped for some reason so we need to sign
// and verify it separately
signJar(currentJar, shortName);
if(!verifyJar(currentJar, shortName)){
// We cannot verify this jar
throw new MojoExecutionException("failed to verify signed jar: " + shortName);
}
} else {
getLog().info("unpacking : " + shortName + ".pack");
Pack200.unpackJar( packedJar );
// specs says that one should do it twice when there are unsigned jars??
// I don't know about the unsigned part, but I found a jar
// that had to be packed, unpacked, packed, and unpacked before
// it could be signed and packed correctly.
// I suppose the best way to do this would be to try the signature
// and if it fails then pack it again, instead of packing and unpack
// every single jar
boolean verified = false;
for(int i=0; i<2; i++){
// This might throw a mojo exception if the signature didn't
// verify. This might happen if the jar has some previous
// signature information
signJar(currentJar, shortName );
// Now we pack and unpack the jar
getLog().info("packing : " + shortName);
Pack200.packJar( currentJar, false );
getLog().info("unpacking : " + shortName + ".pack");
Pack200.unpackJar( packedJar );
// Check if the jar is signed correctly
if(verifyJar(currentJar, shortName)){
verified = true;
break;
}
// verfication failed here
getLog().info("verfication failed, attempt: " + i);
}
if(!verified){
throw new MojoExecutionException("Failed to verify sigature after signing, " +
"packing, and unpacking multiple times");
}
// Now we need to gzip the resulting packed jar.
getLog().info("gzipping: " + shortName + ".pack");
FileInputStream inStream = new FileInputStream(packedJar);
FileOutputStream outFileStream =
new FileOutputStream(packedJar.getAbsolutePath() + ".gz");
GZIPOutputStream outGzStream = new GZIPOutputStream(outFileStream);
IOUtil.copy(inStream, outGzStream);
outGzStream.close();
outFileStream.close();
}
// If we are here then it is assumed the jar has been signed, packed and verified
// We need to rename all the files in the temporaryDirectory so they
// go to the targetDirectory
File [] tmpFiles = tmpArtifactDirectory.listFiles();
for(int i=0; i<tmpFiles.length; i++){
File targetFile = new File(targetDirectory, tmpFiles[i].getName());
// This is better than the File.renameTo because it will through
// and exception if something goes wrong
FileUtils.rename(tmpFiles[i], targetFile);
}
tmpFiles = tmpArtifactDirectory.listFiles();
if(tmpFiles != null && tmpFiles.length != 0){
throw new MojoExecutionException("Could not move files out of: " +
tmpArtifactDirectory);
}
tmpArtifactDirectory.delete();
getLog().info("moved files to: " + targetDirectory);
// make the snapshot copies if necessary
if(jnlp.getMakeSnapshotsWithNoJNLPVersion() && artifact.isSnapshot()) {
String jarBaseName = getArtifactJnlpBaseName(artifact);
String snapshot_outputName = jarBaseName + "-" +
artifact.getBaseVersion() + ".jar";
File versionedFile =
new File(targetDirectory, getArtifactJnlpName(artifact));
// this is method should reduce the number of times a file
// needs to be downloaded by an applet or webstart. However
// it isn't very safe if multiple users are running this.
// this method will be comparing the date of the file just
// setup in the jnlp folder with the last generated snapshot
copyFileToDirectoryIfNecessary( versionedFile, targetDirectory,
snapshot_outputName );
}
// Record that this artifact was successfully processed.
// this might not be necessary in the future
this.processedJnlpArtifacts.add(new File(targetDirectory, outputName));
}
protected void removeSignatures(File currentJar, String shortName)
throws IOException
{
// We should remove any previous signature information. This
// can screw up the packing code, and if it is signed with 2 signatures
// it can not be verified.
ZipFile currentJarZipFile = new ZipFile(currentJar);
Enumeration entries = currentJarZipFile.entries();
// There might be more valid extensions but this is what we've seen so far
// the ?i makes it case insensitive
Pattern signatureChecker =
Pattern.compile("(?i)^meta-inf/.*((\\.sf)|(\\.rsa))$");
getLog().info("checking for old signature : " + shortName);
Vector signatureFiles = new Vector();
while(entries.hasMoreElements()){
ZipEntry entry = (ZipEntry)entries.nextElement();
Matcher matcher = signatureChecker.matcher(entry.getName());
if(matcher.find()){
// we found a old signature in the file
signatureFiles.add(entry.getName());
getLog().warn("found signature: " + entry.getName());
}
}
if(signatureFiles.size() == 0){
// no old files were found
currentJarZipFile.close();
return;
}
// We found some old signature files, write out the file again without
// them
File outFile = new File(currentJar.getParent(), currentJar.getName() + ".unsigned");
ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(outFile));
entries = currentJarZipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = (ZipEntry)entries.nextElement();
if(signatureFiles.contains(entry.getName())){
continue;
}
InputStream entryInStream = currentJarZipFile.getInputStream(entry);
ZipEntry newEntry = new ZipEntry(entry);
zipOutStream.putNextEntry(newEntry);
IOUtil.copy(entryInStream, zipOutStream);
entryInStream.close();
}
zipOutStream.close();
currentJarZipFile.close();
FileUtils.rename(outFile, currentJar);
getLog().info("removed signature");
}
protected boolean verifyJar(File jar, String shortName)
throws MojoExecutionException
{
getLog().info("verifying: " + shortName);
JarSignVerifyMojo verifier = new JarSignVerifyMojo();
verifier.setJarPath(jar);
verifier.setLog(getLog());
verifier.setErrorWhenNotSigned(false);
verifier.setWorkingDir(jar.getParentFile());
try{
verifier.execute();
} catch (MojoExecutionException e){
// We failed to verify the jar. Even though the method
// errorWhenNotSigned is set to false an error is still though in some cases
// we are throwing out the exception here because the best error message has
// already been logged to info by the jarsigner command itself.
// the message in the exception simply says the command returned something
// other than zero.
return false;
}
return verifier.isSigned();
}
public final static String DEFAULT_ARTIFACT_GROUP = "default";
protected void buildArtifactGroups()
{
if(artifactGroups == null || artifactGroups.size() <= 0) {
// There are no artifactGroups
// TODO we should put all the artifacts into the main group
jnlpArtifactGroups.put(DEFAULT_ARTIFACT_GROUP, packagedJnlpArtifacts);
return;
}
for(Iterator i = artifactGroups.iterator(); i.hasNext(); ) {
ArtifactGroup group = (ArtifactGroup)i.next();
ArtifactFilter filter = createArtifactFilter(group);
List groupArtifacts = new ArrayList();
jnlpArtifactGroups.put(group.getName(), groupArtifacts);
for(Iterator j = packagedJnlpArtifacts.iterator(); j.hasNext(); ) {
Artifact artifact = (Artifact)j.next();
if(filter.include(artifact)){
groupArtifacts.add(artifact);
}
}
}
}
public String getArtifactJnlpVersion(Artifact artifact)
{
// FIXME this should convert the version so it is jnlp safe
// FIXME this isn't correctly resovling some artifacts to their
// actual version numbers. This appears to happen based on the
// metadata files stored in the local repository. I wasn't able
// narrow down exactly what was going on, but I think it is due
// to running the jnlp goal without the -U (update snapshots)
// if a snapshot is built locally then its metadata is in a different
// state than if it is downloaded from a remote repository.
return artifact.getVersion();
}
/**
* This returns the base file name (without the .jar) of the artifact
* as it should appear in the href attribute of a jar or nativelib element in the
* jnlp file. This is also the name of the file that should appear before
* __V if the file is hosted on then jnlp-servlet.
* If fileVersions is enabled then this name will not include the version.
*
* @param artifact
* @return
*/
public String getArtifactJnlpBaseName(Artifact artifact)
{
String baseName = artifact.getArtifactId();
if(jnlp == null || !jnlp.getFileVersions()){
baseName += "-" + artifact.getVersion();
}
if(artifact.hasClassifier()){
baseName += "-" + artifact.getClassifier();
}
// Because all the files need to end in jar for jnlp to handle them
// non jar files have there type appended to them so they don't conflict
// if there are two artifacts that only differ by their type.
if(!("jar".equals(artifact.getType()))){
baseName += "-" + artifact.getType();
}
return baseName;
}
/**
* This returns the file name of the artifact as it should
* appear in the href attribute of a jar or nativelib element in the
* jnlp file. If fileVersions is enabled then this name will not include
* the version.
* It will always end in jar even if the type of the artifact isn't a jar.
*
* @param artifact
* @return
*/
public String getArtifactJnlpHref(Artifact artifact)
{
return getArtifactJnlpBaseName(artifact) + ".jar";
}
public String getArtifactJnlpName(Artifact artifact)
{
String jnlpName = getArtifactJnlpBaseName(artifact);
if(jnlp != null && jnlp.getFileVersions()){
// FIXME this should convert the version so it is jnlp safe
jnlpName += "__V" + getArtifactJnlpVersion(artifact);
}
return jnlpName + ".jar";
}
public String getArtifactJnlpDir(Artifact artifact)
{
if(jnlp != null && jnlp.getGroupIdDirs()){
String groupPath = artifact.getGroupId().replace('.', '/');
return groupPath + "/" + artifact.getArtifactId() + "/";
} else {
return "";
}
}
public File getArtifactJnlpDirFile(Artifact artifact)
{
File targetDirectory =
new File(getWorkDirectory(), getArtifactJnlpDir(artifact));
targetDirectory.mkdirs();
return targetDirectory;
}
public File getArtifactTemporaryDirFile(Artifact artifact)
{
String artifactFlatPath = getArtifactFlatPath(artifact);
File tmpDir = new File(getTemporaryDirectory(), artifactFlatPath);
tmpDir.mkdirs();
return tmpDir;
}
public String getArtifactFlatPath(Artifact artifact)
{
return artifact.getGroupId() + "." + artifact.getArtifactId();
}
/**
* this is created once per execution I'm assuming a new instance of this
* class is created for each execution
* @return
*/
public File getTemporaryDirectory()
{
if(temporaryDirectory != null){
return temporaryDirectory;
}
temporaryDirectory = new File(getWorkDirectory(), "tmp/" +
getVersionedArtifactName());
temporaryDirectory.mkdirs();
return temporaryDirectory;
}
private boolean artifactContainsClass( Artifact artifact, final String mainClass )
throws MalformedURLException
{
boolean containsClass = true;
// JarArchiver.grabFilesAndDirs()
ClassLoader cl = new java.net.URLClassLoader( new URL[]{artifact.getFile().toURL()} );
Class c = null;
try
{
c = Class.forName( mainClass, false, cl );
}
catch ( ClassNotFoundException e )
{
getLog().debug( "artifact " + artifact + " doesn't contain the main class: " + mainClass );
containsClass = false;
}
catch ( Throwable t )
{
getLog().info( "artifact " + artifact + " seems to contain the main class: " + mainClass +
" but the jar doesn't seem to contain all dependencies " + t.getMessage() );
}
if ( c != null )
{
getLog().debug( "Checking if the loaded class contains a main method." );
try
{
c.getMethod( "main", new Class[]{String[].class} );
}
catch ( NoSuchMethodException e )
{
getLog().warn( "The specified main class (" + mainClass +
") doesn't seem to contain a main method... Please check your configuration." + e.getMessage() );
}
catch ( NoClassDefFoundError e )
{
// undocumented in SDK 5.0. is this due to the ClassLoader lazy loading the Method thus making this a case tackled by the JVM Spec (Ref 5.3.5)!
// Reported as Incident 633981 to Sun just in case ...
getLog().warn( "Something failed while checking if the main class contains the main() method. " +
"This is probably due to the limited classpath we have provided to the class loader. " +
"The specified main class (" + mainClass +
") found in the jar is *assumed* to contain a main method... " + e.getMessage() );
}
catch ( Throwable t )
{
getLog().error( "Unknown error: Couldn't check if the main class has a main method. " +
"The specified main class (" + mainClass +
") found in the jar is *assumed* to contain a main method...", t );
}
}
return containsClass;
}
void generateJnlpFile( File outputDirectory )
throws MojoExecutionException
{
if ( jnlp.getOutputFile() == null || jnlp.getOutputFile().length() == 0 )
{
getLog().debug( "Jnlp output file name not specified. Using default output file name: launch.jnlp." );
jnlp.setOutputFile( "launch.jnlp" );
}
File jnlpOutputFile = new File( outputDirectory, jnlp.getOutputFile() );
if ( jnlp.getInputTemplate() == null || jnlp.getInputTemplate().length() == 0 )
{
getLog().debug(
"Jnlp template file name not specified. Using default output file name: src/jnlp/template.vm." );
jnlp.setInputTemplate( "src/jnlp/template.vm" );
}
String templateFileName = jnlp.getInputTemplate();
File resourceLoaderPath = getProject().getBasedir();
if ( jnlp.getInputTemplateResourcePath() != null && jnlp.getInputTemplateResourcePath().length() > 0 )
{
resourceLoaderPath = new File( jnlp.getInputTemplateResourcePath() );
}
Generator jnlpGenerator =
new Generator( this, resourceLoaderPath, jnlpOutputFile,
templateFileName );
// decide if this new jnlp is actually different from the old
// jnlp file.
if(!hasJnlpChanged(outputDirectory, jnlpGenerator)){
return;
}
try
{
// this writes out the file
jnlpGenerator.generate();
}
catch ( Exception e )
{
getLog().debug( e .toString() );
throw new MojoExecutionException( "Could not generate the JNLP deployment descriptor", e );
}
// optionally copy the outputfile to one with the version string appended
// use the generator to write out a copy of the file, use its new name
if(jnlp.getMakeJnlpWithVersion()){
try {
String versionedJnlpName = getVersionedArtifactName() + ".jnlp";
File versionedJnlpOutputFile =
new File( outputDirectory, versionedJnlpName );
FileWriter versionedJnlpWriter =
new FileWriter(versionedJnlpOutputFile);
jnlpGenerator.generate(versionedJnlpWriter,
versionedJnlpName, getVersionedArtifactName());
writeLastJnlpVersion(outputDirectory, getJnlpBuildVersion());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public File getLastVersionFile(File outputDirectory)
{
String artifactId = getProject().getArtifactId();
return new File(outputDirectory,
artifactId + "-CURRENT_VERSION.txt");
}
/**
* If there is no version file then this returns null
* @return
*/
public String readLastJnlpVersion(File outputDirectory)
{
File currentVersionFile = getLastVersionFile(outputDirectory);
// check if this file has changed from the old version
if(!currentVersionFile.exists()){
return null;
}
try {
String oldVersion = FileUtils.fileRead(currentVersionFile);
return oldVersion.trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void writeLastJnlpVersion(File outputDirectory, String version)
{
File currentVersionFile = getLastVersionFile(outputDirectory);
try {
FileUtils.fileWrite(currentVersionFile.getAbsolutePath(), version);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method uses the generator because of the timestamp that can be
* included in the file. To do the comparison it uses the current
* dependencies and system properties, but it uses the old file name
* and old versionedArtifactName
*
* @param outputDirectory
* @param generator
* @return
*/
public boolean hasJnlpChanged(File outputDirectory, Generator generator)
{
String artifactId = getProject().getArtifactId();
String oldVersion = readLastJnlpVersion(outputDirectory);
if(oldVersion == null) {
return true;
}
// look for the old version
String oldVersionedArtifactName = artifactId + "-" + oldVersion;
String oldVersionedJnlpName = oldVersionedArtifactName + ".jnlp";
File oldVersionedJnlpFile =
new File(outputDirectory, oldVersionedJnlpName);
if(!oldVersionedJnlpFile.exists()) {
return true;
}
try {
String oldJnlpText = FileUtils.fileRead(oldVersionedJnlpFile);
StringWriter updatedJnlpWriter = new StringWriter();
generator.generate(updatedJnlpWriter,
oldVersionedJnlpName, oldVersionedArtifactName);
String updatedJnlpText = updatedJnlpWriter.toString();
// If the strings match then there is no new version
if(oldJnlpText.equals(updatedJnlpText)){
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public String getJnlpBuildVersion()
{
if(jnlpBuildVersion != null) {
return jnlpBuildVersion;
}
DateFormat utcDateFormatter = new SimpleDateFormat( UTC_TIMESTAMP_PATTERN );
utcDateFormatter.setTimeZone( UTC_TIME_ZONE );
String timestamp = utcDateFormatter.format( new Date() );
String version = getProject().getVersion();
if(version.endsWith("SNAPSHOT")){
version = version.replaceAll("SNAPSHOT", timestamp);
}
jnlpBuildVersion = version;
return version;
}
private void logCollection( final String prefix, final Collection collection )
{
getLog().debug( prefix + " " + collection );
if ( collection == null )
{
return;
}
for ( Iterator it3 = collection.iterator(); it3.hasNext(); )
{
getLog().debug( prefix + it3.next() );
}
}
private void deleteKeyStore()
{
File keyStore = null;
if ( sign.getKeystore() != null )
{
keyStore = new File( sign.getKeystore() );
}
else
{
// FIXME decide if we really want this.
// keyStore = new File( System.getProperty( "user.home") + File.separator + ".keystore" );
}
if ( keyStore == null )
{
return;
}
if ( keyStore.exists() )
{
if ( keyStore.delete() )
{
getLog().debug( "deleted keystore from: " + keyStore.getAbsolutePath() );
}
else
{
getLog().warn( "Couldn't delete keystore from: " + keyStore.getAbsolutePath() );
}
}
else
{
getLog().debug( "Skipping deletion of non existing keystore: " + keyStore.getAbsolutePath() );
}
}
private void genKeyStore()
throws MojoExecutionException
{
GenkeyMojo genKeystore = new GenkeyMojo();
genKeystore.setAlias( sign.getAlias() );
genKeystore.setDname( sign.getDname() );
genKeystore.setKeyalg( sign.getKeyalg() );
genKeystore.setKeypass( sign.getKeypass() );
genKeystore.setKeysize( sign.getKeysize() );
genKeystore.setKeystore( sign.getKeystore() );
genKeystore.setSigalg( sign.getSigalg() );
genKeystore.setStorepass( sign.getStorepass() );
genKeystore.setStoretype( sign.getStoretype() );
genKeystore.setValidity( sign.getValidity() );
genKeystore.setVerbose( this.verbose );
genKeystore.setWorkingDir( getWorkDirectory() );
genKeystore.execute();
}
private File getWorkDirectory()
{
return workDirectory;
}
/**
* Conditionaly copy the file into the target directory.
* The operation is not performed when the target file exists is up to date.
* The target file name is taken from the <code>sourceFile</code> name.
*
* @return <code>true</code> when the file was copied, <code>false</code> otherwise.
* @throws NullPointerException is sourceFile is <code>null</code> or
* <code>sourceFile.getName()</code> is <code>null</code>
* @throws IOException if the copy operation is tempted but failed.
*/
private boolean copyFileToDirectoryIfNecessary( File sourceFile, File targetDirectory,
String outputName)
throws IOException
{
File targetFile = new File( targetDirectory, outputName );
boolean shouldCopy = needsUpdating(sourceFile, targetDirectory, outputName);
if ( shouldCopy )
{
FileUtils.copyFile( sourceFile, targetFile);
}
else
{
getLog().debug(
"Source file hasn't changed. Do not overwrite " + targetFile + " with " + sourceFile + "." );
}
return shouldCopy;
}
private boolean needsUpdating(File sourceFile, File targetDirectory,
String outputName)
{
if ( sourceFile == null )
{
throw new NullPointerException( "sourceFile is null" );
}
File targetFile = new File( targetDirectory, outputName );
return ! targetFile.exists() || targetFile.lastModified() < sourceFile.lastModified();
}
/**
*
* @param relativeName
* @throws IOException
*/
private void signJar(File jarFile, String relativeName )
throws MojoExecutionException, IOException
{
getLog().info("signing: " + relativeName);
JarSignMojo signJar = new JarSignMojo();
signJar.setLog(getLog());
signJar.setAlias( sign.getAlias() );
signJar.setBasedir( basedir );
signJar.setKeypass( sign.getKeypass() );
signJar.setKeystore( sign.getKeystore() );
signJar.setSigFile( sign.getSigfile() );
signJar.setStorepass( sign.getStorepass() );
signJar.setType( sign.getStoretype() );
signJar.setVerbose( this.verbose );
signJar.setWorkingDir( getWorkDirectory() );
// we do our own verification because the jarsignmojo doesn't pass
// the log object, to the jarsignverifymojo, so lot
signJar.setVerify( false );
signJar.setJarPath( jarFile );
File signedJar = new File(jarFile.getParentFile(),
jarFile.getName() + ".signed");
// If the signedJar is set to null then the jar is signed
// in place.
signJar.setSignedJar(signedJar);
long lastModified = jarFile.lastModified();
signJar.execute();
FileUtils.rename(signedJar, jarFile);
jarFile.setLastModified( lastModified );
}
private void checkInput()
throws MojoExecutionException
{
getLog().debug( "a fact " + this.artifactFactory );
getLog().debug( "a resol " + this.artifactResolver );
getLog().debug( "basedir " + this.basedir );
getLog().debug( "gzip " + this.gzip );
getLog().debug( "pack200 " + this.pack200 );
getLog().debug( "project " + this.getProject() );
getLog().debug( "zipArchiver " + this.zipArchiver );
// getLog().debug( "usejnlpservlet " + this.usejnlpservlet );
getLog().debug( "verifyjar " + this.verifyjar );
getLog().debug( "verbose " + this.verbose );
if ( jnlp == null )
{
// throw new MojoExecutionException( "<jnlp> configuration element missing." );
}
if ( SystemUtils.JAVA_VERSION_FLOAT < 1.5f )
{
if ( pack200 )
{
throw new MojoExecutionException( "SDK 5.0 minimum when using pack200." );
}
}
// FIXME
/*
if ( !"pom".equals( getProject().getPackaging() ) ) {
throw new MojoExecutionException( "'" + getProject().getPackaging() + "' packaging unsupported. Use 'pom'" );
}
*/
}
/**
* @return
*/
public MavenProject getProject()
{
return project;
}
void setWorkDirectory( File workDirectory )
{
this.workDirectory = workDirectory;
}
void setVerbose( boolean verbose )
{
this.verbose = verbose;
}
public JnlpConfig getJnlp()
{
return jnlp;
}
public List getPackagedJnlpArtifacts()
{
return packagedJnlpArtifacts;
}
public Map getJnlpArtifactGroups()
{
return jnlpArtifactGroups;
}
/*
public Artifact getArtifactWithMainClass() {
return artifactWithMainClass;
}
*/
public boolean isArtifactWithMainClass( Artifact artifact )
{
final boolean b = artifactWithMainClass.equals( artifact );
getLog().debug( "compare " + artifactWithMainClass + " with " + artifact + ": " + b );
return b;
}
public String getSpec()
{
// shouldn't we automatically identify the spec based on the features used in the spec?
// also detect conflicts. If user specified 1.0 but uses a 1.5 feature we should fail in checkInput().
if ( jnlp.getSpec() != null )
{
return jnlp.getSpec();
}
return "1.0+";
}
/**
* @return
*/
public String getVersionedArtifactName() {
return getProject().getArtifactId() + "-" + getJnlpBuildVersion();
}
}
| plugin/src/main/java/org/codehaus/mojo/webstart/JnlpMojo.java | package org.codehaus.mojo.webstart;
/*
* Copyright 2001-2005 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.
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.Vector;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang.SystemUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.resolver.filter.IncludesArtifactFilter;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.plugin.jar.JarSignMojo;
import org.apache.maven.plugin.jar.JarSignVerifyMojo;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.settings.Settings;
import org.apache.tools.ant.BuildException;
import org.codehaus.mojo.keytool.GenkeyMojo;
import org.codehaus.mojo.webstart.generator.Generator;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.cli.StreamFeeder;
import org.codehaus.plexus.util.cli.StreamPumper;
/**
* Packages a jnlp application.
* <p/>
* The plugin tries to not re-sign/re-pack if the dependent jar hasn't changed.
* As a consequence, if one modifies the pom jnlp config or a keystore, one should clean before rebuilding.
*
* @author <a href="[email protected]">Jerome Lacoste</a>
* @version $Id: JnlpMojo.java 1908 2006-06-06 13:48:13 +0000 (Tue, 06 Jun 2006) lacostej $
* @goal jnlp
* @phase package
* @requiresDependencyResolution runtime
* @requiresProject
* @inheritedByDefault true
* @todo refactor the common code with javadoc plugin
* @todo how to propagate the -X argument to enable verbose?
* @todo initialize the jnlp alias and dname.o from pom.artifactId and pom.organization.name
*/
public class JnlpMojo
extends AbstractMojo
{
/**
* These shouldn't be necessary, but just incase the main ones in
* maven change. They can be found in SnapshotTransform class
*/
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone( "UTC" );
private static final String UTC_TIMESTAMP_PATTERN = "yyyyMMdd.HHmmss";
/**
* Directory to create the resulting artifacts
*
* @parameter expression="${project.build.directory}/jnlp"
* @required
*/
protected File workDirectory;
/**
* The Zip archiver.
*
* @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#zip}"
* @required
*/
private ZipArchiver zipArchiver;
/**
* Project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* Xxx
*
* @parameter
*/
private JnlpConfig jnlp;
/**
* Xxx
*
* @parameter
*/
private Dependencies dependencies;
public static class Dependencies
{
private List includes;
private List excludes;
private List includeClassifiers;
private List excludeClassifiers;
public List getIncludes()
{
return includes;
}
public void setIncludes( List includes )
{
this.includes = includes;
}
public List getIncludeClassifiers() {
return includeClassifiers;
}
public void setIncludeClassifiers(List includeClassifiers) {
this.includeClassifiers = includeClassifiers;
}
public List getExcludes()
{
return excludes;
}
public void setExcludes( List excludes )
{
this.excludes = excludes;
}
public List getExcludeClassifiers() {
return excludeClassifiers;
}
public void setExcludeClassifiers(List excludeClassifiers) {
this.excludeClassifiers = excludeClassifiers;
}
}
/**
* Xxx
*
* @parameter
*/
private List artifactGroups;
/**
* Xxx
*
* @parameter
*/
private SignConfig sign;
/**
* Xxx
*
* @parameter default-value="false"
*/
// private boolean usejnlpservlet;
/**
* Xxx
*
* @parameter default-value="true"
*/
private boolean verifyjar;
/**
* Enables pack200. Requires SDK 5.0.
*
* @parameter default-value="false"
*/
private boolean pack200;
/**
* Xxx
*
* @parameter default-value="false"
*/
private boolean gzip;
/**
* Enable verbose.
*
* @parameter expression="${verbose}" default-value="false"
*/
private boolean verbose;
/**
* @parameter expression="${basedir}"
* @required
* @readonly
*/
private File basedir;
/**
* Artifact resolver, needed to download source jars for inclusion in classpath.
*
* @parameter expression="${component.org.apache.maven.artifact.resolver.ArtifactResolver}"
* @required
* @readonly
* @todo waiting for the component tag
*/
private ArtifactResolver artifactResolver;
/**
* Artifact factory, needed to download source jars for inclusion in classpath.
*
* @parameter expression="${component.org.apache.maven.artifact.factory.ArtifactFactory}"
* @required
* @readonly
* @todo waiting for the component tag
*/
private ArtifactFactory artifactFactory;
/**
* @parameter expression="${localRepository}"
* @required
* @readonly
*/
protected ArtifactRepository localRepository;
/**
* @parameter expression="${component.org.apache.maven.project.MavenProjectHelper}
*/
private MavenProjectHelper projectHelper;
/**
* The current user system settings for use in Maven. This is used for
* <br/>
* plugin manager API calls.
*
* @parameter expression="${settings}"
* @required
* @readonly
*/
private Settings settings;
/**
* The plugin manager instance used to resolve plugin descriptors.
*
* @component role="org.apache.maven.plugin.PluginManager"
*/
private PluginManager pluginManager;
private class CompositeFileFilter
implements FileFilter
{
private List fileFilters = new ArrayList();
CompositeFileFilter( FileFilter filter1, FileFilter filter2 )
{
fileFilters.add( filter1 );
fileFilters.add( filter2 );
}
public boolean accept( File pathname )
{
for ( int i = 0; i < fileFilters.size(); i++ )
{
if ( ! ( (FileFilter) fileFilters.get( i ) ).accept( pathname ) )
{
return false;
}
}
return true;
}
}
/**
* The maven-xbean-plugin can't handle anon inner classes
*
* @author scott
*
*/
private class ModifiedFileFilter
implements FileFilter
{
public boolean accept( File pathname )
{
boolean modified = pathname.lastModified() > getStartTime();
getLog().debug( "File: " + pathname.getName() + " modified: " + modified );
getLog().debug( "lastModified: " + pathname.lastModified() + " plugin start time " + getStartTime() );
return modified;
}
}
private FileFilter modifiedFileFilter = new ModifiedFileFilter();
/**
* @author scott
*
*/
private final class JarFileFilter implements FileFilter {
public boolean accept( File pathname )
{
return pathname.isFile() && pathname.getName().endsWith( ".jar" );
}
}
private FileFilter jarFileFilter = new JarFileFilter();
/**
* @author scott
*
*/
private final class Pack200FileFilter implements FileFilter {
public boolean accept( File pathname )
{
return pathname.isFile() &&
( pathname.getName().endsWith( ".jar.pack.gz" ) || pathname.getName().endsWith( ".jar.pack" ) );
}
}
private FileFilter pack200FileFilter = new Pack200FileFilter();
// the jars to sign and pack are selected if they are newer than the plugin start.
// as the plugin copies the new versions locally before signing/packing them
// we just need to see if the plugin copied a new version
// We achieve that by only filtering files modified after the plugin was started
// FIXME we may want to also resign/repack the jars if other files (the pom, the keystore config) have changed
// today one needs to clean...
private FileFilter updatedJarFileFilter = new CompositeFileFilter( jarFileFilter, modifiedFileFilter );
private FileFilter updatedPack200FileFilter = new CompositeFileFilter( pack200FileFilter, modifiedFileFilter );
/**
* the artifacts packaged in the webstart app. *
*/
private List packagedJnlpArtifacts = new ArrayList();
/**
* A map of groups of dependencies for the jnlp file.
* the key of each group is string which can be referenced in
*/
private Map jnlpArtifactGroups = new HashMap();
private ArrayList processedJnlpArtifacts = new ArrayList();
private Artifact artifactWithMainClass;
// initialized by execute
private long startTime;
private String jnlpBuildVersion;
private File temporaryDirectory;
private long getStartTime()
{
if ( startTime == 0 )
{
throw new IllegalStateException( "startTime not initialized" );
}
return startTime;
}
public void execute()
throws MojoExecutionException
{
checkInput();
if(jnlp == null) {
getLog().debug( "skipping project because no jnlp element was found");
return;
}
// interesting: copied files lastModified time stamp will be rounded.
// We have to be sure that the startTime is before that time...
// rounding to the second - 1 millis should be sufficient..
startTime = System.currentTimeMillis() - 1000;
File workDirectory = getWorkDirectory();
getLog().debug( "using work directory " + workDirectory );
//
// prepare layout
//
if ( !workDirectory.exists() && !workDirectory.mkdirs() )
{
throw new MojoExecutionException( "Failed to create: " + workDirectory.getAbsolutePath() );
}
try
{
File resourcesDir = getJnlp().getResources();
if ( resourcesDir == null )
{
resourcesDir = new File( project.getBasedir(), "src/main/jnlp" );
}
copyResources( resourcesDir, workDirectory );
artifactWithMainClass = null;
processDependencies();
buildArtifactGroups();
if ( artifactWithMainClass == null )
{
getLog().info( "skipping project because no main class: " +
jnlp.getMainClass() + " was found");
return;
/*
throw new MojoExecutionException(
"didn't find artifact with main class: " + jnlp.getMainClass() + ". Did you specify it? " );
*/
}
File jnlpDirectory = workDirectory;
if(jnlp.getGroupIdDirs()) {
// store the jnlp in the same layout as the jar files
// if groupIdDirs is true
jnlpDirectory =
getArtifactJnlpDirFile(getProject().getArtifact());
}
generateJnlpFile( jnlpDirectory );
if(jnlp.getCreateZip()) {
// package the zip. Note this is very simple. Look at the JarMojo which does more things.
// we should perhaps package as a war when inside a project with war packaging ?
File toFile = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".zip" );
if ( toFile.exists() )
{
getLog().debug( "deleting file " + toFile );
toFile.delete();
}
zipArchiver.addDirectory( workDirectory );
zipArchiver.setDestFile( toFile );
getLog().debug( "about to call createArchive" );
zipArchiver.createArchive();
// maven 2 version 2.0.1 method
projectHelper.attachArtifact( project, "zip", toFile );
}
}
catch ( MojoExecutionException e )
{
throw e;
}
catch ( Exception e )
{
throw new MojoExecutionException( "Failure to run the plugin: ", e );
/*
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter( sw, true );
e.printStackTrace( pw );
pw.flush();
sw.flush();
getLog().debug( "An error occurred during the task: " + sw.toString() );
*/
}
}
private void copyResources( File resourcesDir, File workDirectory )
throws IOException
{
if ( ! resourcesDir.exists() )
{
getLog().info( "No resources found in " + resourcesDir.getAbsolutePath() );
}
else
{
if ( ! resourcesDir.isDirectory() )
{
getLog().debug( "Not a directory: " + resourcesDir.getAbsolutePath() );
}
else
{
getLog().debug( "Copying resources from " + resourcesDir.getAbsolutePath() );
// hopefully available from FileUtils 1.0.5-SNAPSHOT
// FileUtils.copyDirectoryStructure( resourcesDir , workDirectory );
// this may needs to be parametrized somehow
String excludes = concat( DirectoryScanner.DEFAULTEXCLUDES, ", " );
copyDirectoryStructure( resourcesDir, workDirectory, "**", excludes );
}
}
}
private static String concat( String[] array, String delim )
{
StringBuffer buffer = new StringBuffer();
for ( int i = 0; i < array.length; i++ )
{
if ( i > 0 )
{
buffer.append( delim );
}
String s = array[i];
buffer.append( s ).append( delim );
}
return buffer.toString();
}
private void copyDirectoryStructure( File sourceDirectory, File destinationDirectory, String includes,
String excludes )
throws IOException
{
if ( ! sourceDirectory.exists() )
{
return;
}
List files = FileUtils.getFiles( sourceDirectory, includes, excludes );
for ( Iterator i = files.iterator(); i.hasNext(); )
{
File file = (File) i.next();
getLog().debug( "Copying " + file + " to " + destinationDirectory );
String path = file.getAbsolutePath().substring( sourceDirectory.getAbsolutePath().length() + 1 );
File destDir = new File( destinationDirectory, path );
getLog().debug( "Copying " + file + " to " + destDir );
if ( file.isDirectory() )
{
destDir.mkdirs();
}
else
{
FileUtils.copyFileToDirectory( file, destDir.getParentFile() );
}
}
}
private ArtifactFilter createArtifactFilter(Dependencies dependencies)
{
AndArtifactFilter filter = new AndArtifactFilter();
if ( dependencies == null) {
return filter;
}
if ( dependencies.getIncludes() != null && !dependencies.getIncludes().isEmpty() )
{
filter.add( new IncludesArtifactFilter( dependencies.getIncludes() ) );
}
if ( dependencies.getIncludeClassifiers() != null && !dependencies.getIncludeClassifiers().isEmpty() )
{
final List classifierList = dependencies.getIncludeClassifiers();
filter.add( new ArtifactFilter (){
public boolean include(Artifact artifact) {
if(!artifact.hasClassifier()) {
return false;
}
String classifer = artifact.getClassifier();
if (classifierList.contains(classifer)) {
return true;
}
return false;
};
});
}
if ( dependencies.getExcludeClassifiers() != null && !dependencies.getExcludeClassifiers().isEmpty() )
{
final List classifierList = dependencies.getExcludeClassifiers();
filter.add( new ArtifactFilter (){
public boolean include(Artifact artifact) {
String classifier = artifact.getClassifier();
// The artifact has no classifier so this excludes rule doesn't
// apply
if(classifier == null || classifier.length() == 0) {
return true;
}
// special pattern hack so excluding * can be handled
// if star is used then any artifact with a classifier is excluded
if(classifierList.contains("*")) {
return false;
}
if (classifierList.contains(classifier)) {
return false;
}
return true;
};
});
}
if ( dependencies.getExcludes() != null && !dependencies.getExcludes().isEmpty() )
{
filter.add( new ExcludesArtifactFilter( dependencies.getExcludes() ) );
}
return filter;
}
/**
* Iterate through all the top level and transitive dependencies declared in the project and
* collect all the runtime scope dependencies for inclusion in the .zip and signing.
*
* @throws IOException
* @throws MojoExecutionException
*/
private void processDependencies()
throws IOException, MojoExecutionException
{
processDependency( getProject().getArtifact(), packagedJnlpArtifacts );
ArtifactFilter filter = createArtifactFilter(dependencies);
Collection artifacts = getProject().getArtifacts();
for ( Iterator it = artifacts.iterator(); it.hasNext(); )
{
Artifact artifact = (Artifact) it.next();
if ( filter.include( artifact ) )
{
processDependency( artifact , packagedJnlpArtifacts);
}
}
// Check if the temporaryDirectory is empty, if so delete it
File tmpDirectory = getTemporaryDirectory();
File [] tmpArtifactDirs = tmpDirectory.listFiles();
if(tmpArtifactDirs != null && tmpArtifactDirs.length != 0){
throw new MojoExecutionException("Left over files in : " + tmpDirectory);
}
tmpDirectory.delete();
}
private void processDependency( Artifact artifact , List artifactList)
throws IOException, MojoExecutionException
{
// TODO: scope handler
// skip provided and test scopes
if ( Artifact.SCOPE_PROVIDED.equals( artifact.getScope() ) ||
Artifact.SCOPE_TEST.equals( artifact.getScope() ) )
{
return;
}
String type = artifact.getType();
// skip artifacts that are not jar or nar
// nar is how we handle native libraries
if ( !("jar".equals( type )) && !("nar".equals( type )))
{
getLog().debug( "Skipping artifact of type " + type + " for " +
getWorkDirectory().getName() );
return;
}
// FIXME when signed, we should update the manifest.
// see http://www.mail-archive.com/[email protected]/msg08081.html
// and maven1: maven-plugins/jnlp/src/main/org/apache/maven/jnlp/UpdateManifest.java
// or shouldn't we? See MOJO-7 comment end of October.
final File toCopy = artifact.getFile();
if ( toCopy == null )
{
getLog().error( "artifact with no file: " + artifact );
getLog().error( "artifact download url: " + artifact.getDownloadUrl() );
getLog().error( "artifact repository: " + artifact.getRepository() );
getLog().error( "artifact repository: " + artifact.getVersion() );
throw new IllegalStateException(
"artifact " + artifact + " has no matching file, why? Check the logs..." );
}
// check if this artifact has the main class in it
if ( artifactContainsClass( artifact, jnlp.getMainClass() ) )
{
if ( artifactWithMainClass == null )
{
artifactWithMainClass = artifact;
getLog().debug( "Found main jar. Artifact " + artifactWithMainClass +
" contains the main class: " + jnlp.getMainClass() );
}
else
{
getLog().warn( "artifact " + artifact + " also contains the main class: " +
jnlp.getMainClass() + ". IGNORED." );
}
}
// Add the artifact to the list even if it is not processed
artifactList.add( artifact );
String outputName = getArtifactJnlpName(artifact);
File targetDirectory = getArtifactJnlpDirFile(artifact);
// Check if this file needs to be updated in the targetDirectory
// currently this check is just based on the existance of a jar and if the
// modified time of the jar in the maven cache is newer or older than
// that in the targetDirectory. It would be better to use the version of the
// jar
if(!needsUpdating(toCopy, targetDirectory, outputName)){
getLog().info( "skipping " + artifact + " it has already been processed");
return;
}
// Instead of copying the file to its final location we make a temporary
// folder and put the jar there. This way if something fails we won't
// leave bad files in the final output folder
File tmpArtifactDirectory = getArtifactTemporaryDirFile(artifact);
File currentJar = new File(tmpArtifactDirectory, outputName);
FileUtils.copyFile( toCopy, currentJar);
//
// pack200 and jar signing
//
// This used to be conditional based on a sign config and
// a pack boolean. We now just try to do these things all the time
// there used to be some automatic keystore generation here but
// we aren't using it anymore
// http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html
// we need to pack then unpack the files before signing them
File packedJar = new File(currentJar.getAbsolutePath() + ".pack");
// There is no need to gz them if we are just going to uncompress them
// again. (gz isn't losy like pack is)
// We should handle the case where a jar cannot be packed.
String shortName = getArtifactFlatPath(artifact) + "/" + outputName;
boolean doPack200 = true;
// We should remove any previous signature information. Signatures on the file
// mess up verification of the signature, because there ends up being 2 signatures
// in the jar. The pack code does a signature verification before packing so
// to be safe we want to remove any signatures before we do any packing.
removeSignatures(currentJar, shortName);
getLog().info("packing : " + shortName);
try {
Pack200.packJar( currentJar, false );
} catch (BuildException e){
// it will throw an ant.BuildException if it can't pack the jar
// One example is with
// <groupId>com.ibm.icu</groupId>
// <artifactId>icu4j</artifactId>
// <version>2.6.1</version>
// That jar has some class that causes the packing code to die trying
// to read it in.
// Another time it will not be able to pack the jar if it has an invalid
// signature. That one we can fix by removing the signature
getLog().warn("Cannot pack: " + artifact, e);
doPack200 = false;
// It might have left a bad pack jar
if(packedJar.exists()){
packedJar.delete();
}
}
if(!doPack200){
// Packing is being skipped for some reason so we need to sign
// and verify it separately
signJar(currentJar, shortName);
if(!verifyJar(currentJar, shortName)){
// We cannot verify this jar
throw new MojoExecutionException("failed to verify signed jar: " + shortName);
}
} else {
getLog().info("unpacking : " + shortName + ".pack");
Pack200.unpackJar( packedJar );
// specs says that one should do it twice when there are unsigned jars??
// I don't know about the unsigned part, but I found a jar
// that had to be packed, unpacked, packed, and unpacked before
// it could be signed and packed correctly.
// I suppose the best way to do this would be to try the signature
// and if it fails then pack it again, instead of packing and unpack
// every single jar
boolean verified = false;
for(int i=0; i<2; i++){
// This might throw a mojo exception if the signature didn't
// verify. This might happen if the jar has some previous
// signature information
signJar(currentJar, shortName );
// Now we pack and unpack the jar
getLog().info("packing : " + shortName);
Pack200.packJar( currentJar, false );
getLog().info("unpacking : " + shortName + ".pack");
Pack200.unpackJar( packedJar );
// Check if the jar is signed correctly
if(verifyJar(currentJar, shortName)){
verified = true;
break;
}
// verfication failed here
getLog().info("verfication failed, attempt: " + i);
}
if(!verified){
throw new MojoExecutionException("Failed to verify sigature after signing, " +
"packing, and unpacking multiple times");
}
// Now we need to gzip the resulting packed jar.
getLog().info("gzipping: " + shortName + ".pack");
FileInputStream inStream = new FileInputStream(packedJar);
FileOutputStream outFileStream =
new FileOutputStream(packedJar.getAbsolutePath() + ".gz");
GZIPOutputStream outGzStream = new GZIPOutputStream(outFileStream);
IOUtil.copy(inStream, outGzStream);
outGzStream.close();
outFileStream.close();
}
// If we are here then it is assumed the jar has been signed, packed and verified
// We need to rename all the files in the temporaryDirectory so they
// go to the targetDirectory
File [] tmpFiles = tmpArtifactDirectory.listFiles();
for(int i=0; i<tmpFiles.length; i++){
File targetFile = new File(targetDirectory, tmpFiles[i].getName());
// This is better than the File.renameTo because it will through
// and exception if something goes wrong
FileUtils.rename(tmpFiles[i], targetFile);
}
tmpFiles = tmpArtifactDirectory.listFiles();
if(tmpFiles != null && tmpFiles.length != 0){
throw new MojoExecutionException("Could not move files out of: " +
tmpArtifactDirectory);
}
tmpArtifactDirectory.delete();
getLog().info("moved files to: " + targetDirectory);
// make the snapshot copies if necessary
if(jnlp.getMakeSnapshotsWithNoJNLPVersion() && artifact.isSnapshot()) {
String jarBaseName = getArtifactJnlpBaseName(artifact);
String snapshot_outputName = jarBaseName + "-" +
artifact.getBaseVersion() + ".jar";
File versionedFile =
new File(targetDirectory, getArtifactJnlpName(artifact));
// this is method should reduce the number of times a file
// needs to be downloaded by an applet or webstart. However
// it isn't very safe if multiple users are running this.
// this method will be comparing the date of the file just
// setup in the jnlp folder with the last generated snapshot
copyFileToDirectoryIfNecessary( versionedFile, targetDirectory,
snapshot_outputName );
}
// Record that this artifact was successfully processed.
// this might not be necessary in the future
this.processedJnlpArtifacts.add(new File(targetDirectory, outputName));
}
protected void removeSignatures(File currentJar, String shortName)
throws IOException
{
// We should remove any previous signature information. This
// can screw up the packing code, and if it is signed with 2 signatures
// it can not be verified.
ZipFile currentJarZipFile = new ZipFile(currentJar);
Enumeration entries = currentJarZipFile.entries();
// There might be more valid extensions but this is what we've seen so far
// the ?i makes it case insensitive
Pattern signatureChecker =
Pattern.compile("(?i)^meta-inf/.*(\\.sf)|(\\.rsa)$");
getLog().info("checking for old signature : " + shortName);
Vector signatureFiles = new Vector();
while(entries.hasMoreElements()){
ZipEntry entry = (ZipEntry)entries.nextElement();
Matcher matcher = signatureChecker.matcher(entry.getName());
if(matcher.find()){
// we found a old signature in the file
signatureFiles.add(entry.getName());
getLog().warn("found signature: " + entry.getName());
}
}
if(signatureFiles.size() == 0){
// no old files were found
currentJarZipFile.close();
return;
}
// We found some old signature files, write out the file again without
// them
File outFile = new File(currentJar.getParent(), currentJar.getName() + ".unsigned");
ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(outFile));
entries = currentJarZipFile.entries();
while(entries.hasMoreElements()){
ZipEntry entry = (ZipEntry)entries.nextElement();
if(signatureFiles.contains(entry.getName())){
continue;
}
InputStream entryInStream = currentJarZipFile.getInputStream(entry);
ZipEntry newEntry = new ZipEntry(entry);
zipOutStream.putNextEntry(newEntry);
IOUtil.copy(entryInStream, zipOutStream);
entryInStream.close();
}
zipOutStream.close();
currentJarZipFile.close();
FileUtils.rename(outFile, currentJar);
getLog().info("removed signature");
}
protected boolean verifyJar(File jar, String shortName)
throws MojoExecutionException
{
getLog().info("verifying: " + shortName);
JarSignVerifyMojo verifier = new JarSignVerifyMojo();
verifier.setJarPath(jar);
verifier.setLog(getLog());
verifier.setErrorWhenNotSigned(false);
verifier.setWorkingDir(jar.getParentFile());
try{
verifier.execute();
} catch (MojoExecutionException e){
// We failed to verify the jar. Even though the method
// errorWhenNotSigned is set to false an error is still though in some cases
// we are throwing out the exception here because the best error message has
// already been logged to info by the jarsigner command itself.
// the message in the exception simply says the command returned something
// other than zero.
return false;
}
return verifier.isSigned();
}
public final static String DEFAULT_ARTIFACT_GROUP = "default";
protected void buildArtifactGroups()
{
if(artifactGroups == null || artifactGroups.size() <= 0) {
// There are no artifactGroups
// TODO we should put all the artifacts into the main group
jnlpArtifactGroups.put(DEFAULT_ARTIFACT_GROUP, packagedJnlpArtifacts);
return;
}
for(Iterator i = artifactGroups.iterator(); i.hasNext(); ) {
ArtifactGroup group = (ArtifactGroup)i.next();
ArtifactFilter filter = createArtifactFilter(group);
List groupArtifacts = new ArrayList();
jnlpArtifactGroups.put(group.getName(), groupArtifacts);
for(Iterator j = packagedJnlpArtifacts.iterator(); j.hasNext(); ) {
Artifact artifact = (Artifact)j.next();
if(filter.include(artifact)){
groupArtifacts.add(artifact);
}
}
}
}
public String getArtifactJnlpVersion(Artifact artifact)
{
// FIXME this should convert the version so it is jnlp safe
// FIXME this isn't correctly resovling some artifacts to their
// actual version numbers. This appears to happen based on the
// metadata files stored in the local repository. I wasn't able
// narrow down exactly what was going on, but I think it is due
// to running the jnlp goal without the -U (update snapshots)
// if a snapshot is built locally then its metadata is in a different
// state than if it is downloaded from a remote repository.
return artifact.getVersion();
}
/**
* This returns the base file name (without the .jar) of the artifact
* as it should appear in the href attribute of a jar or nativelib element in the
* jnlp file. This is also the name of the file that should appear before
* __V if the file is hosted on then jnlp-servlet.
* If fileVersions is enabled then this name will not include the version.
*
* @param artifact
* @return
*/
public String getArtifactJnlpBaseName(Artifact artifact)
{
String baseName = artifact.getArtifactId();
if(jnlp == null || !jnlp.getFileVersions()){
baseName += "-" + artifact.getVersion();
}
if(artifact.hasClassifier()){
baseName += "-" + artifact.getClassifier();
}
// Because all the files need to end in jar for jnlp to handle them
// non jar files have there type appended to them so they don't conflict
// if there are two artifacts that only differ by their type.
if(!("jar".equals(artifact.getType()))){
baseName += "-" + artifact.getType();
}
return baseName;
}
/**
* This returns the file name of the artifact as it should
* appear in the href attribute of a jar or nativelib element in the
* jnlp file. If fileVersions is enabled then this name will not include
* the version.
* It will always end in jar even if the type of the artifact isn't a jar.
*
* @param artifact
* @return
*/
public String getArtifactJnlpHref(Artifact artifact)
{
return getArtifactJnlpBaseName(artifact) + ".jar";
}
public String getArtifactJnlpName(Artifact artifact)
{
String jnlpName = getArtifactJnlpBaseName(artifact);
if(jnlp != null && jnlp.getFileVersions()){
// FIXME this should convert the version so it is jnlp safe
jnlpName += "__V" + getArtifactJnlpVersion(artifact);
}
return jnlpName + ".jar";
}
public String getArtifactJnlpDir(Artifact artifact)
{
if(jnlp != null && jnlp.getGroupIdDirs()){
String groupPath = artifact.getGroupId().replace('.', '/');
return groupPath + "/" + artifact.getArtifactId() + "/";
} else {
return "";
}
}
public File getArtifactJnlpDirFile(Artifact artifact)
{
File targetDirectory =
new File(getWorkDirectory(), getArtifactJnlpDir(artifact));
targetDirectory.mkdirs();
return targetDirectory;
}
public File getArtifactTemporaryDirFile(Artifact artifact)
{
String artifactFlatPath = getArtifactFlatPath(artifact);
File tmpDir = new File(getTemporaryDirectory(), artifactFlatPath);
tmpDir.mkdirs();
return tmpDir;
}
public String getArtifactFlatPath(Artifact artifact)
{
return artifact.getGroupId() + "." + artifact.getArtifactId();
}
/**
* this is created once per execution I'm assuming a new instance of this
* class is created for each execution
* @return
*/
public File getTemporaryDirectory()
{
if(temporaryDirectory != null){
return temporaryDirectory;
}
temporaryDirectory = new File(getWorkDirectory(), "tmp/" +
getVersionedArtifactName());
temporaryDirectory.mkdirs();
return temporaryDirectory;
}
private boolean artifactContainsClass( Artifact artifact, final String mainClass )
throws MalformedURLException
{
boolean containsClass = true;
// JarArchiver.grabFilesAndDirs()
ClassLoader cl = new java.net.URLClassLoader( new URL[]{artifact.getFile().toURL()} );
Class c = null;
try
{
c = Class.forName( mainClass, false, cl );
}
catch ( ClassNotFoundException e )
{
getLog().debug( "artifact " + artifact + " doesn't contain the main class: " + mainClass );
containsClass = false;
}
catch ( Throwable t )
{
getLog().info( "artifact " + artifact + " seems to contain the main class: " + mainClass +
" but the jar doesn't seem to contain all dependencies " + t.getMessage() );
}
if ( c != null )
{
getLog().debug( "Checking if the loaded class contains a main method." );
try
{
c.getMethod( "main", new Class[]{String[].class} );
}
catch ( NoSuchMethodException e )
{
getLog().warn( "The specified main class (" + mainClass +
") doesn't seem to contain a main method... Please check your configuration." + e.getMessage() );
}
catch ( NoClassDefFoundError e )
{
// undocumented in SDK 5.0. is this due to the ClassLoader lazy loading the Method thus making this a case tackled by the JVM Spec (Ref 5.3.5)!
// Reported as Incident 633981 to Sun just in case ...
getLog().warn( "Something failed while checking if the main class contains the main() method. " +
"This is probably due to the limited classpath we have provided to the class loader. " +
"The specified main class (" + mainClass +
") found in the jar is *assumed* to contain a main method... " + e.getMessage() );
}
catch ( Throwable t )
{
getLog().error( "Unknown error: Couldn't check if the main class has a main method. " +
"The specified main class (" + mainClass +
") found in the jar is *assumed* to contain a main method...", t );
}
}
return containsClass;
}
void generateJnlpFile( File outputDirectory )
throws MojoExecutionException
{
if ( jnlp.getOutputFile() == null || jnlp.getOutputFile().length() == 0 )
{
getLog().debug( "Jnlp output file name not specified. Using default output file name: launch.jnlp." );
jnlp.setOutputFile( "launch.jnlp" );
}
File jnlpOutputFile = new File( outputDirectory, jnlp.getOutputFile() );
if ( jnlp.getInputTemplate() == null || jnlp.getInputTemplate().length() == 0 )
{
getLog().debug(
"Jnlp template file name not specified. Using default output file name: src/jnlp/template.vm." );
jnlp.setInputTemplate( "src/jnlp/template.vm" );
}
String templateFileName = jnlp.getInputTemplate();
File resourceLoaderPath = getProject().getBasedir();
if ( jnlp.getInputTemplateResourcePath() != null && jnlp.getInputTemplateResourcePath().length() > 0 )
{
resourceLoaderPath = new File( jnlp.getInputTemplateResourcePath() );
}
Generator jnlpGenerator =
new Generator( this, resourceLoaderPath, jnlpOutputFile,
templateFileName );
// decide if this new jnlp is actually different from the old
// jnlp file.
if(!hasJnlpChanged(outputDirectory, jnlpGenerator)){
return;
}
try
{
// this writes out the file
jnlpGenerator.generate();
}
catch ( Exception e )
{
getLog().debug( e .toString() );
throw new MojoExecutionException( "Could not generate the JNLP deployment descriptor", e );
}
// optionally copy the outputfile to one with the version string appended
// use the generator to write out a copy of the file, use its new name
if(jnlp.getMakeJnlpWithVersion()){
try {
String versionedJnlpName = getVersionedArtifactName() + ".jnlp";
File versionedJnlpOutputFile =
new File( outputDirectory, versionedJnlpName );
FileWriter versionedJnlpWriter =
new FileWriter(versionedJnlpOutputFile);
jnlpGenerator.generate(versionedJnlpWriter,
versionedJnlpName, getVersionedArtifactName());
writeLastJnlpVersion(outputDirectory, getJnlpBuildVersion());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public File getLastVersionFile(File outputDirectory)
{
String artifactId = getProject().getArtifactId();
return new File(outputDirectory,
artifactId + "-CURRENT_VERSION.txt");
}
/**
* If there is no version file then this returns null
* @return
*/
public String readLastJnlpVersion(File outputDirectory)
{
File currentVersionFile = getLastVersionFile(outputDirectory);
// check if this file has changed from the old version
if(!currentVersionFile.exists()){
return null;
}
try {
String oldVersion = FileUtils.fileRead(currentVersionFile);
return oldVersion.trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void writeLastJnlpVersion(File outputDirectory, String version)
{
File currentVersionFile = getLastVersionFile(outputDirectory);
try {
FileUtils.fileWrite(currentVersionFile.getAbsolutePath(), version);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method uses the generator because of the timestamp that can be
* included in the file. To do the comparison it uses the current
* dependencies and system properties, but it uses the old file name
* and old versionedArtifactName
*
* @param outputDirectory
* @param generator
* @return
*/
public boolean hasJnlpChanged(File outputDirectory, Generator generator)
{
String artifactId = getProject().getArtifactId();
String oldVersion = readLastJnlpVersion(outputDirectory);
if(oldVersion == null) {
return true;
}
// look for the old version
String oldVersionedArtifactName = artifactId + "-" + oldVersion;
String oldVersionedJnlpName = oldVersionedArtifactName + ".jnlp";
File oldVersionedJnlpFile =
new File(outputDirectory, oldVersionedJnlpName);
if(!oldVersionedJnlpFile.exists()) {
return true;
}
try {
String oldJnlpText = FileUtils.fileRead(oldVersionedJnlpFile);
StringWriter updatedJnlpWriter = new StringWriter();
generator.generate(updatedJnlpWriter,
oldVersionedJnlpName, oldVersionedArtifactName);
String updatedJnlpText = updatedJnlpWriter.toString();
// If the strings match then there is no new version
if(oldJnlpText.equals(updatedJnlpText)){
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
public String getJnlpBuildVersion()
{
if(jnlpBuildVersion != null) {
return jnlpBuildVersion;
}
DateFormat utcDateFormatter = new SimpleDateFormat( UTC_TIMESTAMP_PATTERN );
utcDateFormatter.setTimeZone( UTC_TIME_ZONE );
String timestamp = utcDateFormatter.format( new Date() );
String version = getProject().getVersion();
if(version.endsWith("SNAPSHOT")){
version = version.replaceAll("SNAPSHOT", timestamp);
}
jnlpBuildVersion = version;
return version;
}
private void logCollection( final String prefix, final Collection collection )
{
getLog().debug( prefix + " " + collection );
if ( collection == null )
{
return;
}
for ( Iterator it3 = collection.iterator(); it3.hasNext(); )
{
getLog().debug( prefix + it3.next() );
}
}
private void deleteKeyStore()
{
File keyStore = null;
if ( sign.getKeystore() != null )
{
keyStore = new File( sign.getKeystore() );
}
else
{
// FIXME decide if we really want this.
// keyStore = new File( System.getProperty( "user.home") + File.separator + ".keystore" );
}
if ( keyStore == null )
{
return;
}
if ( keyStore.exists() )
{
if ( keyStore.delete() )
{
getLog().debug( "deleted keystore from: " + keyStore.getAbsolutePath() );
}
else
{
getLog().warn( "Couldn't delete keystore from: " + keyStore.getAbsolutePath() );
}
}
else
{
getLog().debug( "Skipping deletion of non existing keystore: " + keyStore.getAbsolutePath() );
}
}
private void genKeyStore()
throws MojoExecutionException
{
GenkeyMojo genKeystore = new GenkeyMojo();
genKeystore.setAlias( sign.getAlias() );
genKeystore.setDname( sign.getDname() );
genKeystore.setKeyalg( sign.getKeyalg() );
genKeystore.setKeypass( sign.getKeypass() );
genKeystore.setKeysize( sign.getKeysize() );
genKeystore.setKeystore( sign.getKeystore() );
genKeystore.setSigalg( sign.getSigalg() );
genKeystore.setStorepass( sign.getStorepass() );
genKeystore.setStoretype( sign.getStoretype() );
genKeystore.setValidity( sign.getValidity() );
genKeystore.setVerbose( this.verbose );
genKeystore.setWorkingDir( getWorkDirectory() );
genKeystore.execute();
}
private File getWorkDirectory()
{
return workDirectory;
}
/**
* Conditionaly copy the file into the target directory.
* The operation is not performed when the target file exists is up to date.
* The target file name is taken from the <code>sourceFile</code> name.
*
* @return <code>true</code> when the file was copied, <code>false</code> otherwise.
* @throws NullPointerException is sourceFile is <code>null</code> or
* <code>sourceFile.getName()</code> is <code>null</code>
* @throws IOException if the copy operation is tempted but failed.
*/
private boolean copyFileToDirectoryIfNecessary( File sourceFile, File targetDirectory,
String outputName)
throws IOException
{
File targetFile = new File( targetDirectory, outputName );
boolean shouldCopy = needsUpdating(sourceFile, targetDirectory, outputName);
if ( shouldCopy )
{
FileUtils.copyFile( sourceFile, targetFile);
}
else
{
getLog().debug(
"Source file hasn't changed. Do not overwrite " + targetFile + " with " + sourceFile + "." );
}
return shouldCopy;
}
private boolean needsUpdating(File sourceFile, File targetDirectory,
String outputName)
{
if ( sourceFile == null )
{
throw new NullPointerException( "sourceFile is null" );
}
File targetFile = new File( targetDirectory, outputName );
return ! targetFile.exists() || targetFile.lastModified() < sourceFile.lastModified();
}
/**
*
* @param relativeName
* @throws IOException
*/
private void signJar(File jarFile, String relativeName )
throws MojoExecutionException, IOException
{
getLog().info("signing: " + relativeName);
JarSignMojo signJar = new JarSignMojo();
signJar.setLog(getLog());
signJar.setAlias( sign.getAlias() );
signJar.setBasedir( basedir );
signJar.setKeypass( sign.getKeypass() );
signJar.setKeystore( sign.getKeystore() );
signJar.setSigFile( sign.getSigfile() );
signJar.setStorepass( sign.getStorepass() );
signJar.setType( sign.getStoretype() );
signJar.setVerbose( this.verbose );
signJar.setWorkingDir( getWorkDirectory() );
// we do our own verification because the jarsignmojo doesn't pass
// the log object, to the jarsignverifymojo, so lot
signJar.setVerify( false );
signJar.setJarPath( jarFile );
File signedJar = new File(jarFile.getParentFile(),
jarFile.getName() + ".signed");
// If the signedJar is set to null then the jar is signed
// in place.
signJar.setSignedJar(signedJar);
long lastModified = jarFile.lastModified();
signJar.execute();
FileUtils.rename(signedJar, jarFile);
jarFile.setLastModified( lastModified );
}
private void checkInput()
throws MojoExecutionException
{
getLog().debug( "a fact " + this.artifactFactory );
getLog().debug( "a resol " + this.artifactResolver );
getLog().debug( "basedir " + this.basedir );
getLog().debug( "gzip " + this.gzip );
getLog().debug( "pack200 " + this.pack200 );
getLog().debug( "project " + this.getProject() );
getLog().debug( "zipArchiver " + this.zipArchiver );
// getLog().debug( "usejnlpservlet " + this.usejnlpservlet );
getLog().debug( "verifyjar " + this.verifyjar );
getLog().debug( "verbose " + this.verbose );
if ( jnlp == null )
{
// throw new MojoExecutionException( "<jnlp> configuration element missing." );
}
if ( SystemUtils.JAVA_VERSION_FLOAT < 1.5f )
{
if ( pack200 )
{
throw new MojoExecutionException( "SDK 5.0 minimum when using pack200." );
}
}
// FIXME
/*
if ( !"pom".equals( getProject().getPackaging() ) ) {
throw new MojoExecutionException( "'" + getProject().getPackaging() + "' packaging unsupported. Use 'pom'" );
}
*/
}
/**
* @return
*/
public MavenProject getProject()
{
return project;
}
void setWorkDirectory( File workDirectory )
{
this.workDirectory = workDirectory;
}
void setVerbose( boolean verbose )
{
this.verbose = verbose;
}
public JnlpConfig getJnlp()
{
return jnlp;
}
public List getPackagedJnlpArtifacts()
{
return packagedJnlpArtifacts;
}
public Map getJnlpArtifactGroups()
{
return jnlpArtifactGroups;
}
/*
public Artifact getArtifactWithMainClass() {
return artifactWithMainClass;
}
*/
public boolean isArtifactWithMainClass( Artifact artifact )
{
final boolean b = artifactWithMainClass.equals( artifact );
getLog().debug( "compare " + artifactWithMainClass + " with " + artifact + ": " + b );
return b;
}
public String getSpec()
{
// shouldn't we automatically identify the spec based on the features used in the spec?
// also detect conflicts. If user specified 1.0 but uses a 1.5 feature we should fail in checkInput().
if ( jnlp.getSpec() != null )
{
return jnlp.getSpec();
}
return "1.0+";
}
/**
* @return
*/
public String getVersionedArtifactName() {
return getProject().getArtifactId() + "-" + getJnlpBuildVersion();
}
}
| fixed up regex so it doesn't match .sf files
git-svn-id: 4f0dbfeeb358eb5effd1ef9d64a147967f90bd05@1925 e004626d-f90d-0410-840a-8a47d1743edb
| plugin/src/main/java/org/codehaus/mojo/webstart/JnlpMojo.java | fixed up regex so it doesn't match .sf files |
|
Java | mit | 3823a0c5c84f87cd0475c1802e5410949cf1d2ba | 0 | draoullig/docker-build-step-plugin,tylerdavis/docker-build-step-plugin,wzheng2310/docker-build-step-plugin,BlackPepperSoftware/docker-build-step-plugin,BlackPepperSoftware/docker-build-step-plugin,wzheng2310/docker-build-step-plugin,tylerdavis/docker-build-step-plugin,ldtkms/docker-build-step-plugin,draoullig/docker-build-step-plugin,ldtkms/docker-build-step-plugin | package org.jenkinsci.plugins.dockerbuildstep.cmd;
import java.util.Arrays;
import java.util.List;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import org.jenkinsci.plugins.dockerbuildstep.action.EnvInvisibleAction;
import org.kohsuke.stapler.DataBoundConstructor;
import com.kpelykh.docker.client.DockerClient;
import com.kpelykh.docker.client.DockerException;
import com.kpelykh.docker.client.model.ContainerInspectResponse;
public class StartCommand extends DockerCommand {
private String containerIds;
@DataBoundConstructor
public StartCommand(String containerIds) {
this.containerIds = containerIds;
}
public String getContainerIds() {
return containerIds;
}
@Override
public void execute(@SuppressWarnings("rawtypes") AbstractBuild build, BuildListener listener) throws DockerException {
if (containerIds == null || containerIds.isEmpty()) {
throw new IllegalArgumentException("At least one parameter is required");
}
List<String> ids = Arrays.asList(containerIds.split(","));
DockerClient client = getClient();
for(String id : ids) {
id = id.trim();
client.startContainer(id);
ContainerInspectResponse inspectResp = client.inspectContainer(id);
EnvInvisibleAction envAction = new EnvInvisibleAction(inspectResp);
build.addAction(envAction);
}
}
@Extension
public static class StartCommandDescriptor extends DockerCommandDescriptor {
@Override
public String getDisplayName() {
return "Start constainer(s)";
}
}
}
| src/main/java/org/jenkinsci/plugins/dockerbuildstep/cmd/StartCommand.java | package org.jenkinsci.plugins.dockerbuildstep.cmd;
import java.util.Arrays;
import java.util.List;
import hudson.Extension;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import org.jenkinsci.plugins.dockerbuildstep.action.EnvInvisibleAction;
import org.kohsuke.stapler.DataBoundConstructor;
import com.kpelykh.docker.client.DockerClient;
import com.kpelykh.docker.client.DockerException;
import com.kpelykh.docker.client.model.ContainerInspectResponse;
public class StartCommand extends DockerCommand {
private String containerIds;
@DataBoundConstructor
public StartCommand(String containerIds) {
this.containerIds = containerIds;
}
public String getContainerIds() {
return containerIds;
}
@Override
public void execute(@SuppressWarnings("rawtypes") AbstractBuild build, BuildListener listener) throws DockerException {
if (containerIds == null || containerIds.isEmpty()) {
throw new IllegalArgumentException("At least one parameter is required");
}
List<String> ids = Arrays.asList(containerIds.split(","));
DockerClient client = getClient();
for(String id : ids) {
id = id.trim();
client.startContainer(id);
ContainerInspectResponse inspectResp = client.inspectContainer(id);
System.out.println("Adding action for " + id);
EnvInvisibleAction envAction = new EnvInvisibleAction(inspectResp);
build.addAction(envAction);
}
}
@Extension
public static class StartCommandDescriptor extends DockerCommandDescriptor {
@Override
public String getDisplayName() {
return "Start constainer(s)";
}
}
}
| Remove sysout
| src/main/java/org/jenkinsci/plugins/dockerbuildstep/cmd/StartCommand.java | Remove sysout |
|
Java | mit | 561b3cf532612e9f79f39989ee97e88210d74bb9 | 0 | talah/BBTH | package bbth.game;
import java.util.Map;
import android.graphics.Canvas;
import android.graphics.Paint;
import bbth.engine.achievements.AchievementInfo;
import bbth.engine.core.GameActivity;
import bbth.engine.net.bluetooth.Bluetooth;
import bbth.engine.net.simulation.LockStepProtocol;
import bbth.engine.ui.Anchor;
import bbth.engine.ui.UIButton;
import bbth.engine.ui.UIButtonDelegate;
import bbth.engine.ui.UIImageView;
import bbth.engine.ui.UILabel;
import bbth.engine.ui.UINavigationController;
import bbth.engine.ui.UIView;
public class TitleScreen extends UIView implements UIButtonDelegate {
private UIImageView titleBar;
private float animDelay = 1.0f;
private UIButton singleplayerButton, multiplayerButton, achievementsButton;
private InfiniteCombatView combatView;
private UINavigationController controller;
private Paint paint = new Paint();
private Map<String, AchievementInfo> achievements;
public TitleScreen(UINavigationController controller, Map<String, AchievementInfo> achievements) {
setSize(BBTHGame.WIDTH, BBTHGame.HEIGHT);
this.controller = controller;
this.achievements = achievements;
combatView = new InfiniteCombatView();
titleBar = new UIImageView(R.drawable.logo);
titleBar.setAnchor(Anchor.TOP_CENTER);
titleBar.setPosition(BBTHGame.WIDTH/2, -150);
titleBar.setSize(300, 140);
titleBar.animatePosition(BBTHGame.WIDTH/2, 20, 3);
this.addSubview(titleBar);
singleplayerButton = new UIButton("Single Player", this);
singleplayerButton.setSize(BBTHGame.WIDTH * 0.75f, 45);
singleplayerButton.setAnchor(Anchor.CENTER_CENTER);
singleplayerButton.setPosition(-BBTHGame.WIDTH, BBTHGame.HEIGHT / 2 - 65);
singleplayerButton.animatePosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2 - 65, 0.5f);
singleplayerButton.setButtonDelegate(this);
multiplayerButton = new UIButton("Multi Player", this);
multiplayerButton.setSize(BBTHGame.WIDTH * 0.75f, 45);
multiplayerButton.setAnchor(Anchor.CENTER_CENTER);
multiplayerButton.setPosition(-BBTHGame.WIDTH * 2.0f, BBTHGame.HEIGHT / 2);
multiplayerButton.animatePosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2, 1.0f);
multiplayerButton.setButtonDelegate(this);
achievementsButton = new UIButton("Achievements", this);
achievementsButton.setSize(BBTHGame.WIDTH * 0.75f, 45);
achievementsButton.setAnchor(Anchor.CENTER_CENTER);
achievementsButton.setPosition(-BBTHGame.WIDTH * 3.0f, BBTHGame.HEIGHT / 2 + 65);
achievementsButton.animatePosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2 + 65, 1.5f);
achievementsButton.setButtonDelegate(this);
}
@Override
public void onDraw(Canvas canvas) {
combatView.onDraw(canvas);
paint.setARGB(128, 0, 0, 0);
canvas.drawRect(0, 0, BBTHGame.WIDTH, BBTHGame.HEIGHT, paint);
super.onDraw(canvas);
}
@Override
public void onTouchDown(float x, float y) {
super.onTouchDown(x, y);
endAnimations();
}
@Override
public void willHide(boolean animating) {
super.willHide(animating);
endAnimations();
}
private void endAnimations() {
if (titleBar.isAnimatingPosition) {
animDelay = 0f;
titleBar.isAnimatingPosition = false;
titleBar.setPosition(BBTHGame.WIDTH / 2.f, 20);
}
if (singleplayerButton.isAnimatingPosition) {
animDelay = 0f;
singleplayerButton.isAnimatingPosition = false;
singleplayerButton.setPosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2 - 65);
}
if (multiplayerButton.isAnimatingPosition) {
animDelay = 0f;
multiplayerButton.isAnimatingPosition = false;
multiplayerButton.setPosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2);
}
if (achievementsButton.isAnimatingPosition) {
animDelay = 0f;
achievementsButton.isAnimatingPosition = false;
achievementsButton.setPosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2 + 65);
}
}
@Override
public void onUpdate(float seconds) {
super.onUpdate(seconds);
combatView.onUpdate(seconds);
if (!titleBar.isAnimatingPosition)
animDelay -= seconds;
if (animDelay <= 0) {
addSubview(singleplayerButton);
addSubview(multiplayerButton);
addSubview(achievementsButton);
}
}
@Override
public void onClick(UIButton button) {
if (button == singleplayerButton) {
LockStepProtocol protocol = new LockStepProtocol();
controller.push(new SongSelectionScreen(controller, Team.SERVER, new Bluetooth(GameActivity.instance, protocol), protocol, true), BBTHGame.MOVE_LEFT_TRANSITION);
} else if (button == multiplayerButton) {
controller.push(new GameSetupScreen(controller), BBTHGame.MOVE_LEFT_TRANSITION);
} else if (button == achievementsButton) {
controller.push(new AchievementsScreen(controller, achievements));
}
}
}
| gameSrc/bbth/game/TitleScreen.java | package bbth.game;
import java.util.Map;
import android.graphics.Canvas;
import android.graphics.Paint;
import bbth.engine.achievements.AchievementInfo;
import bbth.engine.core.GameActivity;
import bbth.engine.net.bluetooth.Bluetooth;
import bbth.engine.net.simulation.LockStepProtocol;
import bbth.engine.ui.Anchor;
import bbth.engine.ui.UIButton;
import bbth.engine.ui.UIButtonDelegate;
import bbth.engine.ui.UIImageView;
import bbth.engine.ui.UILabel;
import bbth.engine.ui.UINavigationController;
import bbth.engine.ui.UIView;
public class TitleScreen extends UIView implements UIButtonDelegate {
private UIImageView titleBar;
private float animDelay = 1.0f;
private UIButton singleplayerButton, multiplayerButton, achievementsButton;
private InfiniteCombatView combatView;
private UINavigationController controller;
private Paint paint = new Paint();
private Map<String, AchievementInfo> achievements;
public TitleScreen(UINavigationController controller, Map<String, AchievementInfo> achievements) {
setSize(BBTHGame.WIDTH, BBTHGame.HEIGHT);
this.controller = controller;
this.achievements = achievements;
combatView = new InfiniteCombatView();
titleBar = new UIImageView(R.drawable.logo);
titleBar.setAnchor(Anchor.TOP_CENTER);
titleBar.setPosition(BBTHGame.WIDTH/2, -150);
titleBar.setSize(300, 140);
titleBar.animatePosition(BBTHGame.WIDTH/2, 20, 3);
this.addSubview(titleBar);
singleplayerButton = new UIButton("Single Player", this);
singleplayerButton.setSize(BBTHGame.WIDTH * 0.75f, 45);
singleplayerButton.setAnchor(Anchor.CENTER_CENTER);
singleplayerButton.setPosition(-BBTHGame.WIDTH, BBTHGame.HEIGHT / 2 - 65);
singleplayerButton.animatePosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2 - 65, 0.5f);
singleplayerButton.setButtonDelegate(this);
multiplayerButton = new UIButton("Multi Player", this);
multiplayerButton.setSize(BBTHGame.WIDTH * 0.75f, 45);
multiplayerButton.setAnchor(Anchor.CENTER_CENTER);
multiplayerButton.setPosition(-BBTHGame.WIDTH * 2.0f, BBTHGame.HEIGHT / 2);
multiplayerButton.animatePosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2, 1.0f);
multiplayerButton.setButtonDelegate(this);
achievementsButton = new UIButton("Achievements", this);
achievementsButton.setSize(BBTHGame.WIDTH * 0.75f, 45);
achievementsButton.setAnchor(Anchor.CENTER_CENTER);
achievementsButton.setPosition(-BBTHGame.WIDTH * 3.0f, BBTHGame.HEIGHT / 2 + 65);
achievementsButton.animatePosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2 + 65, 1.5f);
achievementsButton.setButtonDelegate(this);
}
@Override
public void onDraw(Canvas canvas) {
combatView.onDraw(canvas);
paint.setARGB(128, 0, 0, 0);
canvas.drawRect(0, 0, BBTHGame.WIDTH, BBTHGame.HEIGHT, paint);
super.onDraw(canvas);
}
@Override
public void onTouchDown(float x, float y) {
super.onTouchDown(x, y);
if (titleBar.isAnimatingPosition) {
animDelay = 0f;
titleBar.isAnimatingPosition = false;
titleBar.setPosition(BBTHGame.WIDTH / 2.f, 20);
}
}
@Override
public void onUpdate(float seconds) {
super.onUpdate(seconds);
combatView.onUpdate(seconds);
if (!titleBar.isAnimatingPosition)
animDelay -= seconds;
if (animDelay <= 0) {
addSubview(singleplayerButton);
addSubview(multiplayerButton);
addSubview(achievementsButton);
}
}
@Override
public void onClick(UIButton button) {
if (button == singleplayerButton) {
LockStepProtocol protocol = new LockStepProtocol();
controller.push(new SongSelectionScreen(controller, Team.SERVER, new Bluetooth(GameActivity.instance, protocol), protocol, true), BBTHGame.MOVE_LEFT_TRANSITION);
} else if (button == multiplayerButton) {
controller.push(new GameSetupScreen(controller), BBTHGame.MOVE_LEFT_TRANSITION);
} else if (button == achievementsButton) {
controller.push(new AchievementsScreen(controller, achievements));
}
}
}
| Animations now end properly in TitleScreen.
| gameSrc/bbth/game/TitleScreen.java | Animations now end properly in TitleScreen. |
|
Java | mit | 205a95670395e645af723e76f7a5891429596064 | 0 | JetBrains/ideavim,JetBrains/ideavim | package com.maddyhome.idea.vim;
/*
* IdeaVim - A Vim emulator plugin for IntelliJ Idea
* Copyright (C) 2003-2008 Rick Maddy
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.ide.AppLifecycleListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actionSystem.TypedAction;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.util.messages.MessageBus;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.ex.CommandParser;
import com.maddyhome.idea.vim.group.*;
import com.maddyhome.idea.vim.helper.*;
import com.maddyhome.idea.vim.key.RegisterActions;
import com.maddyhome.idea.vim.option.Options;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* This plugin attempts to emulate the keybinding and general functionality of Vim and gVim. See the supplied
* documentation for a complete list of supported and unsupported Vim emulation. The code base contains some debugging
* output that can be enabled in necessary.
* <p/>
* This is an application level plugin meaning that all open projects will share a common instance of the plugin.
* Registers and marks are shared across open projects so you can copy and paste between files of different projects.
*
* @version 0.1
*/
@State(
name = "VimSettings",
storages = {
@Storage(
id = "main",
file = "$APP_CONFIG$/vim_settings.xml"
)}
)
public class VimPlugin implements ApplicationComponent, PersistentStateComponent<Element>
{
private static VimPlugin instance;
private VimTypedActionHandler vimHandler;
private RegisterActions actions;
private boolean isBlockCursor = false;
private boolean isSmoothScrolling = false;
private String previousKeyMap = "";
private boolean enabled = true;
private static Logger LOG = Logger.getInstance(VimPlugin.class.getName());
private PropertyChangeListener myLookupPropertiesListener;
/**
* Creates the Vim Plugin
*/
public VimPlugin(final MessageBus bus) {
LOG.debug("VimPlugin ctr");
instance = this;
bus.connect().subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() {
@Override
public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
// Ensure that Vim keymap is installed and install if not
VimKeyMapUtil.installKeyBoardBindings(instance);
// Turn on proper keymap
VimKeyMapUtil.enableKeyBoardBindings(VimPlugin.isEnabled());
}
});
}
});
}
public static VimPlugin getInstance() {
return instance;
}
/**
* Supplies the name of the plugin
*
* @return The plugin name
*/
@NotNull
public String getComponentName() {
return "VimPlugin";
}
public String getPreviousKeyMap() {
return previousKeyMap;
}
public void setPreviousKeyMap(final String keymap) {
previousKeyMap = keymap;
}
/**
* Initialize the Vim Plugin. This plugs the vim key handler into the editor action mananger.
*/
public void initComponent() {
LOG.debug("initComponent");
EditorActionManager manager = EditorActionManager.getInstance();
TypedAction action = manager.getTypedAction();
// Replace the default key handler with the Vim key handler
vimHandler = new VimTypedActionHandler(action.getHandler());
action.setupHandler(vimHandler);
// Add some listeners so we can handle special events
setupListeners();
getActions();
LOG.debug("done");
}
/**
* This sets up some listeners so we can handle various events that occur
*/
private void setupListeners() {
DocumentManager.getInstance().addDocumentListener(new MarkGroup.MarkUpdater());
if (ApiHelper.supportsColorSchemes()) {
DocumentManager.getInstance().addDocumentListener(new SearchGroup.DocumentSearchListener());
}
DocumentManager.getInstance().init();
EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(EditorFactoryEvent event) {
isBlockCursor = event.getEditor().getSettings().isBlockCursor();
isSmoothScrolling = event.getEditor().getSettings().isAnimatedScrolling();
if (VimPlugin.isEnabled()) {
event.getEditor().getSettings().setBlockCursor(!CommandState.inInsertMode(event.getEditor()));
event.getEditor().getSettings().setAnimatedScrolling(false);
}
EditorData.initializeEditor(event.getEditor());
DocumentManager.getInstance().addListeners(event.getEditor().getDocument());
}
public void editorReleased(EditorFactoryEvent event) {
EditorData.uninitializeEditor(event.getEditor());
event.getEditor().getSettings().setAnimatedScrolling(isSmoothScrolling);
DocumentManager.getInstance().removeListeners(event.getEditor().getDocument());
}
});
// Since the Vim plugin custom actions aren't available to the call to <code>initComponent()</code>
// we need to force the generation of the key map when the first project is opened.
ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() {
public void projectOpened(Project project) {
listeners.add(new MotionGroup.MotionEditorChange());
listeners.add(new FileGroup.SelectionCheck());
if (ApiHelper.supportsColorSchemes()) {
listeners.add(new SearchGroup.EditorSelectionCheck());
}
for (FileEditorManagerListener listener : listeners) {
FileEditorManager.getInstance(project).addFileEditorManagerListener(listener);
}
myLookupPropertiesListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())) {
final Lookup lookup = (Lookup)evt.getNewValue();
if (lookup != null) {
final Editor editor = lookup.getEditor();
CommandGroups.getInstance().getChange().insertBeforeCursor(editor, new EditorDataContext(editor));
}
}
}
};
LookupManager.getInstance(project).addPropertyChangeListener(myLookupPropertiesListener);
}
public void projectClosed(Project project) {
for (FileEditorManagerListener listener : listeners) {
FileEditorManager.getInstance(project).removeFileEditorManagerListener(listener);
}
LookupManager.getInstance(project).removePropertyChangeListener(myLookupPropertiesListener);
listeners.clear();
}
ArrayList<FileEditorManagerListener> listeners = new ArrayList<FileEditorManagerListener>();
});
CommandProcessor.getInstance().addCommandListener(DelegateCommandListener.getInstance());
}
/**
* This shuts down the Vim plugin. All we need to do is reinstall the original key handler
*/
public void disposeComponent() {
LOG.debug("disposeComponent");
turnOffPlugin();
EditorActionManager manager = EditorActionManager.getInstance();
TypedAction action = manager.getTypedAction();
action.setupHandler(vimHandler.getOriginalTypedHandler());
LOG.debug("done");
}
@Override
public void loadState(final Element element) {
LOG.debug("Loading state");
// Restore whether the plugin is enabled or not
Element state = element.getChild("state");
if (state != null) {
enabled = Boolean.valueOf(state.getAttributeValue("enabled"));
previousKeyMap = state.getAttributeValue("keymap");
}
CommandGroups.getInstance().readData(element);
}
@Override
public Element getState() {
LOG.debug("Saving state");
final Element element = new Element("ideavim");
// Save whether the plugin is enabled or not
final Element state = new Element("state");
state.setAttribute("enabled", Boolean.toString(enabled));
state.setAttribute("keymap", previousKeyMap);
element.addContent(state);
CommandGroups.getInstance().saveData(element);
return element;
}
/**
* Indicates whether the user has enabled or disabled the plugin
*
* @return true if the Vim plugin is enabled, false if not
*/
public static boolean isEnabled() {
return getInstance().enabled;
}
public static void setEnabled(boolean set) {
if (!set) {
getInstance().turnOffPlugin();
}
getInstance().enabled = set;
if (set) {
getInstance().turnOnPlugin();
}
VimKeyMapUtil.enableKeyBoardBindings(set);
}
/**
* Inidicate to the user that an error has occurred. Just beep.
*/
public static void indicateError() {
if (!Options.getInstance().isSet("visualbell")) {
Toolkit.getDefaultToolkit().beep();
}
}
public static void showMode(String msg) {
showMessage(msg);
}
public static void showMessage(String msg) {
ProjectManager pm = ProjectManager.getInstance();
Project[] projs = pm.getOpenProjects();
for (Project proj : projs) {
StatusBar bar = WindowManager.getInstance().getStatusBar(proj);
if (msg == null || msg.length() == 0) {
bar.setInfo("");
}
else {
bar.setInfo("VIM - " + msg);
}
}
}
public void turnOnPlugin() {
KeyHandler.getInstance().fullReset(null);
setCursors(true);
setSmoothScrolling(false);
CommandGroups.getInstance().getMotion().turnOn();
}
public void turnOffPlugin() {
KeyHandler.getInstance().fullReset(null);
setCursors(isBlockCursor);
setSmoothScrolling(isSmoothScrolling);
CommandGroups.getInstance().getMotion().turnOff();
}
private void setCursors(boolean isBlock) {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
editor.getSettings().setBlockCursor(isBlock);
}
}
private void setSmoothScrolling(boolean isOn) {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
editor.getSettings().setAnimatedScrolling(isOn);
}
}
private RegisterActions getActions() {
if (actions == null) {
// Register vim actions in command mode
actions = RegisterActions.getInstance();
// Register ex handlers
CommandParser.getInstance().registerHandlers();
}
return actions;
}
}
| src/com/maddyhome/idea/vim/VimPlugin.java | package com.maddyhome.idea.vim;
/*
* IdeaVim - A Vim emulator plugin for IntelliJ Idea
* Copyright (C) 2003-2008 Rick Maddy
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
import com.intellij.ide.AppLifecycleListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actionSystem.TypedAction;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.util.messages.MessageBus;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.ex.CommandParser;
import com.maddyhome.idea.vim.group.*;
import com.maddyhome.idea.vim.helper.ApiHelper;
import com.maddyhome.idea.vim.helper.DelegateCommandListener;
import com.maddyhome.idea.vim.helper.DocumentManager;
import com.maddyhome.idea.vim.helper.EditorData;
import com.maddyhome.idea.vim.key.RegisterActions;
import com.maddyhome.idea.vim.option.Options;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.ArrayList;
/**
* This plugin attempts to emulate the keybinding and general functionality of Vim and gVim. See the supplied
* documentation for a complete list of supported and unsupported Vim emulation. The code base contains some debugging
* output that can be enabled in necessary.
* <p/>
* This is an application level plugin meaning that all open projects will share a common instance of the plugin.
* Registers and marks are shared across open projects so you can copy and paste between files of different projects.
*
* @version 0.1
*/
@State(
name = "VimSettings",
storages = {
@Storage(
id = "main",
file = "$APP_CONFIG$/vim_settings.xml"
)}
)
public class VimPlugin implements ApplicationComponent, PersistentStateComponent<Element>
{
private static VimPlugin instance;
private VimTypedActionHandler vimHandler;
private RegisterActions actions;
private boolean isBlockCursor = false;
private boolean isSmoothScrolling = false;
private String previousKeyMap = "";
private boolean enabled = true;
private static Logger LOG = Logger.getInstance(VimPlugin.class.getName());
/**
* Creates the Vim Plugin
*/
public VimPlugin(final MessageBus bus) {
LOG.debug("VimPlugin ctr");
instance = this;
bus.connect().subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() {
@Override
public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
// Ensure that Vim keymap is installed and install if not
VimKeyMapUtil.installKeyBoardBindings(instance);
// Turn on proper keymap
VimKeyMapUtil.enableKeyBoardBindings(VimPlugin.isEnabled());
}
});
}
});
}
public static VimPlugin getInstance() {
return instance;
}
/**
* Supplies the name of the plugin
*
* @return The plugin name
*/
@NotNull
public String getComponentName() {
return "VimPlugin";
}
public String getPreviousKeyMap() {
return previousKeyMap;
}
public void setPreviousKeyMap(final String keymap) {
previousKeyMap = keymap;
}
/**
* Initialize the Vim Plugin. This plugs the vim key handler into the editor action mananger.
*/
public void initComponent() {
LOG.debug("initComponent");
EditorActionManager manager = EditorActionManager.getInstance();
TypedAction action = manager.getTypedAction();
// Replace the default key handler with the Vim key handler
vimHandler = new VimTypedActionHandler(action.getHandler());
action.setupHandler(vimHandler);
// Add some listeners so we can handle special events
setupListeners();
getActions();
LOG.debug("done");
}
/**
* This sets up some listeners so we can handle various events that occur
*/
private void setupListeners() {
DocumentManager.getInstance().addDocumentListener(new MarkGroup.MarkUpdater());
if (ApiHelper.supportsColorSchemes()) {
DocumentManager.getInstance().addDocumentListener(new SearchGroup.DocumentSearchListener());
}
DocumentManager.getInstance().init();
EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(EditorFactoryEvent event) {
isBlockCursor = event.getEditor().getSettings().isBlockCursor();
isSmoothScrolling = event.getEditor().getSettings().isAnimatedScrolling();
if (VimPlugin.isEnabled()) {
event.getEditor().getSettings().setBlockCursor(!CommandState.inInsertMode(event.getEditor()));
event.getEditor().getSettings().setAnimatedScrolling(false);
}
EditorData.initializeEditor(event.getEditor());
DocumentManager.getInstance().addListeners(event.getEditor().getDocument());
}
public void editorReleased(EditorFactoryEvent event) {
EditorData.uninitializeEditor(event.getEditor());
event.getEditor().getSettings().setAnimatedScrolling(isSmoothScrolling);
DocumentManager.getInstance().removeListeners(event.getEditor().getDocument());
}
});
// Since the Vim plugin custom actions aren't available to the call to <code>initComponent()</code>
// we need to force the generation of the key map when the first project is opened.
ProjectManager.getInstance().addProjectManagerListener(new ProjectManagerAdapter() {
public void projectOpened(Project project) {
listeners.add(new MotionGroup.MotionEditorChange());
listeners.add(new FileGroup.SelectionCheck());
if (ApiHelper.supportsColorSchemes()) {
listeners.add(new SearchGroup.EditorSelectionCheck());
}
for (FileEditorManagerListener listener : listeners) {
FileEditorManager.getInstance(project).addFileEditorManagerListener(listener);
}
}
public void projectClosed(Project project) {
for (FileEditorManagerListener listener : listeners) {
FileEditorManager.getInstance(project).removeFileEditorManagerListener(listener);
}
listeners.clear();
}
ArrayList<FileEditorManagerListener> listeners = new ArrayList<FileEditorManagerListener>();
});
CommandProcessor.getInstance().addCommandListener(DelegateCommandListener.getInstance());
}
/**
* This shuts down the Vim plugin. All we need to do is reinstall the original key handler
*/
public void disposeComponent() {
LOG.debug("disposeComponent");
turnOffPlugin();
EditorActionManager manager = EditorActionManager.getInstance();
TypedAction action = manager.getTypedAction();
action.setupHandler(vimHandler.getOriginalTypedHandler());
LOG.debug("done");
}
@Override
public void loadState(final Element element) {
LOG.debug("Loading state");
// Restore whether the plugin is enabled or not
Element state = element.getChild("state");
if (state != null) {
enabled = Boolean.valueOf(state.getAttributeValue("enabled"));
previousKeyMap = state.getAttributeValue("keymap");
}
CommandGroups.getInstance().readData(element);
}
@Override
public Element getState() {
LOG.debug("Saving state");
final Element element = new Element("ideavim");
// Save whether the plugin is enabled or not
final Element state = new Element("state");
state.setAttribute("enabled", Boolean.toString(enabled));
state.setAttribute("keymap", previousKeyMap);
element.addContent(state);
CommandGroups.getInstance().saveData(element);
return element;
}
/**
* Indicates whether the user has enabled or disabled the plugin
*
* @return true if the Vim plugin is enabled, false if not
*/
public static boolean isEnabled() {
return getInstance().enabled;
}
public static void setEnabled(boolean set) {
if (!set) {
getInstance().turnOffPlugin();
}
getInstance().enabled = set;
if (set) {
getInstance().turnOnPlugin();
}
VimKeyMapUtil.enableKeyBoardBindings(set);
}
/**
* Inidicate to the user that an error has occurred. Just beep.
*/
public static void indicateError() {
if (!Options.getInstance().isSet("visualbell")) {
Toolkit.getDefaultToolkit().beep();
}
}
public static void showMode(String msg) {
showMessage(msg);
}
public static void showMessage(String msg) {
ProjectManager pm = ProjectManager.getInstance();
Project[] projs = pm.getOpenProjects();
for (Project proj : projs) {
StatusBar bar = WindowManager.getInstance().getStatusBar(proj);
if (msg == null || msg.length() == 0) {
bar.setInfo("");
}
else {
bar.setInfo("VIM - " + msg);
}
}
}
public void turnOnPlugin() {
KeyHandler.getInstance().fullReset(null);
setCursors(true);
setSmoothScrolling(false);
CommandGroups.getInstance().getMotion().turnOn();
}
public void turnOffPlugin() {
KeyHandler.getInstance().fullReset(null);
setCursors(isBlockCursor);
setSmoothScrolling(isSmoothScrolling);
CommandGroups.getInstance().getMotion().turnOff();
}
private void setCursors(boolean isBlock) {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
editor.getSettings().setBlockCursor(isBlock);
}
}
private void setSmoothScrolling(boolean isOn) {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
editor.getSettings().setAnimatedScrolling(isOn);
}
}
private RegisterActions getActions() {
if (actions == null) {
// Register vim actions in command mode
actions = RegisterActions.getInstance();
// Register ex handlers
CommandParser.getInstance().registerHandlers();
}
return actions;
}
}
| Turn on insert mode when active lookup is invoked
| src/com/maddyhome/idea/vim/VimPlugin.java | Turn on insert mode when active lookup is invoked |
|
Java | mit | 7a49a8c6f15608c6c95a1efacdcb70af701cfc1a | 0 | tkuhn/nanopub-server,tkuhn/nanopub-server | package ch.tkuhn.nanopub.server;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import net.trustyuri.TrustyUriUtils;
public class NanopubListPage extends Page {
public static final String PAGE_NAME = "nanopubs";
private boolean asHtml;
public static void show(ServerRequest req, HttpServletResponse httpResp) throws IOException {
NanopubListPage obj = new NanopubListPage(req, httpResp);
obj.show();
}
private final int pageSize;
private final long lastPage;
private final long pageNo;
private final long nextNpNo;
private final String pageContent;
public NanopubListPage(ServerRequest req, HttpServletResponse httpResp) {
super(req, httpResp);
NanopubDb db = NanopubDb.get();
synchronized(db) {
pageSize = db.getPageSize();
lastPage = db.getCurrentPageNo();
nextNpNo = db.getNextNanopubNo();
String[] paramValues = req.getHttpRequest().getParameterValues("page");
if (paramValues != null && paramValues.length > 0) {
pageNo = Integer.parseInt(paramValues[0]);
} else {
pageNo = lastPage;
}
pageContent = db.getPageContent(pageNo);
getResp().addHeader("ETag", "W/\"" + db.getJournalStateId() + "\"");
}
setCanonicalLink("/" + PAGE_NAME + "?page=" + pageNo);
getResp().addHeader("Link", "<" + PAGE_NAME + "?page=1>; rel=\"start\"");
if (pageNo > 1) {
getResp().addHeader("Link", "<" + PAGE_NAME + "?page=" + (pageNo-1) + ">; rel=\"prev\"");
}
if (pageNo < lastPage) {
getResp().addHeader("Link", "<" + PAGE_NAME + "?page=" + (pageNo+1) + ">; rel=\"next\"");
}
String rf = getReq().getPresentationFormat();
if (rf == null) {
String suppFormats = "text/plain,text/html";
asHtml = "text/html".equals(Utils.getMimeType(getHttpReq(), suppFormats));
} else {
asHtml = "text/html".equals(getReq().getPresentationFormat());
}
}
public void show() throws IOException {
printStart();
long n = (pageNo-1) * pageSize;
for (String uri : pageContent.split("\\n")) {
if (uri.isEmpty()) continue;
printElement(n, uri);
n++;
}
if (asHtml && n == 0) {
println("<tr><td>*EMPTY*</td></tr>");
}
if (asHtml && n % pageSize > 0 && nextNpNo == n) {
println("<tr><td>*END*</td></tr>");
}
printEnd();
if (asHtml) {
getResp().setContentType("text/html");
} else {
getResp().setContentType("text/plain");
}
}
private void printStart() throws IOException {
if (asHtml) {
String title = "Nanopublications: Page " + pageNo + " of " + lastPage;
printHtmlHeader(title);
print("<h1>" + title + "</h1>");
println("<p>[ ");
println("<a href=\"" + PAGE_NAME + ".txt?page=" + pageNo + "\" rel=\"alternate\" type=\"text/plain\">as plain text</a> | ");
if (pageNo < lastPage) {
println("<a href=\"" + PackagePage.PAGE_NAME + ".trig.gz?page=" + pageNo + "\" type=\"application/gzip\">as package</a> | ");
}
println("<a href=\".\" rel=\"home\">home</a> |");
println("<a href=\"" + PAGE_NAME + ".html?page=1\" rel=\"start\"><< first page</a> | ");
if (pageNo == 1) {
println("< previous page | ");
} else {
println("<a href=\"" + PAGE_NAME + ".html?page=" + (pageNo-1) + "\" rel=\"prev\">< previous page</a> |");
}
if (pageNo == lastPage) {
println("next page > | ");
} else {
println("<a href=\"" + PAGE_NAME + ".html?page=" + (pageNo+1) + "\" rel=\"next\">next page ></a> | ");
}
println("<a href=\"" + PAGE_NAME + ".html?page=" + lastPage + "\">last page >></a> ");
println("]</p>");
println("<table><tbody>");
}
}
private void printElement(long n, String npUri) throws IOException {
String artifactCode = TrustyUriUtils.getArtifactCode(npUri);
if (asHtml) {
print("<tr>");
print("<td>" + n + "</td>");
print("<td>");
printAltLinks(artifactCode);
print("</td>");
print("<td><span class=\"code\">" + npUri + "</span></td>");
println("</tr>");
} else {
println(npUri);
}
}
private void printEnd() throws IOException {
if (asHtml) {
println("</tbody></table>");
printHtmlFooter();
}
}
}
| src/main/java/ch/tkuhn/nanopub/server/NanopubListPage.java | package ch.tkuhn.nanopub.server;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import net.trustyuri.TrustyUriUtils;
public class NanopubListPage extends Page {
public static final String PAGE_NAME = "nanopubs";
private boolean asHtml;
public static void show(ServerRequest req, HttpServletResponse httpResp) throws IOException {
NanopubListPage obj = new NanopubListPage(req, httpResp);
obj.show();
}
private final int pageSize;
private final long lastPage;
private final long pageNo;
private final long nextNpNo;
private final String pageContent;
public NanopubListPage(ServerRequest req, HttpServletResponse httpResp) {
super(req, httpResp);
NanopubDb db = NanopubDb.get();
synchronized(db) {
pageSize = db.getPageSize();
lastPage = db.getCurrentPageNo();
nextNpNo = db.getNextNanopubNo();
String[] paramValues = req.getHttpRequest().getParameterValues("page");
if (paramValues != null && paramValues.length > 0) {
pageNo = Integer.parseInt(paramValues[0]);
} else {
pageNo = lastPage;
}
pageContent = db.getPageContent(pageNo);
getResp().addHeader("ETag", "W/\"" + db.getJournalStateId() + "\"");
}
setCanonicalLink("/" + PAGE_NAME + "?page=" + pageNo);
getResp().addHeader("Link", "<" + PAGE_NAME + "?page=1>; rel=\"start\"");
if (pageNo > 1) {
getResp().addHeader("Link", "<" + PAGE_NAME + "?page=" + (pageNo-1) + ">; rel=\"prev\"");
}
if (pageNo < lastPage) {
getResp().addHeader("Link", "<" + PAGE_NAME + "?page=" + (pageNo+1) + ">; rel=\"next\"");
}
String rf = getReq().getPresentationFormat();
if (rf == null) {
String suppFormats = "text/plain,text/html";
asHtml = "text/html".equals(Utils.getMimeType(getHttpReq(), suppFormats));
} else {
asHtml = "text/html".equals(getReq().getPresentationFormat());
}
}
public void show() throws IOException {
printStart();
long n = (pageNo-1) * pageSize;
for (String uri : pageContent.split("\\n")) {
if (uri.isEmpty()) continue;
printElement(n, uri);
n++;
}
if (asHtml && n == 0) {
println("<tr><td>*EMPTY*</td></tr>");
}
if (asHtml && n % pageSize > 0 && nextNpNo == n) {
println("<tr><td>*END*</td></tr>");
}
printEnd();
if (asHtml) {
getResp().setContentType("text/html");
} else {
getResp().setContentType("text/plain");
}
}
private void printStart() throws IOException {
if (asHtml) {
String title = "Nanopublications: Page " + pageNo + " of " + lastPage;
printHtmlHeader(title);
print("<h1>" + title + "</h1>");
println("<p>[ ");
println("<a href=\"" + PAGE_NAME + ".txt?page=" + pageNo + "\" rel=\"alternate\" type=\"text/plain\">as plain text</a> | ");
if (pageNo < lastPage) {
println("<a href=\"" + PackagePage.PAGE_NAME + ".trig?page=" + pageNo + "\" type=\"application/trig\">as package</a> | ");
}
println("<a href=\".\" rel=\"home\">home</a> |");
println("<a href=\"" + PAGE_NAME + ".html?page=1\" rel=\"start\"><< first page</a> | ");
if (pageNo == 1) {
println("< previous page | ");
} else {
println("<a href=\"" + PAGE_NAME + ".html?page=" + (pageNo-1) + "\" rel=\"prev\">< previous page</a> |");
}
if (pageNo == lastPage) {
println("next page > | ");
} else {
println("<a href=\"" + PAGE_NAME + ".html?page=" + (pageNo+1) + "\" rel=\"next\">next page ></a> | ");
}
println("<a href=\"" + PAGE_NAME + ".html?page=" + lastPage + "\">last page >></a> ");
println("]</p>");
println("<table><tbody>");
}
}
private void printElement(long n, String npUri) throws IOException {
String artifactCode = TrustyUriUtils.getArtifactCode(npUri);
if (asHtml) {
print("<tr>");
print("<td>" + n + "</td>");
print("<td>");
printAltLinks(artifactCode);
print("</td>");
print("<td><span class=\"code\">" + npUri + "</span></td>");
println("</tr>");
} else {
println(npUri);
}
}
private void printEnd() throws IOException {
if (asHtml) {
println("</tbody></table>");
printHtmlFooter();
}
}
}
| Link to gzipped version of packages | src/main/java/ch/tkuhn/nanopub/server/NanopubListPage.java | Link to gzipped version of packages |
|
Java | mit | 10be2b4c2622c0d15de7bd1f9adfbbcd80585c68 | 0 | technology16/dbreplicator2,Technologiya/dbreplicator2,technology16/dbreplicator2,Technologiya/dbreplicator2 | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Technologiya
*
* 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 ru.taximaxim.dbreplicator2.el;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import ru.taximaxim.dbreplicator2.jdbc.StatementsHashMap;
import ru.taximaxim.dbreplicator2.replica.strategies.replication.data.DataServiceSkeleton;
/**
* Класс реализации механизма логирования ошибок
*
* @author volodin_aa
*
*/
public class ErrorsLog extends DataServiceSkeleton
implements ErrorsLogService {
private static final Logger LOG = Logger.getLogger(ErrorsLog.class);
/**
* кешированный запрос обновления
*/
private final StatementsHashMap<String, PreparedStatement> statementsCache = new StatementsHashMap<String, PreparedStatement>();
/**
* Получение выражения на основе текста запроса. Выражения кешируются.
*
* @param query
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private PreparedStatement getStatement(String query) throws SQLException {
PreparedStatement statement = statementsCache.get(query);
if (statement == null) {
statement = getConnection().prepareStatement(query);
statementsCache.put(query, statement);
}
return statement;
}
/**
* Конструктор на основе соединения к БД
*/
public ErrorsLog(DataSource dataSource) {
super(dataSource);
}
@Override
public void add(Integer runnerId, String tableId, Long foreignId, String error,
Throwable e) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("Подробности: ");
e.printStackTrace(printWriter);
printWriter.flush();
add(runnerId, tableId, foreignId, error + "\n" + writer.toString());
}
@Override
public void add(Integer runnerId, String tableId, Long foreignId, String error,
SQLException e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("Подробности: ");
e.printStackTrace(printWriter);
SQLException nextEx = e.getNextException();
while (nextEx != null) {
printWriter.println("Подробности: ");
nextEx.printStackTrace(printWriter);
nextEx = nextEx.getNextException();
}
add(runnerId, tableId, foreignId, error + "\n" + writer.toString());
}
@Override
public void add(Integer runnerId, String tableId, Long foreignId, String error) {
try {
PreparedStatement statement = getStatement(
"INSERT INTO rep2_errors_log (id_runner, id_table, id_foreign, c_date, c_error, c_status) values (?, ?, ?, ?, ?, 0)");
statement.setObject(1, runnerId);
statement.setObject(2, tableId);
statement.setObject(3, foreignId);
statement.setTimestamp(4, new Timestamp(new Date().getTime()));
statement.setString(5, error.replaceAll("\0", "�"));
statement.execute();
} catch (Throwable e) {
LOG.error("Ошибка записи в rep2_errors_log:", e);
LOG.error(error);
}
}
protected int addIsNull(StringBuffer query, Object value) {
if (value == null) {
query.append(" IS NULL");
return 0;
} else {
query.append("=?");
return 1;
}
}
@Override
public void setStatus(Integer runnerId, String tableId, Long foreignId, int status) {
StringBuffer updateQuery = new StringBuffer(
"UPDATE rep2_errors_log SET c_status = ? WHERE c_status<> ? AND id_runner");
try {
int runnerIdPos = addIsNull(updateQuery, runnerId);
updateQuery.append(" AND id_table");
int tableIdPos = addIsNull(updateQuery, tableId);
updateQuery.append(" AND id_foreign");
int foreignIdPos = addIsNull(updateQuery, foreignId);
PreparedStatement statement = getStatement(updateQuery.toString());
statement.setInt(1, status);
statement.setInt(2, status);
if (runnerIdPos != 0) {
statement.setInt(2 + runnerIdPos, runnerId);
}
if (tableIdPos != 0) {
statement.setString(2 + runnerIdPos + tableIdPos, tableId);
}
if (foreignIdPos != 0) {
statement.setLong(2 + runnerIdPos + tableIdPos + foreignIdPos, foreignId);
}
statement.execute();
} catch (Throwable e) {
LOG.fatal(String.format(
"Ошибка при установки статуса в rep2_errors_log: runnerId=[%s], tableId=[%s], foreignId=[%s], c_status=%s",
runnerId, tableId, foreignId, status), e);
}
}
@Override
public void close() {
try (StatementsHashMap<String, PreparedStatement> statementsCache = this.statementsCache) {
super.close();
} catch (SQLException e) {
LOG.fatal("Ошибка закрытия ресурсов!", e);
}
}
} | src/main/java/ru/taximaxim/dbreplicator2/el/ErrorsLog.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Technologiya
*
* 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 ru.taximaxim.dbreplicator2.el;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import ru.taximaxim.dbreplicator2.jdbc.StatementsHashMap;
import ru.taximaxim.dbreplicator2.replica.strategies.replication.data.DataServiceSkeleton;
/**
* Класс реализации механизма логирования ошибок
*
* @author volodin_aa
*
*/
public class ErrorsLog extends DataServiceSkeleton
implements ErrorsLogService {
private static final Logger LOG = Logger.getLogger(ErrorsLog.class);
/**
* кешированный запрос обновления
*/
private final StatementsHashMap<String, PreparedStatement> statementsCache = new StatementsHashMap<String, PreparedStatement>();
/**
* Получение выражения на основе текста запроса. Выражения кешируются.
*
* @param query
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
private PreparedStatement getStatement(String query) throws SQLException {
PreparedStatement statement = statementsCache.get(query);
if (statement == null) {
statement = getConnection().prepareStatement(query);
statementsCache.put(query, statement);
}
return statement;
}
/**
* Конструктор на основе соединения к БД
*/
public ErrorsLog(DataSource dataSource) {
super(dataSource);
}
@Override
public void add(Integer runnerId, String tableId, Long foreignId, String error,
Throwable e) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("Подробности: ");
e.printStackTrace(printWriter);
printWriter.flush();
add(runnerId, tableId, foreignId, error + "\n" + writer.toString());
}
@Override
public void add(Integer runnerId, String tableId, Long foreignId, String error,
SQLException e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("Подробности: ");
e.printStackTrace(printWriter);
SQLException nextEx = e.getNextException();
while (nextEx != null) {
printWriter.println("Подробности: ");
nextEx.printStackTrace(printWriter);
nextEx = nextEx.getNextException();
}
add(runnerId, tableId, foreignId, error + "\n" + writer.toString());
}
@Override
public void add(Integer runnerId, String tableId, Long foreignId, String error) {
try {
PreparedStatement statement = getStatement(
"INSERT INTO rep2_errors_log (id_runner, id_table, id_foreign, c_date, c_error, c_status) values (?, ?, ?, ?, ?, 0)");
statement.setObject(1, runnerId);
statement.setObject(2, tableId);
statement.setObject(3, foreignId);
statement.setTimestamp(4, new Timestamp(new Date().getTime()));
statement.setString(5, error.replaceAll("\0", "�"));
statement.execute();
} catch (Throwable e) {
LOG.fatal("Ошибка записи в rep2_errors_log:", e);
LOG.error(error);
}
}
protected int addIsNull(StringBuffer query, Object value) {
if (value == null) {
query.append(" IS NULL");
return 0;
} else {
query.append("=?");
return 1;
}
}
@Override
public void setStatus(Integer runnerId, String tableId, Long foreignId, int status) {
StringBuffer updateQuery = new StringBuffer(
"UPDATE rep2_errors_log SET c_status = ? WHERE c_status<> ? AND id_runner");
try {
int runnerIdPos = addIsNull(updateQuery, runnerId);
updateQuery.append(" AND id_table");
int tableIdPos = addIsNull(updateQuery, tableId);
updateQuery.append(" AND id_foreign");
int foreignIdPos = addIsNull(updateQuery, foreignId);
PreparedStatement statement = getStatement(updateQuery.toString());
statement.setInt(1, status);
statement.setInt(2, status);
if (runnerIdPos != 0) {
statement.setInt(2 + runnerIdPos, runnerId);
}
if (tableIdPos != 0) {
statement.setString(2 + runnerIdPos + tableIdPos, tableId);
}
if (foreignIdPos != 0) {
statement.setLong(2 + runnerIdPos + tableIdPos + foreignIdPos, foreignId);
}
statement.execute();
} catch (Throwable e) {
LOG.fatal(String.format(
"Ошибка при установки статуса в rep2_errors_log: runnerId=[%s], tableId=[%s], foreignId=[%s], c_status=%s",
runnerId, tableId, foreignId, status), e);
}
}
@Override
public void close() {
try (StatementsHashMap<String, PreparedStatement> statementsCache = this.statementsCache) {
super.close();
} catch (SQLException e) {
LOG.fatal("Ошибка закрытия ресурсов!", e);
}
}
} | Снизил уровень ошибки записи в rep2_errors_log до ERROR. FATAL спамил
сквозь emailthrottle | src/main/java/ru/taximaxim/dbreplicator2/el/ErrorsLog.java | Снизил уровень ошибки записи в rep2_errors_log до ERROR. FATAL спамил сквозь emailthrottle |
|
Java | agpl-3.0 | dda3912f77e34322ade551ad0a929901c4fba4f1 | 0 | elki-project/elki,elki-project/elki,elki-project/elki | package de.lmu.ifi.dbs.elki.evaluation.clustering;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures
Copyright (C) 2011
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team
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/>.
*/
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.logging.LoggingUtil;
import de.lmu.ifi.dbs.elki.math.MeanVariance;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
/**
* Class storing the contingency table and related data on two clusterings.
*
* @author Erich Schubert
*/
public class ClusterContingencyTable {
/**
* Noise cluster handling
*/
protected boolean breakNoiseClusters = false;
/**
* Self pairing
*/
protected boolean selfPairing = true;
/**
* Number of clusters in first
*/
protected int size1 = -1;
/**
* Number of clusters in second
*/
protected int size2 = -1;
/**
* Contingency matrix
*/
protected int[][] contingency = null;
/**
* Noise flags
*/
protected BitSet noise1 = null;
/**
* Noise flags
*/
protected BitSet noise2 = null;
/**
* Pair counting measures
*/
protected PairCounting paircount = null;
/**
* Entropy-based measures
*/
protected Entropy entropy = null;
/**
* Set matching purity measures
*/
protected SetMatchingPurity smp = null;
/**
* Edit-Distance measures
*/
protected EditDistance edit = null;
/**
* BCubed measures
*/
protected BCubed bcubed = null;
/**
* Constructor.
*
* @param selfPairing Build self-pairs
* @param breakNoiseClusters Break noise clusters into individual objects
*/
public ClusterContingencyTable(boolean selfPairing, boolean breakNoiseClusters) {
super();
this.selfPairing = selfPairing;
this.breakNoiseClusters = breakNoiseClusters;
}
/**
* Process two clustering results.
*
* @param result1 First clustering
* @param result2 Second clustering
*/
public void process(Clustering<?> result1, Clustering<?> result2) {
// Get the clusters
final List<? extends Cluster<?>> cs1 = result1.getAllClusters();
final List<? extends Cluster<?>> cs2 = result2.getAllClusters();
// Initialize
size1 = cs1.size();
size2 = cs2.size();
contingency = new int[size1 + 2][size2 + 2];
noise1 = new BitSet(size1);
noise2 = new BitSet(size2);
// Fill main part of matrix
{
{
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
if(c2.isNoise()) {
noise2.set(i2);
}
contingency[size1 + 1][i2] = c2.size();
contingency[size1 + 1][size2] += c2.size();
}
}
final Iterator<? extends Cluster<?>> it1 = cs1.iterator();
for(int i1 = 0; it1.hasNext(); i1++) {
final Cluster<?> c1 = it1.next();
if(c1.isNoise()) {
noise1.set(i1);
}
final DBIDs ids = DBIDUtil.ensureSet(c1.getIDs());
contingency[i1][size2 + 1] = c1.size();
contingency[size1][size2 + 1] += c1.size();
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
int count = 0;
for(DBID id : c2.getIDs()) {
if(ids.contains(id)) {
count++;
}
}
contingency[i1][i2] = count;
contingency[i1][size2] += count;
contingency[size1][i2] += count;
contingency[size1][size2] += count;
}
}
}
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
if(contingency != null) {
for(int i1 = 0; i1 < size1 + 2; i1++) {
if(i1 >= size1) {
buf.append("------\n");
}
for(int i2 = 0; i2 < size2 + 2; i2++) {
if(i2 >= size2) {
buf.append("| ");
}
buf.append(contingency[i1][i2]).append(" ");
}
buf.append("\n");
}
}
// if(pairconfuse != null) {
// buf.append(FormatUtil.format(pairconfuse));
// }
return buf.toString();
}
/**
* Get (compute) the pair counting measures.
*
* @return Pair counting measures
*/
public PairCounting getPaircount() {
if(paircount == null) {
paircount = new PairCounting();
}
return paircount;
}
/**
* Get (compute) the entropy based measures
*
* @return Entropy based measures
*/
public Entropy getEntropy() {
if(entropy == null) {
entropy = new Entropy();
}
return entropy;
}
/**
* Get (compute) the edit-distance based measures
*
* @return Edit-distance based measures
*/
public EditDistance getEdit() {
if(edit == null) {
edit = new EditDistance();
}
return edit;
}
/**
* The BCubed based measures
*
* @return BCubed measures
*/
public BCubed getBCubed() {
if(bcubed == null) {
bcubed = new BCubed();
}
return bcubed;
}
/**
* The set-matching measures
*
* @return Set-Matching measures
*/
public SetMatchingPurity getSetMatching() {
if(smp == null) {
smp = new SetMatchingPurity();
}
return smp;
}
/**
* Pair-counting measures.
*
* @author Erich Schubert
*/
public class PairCounting {
/**
* Pair counting confusion matrix (flat: inBoth, inFirst, inSecond, inNone)
*/
protected long[] pairconfuse = null;
/**
* Compute the pair sizes
*/
protected void computePairSizes() {
assert (contingency != null) : "No clustering loaded.";
// Aggregations
long inBoth = 0, in1 = 0, in2 = 0, total = 0;
// Process first clustering:
{
for(int i1 = 0; i1 < size1; i1++) {
final int size = contingency[i1][size2 + 1];
if(breakNoiseClusters && noise1.get(i1)) {
if(selfPairing) {
in1 += size;
} // else: 0
}
else {
if(selfPairing) {
in1 += size * size;
}
else {
in1 += size * (size - 1);
}
}
}
}
// Process second clustering:
{
for(int i2 = 0; i2 < size2; i2++) {
final int size = contingency[size1 + 1][i2];
if(breakNoiseClusters && noise2.get(i2)) {
if(selfPairing) {
in2 += size;
} // else: 0
}
else {
if(selfPairing) {
in2 += size * size;
}
else {
in2 += size * (size - 1);
}
}
}
}
// Process combinations
for(int i1 = 0; i1 < size1; i1++) {
for(int i2 = 0; i2 < size2; i2++) {
final int size = contingency[i1][i2];
if(breakNoiseClusters && (noise1.get(i1) || noise2.get(i2))) {
if(selfPairing) {
inBoth += size;
} // else: 0
}
else {
if(selfPairing) {
inBoth += size * size;
}
else {
inBoth += size * (size - 1);
}
}
}
}
// The official sum
int tsize = contingency[size1][size2];
if(contingency[size1][size2 + 1] != tsize || contingency[size1 + 1][size2] != tsize) {
LoggingUtil.warning("PairCounting F-Measure is not well defined for overlapping and incomplete clusterings.");
}
if(tsize >= Math.sqrt(Long.MAX_VALUE)) {
LoggingUtil.warning("Your data set size probably is too big for this implementation, which uses only long precision.");
}
if(selfPairing) {
total = tsize * tsize;
}
else {
total = tsize * (tsize - 1);
}
long inFirst = in1 - inBoth, inSecond = in2 - inBoth;
long inNone = total - (inBoth + inFirst + inSecond);
pairconfuse = new long[] { inBoth, inFirst, inSecond, inNone };
}
/**
* Get the pair-counting confusion matrix.
*
* @return Confusion matrix
*/
public long[] getPairConfusionMatrix() {
if(pairconfuse == null) {
computePairSizes();
}
return pairconfuse;
}
/**
* Get the pair-counting F-Measure
*
* @param beta Beta value.
* @return F-Measure
*/
public double fMeasure(double beta) {
final double beta2 = beta * beta;
getPairConfusionMatrix();
double fmeasure = ((1 + beta2) * pairconfuse[0]) / ((1 + beta2) * pairconfuse[0] + beta2 * pairconfuse[1] + pairconfuse[2]);
return fmeasure;
}
/**
* Get the pair-counting F1-Measure.
*
* @return F1-Measure
*/
public double f1Measure() {
return fMeasure(1.0);
}
/**
* Computes the pair-counting precision.
*
* @return pair-counting precision
*/
public double precision() {
getPairConfusionMatrix();
return ((double) pairconfuse[0]) / (pairconfuse[0] + pairconfuse[2]);
}
/**
* Computes the pair-counting recall.
*
* @return pair-counting recall
*/
public double recall() {
getPairConfusionMatrix();
return ((double) pairconfuse[0]) / (pairconfuse[0] + pairconfuse[1]);
}
/**
* Computes the pair-counting Fowlkes-mallows.
*
* @return pair-counting Fowlkes-mallows
*/
public double fowlkesMallows() {
return Math.sqrt(precision() * recall());
}
/**
* Computes the Rand index (RI).
*
* @return The Rand index (RI).
*/
public double randIndex() {
getPairConfusionMatrix();
final double sum = pairconfuse[0] + pairconfuse[1] + pairconfuse[2] + pairconfuse[3];
return (pairconfuse[0] + pairconfuse[3]) / sum;
}
/**
* Computes the adjusted Rand index (ARI).
*
* @return The adjusted Rand index (ARI).
*/
public double adjustedRandIndex() {
getPairConfusionMatrix();
final double nom = pairconfuse[0] * pairconfuse[3] - pairconfuse[1] * pairconfuse[2];
final long d1 = (pairconfuse[0] + pairconfuse[1]) * (pairconfuse[1] + pairconfuse[3]);
final long d2 = (pairconfuse[0] + pairconfuse[2]) * (pairconfuse[2] + pairconfuse[3]);
return 2 * nom / (d1 + d2);
}
/**
* Computes the Jaccard index
*
* @return The Jaccard index
*/
public double jaccard() {
getPairConfusionMatrix();
final double sum = pairconfuse[0] + pairconfuse[1] + pairconfuse[2];
return pairconfuse[0] / sum;
}
/**
* Computes the Mirkin index
*
* @return The Mirkin index
*/
public long mirkin() {
getPairConfusionMatrix();
return 2 * (pairconfuse[1] + pairconfuse[2]);
}
}
/**
* Entropy based measures
*
* References:
* <p>
* Meilă, M.<br />
* Comparing clusterings by the variation of information<br />
* Learning theory and kernel machines Volume 2777/2003
* </p>
*
* @author Sascha Goldhofer
*/
@Reference(authors = "Meilă, M.", title = "Comparing clusterings by the variation of information", booktitle = "Learning theory and kernel machines Volume 2777/2003", url = "http://dx.doi.org/10.1007/978-3-540-45167-9_14")
public class Entropy {
/**
* Entropy in first
*/
protected double entropyFirst = -1.0;
/**
* Entropy in second
*/
protected double entropySecond = -1.0;
/**
* Joint entropy
*/
protected double entropyJoint = -1.0;
/**
* Get the entropy of the first clustering using Log_2. (not normalized, 0 =
* unequal)
*
* @return Entropy of first clustering
*/
public double entropyFirst() {
if(entropyFirst < 0) {
entropyFirst = 0.0;
// iterate over first clustering
for(int i1 = 0; i1 < size1; i1++) {
if(contingency[i1][size2] > 0) {
double probability = 1.0 * contingency[i1][size2] / contingency[size1][size2];
entropyFirst += probability * Math.log(probability);
}
}
entropyFirst = -entropyFirst;
}
return entropyFirst;
}
/**
* Get the entropy of the second clustering using Log_2. (not normalized, 0
* = unequal)
*
* @return Entropy of second clustering
*/
public double entropySecond() {
if(entropySecond < 0) {
entropySecond = 0.0;
// iterate over first clustering
for(int i2 = 0; i2 < size2; i2++) {
if(contingency[size1][i2] > 0) {
double probability = 1.0 * contingency[size1][i2] / contingency[size1][size2];
entropySecond += probability * Math.log(probability);
}
}
entropySecond = -entropySecond;
}
return entropySecond;
}
/**
* Get the joint entropy of both clusterings (not normalized, 0 = unequal)
*
* @return Joint entropy of both clusterings
*/
public double entropyJoint() {
if(entropyJoint == -1.0) {
entropyJoint = 0.0;
for(int i1 = 0; i1 < size1; i1++) {
for(int i2 = 0; i2 < size2; i2++) {
if(contingency[i1][i2] > 0) {
double probability = 1.0 * contingency[i1][i2] / contingency[size1][size2];
entropyJoint += probability * Math.log(probability);
}
}
}
entropyJoint = -entropyJoint;
}
return entropyJoint;
}
/**
* Get the conditional entropy of the first clustering. (not normalized, 0 =
* equal)
*
* @return Conditional entropy of first clustering
*/
public double entropyConditionalFirst() {
return (entropyJoint() - entropySecond());
}
/**
* Get the conditional entropy of the first clustering. (not normalized, 0 =
* equal)
*
* @return Conditional entropy of second clustering
*/
public double entropyConditionalSecond() {
return (entropyJoint() - entropyFirst());
}
/**
* Get Powers entropy (not normalized, 0 = unequal)
*
* @return Powers
*/
public double entropyPowers() {
return (2 * entropyJoint() / (entropyFirst() + entropySecond()));
}
/**
* Get the mutual information (not normalized, 0 = unequal)
*
* @return Mutual information
*/
public double entropyMutualInformation() {
return (entropyFirst() + entropySecond() - entropyJoint());
}
/**
* Get the joint-normalized mutual information
*
* @return Joint Normalized Mutual information
*/
public double entropyNMIJoint() {
return (entropyMutualInformation() / entropyJoint());
}
/**
* Get the min-normalized mutual information
*
* @return Min Normalized Mutual information
*/
public double entropyNMIMin() {
return (entropyMutualInformation() / Math.min(entropyFirst(), entropySecond()));
}
/**
* Get the max-normalized mutual information
*
* @return Max Normalized Mutual information
*/
public double entropyNMIMax() {
return (entropyMutualInformation() / Math.max(entropyFirst(), entropySecond()));
}
/**
* Get the sum-normalized mutual information
*
* @return Sum Normalized Mutual information
*/
public double entropyNMISum() {
return (2 * entropyMutualInformation() / (entropyFirst() + entropySecond()));
}
/**
* Get the sqrt-normalized mutual information
*
* @return Sqrt Normalized Mutual information
*/
public double entropyNMISqrt() {
return (entropyMutualInformation() / Math.sqrt(entropyFirst() * entropySecond()));
}
/**
* Get the variation of information (not normalized, 0 = equal)
*
* @return Variation of information
*/
public double variationOfInformation() {
return (2 * entropyJoint() - (entropyFirst() + entropySecond()));
}
/**
* Get the normalized variation of information (normalized, 0 = equal)
*
* @return Normalized Variation of information
*/
public double normalizedVariationOfInformation() {
return (1.0 - (entropyMutualInformation() / entropyJoint()));
}
/**
* Get the entropy F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(entropyFirst, entropySecond);
}
}
/**
* Set matching purity measures
*
* References:
* <p>
* Zhao, Y. and Karypis, G.<br />
* Criterion functions for document clustering: Experiments and analysis<br />
* University of Minnesota, Department of Computer Science, Technical Report
* 01-40, 2001
* </p>
* <p>
* Meilă, M<br />
* Comparing clusterings<br />
* University of Washington, Seattle, Technical Report 418, 2002
* </p>
*
* @author Sascha Goldhofer
*/
@Reference(authors = "Zhao, Y. and Karypis, G.", title = "Criterion functions for document clustering: Experiments and analysis", booktitle = "University of Minnesota, Department of Computer Science, Technical Report 01-40, 2001", url = "http://www-users.cs.umn.edu/~karypis/publications/Papers/PDF/vscluster.pdf")
public class SetMatchingPurity {
/**
* Result cache
*/
protected double smPurity = -1.0, smInversePurity = -1.0;
/**
* Get the set matchings purity (first:second clustering) (normalized, 1 =
* equal)
*
* @return purity
*/
public double purity() {
if(smPurity < 0) {
smPurity = 0.0;
// iterate first clustering
for(int i1 = 0; i1 < size1; i1++) {
double precisionMax = 0.0;
for(int i2 = 0; i2 < size2; i2++) {
precisionMax = Math.max(precisionMax, (1.0 * contingency[i1][i2]));
// / contingency[i1][size2]));
}
smPurity += (precisionMax / contingency[size1][size2]);
// * contingency[i1][size2]/contingency[size1][size2];
}
}
return smPurity;
}
/**
* Get the set matchings inverse purity (second:first clustering)
* (normalized, 1 = equal)
*
* @return Inverse purity
*/
public double inversePurity() {
if(smInversePurity < 0) {
smInversePurity = 0.0;
// iterate second clustering
for(int i2 = 0; i2 < size2; i2++) {
double recallMax = 0.0;
for(int i1 = 0; i1 < size1; i1++) {
recallMax = Math.max(recallMax, (1.0 * contingency[i1][i2]));
// / contingency[i1][size2]));
}
smInversePurity += (recallMax / contingency[size1][size2]);
// * contingency[i1][size2]/contingency[size1][size2];
}
}
return smInversePurity;
}
/**
* Get the set matching F1-Measure
*
* @return Set Matching F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(purity(), inversePurity());
}
}
/**
* Edit distance measures
*
* @author Sascha Goldhofer
*/
public class EditDistance {
/**
* Edit operations for first clustering to second clustering.
*/
int editFirst = -1;
/**
* Edit operations for second clustering to first clustering.
*/
int editSecond = -1;
/**
* Get the baseline editing Operations ( = total Objects)
*
* @return worst case amount of operations
*/
public int editOperationsBaseline() {
// total objects merge operations...
return contingency[size1][size2];
}
/**
* Get the editing operations required to transform first clustering to
* second clustering
*
* @return Editing operations used to transform first into second clustering
*/
public int editOperationsFirst() {
if(editFirst == -1) {
editFirst = 0;
// iterate over first clustering
for(int i1 = 0; i1 < size1; i1++) {
// get largest cell
int largestLabelSet = 0;
for(int i2 = 0; i2 < size2; i2++) {
largestLabelSet = Math.max(largestLabelSet, contingency[i1][i2]);
}
// merge: found (largest) cluster to second clusterings cluster
editFirst++;
// move: wrong objects from this cluster to correct cluster (of second
// clustering)
editFirst += contingency[i1][size2] - largestLabelSet;
}
}
return editFirst;
}
/**
* Get the editing operations required to transform second clustering to
* first clustering
*
* @return Editing operations used to transform second into first clustering
*/
public int editOperationsSecond() {
if(editSecond == -1) {
editSecond = 0;
// iterate over second clustering
for(int i2 = 0; i2 < size2; i2++) {
// get largest cell
int largestLabelSet = 0;
for(int i1 = 0; i1 < size1; i1++) {
largestLabelSet = Math.max(largestLabelSet, contingency[i1][i2]);
}
// merge: found (largest) cluster to second clusterings cluster
editSecond++;
// move: wrong objects from this cluster to correct cluster (of second
// clustering)
editSecond += contingency[size1][i2] - largestLabelSet;
}
}
return editSecond;
}
/**
* Get the editing distance to transform second clustering to first
* clustering (normalized, 1=equal)
*
* @return Editing distance first into second clustering
*/
public double editDistanceFirst() {
return 1.0 * editOperationsFirst() / editOperationsBaseline();
}
/**
* Get the editing distance to transform second clustering to first
* clustering (normalized, 1=equal)
*
* @return Editing distance second into first clustering
*/
public double editDistanceSecond() {
return 1.0 * editOperationsSecond() / editOperationsBaseline();
}
/**
* Get the edit distance F1-Measure
*
* @return Edit Distance F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(editDistanceFirst(), editDistanceSecond());
}
}
/**
* BCubed measures
*
* @author Sascha Goldhofer
*/
public class BCubed {
/**
* Result cache
*/
protected double bCubedPrecision = -1.0, bCubedRecall = -1.0;
/**
* Get the BCubed Precision (first clustering) (normalized, 0 = unequal)
*
* @return BCubed Precision
*/
public double precision() {
if(bCubedPrecision < 0) {
bCubedPrecision = 0.0;
bCubedRecall = 0.0;
for(int i1 = 0; i1 < size1; i1++) {
for(int i2 = 0; i2 < size2; i2++) {
// precision of one item
double precision = 1.0 * contingency[i1][i2] / contingency[i1][size2];
// precision for all items in cluster
bCubedPrecision += (precision * contingency[i1][i2]);
// recall of one item
double recall = 1.0 * contingency[i1][i2] / contingency[size1][i2];
// recall for all items in cluster
bCubedRecall += (recall * contingency[i1][i2]);
}
}
bCubedPrecision = bCubedPrecision / contingency[size1][size2];
bCubedRecall = bCubedRecall / contingency[size1][size2];
}
return bCubedPrecision;
}
/**
* Get the BCubed Recall (first clustering) (normalized, 0 = unequal)
*
* @return BCubed Recall
*/
public double recall() {
if(bCubedRecall < 0) {
precision();
}
return bCubedRecall;
}
/**
* Get the BCubed F1-Measure
*
* @return BCubed F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(precision(), recall());
}
}
/**
* Compute the average Gini for each cluster (in both clusterings -
* symmetric).
*
* @return Mean and variance of Gini
*/
public MeanVariance averageSymmetricGini() {
MeanVariance mv = new MeanVariance();
for(int i1 = 0; i1 < size1; i1++) {
double purity = 0.0;
if(contingency[i1][size2] > 0) {
final double cs = contingency[i1][size2]; // sum, as double.
for(int i2 = 0; i2 < size2; i2++) {
double rel = contingency[i1][i2] / cs;
purity += rel * rel;
}
}
mv.put(purity);
}
for(int i2 = 0; i2 < size2; i2++) {
double purity = 0.0;
if(contingency[size1][i2] > 0) {
final double cs = contingency[size1][i2]; // sum, as double.
for(int i1 = 0; i1 < size1; i1++) {
double rel = contingency[i1][i2] / cs;
purity += rel * rel;
}
}
mv.put(purity);
}
return mv;
}
/**
* Utility class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static final class Util {
/**
* F-Measure
*
* @param precision Precision
* @param recall Recall
* @param beta Beta value
* @return F-Measure
*/
public static double fMeasure(double precision, double recall, double beta) {
final double beta2 = beta * beta;
return (1 + beta2) * precision * recall / (beta2 * precision + recall);
}
/**
* F1-Measure (F-Measure with beta = 1)
*
* @param precision Precision
* @param recall Recall
* @return F-Measure
*/
public static double f1Measure(double precision, double recall) {
return 2 * precision * recall / (precision + recall);
}
}
} | src/de/lmu/ifi/dbs/elki/evaluation/clustering/ClusterContingencyTable.java | package de.lmu.ifi.dbs.elki.evaluation.clustering;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures
Copyright (C) 2011
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team
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/>.
*/
import java.util.BitSet;
import java.util.Iterator;
import java.util.List;
import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.logging.LoggingUtil;
import de.lmu.ifi.dbs.elki.math.MeanVariance;
/**
* Class storing the contingency table and related data on two clusterings.
*
* @author Erich Schubert
*/
public class ClusterContingencyTable {
/**
* Noise cluster handling
*/
protected boolean breakNoiseClusters = false;
/**
* Self pairing
*/
protected boolean selfPairing = true;
/**
* Number of clusters in first
*/
protected int size1 = -1;
/**
* Number of clusters in second
*/
protected int size2 = -1;
/**
* Contingency matrix
*/
protected int[][] contingency = null;
/**
* Noise flags
*/
protected BitSet noise1 = null;
/**
* Noise flags
*/
protected BitSet noise2 = null;
/**
* Pair counting measures
*/
protected PairCounting paircount = null;
/**
* Entropy-based measures
*/
protected Entropy entropy = null;
/**
* Set matching purity measures
*/
protected SetMatchingPurity smp = null;
/**
* Edit-Distance measures
*/
protected EditDistance edit = null;
/**
* BCubed measures
*/
protected BCubed bcubed = null;
/**
* Constructor.
*
* @param selfPairing Build self-pairs
* @param breakNoiseClusters Break noise clusters into individual objects
*/
public ClusterContingencyTable(boolean selfPairing, boolean breakNoiseClusters) {
super();
this.selfPairing = selfPairing;
this.breakNoiseClusters = breakNoiseClusters;
}
/**
* Process two clustering results.
*
* @param result1 First clustering
* @param result2 Second clustering
*/
public void process(Clustering<?> result1, Clustering<?> result2) {
// Get the clusters
final List<? extends Cluster<?>> cs1 = result1.getAllClusters();
final List<? extends Cluster<?>> cs2 = result2.getAllClusters();
// Initialize
size1 = cs1.size();
size2 = cs2.size();
contingency = new int[size1 + 2][size2 + 2];
noise1 = new BitSet(size1);
noise2 = new BitSet(size2);
// Fill main part of matrix
{
{
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
if(c2.isNoise()) {
noise2.set(i2);
}
contingency[size1 + 1][i2] = c2.size();
contingency[size1 + 1][size2] += c2.size();
}
}
final Iterator<? extends Cluster<?>> it1 = cs1.iterator();
for(int i1 = 0; it1.hasNext(); i1++) {
final Cluster<?> c1 = it1.next();
if(c1.isNoise()) {
noise1.set(i1);
}
final DBIDs ids = DBIDUtil.ensureSet(c1.getIDs());
contingency[i1][size2 + 1] = c1.size();
contingency[size1][size2 + 1] += c1.size();
final Iterator<? extends Cluster<?>> it2 = cs2.iterator();
for(int i2 = 0; it2.hasNext(); i2++) {
final Cluster<?> c2 = it2.next();
int count = 0;
for(DBID id : c2.getIDs()) {
if(ids.contains(id)) {
count++;
}
}
contingency[i1][i2] = count;
contingency[i1][size2] += count;
contingency[size1][i2] += count;
contingency[size1][size2] += count;
}
}
}
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
if(contingency != null) {
for(int i1 = 0; i1 < size1 + 2; i1++) {
if(i1 >= size1) {
buf.append("------\n");
}
for(int i2 = 0; i2 < size2 + 2; i2++) {
if(i2 >= size2) {
buf.append("| ");
}
buf.append(contingency[i1][i2]).append(" ");
}
buf.append("\n");
}
}
// if(pairconfuse != null) {
// buf.append(FormatUtil.format(pairconfuse));
// }
return buf.toString();
}
/**
* Get (compute) the pair counting measures.
*
* @return Pair counting measures
*/
public PairCounting getPaircount() {
if(paircount == null) {
paircount = new PairCounting();
}
return paircount;
}
/**
* Get (compute) the entropy based measures
*
* @return Entropy based measures
*/
public Entropy getEntropy() {
if(entropy == null) {
entropy = new Entropy();
}
return entropy;
}
/**
* Get (compute) the edit-distance based measures
*
* @return Edit-distance based measures
*/
public EditDistance getEdit() {
if(edit == null) {
edit = new EditDistance();
}
return edit;
}
/**
* The BCubed based measures
*
* @return BCubed measures
*/
public BCubed getBCubed() {
if(bcubed == null) {
bcubed = new BCubed();
}
return bcubed;
}
/**
* The set-matching measures
*
* @return Set-Matching measures
*/
public SetMatchingPurity getSetMatching() {
if(smp == null) {
smp = new SetMatchingPurity();
}
return smp;
}
/**
* Pair-counting measures.
*
* @author Erich Schubert
*/
public class PairCounting {
/**
* Pair counting confusion matrix (flat: inBoth, inFirst, inSecond, inNone)
*/
protected long[] pairconfuse = null;
/**
* Compute the pair sizes
*/
protected void computePairSizes() {
assert (contingency != null) : "No clustering loaded.";
// Aggregations
long inBoth = 0, in1 = 0, in2 = 0, total = 0;
// Process first clustering:
{
for(int i1 = 0; i1 < size1; i1++) {
final int size = contingency[i1][size2 + 1];
if(breakNoiseClusters && noise1.get(i1)) {
if(selfPairing) {
in1 += size;
} // else: 0
}
else {
if(selfPairing) {
in1 += size * size;
}
else {
in1 += size * (size - 1);
}
}
}
}
// Process second clustering:
{
for(int i2 = 0; i2 < size2; i2++) {
final int size = contingency[size1 + 1][i2];
if(breakNoiseClusters && noise2.get(i2)) {
if(selfPairing) {
in2 += size;
} // else: 0
}
else {
if(selfPairing) {
in2 += size * size;
}
else {
in2 += size * (size - 1);
}
}
}
}
// Process combinations
for(int i1 = 0; i1 < size1; i1++) {
for(int i2 = 0; i2 < size2; i2++) {
final int size = contingency[i1][i2];
if(breakNoiseClusters && (noise1.get(i1) || noise2.get(i2))) {
if(selfPairing) {
inBoth += size;
} // else: 0
}
else {
if(selfPairing) {
inBoth += size * size;
}
else {
inBoth += size * (size - 1);
}
}
}
}
// The official sum
int tsize = contingency[size1][size2];
if(contingency[size1][size2 + 1] != tsize || contingency[size1 + 1][size2] != tsize) {
LoggingUtil.warning("PairCounting F-Measure is not well defined for overlapping and incomplete clusterings.");
}
if(tsize >= Math.sqrt(Long.MAX_VALUE)) {
LoggingUtil.warning("Your data set size probably is too big for this implementation, which uses only long precision.");
}
if(selfPairing) {
total = tsize * tsize;
}
else {
total = tsize * (tsize - 1);
}
long inFirst = in1 - inBoth, inSecond = in2 - inBoth;
long inNone = total - (inBoth + inFirst + inSecond);
pairconfuse = new long[] { inBoth, inFirst, inSecond, inNone };
}
/**
* Get the pair-counting confusion matrix.
*
* @return Confusion matrix
*/
public long[] getPairConfusionMatrix() {
if(pairconfuse == null) {
computePairSizes();
}
return pairconfuse;
}
/**
* Get the pair-counting F-Measure
*
* @param beta Beta value.
* @return F-Measure
*/
public double fMeasure(double beta) {
final double beta2 = beta * beta;
getPairConfusionMatrix();
double fmeasure = ((1 + beta2) * pairconfuse[0]) / ((1 + beta2) * pairconfuse[0] + beta2 * pairconfuse[1] + pairconfuse[2]);
return fmeasure;
}
/**
* Get the pair-counting F1-Measure.
*
* @return F1-Measure
*/
public double f1Measure() {
return fMeasure(1.0);
}
/**
* Computes the pair-counting precision.
*
* @return pair-counting precision
*/
public double precision() {
getPairConfusionMatrix();
return ((double) pairconfuse[0]) / (pairconfuse[0] + pairconfuse[2]);
}
/**
* Computes the pair-counting recall.
*
* @return pair-counting recall
*/
public double recall() {
getPairConfusionMatrix();
return ((double) pairconfuse[0]) / (pairconfuse[0] + pairconfuse[1]);
}
/**
* Computes the pair-counting Fowlkes-mallows.
*
* @return pair-counting Fowlkes-mallows
*/
public double fowlkesMallows() {
return Math.sqrt(precision() * recall());
}
/**
* Computes the Rand index (RI).
*
* @return The Rand index (RI).
*/
public double randIndex() {
getPairConfusionMatrix();
final double sum = pairconfuse[0] + pairconfuse[1] + pairconfuse[2] + pairconfuse[3];
return (pairconfuse[0] + pairconfuse[3]) / sum;
}
/**
* Computes the adjusted Rand index (ARI).
*
* @return The adjusted Rand index (ARI).
*/
public double adjustedRandIndex() {
getPairConfusionMatrix();
final double nom = pairconfuse[0] * pairconfuse[3] - pairconfuse[1] * pairconfuse[2];
final long d1 = (pairconfuse[0] + pairconfuse[1]) * (pairconfuse[1] + pairconfuse[3]);
final long d2 = (pairconfuse[0] + pairconfuse[2]) * (pairconfuse[2] + pairconfuse[3]);
return 2 * nom / (d1 + d2);
}
/**
* Computes the Jaccard index
*
* @return The Jaccard index
*/
public double jaccard() {
getPairConfusionMatrix();
final double sum = pairconfuse[0] + pairconfuse[1] + pairconfuse[2];
return pairconfuse[0] / sum;
}
/**
* Computes the Mirkin index
*
* @return The Mirkin index
*/
public long mirkin() {
getPairConfusionMatrix();
return 2 * (pairconfuse[1] + pairconfuse[2]);
}
}
/**
* Entropy based measures
*
* @author Sascha Goldhofer
*/
public class Entropy {
/**
* Entropy in first
*/
protected double entropyFirst = -1.0;
/**
* Entropy in second
*/
protected double entropySecond = -1.0;
/**
* Joint entropy
*/
protected double entropyJoint = -1.0;
/**
* Get the entropy of the first clustering using Log_2. (not normalized, 0 =
* unequal)
*
* @return Entropy of first clustering
*/
public double entropyFirst() {
if(entropyFirst < 0) {
entropyFirst = 0.0;
// iterate over first clustering
for(int i1 = 0; i1 < size1; i1++) {
if(contingency[i1][size2] > 0) {
double probability = 1.0 * contingency[i1][size2] / contingency[size1][size2];
entropyFirst += probability * Math.log(probability);
}
}
entropyFirst = -entropyFirst;
}
return entropyFirst;
}
/**
* Get the entropy of the second clustering using Log_2. (not normalized, 0
* = unequal)
*
* @return Entropy of second clustering
*/
public double entropySecond() {
if(entropySecond < 0) {
entropySecond = 0.0;
// iterate over first clustering
for(int i2 = 0; i2 < size2; i2++) {
if(contingency[size1][i2] > 0) {
double probability = 1.0 * contingency[size1][i2] / contingency[size1][size2];
entropySecond += probability * Math.log(probability);
}
}
entropySecond = -entropySecond;
}
return entropySecond;
}
/**
* Get the joint entropy of both clusterings (not normalized, 0 = unequal)
*
* @return Joint entropy of both clusterings
*/
public double entropyJoint() {
if(entropyJoint == -1.0) {
entropyJoint = 0.0;
for(int i1 = 0; i1 < size1; i1++) {
for(int i2 = 0; i2 < size2; i2++) {
if(contingency[i1][i2] > 0) {
double probability = 1.0 * contingency[i1][i2] / contingency[size1][size2];
entropyJoint += probability * Math.log(probability);
}
}
}
entropyJoint = -entropyJoint;
}
return entropyJoint;
}
/**
* Get the conditional entropy of the first clustering. (not normalized, 0 =
* equal)
*
* @return Conditional entropy of first clustering
*/
public double entropyConditionalFirst() {
return (entropyJoint() - entropySecond());
}
/**
* Get the conditional entropy of the first clustering. (not normalized, 0 =
* equal)
*
* @return Conditional entropy of second clustering
*/
public double entropyConditionalSecond() {
return (entropyJoint() - entropyFirst());
}
/**
* Get Powers entropy (not normalized, 0 = unequal)
*
* @return Powers
*/
public double entropyPowers() {
return (2 * entropyJoint() / (entropyFirst() + entropySecond()));
}
/**
* Get the mutual information (not normalized, 0 = unequal)
*
* @return Mutual information
*/
public double entropyMutualInformation() {
return (entropyFirst() + entropySecond() - entropyJoint());
}
/**
* Get the joint-normalized mutual information
*
* @return Joint Normalized Mutual information
*/
public double entropyNMIJoint() {
return (entropyMutualInformation() / entropyJoint());
}
/**
* Get the min-normalized mutual information
*
* @return Min Normalized Mutual information
*/
public double entropyNMIMin() {
return (entropyMutualInformation() / Math.min(entropyFirst(), entropySecond()));
}
/**
* Get the max-normalized mutual information
*
* @return Max Normalized Mutual information
*/
public double entropyNMIMax() {
return (entropyMutualInformation() / Math.max(entropyFirst(), entropySecond()));
}
/**
* Get the sum-normalized mutual information
*
* @return Sum Normalized Mutual information
*/
public double entropyNMISum() {
return (2 * entropyMutualInformation() / (entropyFirst() + entropySecond()));
}
/**
* Get the sqrt-normalized mutual information
*
* @return Sqrt Normalized Mutual information
*/
public double entropyNMISqrt() {
return (entropyMutualInformation() / Math.sqrt(entropyFirst() * entropySecond()));
}
/**
* Get the variation of information (not normalized, 0 = equal)
*
* @return Variation of information
*/
public double variationOfInformation() {
return (2 * entropyJoint() - (entropyFirst() + entropySecond()));
}
/**
* Get the normalized variation of information (normalized, 0 = equal)
*
* @return Normalized Variation of information
*/
public double normalizedVariationOfInformation() {
return (1.0 - (entropyMutualInformation() / entropyJoint()));
}
/**
* Get the entropy F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(entropyFirst, entropySecond);
}
}
/**
* Set matching purity measures
*
* @author Sascha Goldhofer
*/
public class SetMatchingPurity {
/**
* Result cache
*/
protected double smPurity = -1.0, smInversePurity = -1.0;
/**
* Get the set matchings purity (first:second clustering) (normalized, 1 =
* equal)
*
* @return purity
*/
public double purity() {
if(smPurity < 0) {
smPurity = 0.0;
// iterate first clustering
for(int i1 = 0; i1 < size1; i1++) {
double precisionMax = 0.0;
for(int i2 = 0; i2 < size2; i2++) {
precisionMax = Math.max(precisionMax, (1.0 * contingency[i1][i2]));
// / contingency[i1][size2]));
}
smPurity += (precisionMax / contingency[size1][size2]);
// * contingency[i1][size2]/contingency[size1][size2];
}
}
return smPurity;
}
/**
* Get the set matchings inverse purity (second:first clustering)
* (normalized, 1 = equal)
*
* @return Inverse purity
*/
public double inversePurity() {
if(smInversePurity < 0) {
smInversePurity = 0.0;
// iterate second clustering
for(int i2 = 0; i2 < size2; i2++) {
double recallMax = 0.0;
for(int i1 = 0; i1 < size1; i1++) {
recallMax = Math.max(recallMax, (1.0 * contingency[i1][i2]));
// / contingency[i1][size2]));
}
smInversePurity += (recallMax / contingency[size1][size2]);
// * contingency[i1][size2]/contingency[size1][size2];
}
}
return smInversePurity;
}
/**
* Get the set matching F1-Measure
*
* @return Set Matching F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(purity(), inversePurity());
}
}
/**
* Edit distance measures
*
* @author Sascha Goldhofer
*/
public class EditDistance {
/**
* Edit operations for first clustering to second clustering.
*/
int editFirst = -1;
/**
* Edit operations for second clustering to first clustering.
*/
int editSecond = -1;
/**
* Get the baseline editing Operations ( = total Objects)
*
* @return worst case amount of operations
*/
public int editOperationsBaseline() {
// total objects merge operations...
return contingency[size1][size2];
}
/**
* Get the editing operations required to transform first clustering to
* second clustering
*
* @return Editing operations used to transform first into second clustering
*/
public int editOperationsFirst() {
if(editFirst == -1) {
editFirst = 0;
// iterate over first clustering
for(int i1 = 0; i1 < size1; i1++) {
// get largest cell
int largestLabelSet = 0;
for(int i2 = 0; i2 < size2; i2++) {
largestLabelSet = Math.max(largestLabelSet, contingency[i1][i2]);
}
// merge: found (largest) cluster to second clusterings cluster
editFirst++;
// move: wrong objects from this cluster to correct cluster (of second
// clustering)
editFirst += contingency[i1][size2] - largestLabelSet;
}
}
return editFirst;
}
/**
* Get the editing operations required to transform second clustering to
* first clustering
*
* @return Editing operations used to transform second into first clustering
*/
public int editOperationsSecond() {
if(editSecond == -1) {
editSecond = 0;
// iterate over second clustering
for(int i2 = 0; i2 < size2; i2++) {
// get largest cell
int largestLabelSet = 0;
for(int i1 = 0; i1 < size1; i1++) {
largestLabelSet = Math.max(largestLabelSet, contingency[i1][i2]);
}
// merge: found (largest) cluster to second clusterings cluster
editSecond++;
// move: wrong objects from this cluster to correct cluster (of second
// clustering)
editSecond += contingency[size1][i2] - largestLabelSet;
}
}
return editSecond;
}
/**
* Get the editing distance to transform second clustering to first
* clustering (normalized, 1=equal)
*
* @return Editing distance first into second clustering
*/
public double editDistanceFirst() {
return 1.0 * editOperationsFirst() / editOperationsBaseline();
}
/**
* Get the editing distance to transform second clustering to first
* clustering (normalized, 1=equal)
*
* @return Editing distance second into first clustering
*/
public double editDistanceSecond() {
return 1.0 * editOperationsSecond() / editOperationsBaseline();
}
/**
* Get the edit distance F1-Measure
*
* @return Edit Distance F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(editDistanceFirst(), editDistanceSecond());
}
}
/**
* BCubed measures
*
* @author Sascha Goldhofer
*/
public class BCubed {
/**
* Result cache
*/
protected double bCubedPrecision = -1.0, bCubedRecall = -1.0;
/**
* Get the BCubed Precision (first clustering) (normalized, 0 = unequal)
*
* @return BCubed Precision
*/
public double precision() {
if(bCubedPrecision < 0) {
bCubedPrecision = 0.0;
bCubedRecall = 0.0;
for(int i1 = 0; i1 < size1; i1++) {
for(int i2 = 0; i2 < size2; i2++) {
// precision of one item
double precision = 1.0 * contingency[i1][i2] / contingency[i1][size2];
// precision for all items in cluster
bCubedPrecision += (precision * contingency[i1][i2]);
// recall of one item
double recall = 1.0 * contingency[i1][i2] / contingency[size1][i2];
// recall for all items in cluster
bCubedRecall += (recall * contingency[i1][i2]);
}
}
bCubedPrecision = bCubedPrecision / contingency[size1][size2];
bCubedRecall = bCubedRecall / contingency[size1][size2];
}
return bCubedPrecision;
}
/**
* Get the BCubed Recall (first clustering) (normalized, 0 = unequal)
*
* @return BCubed Recall
*/
public double recall() {
if(bCubedRecall < 0) {
precision();
}
return bCubedRecall;
}
/**
* Get the BCubed F1-Measure
*
* @return BCubed F1-Measure
*/
public double f1Measure() {
return Util.f1Measure(precision(), recall());
}
}
/**
* Compute the average Gini for each cluster (in both clusterings -
* symmetric).
*
* @return Mean and variance of Gini
*/
public MeanVariance averageSymmetricGini() {
MeanVariance mv = new MeanVariance();
for(int i1 = 0; i1 < size1; i1++) {
double purity = 0.0;
if(contingency[i1][size2] > 0) {
final double cs = contingency[i1][size2]; // sum, as double.
for(int i2 = 0; i2 < size2; i2++) {
double rel = contingency[i1][i2] / cs;
purity += rel * rel;
}
}
mv.put(purity);
}
for(int i2 = 0; i2 < size2; i2++) {
double purity = 0.0;
if(contingency[size1][i2] > 0) {
final double cs = contingency[size1][i2]; // sum, as double.
for(int i1 = 0; i1 < size1; i1++) {
double rel = contingency[i1][i2] / cs;
purity += rel * rel;
}
}
mv.put(purity);
}
return mv;
}
/**
* Utility class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static final class Util {
/**
* F-Measure
*
* @param precision Precision
* @param recall Recall
* @param beta Beta value
* @return F-Measure
*/
public static double fMeasure(double precision, double recall, double beta) {
final double beta2 = beta * beta;
return (1 + beta2) * precision * recall / (beta2 * precision + recall);
}
/**
* F1-Measure (F-Measure with beta = 1)
*
* @param precision Precision
* @param recall Recall
* @return F-Measure
*/
public static double f1Measure(double precision, double recall) {
return 2 * precision * recall / (precision + recall);
}
}
} | Start adding references.
| src/de/lmu/ifi/dbs/elki/evaluation/clustering/ClusterContingencyTable.java | Start adding references. |
|
Java | agpl-3.0 | ba2b329337d225537698ca6f18808c34398502bf | 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 | ebbd79d6-2e5f-11e5-9284-b827eb9e62be | hello.java | ebb5d942-2e5f-11e5-9284-b827eb9e62be | ebbd79d6-2e5f-11e5-9284-b827eb9e62be | hello.java | ebbd79d6-2e5f-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 799c52ac77b6074d6e1345940705e2f168256951 | 0 | datacite/mds,ulbricht/mds,datacite/mds,ulbricht/mds,datacite/mds,ulbricht/mds,datacite/mds,datacite/mds,ulbricht/mds | package org.datacite.mds.validation.util;
import java.lang.annotation.Annotation;
import java.net.IDN;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.commons.validator.UrlValidator;
public class ValidationUtils {
private static Validator getValidator() {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
/**
* Wrapper to simply validate a property of an object.
*
* @param object
* object to validate
* @param propertyName
* property to validate (e.g. field)
* @return true if property validates
* @see javax.validation.Validator.validateProperty
*/
public static <T> boolean isValid(T object, String propertyName) {
Set<?> violations = getValidator().validateProperty(object, propertyName);
return violations.isEmpty();
}
/**
* Wrapper to validate a an object.
*
* @param object
* object to validate
* @return true if object validates
* @see javax.validation.Validator.validateProperty
*/
public static <T> boolean isValid(T object) {
Set<?> violations = getValidator().validate(object);
return violations.isEmpty();
}
/**
* Check if a specific constraint annotation is violated
*
* @param object
* object to validate
* @param constraint
* constraint annotation to be checked
* @return true if the given constraint is not violated
*/
public static <T> boolean isValid(T object, Class<? extends Annotation> constraint) {
Set<ConstraintViolation<T>> violations = getValidator().validate(object);
for (ConstraintViolation<T> violation : violations) {
if (violation.getConstraintDescriptor().getAnnotation().annotationType().equals(constraint)) {
return false;
}
}
return true;
}
public static <T> String getFirstViolationMessage(T object) {
for (ConstraintViolation<T> violation : getValidator().validate(object)) {
return violation.getMessage();
}
return null;
}
public static void addConstraintViolation(ConstraintValidatorContext context, String message, String node) {
context.buildConstraintViolationWithTemplate(message).addNode(node).addConstraintViolation();
}
public static void addConstraintViolation(ConstraintValidatorContext context, String message) {
context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
}
public static boolean isHostname(String str) {
try {
URL url = new URL("http://" + str);
if (!url.getHost().equals(str)) {
// domain should only consists of the pure host name
return false;
}
str = IDN.toASCII(str); // convert international domain names (IDN)
if (str.matches(".*\\.xn--[^.]*$")) {
// UrlValidator doesn't handle top level IDNs
// so we add .org if necessary
str += ".org";
}
UrlValidator urlValidator = new UrlValidator();
if (!urlValidator.isValid("http://" + str)) {
// url should be valid, e.g. "test.t" or "com" should be fail
return false;
}
} catch (Exception ex) {
// url should be well formed
return false;
}
return true;
}
}
| src/main/java/org/datacite/mds/validation/util/ValidationUtils.java | package org.datacite.mds.validation.util;
import java.lang.annotation.Annotation;
import java.net.IDN;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.commons.validator.UrlValidator;
public class ValidationUtils {
private static Validator getValidator() {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
/**
* Wrapper to simply validate a property of an object.
*
* @param object
* object to validate
* @param propertyName
* property to validate (e.g. field)
* @return true if property validates
* @see javax.validation.Validator.validateProperty
*/
public static <T> boolean isValid(T object, String propertyName) {
Set<?> violations = getValidator().validateProperty(object, propertyName);
return violations.isEmpty();
}
/**
* Wrapper to validate a an object.
*
* @param object
* object to validate
* @return true if object validates
* @see javax.validation.Validator.validateProperty
*/
public static <T> boolean isValid(T object) {
Set<?> violations = getValidator().validate(object);
return violations.isEmpty();
}
/**
* Check if a specific constraint annotation is violated
*
* @param object
* object to validate
* @param constraint
* constraint annotation to be checked
* @return true if the given constraint is not violated
*/
public static <T> boolean isValid(T object, Class<? extends Annotation> constraint) {
Set<ConstraintViolation<T>> violations = getValidator().validate(object);
for (ConstraintViolation<T> violation : violations) {
if (violation.getConstraintDescriptor().getAnnotation().annotationType().equals(constraint)) {
return false;
}
}
return true;
}
public static void addConstraintViolation(ConstraintValidatorContext context, String message, String node) {
context.buildConstraintViolationWithTemplate(message).addNode(node).addConstraintViolation();
}
public static void addConstraintViolation(ConstraintValidatorContext context, String message) {
context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
}
public static boolean isHostname(String str) {
try {
URL url = new URL("http://" + str);
if (!url.getHost().equals(str)) {
// domain should only consists of the pure host name
return false;
}
str = IDN.toASCII(str); // convert international domain names (IDN)
if (str.matches(".*\\.xn--[^.]*$")) {
// UrlValidator doesn't handle top level IDNs
// so we add .org if necessary
str += ".org";
}
UrlValidator urlValidator = new UrlValidator();
if (!urlValidator.isValid("http://" + str)) {
// url should be valid, e.g. "test.t" or "com" should be fail
return false;
}
} catch (Exception ex) {
// url should be well formed
return false;
}
return true;
}
}
| add getViolationMessage method
| src/main/java/org/datacite/mds/validation/util/ValidationUtils.java | add getViolationMessage method |
|
Java | apache-2.0 | edb719f49f36e789ee673a1ba72cca0d5fc11160 | 0 | LonoCloud/transit-java,freakynit/transit-java,freakynit/transit-java,alexanderkiel/transit-java,cognitect/transit-java,alexanderkiel/transit-java,cognitect/transit-java,LonoCloud/transit-java | // Copyright (c) Cognitect, Inc.
// All rights reserved.
package com.cognitect.transit;
import com.cognitect.transit.impl.AbstractParser;
import com.cognitect.transit.impl.JsonParser;
import com.cognitect.transit.impl.ReadCache;
import com.cognitect.transit.impl.WriteCache;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TransitJSONMachineModeTest extends TestCase {
public TransitJSONMachineModeTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TransitJSONMachineModeTest.class);
}
// Reading
public Reader reader(String s) throws IOException {
InputStream in = new ByteArrayInputStream(s.getBytes());
return TransitFactory.reader(TransitFactory.Format.JSON, in, null);
}
public void testReadTime() throws Exception {
Date d = new Date();
long t = d.getTime();
Date dt = ((Date)reader("\"~t" + t + "\"").read());
assertEquals(t, dt.getTime());
List l = ((List)reader("[\"~t" + t + "\"]").read());
dt = (Date) l.get(0);
assertEquals(t, dt.getTime());
}
public void testReadMap() throws IOException {
Map m = (Map)reader("[\"~^\",\"foo\",1,\"bar\",2]").read();
assertTrue(m instanceof HashMap);
assertTrue(m.containsKey("foo"));
assertTrue(m.containsKey("bar"));
assertEquals(1L, m.get("foo"));
assertEquals(2L, m.get("bar"));
}
public void testReadMapWithNested() throws IOException {
Map m = (Map)reader("[\"~^\",\"foo\",1,\"bar\",[\"~^\",\"baz\",3]]").read();
assertTrue(m instanceof HashMap);
assertTrue(m.get("bar") instanceof HashMap);
assertTrue(((Map)m.get("bar")).containsKey("baz"));
assertEquals(3L, ((Map)m.get("bar")).get("baz"));
}
// Writing
public String write(Object o) throws Exception {
OutputStream out = new ByteArrayOutputStream();
Writer w = TransitFactory.writer(TransitFactory.Format.JSON_MACHINE, out, null);
w.write(o);
return out.toString();
}
public boolean isEqual(Object o1, Object o2) {
if(o1 instanceof Boolean)
return o1 == o2;
else
return false;
}
public void testRoundTrip() throws Exception {
Object inObject = true;
OutputStream out = new ByteArrayOutputStream();
Writer w = TransitFactory.writer(TransitFactory.Format.JSON_MACHINE, out, null);
w.write(inObject);
String s = out.toString();
InputStream in = new ByteArrayInputStream(s.getBytes());
Reader reader = TransitFactory.reader(TransitFactory.Format.JSON, in, null);
Object outObject = reader.read();
assertTrue(isEqual(inObject, outObject));
}
public void testWriteMap() throws Exception {
Map m = new HashMap();
m.put("foo", 1);
m.put("bar", 2);
assertEquals("[\"~^\",\"foo\",1,\"bar\",2]", write(m));
}
public void testWriteEmptyMap() throws Exception {
Map m = new HashMap();
assertEquals("[\"~^\"]", write(m));
}
public String scalar(String value) {
return "{\"~#'\":"+value+"}";
}
public void testWriteTime() throws Exception {
final Date d = new Date();
long tm = d.getTime();
String t = write(d);
List l = new ArrayList() {{ add(d); }};
assertEquals(scalar("\"~t" + tm + "\""), t);
t = write(l);
assertEquals("[\"~t" + tm + "\"]", t);
}
}
| src/test/java/com/cognitect/transit/TransitJSONMachineModeTest.java | // Copyright (c) Cognitect, Inc.
// All rights reserved.
package com.cognitect.transit;
import com.cognitect.transit.impl.AbstractParser;
import com.cognitect.transit.impl.JsonParser;
import com.cognitect.transit.impl.ReadCache;
import com.cognitect.transit.impl.WriteCache;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TransitJSONMachineModeTest extends TestCase {
public TransitJSONMachineModeTest(String testName) {
super(testName);
}
public static Test suite() {
return new TestSuite(TransitJSONMachineModeTest.class);
}
// Reading
public Reader reader(String s) throws IOException {
InputStream in = new ByteArrayInputStream(s.getBytes());
return TransitFactory.reader(TransitFactory.Format.JSON, in, null);
}
private long readTimeString(String timeString) throws IOException {
// TODO: Impl date format
return 0;
}
private SimpleDateFormat formatter(String formatString) {
SimpleDateFormat df = new SimpleDateFormat(formatString);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
return df;
}
public void testReadTime() throws Exception {
Date d = new Date();
long t = d.getTime();
Date dt = ((Date)reader("\"~t" + t + "\"").read());
assertEquals(t, dt.getTime());
}
public void testReadMap() throws IOException {
Map m = (Map)reader("[\"~^\",\"foo\",1,\"bar\",2]").read();
assertTrue(m instanceof HashMap);
assertTrue(m.containsKey("foo"));
assertTrue(m.containsKey("bar"));
assertEquals(1L, m.get("foo"));
assertEquals(2L, m.get("bar"));
}
public void testReadMapWithNested() throws IOException {
Map m = (Map)reader("[\"~^\",\"foo\",1,\"bar\",[\"~^\",\"baz\",3]]").read();
assertTrue(m instanceof HashMap);
assertTrue(m.get("bar") instanceof HashMap);
assertTrue(((Map)m.get("bar")).containsKey("baz"));
assertEquals(3L, ((Map)m.get("bar")).get("baz"));
}
// Writing
public String write(Object o) throws Exception {
OutputStream out = new ByteArrayOutputStream();
Writer w = TransitFactory.writer(TransitFactory.Format.JSON_MACHINE, out, null);
w.write(o);
return out.toString();
}
public boolean isEqual(Object o1, Object o2) {
if(o1 instanceof Boolean)
return o1 == o2;
else
return false;
}
public void testRoundTrip() throws Exception {
Object inObject = true;
OutputStream out = new ByteArrayOutputStream();
Writer w = TransitFactory.writer(TransitFactory.Format.JSON_MACHINE, out, null);
w.write(inObject);
String s = out.toString();
InputStream in = new ByteArrayInputStream(s.getBytes());
Reader reader = TransitFactory.reader(TransitFactory.Format.JSON, in, null);
Object outObject = reader.read();
assertTrue(isEqual(inObject, outObject));
}
public void testWriteMap() throws Exception {
Map m = new HashMap();
m.put("foo", 1);
m.put("bar", 2);
assertEquals("[\"~^\",\"foo\",1,\"bar\",2]", write(m));
}
public void testWriteEmptyMap() throws Exception {
Map m = new HashMap();
assertEquals("[\"~^\"]", write(m));
}
public String scalar(String value) {
return "{\"~#'\":"+value+"}";
}
public void testWriteTime() throws Exception {
final Date d = new Date();
long tm = d.getTime();
String t = write(d);
List l = new ArrayList() {{ add(d); }};
assertEquals(scalar("\"~t" + tm + "\""), t);
t = write(l);
assertEquals("[\"~t" + tm + "\"]", t);
}
}
| JSON-M times reading properly - added tests.
| src/test/java/com/cognitect/transit/TransitJSONMachineModeTest.java | JSON-M times reading properly - added tests. |
|
Java | apache-2.0 | dc3d84aa813457841e04281b5ba03ef629d402c2 | 0 | vector-im/vector-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android | /*
* Copyright 2017 Vector Creations Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.util.Pair;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.matrix.androidsdk.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import im.vector.VectorApp;
/**
* This class contains the phone number toolbox
*/
public class PhoneNumberUtils {
private static final String LOG_TAG = "PhoneNumberUtils";
// preference keys
public static final String COUNTRY_CODE_PREF_KEY = "COUNTRY_CODE_PREF_KEY";
private static String[] mCountryCodes;
private static String[] mCountryNames;
// ex FR -> France
private static Map<String, String> mCountryNameByCC;
// ex FR -> 33
private static List<CountryPhoneData> mCountryIndicatorList;
/**
* The locale has been updated.
* The country code to string maps become invalid
*/
public static void onLocaleUpdate() {
mCountryCodes = null;
mCountryIndicatorList = null;
}
/**
* Build the country codes list
*/
private static void buildCountryCodesList() {
if (null == mCountryCodes) {
Locale applicationLocale = VectorApp.getApplicationLocale(VectorApp.getInstance());
// retrieve the ISO country code
String[] isoCountryCodes = Locale.getISOCountries();
List<Pair<String, String>> countryCodes = new ArrayList<>();
// retrieve the human display name
for (String countryCode : isoCountryCodes) {
Locale locale = new Locale("", countryCode);
countryCodes.add(new Pair<>(countryCode, locale.getDisplayCountry(applicationLocale)));
}
// sort by human display names
Collections.sort(countryCodes, new Comparator<Pair<String, String>>() {
@Override
public int compare(Pair<String, String> lhs, Pair<String, String> rhs) {
return lhs.second.compareTo(rhs.second);
}
});
mCountryNameByCC = new HashMap<>(isoCountryCodes.length);
mCountryCodes = new String[isoCountryCodes.length];
mCountryNames = new String[isoCountryCodes.length];
for (int index = 0; index < isoCountryCodes.length; index++) {
Pair<String, String> pair = countryCodes.get(index);
mCountryCodes[index] = pair.first;
mCountryNames[index] = pair.second;
mCountryNameByCC.put(pair.first, pair.second);
}
}
}
/**
* Get the list of all country names with their phone number indicator
*
* @return list of pair name - indicator
*/
public static List<CountryPhoneData> getCountriesWithIndicator() {
if (mCountryIndicatorList == null) {
mCountryIndicatorList = new ArrayList<>();
buildCountryCodesList();
for (Map.Entry<String, String> entry : mCountryNameByCC.entrySet()) {
final int indicator = PhoneNumberUtil.getInstance().getCountryCodeForRegion(entry.getKey());
if (indicator > 0) {
mCountryIndicatorList.add(new CountryPhoneData(entry.getKey(), entry.getValue(), indicator));
}
}
// sort by human display names
Collections.sort(mCountryIndicatorList, new Comparator<CountryPhoneData>() {
@Override
public int compare(CountryPhoneData lhs, CountryPhoneData rhs) {
return lhs.getCountryName().compareTo(rhs.getCountryName());
}
});
}
return mCountryIndicatorList;
}
/**
* @return the country codes.
*/
public static String[] getCountryCodes() {
buildCountryCodesList();
return mCountryCodes;
}
/**
* @return the human readable country codes.
*/
public static String[] getHumanCountryCodes() {
buildCountryCodesList();
return mCountryNames;
}
/**
* Provide a human readable name for a a country code.
*
* @param countryCode the country code
* @return the human readable name
*/
public static String getHumanCountryCode(final String countryCode) {
buildCountryCodesList();
String name = null;
if (!TextUtils.isEmpty(countryCode)) {
name = mCountryNameByCC.get(countryCode);
}
return name;
}
/**
* Provide the selected country code
*
* @param context the application context
* @return the ISO country code or "" if it does not exist
*/
public static String getCountryCode(final Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (!preferences.contains(COUNTRY_CODE_PREF_KEY) || TextUtils.isEmpty(preferences.getString(COUNTRY_CODE_PREF_KEY, ""))) {
try {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getNetworkCountryIso().toUpperCase();
if (TextUtils.isEmpty(countryCode)
&& !TextUtils.isEmpty(Locale.getDefault().getCountry())
&& PhoneNumberUtil.getInstance().getCountryCodeForRegion(Locale.getDefault().getCountry()) != 0) {
// Use Locale as a last resort
setCountryCode(context, Locale.getDefault().getCountry());
} else {
setCountryCode(context, countryCode);
}
} catch (Exception e) {
Log.e(LOG_TAG, "## getCountryCode failed " + e.getMessage());
}
}
return preferences.getString(COUNTRY_CODE_PREF_KEY, "");
}
/**
* Update the selected country code.
*
* @param context the context
* @param countryCode the country code
*/
public static void setCountryCode(final Context context, final String countryCode) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(COUNTRY_CODE_PREF_KEY, countryCode);
editor.commit();
}
/**
* Compute an unique key from a text and a country code
*
* @param text the text
* @param countryCode the country code
* @return the unique key
*/
private static String getMapKey(final String text, final String countryCode) {
return "μ" + countryCode + "μ" + text;
}
/**
* Phone numbers cache by text.
*/
static HashMap<String, Object> mPhoneNumberByText = new HashMap<>();
/**
* Provide libphonenumber phonenumber from an unformatted one.
*
* @param text the unformatted phone number
* @param countryCode the cuntry code
* @return the phone number
*/
public static Phonenumber.PhoneNumber getPhoneNumber(final String text, final String countryCode) {
String key = getMapKey(text, countryCode);
Phonenumber.PhoneNumber phoneNumber = null;
if (mPhoneNumberByText.containsKey(key)) {
Object value = mPhoneNumberByText.get(key);
if (value instanceof Phonenumber.PhoneNumber) {
phoneNumber = (Phonenumber.PhoneNumber) value;
}
} else {
try {
phoneNumber = PhoneNumberUtil.getInstance().parse(text, countryCode);
} catch (Exception e) {
Log.e(LOG_TAG, "## getPhoneNumber() : failed " + e.getMessage());
}
if (null != phoneNumber) {
mPhoneNumberByText.put(key, phoneNumber);
} else {
// add a dummy object to avoid searching twice
mPhoneNumberByText.put(key, "");
}
}
return phoneNumber;
}
/**
* E164 phone number by unformatted phonenumber
*/
static HashMap<String, String> mE164PhoneNumberByText = new HashMap<>();
/**
* Convert an unformatted phone number to a E164 format one.
*
* @param context the coontext
* @param phoneNumber the unformatted phone number
* @return the E164 phone number
*/
public static String getE164format(final Context context, final String phoneNumber) {
return getE164format(phoneNumber, getCountryCode(context));
}
/**
* Convert an unformatted phone number to a E164 format one.
*
* @param phoneNumber the unformatted phone number
* @param countryCode teh country code
* @return the E164 phone number
*/
public static String getE164format(final String phoneNumber, final String countryCode) {
if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(countryCode)) {
return null;
}
String key = getMapKey(phoneNumber, countryCode);
String e164Pn = mE164PhoneNumberByText.get(key);
if (null == e164Pn) {
e164Pn = "";
try {
e164Pn = PhoneNumberUtil.getInstance().format(getPhoneNumber(phoneNumber, countryCode), PhoneNumberUtil.PhoneNumberFormat.E164);
} catch (Exception e) {
Log.e(LOG_TAG, "## getE164format() failed " + e.getMessage());
}
if (e164Pn.startsWith("+")) {
e164Pn = e164Pn.substring(1);
}
mE164PhoneNumberByText.put(key, e164Pn);
}
return !TextUtils.isEmpty(e164Pn) ? e164Pn : null;
}
/**
* Convert a @{@link com.google.i18n.phonenumbers.Phonenumber.PhoneNumber} to a string with E164 format.
* @param phoneNumber
* @return formatted screen
*/
public static String getE164format(final Phonenumber.PhoneNumber phoneNumber) {
String phoneNumberFormatted = null;
if (phoneNumber != null) {
phoneNumberFormatted = PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
}
return phoneNumberFormatted;
}
/**
* Try to extract a phone number from the given String
*
* @param context context
* @param potentialPhoneNumber the potential phone number
* @return PhoneNumber object if valid phone number
*/
public static Phonenumber.PhoneNumber extractPhoneNumber(final Context context, final String potentialPhoneNumber) {
Phonenumber.PhoneNumber phoneNumber = null;
if (android.util.Patterns.PHONE.matcher(potentialPhoneNumber).matches()) {
try {
if (potentialPhoneNumber.startsWith("+")) {
phoneNumber = PhoneNumberUtil.getInstance().parse(potentialPhoneNumber, null);
} else {
// Try with a "+" prefix
phoneNumber = PhoneNumberUtil.getInstance().parse("+" + potentialPhoneNumber, null);
}
} catch (NumberParseException e) {
// Try with specifying the calling code
try {
phoneNumber = PhoneNumberUtil.getInstance().parse(potentialPhoneNumber, PhoneNumberUtils.getCountryCode(context));
} catch (NumberParseException e1) {
// Do nothing
}
} catch (Exception e) {
// Do nothing
}
// PhoneNumberUtils parse does its best to extract a phone number from the string.
// For example, parse(abc100) returns 100.
// So, we check if it is a valid phone number.
if ((null != phoneNumber) && !PhoneNumberUtil.getInstance().isValidNumber(phoneNumber)) {
phoneNumber = null;
}
}
return phoneNumber;
}
}
| vector/src/main/java/im/vector/util/PhoneNumberUtils.java | /*
* Copyright 2017 Vector Creations Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.util.Pair;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.matrix.androidsdk.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* This class contains the phone number toolbox
*/
public class PhoneNumberUtils {
private static final String LOG_TAG = "PhoneNumberUtils";
// preference keys
public static final String COUNTRY_CODE_PREF_KEY = "COUNTRY_CODE_PREF_KEY";
private static String[] mCountryCodes;
private static String[] mCountryNames;
// ex FR -> France
private static Map<String, String> mCountryNameByCC;
// ex FR -> 33
private static List<CountryPhoneData> mCountryIndicatorList;
/**
* The locale has been updated.
* The country code to string maps become invalid
*/
public static void onLocaleUpdate() {
mCountryCodes = null;
}
/**
* Build the country codes list
*/
private static void buildCountryCodesList() {
if (null == mCountryCodes) {
// retrieve the ISO country code
String[] isoCountryCodes = Locale.getISOCountries();
List<Pair<String, String>> countryCodes = new ArrayList<>();
// retrieve the human display name
for (String countryCode : isoCountryCodes) {
Locale locale = new Locale("", countryCode);
countryCodes.add(new Pair<>(countryCode, locale.getDisplayCountry()));
}
// sort by human display names
Collections.sort(countryCodes, new Comparator<Pair<String, String>>() {
@Override
public int compare(Pair<String, String> lhs, Pair<String, String> rhs) {
return lhs.second.compareTo(rhs.second);
}
});
mCountryNameByCC = new HashMap<>(isoCountryCodes.length);
mCountryCodes = new String[isoCountryCodes.length];
mCountryNames = new String[isoCountryCodes.length];
for (int index = 0; index < isoCountryCodes.length; index++) {
Pair<String, String> pair = countryCodes.get(index);
mCountryCodes[index] = pair.first;
mCountryNames[index] = pair.second;
mCountryNameByCC.put(pair.first, pair.second);
}
}
}
/**
* Get the list of all country names with their phone number indicator
*
* @return list of pair name - indicator
*/
public static List<CountryPhoneData> getCountriesWithIndicator() {
if (mCountryIndicatorList == null) {
mCountryIndicatorList = new ArrayList<>();
buildCountryCodesList();
for (Map.Entry<String, String> entry : mCountryNameByCC.entrySet()) {
final int indicator = PhoneNumberUtil.getInstance().getCountryCodeForRegion(entry.getKey());
if (indicator > 0) {
mCountryIndicatorList.add(new CountryPhoneData(entry.getKey(), entry.getValue(), indicator));
}
}
// sort by human display names
Collections.sort(mCountryIndicatorList, new Comparator<CountryPhoneData>() {
@Override
public int compare(CountryPhoneData lhs, CountryPhoneData rhs) {
return lhs.getCountryName().compareTo(rhs.getCountryName());
}
});
}
return mCountryIndicatorList;
}
/**
* @return the country codes.
*/
public static String[] getCountryCodes() {
buildCountryCodesList();
return mCountryCodes;
}
/**
* @return the human readable country codes.
*/
public static String[] getHumanCountryCodes() {
buildCountryCodesList();
return mCountryNames;
}
/**
* Provide a human readable name for a a country code.
*
* @param countryCode the country code
* @return the human readable name
*/
public static String getHumanCountryCode(final String countryCode) {
buildCountryCodesList();
String name = null;
if (!TextUtils.isEmpty(countryCode)) {
name = mCountryNameByCC.get(countryCode);
}
return name;
}
/**
* Provide the selected country code
*
* @param context the application context
* @return the ISO country code or "" if it does not exist
*/
public static String getCountryCode(final Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (!preferences.contains(COUNTRY_CODE_PREF_KEY) || TextUtils.isEmpty(preferences.getString(COUNTRY_CODE_PREF_KEY, ""))) {
try {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getNetworkCountryIso().toUpperCase();
if (TextUtils.isEmpty(countryCode)
&& !TextUtils.isEmpty(Locale.getDefault().getCountry())
&& PhoneNumberUtil.getInstance().getCountryCodeForRegion(Locale.getDefault().getCountry()) != 0) {
// Use Locale as a last resort
setCountryCode(context, Locale.getDefault().getCountry());
} else {
setCountryCode(context, countryCode);
}
} catch (Exception e) {
Log.e(LOG_TAG, "## getCountryCode failed " + e.getMessage());
}
}
return preferences.getString(COUNTRY_CODE_PREF_KEY, "");
}
/**
* Update the selected country code.
*
* @param context the context
* @param countryCode the country code
*/
public static void setCountryCode(final Context context, final String countryCode) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(COUNTRY_CODE_PREF_KEY, countryCode);
editor.commit();
}
/**
* Compute an unique key from a text and a country code
*
* @param text the text
* @param countryCode the country code
* @return the unique key
*/
private static String getMapKey(final String text, final String countryCode) {
return "μ" + countryCode + "μ" + text;
}
/**
* Phone numbers cache by text.
*/
static HashMap<String, Object> mPhoneNumberByText = new HashMap<>();
/**
* Provide libphonenumber phonenumber from an unformatted one.
*
* @param text the unformatted phone number
* @param countryCode the cuntry code
* @return the phone number
*/
public static Phonenumber.PhoneNumber getPhoneNumber(final String text, final String countryCode) {
String key = getMapKey(text, countryCode);
Phonenumber.PhoneNumber phoneNumber = null;
if (mPhoneNumberByText.containsKey(key)) {
Object value = mPhoneNumberByText.get(key);
if (value instanceof Phonenumber.PhoneNumber) {
phoneNumber = (Phonenumber.PhoneNumber) value;
}
} else {
try {
phoneNumber = PhoneNumberUtil.getInstance().parse(text, countryCode);
} catch (Exception e) {
Log.e(LOG_TAG, "## getPhoneNumber() : failed " + e.getMessage());
}
if (null != phoneNumber) {
mPhoneNumberByText.put(key, phoneNumber);
} else {
// add a dummy object to avoid searching twice
mPhoneNumberByText.put(key, "");
}
}
return phoneNumber;
}
/**
* E164 phone number by unformatted phonenumber
*/
static HashMap<String, String> mE164PhoneNumberByText = new HashMap<>();
/**
* Convert an unformatted phone number to a E164 format one.
*
* @param context the coontext
* @param phoneNumber the unformatted phone number
* @return the E164 phone number
*/
public static String getE164format(final Context context, final String phoneNumber) {
return getE164format(phoneNumber, getCountryCode(context));
}
/**
* Convert an unformatted phone number to a E164 format one.
*
* @param phoneNumber the unformatted phone number
* @param countryCode teh country code
* @return the E164 phone number
*/
public static String getE164format(final String phoneNumber, final String countryCode) {
if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(countryCode)) {
return null;
}
String key = getMapKey(phoneNumber, countryCode);
String e164Pn = mE164PhoneNumberByText.get(key);
if (null == e164Pn) {
e164Pn = "";
try {
e164Pn = PhoneNumberUtil.getInstance().format(getPhoneNumber(phoneNumber, countryCode), PhoneNumberUtil.PhoneNumberFormat.E164);
} catch (Exception e) {
Log.e(LOG_TAG, "## getE164format() failed " + e.getMessage());
}
if (e164Pn.startsWith("+")) {
e164Pn = e164Pn.substring(1);
}
mE164PhoneNumberByText.put(key, e164Pn);
}
return !TextUtils.isEmpty(e164Pn) ? e164Pn : null;
}
/**
* Convert a @{@link com.google.i18n.phonenumbers.Phonenumber.PhoneNumber} to a string with E164 format.
* @param phoneNumber
* @return formatted screen
*/
public static String getE164format(final Phonenumber.PhoneNumber phoneNumber) {
String phoneNumberFormatted = null;
if (phoneNumber != null) {
phoneNumberFormatted = PhoneNumberUtil.getInstance().format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
}
return phoneNumberFormatted;
}
/**
* Try to extract a phone number from the given String
*
* @param context context
* @param potentialPhoneNumber the potential phone number
* @return PhoneNumber object if valid phone number
*/
public static Phonenumber.PhoneNumber extractPhoneNumber(final Context context, final String potentialPhoneNumber) {
Phonenumber.PhoneNumber phoneNumber = null;
if (android.util.Patterns.PHONE.matcher(potentialPhoneNumber).matches()) {
try {
if (potentialPhoneNumber.startsWith("+")) {
phoneNumber = PhoneNumberUtil.getInstance().parse(potentialPhoneNumber, null);
} else {
// Try with a "+" prefix
phoneNumber = PhoneNumberUtil.getInstance().parse("+" + potentialPhoneNumber, null);
}
} catch (NumberParseException e) {
// Try with specifying the calling code
try {
phoneNumber = PhoneNumberUtil.getInstance().parse(potentialPhoneNumber, PhoneNumberUtils.getCountryCode(context));
} catch (NumberParseException e1) {
// Do nothing
}
} catch (Exception e) {
// Do nothing
}
// PhoneNumberUtils parse does its best to extract a phone number from the string.
// For example, parse(abc100) returns 100.
// So, we check if it is a valid phone number.
if ((null != phoneNumber) && !PhoneNumberUtil.getInstance().isValidNumber(phoneNumber)) {
phoneNumber = null;
}
}
return phoneNumber;
}
}
| add_language_selection
fix invalid contries list.
| vector/src/main/java/im/vector/util/PhoneNumberUtils.java | add_language_selection fix invalid contries list. |
|
Java | apache-2.0 | 6057c57057a100766b0db9b34e6fea1ebb38f56a | 0 | Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,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.catalina.ha.deploy;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.ha.ClusterDeployer;
import org.apache.catalina.ha.ClusterListener;
import org.apache.catalina.ha.ClusterMessage;
import org.apache.catalina.tribes.Member;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.modeler.Registry;
/**
* <p>
* A farm war deployer is a class that is able to deploy/undeploy web
* applications in WAR form within the cluster.
* </p>
* Any host can act as the admin, and will have three directories
* <ul>
* <li>deployDir - the directory where we watch for changes</li>
* <li>applicationDir - the directory where we install applications</li>
* <li>tempDir - a temporaryDirectory to store binary data when downloading a
* war from the cluster</li>
* </ul>
* Currently we only support deployment of WAR files since they are easier to
* send across the wire.
*
* @author Filip Hanik
* @author Peter Rossbach
* @version $Revision$
*/
public class FarmWarDeployer extends ClusterListener implements ClusterDeployer, FileChangeListener {
/*--Static Variables----------------------------------------*/
private static final Log log = LogFactory.getLog(FarmWarDeployer.class);
/**
* The descriptive information about this implementation.
*/
private static final String info = "FarmWarDeployer/1.2";
/*--Instance Variables--------------------------------------*/
protected boolean started = false; //default 5 seconds
protected HashMap<String, FileMessageFactory> fileFactories =
new HashMap<String, FileMessageFactory>();
protected String deployDir;
protected String tempDir;
protected String watchDir;
protected boolean watchEnabled = false;
protected WarWatcher watcher = null;
/**
* Iteration count for background processing.
*/
private int count = 0;
/**
* Frequency of the Farm watchDir check. Cluster wide deployment will be
* done once for the specified amount of backgrondProcess calls (ie, the
* lower the amount, the most often the checks will occur).
*/
protected int processDeployFrequency = 2;
/**
* Path where context descriptors should be deployed.
*/
protected File configBase = null;
/**
* The associated host.
*/
protected Host host = null;
/**
* The host appBase.
*/
protected File appBase = null;
/**
* MBean server.
*/
protected MBeanServer mBeanServer = null;
/**
* The associated deployer ObjectName.
*/
protected ObjectName oname = null;
/*--Constructor---------------------------------------------*/
public FarmWarDeployer() {
}
/**
* Return descriptive information about this deployer implementation and the
* corresponding version number, in the format
* <code><description>/<version></code>.
*/
public String getInfo() {
return (info);
}
/*--Logic---------------------------------------------------*/
@Override
public void start() throws Exception {
if (started)
return;
Container hcontainer = getCluster().getContainer();
if(!(hcontainer instanceof Host)) {
log.error("FarmWarDeployer can only work as host cluster subelement!");
return ;
}
host = (Host) hcontainer;
// Check to correct engine and host setup
Container econtainer = host.getParent();
if(!(econtainer instanceof Engine)) {
log.error("FarmWarDeployer can only work if parent of " + host.getName()+ " is an engine!");
return ;
}
Engine engine = (Engine) econtainer;
String hostname = null;
hostname = host.getName();
try {
oname = new ObjectName(engine.getName() + ":type=Deployer,host="
+ hostname);
} catch (Exception e) {
log.error("Can't construct MBean object name" + e);
return;
}
if (watchEnabled) {
watcher = new WarWatcher(this, new File(getWatchDir()));
if (log.isInfoEnabled()) {
log.info("Cluster deployment is watching " + getWatchDir()
+ " for changes.");
}
}
configBase = new File(System.getProperty(Globals.CATALINA_BASE_PROP), "conf");
configBase = new File(configBase, engine.getName());
configBase = new File(configBase, hostname);
// Retrieve the MBean server
mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
started = true;
count = 0;
getCluster().addClusterListener(this);
if (log.isInfoEnabled())
log.info("Cluster FarmWarDeployer started.");
}
/*
* stop cluster wide deployments
*
* @see org.apache.catalina.ha.ClusterDeployer#stop()
*/
@Override
public void stop() throws LifecycleException {
started = false;
getCluster().removeClusterListener(this);
count = 0;
if (watcher != null) {
watcher.clear();
watcher = null;
}
if (log.isInfoEnabled())
log.info("Cluster FarmWarDeployer stopped.");
}
public void cleanDeployDir() {
throw new java.lang.UnsupportedOperationException(
"Method cleanDeployDir() not yet implemented.");
}
/**
* Callback from the cluster, when a message is received, The cluster will
* broadcast it invoking the messageReceived on the receiver.
*
* @param msg
* ClusterMessage - the message received from the cluster
*/
@Override
public void messageReceived(ClusterMessage msg) {
try {
if (msg instanceof FileMessage) {
FileMessage fmsg = (FileMessage) msg;
if (log.isDebugEnabled())
log.debug("receive cluster deployment [ path: "
+ fmsg.getContextPath() + " war: "
+ fmsg.getFileName() + " ]");
FileMessageFactory factory = getFactory(fmsg);
// TODO correct second try after app is in service!
if (factory.writeMessage(fmsg)) {
//last message received war file is completed
String name = factory.getFile().getName();
if (!name.endsWith(".war"))
name = name + ".war";
File deployable = new File(getDeployDir(), name);
try {
String path = fmsg.getContextPath();
if (!isServiced(path)) {
addServiced(path);
try {
remove(path);
if (!factory.getFile().renameTo(deployable)) {
log.error("Failed to rename [" +
factory.getFile() + "] to [" +
deployable + "]");
}
check(path);
} finally {
removeServiced(path);
}
if (log.isDebugEnabled())
log.debug("deployment from " + path
+ " finished.");
} else
log.error("Application " + path
+ " in used. touch war file " + name
+ " again!");
} catch (Exception ex) {
log.error(ex);
} finally {
removeFactory(fmsg);
}
}
} else if (msg instanceof UndeployMessage) {
try {
UndeployMessage umsg = (UndeployMessage) msg;
String path = umsg.getContextPath();
if (log.isDebugEnabled())
log.debug("receive cluster undeployment from " + path);
if (!isServiced(path)) {
addServiced(path);
try {
remove(path);
} finally {
removeServiced(path);
}
if (log.isDebugEnabled())
log.debug("undeployment from " + path
+ " finished.");
} else
log.error("Application "
+ path
+ " in used. Sorry not remove from backup cluster nodes!");
} catch (Exception ex) {
log.error(ex);
}
}
} catch (java.io.IOException x) {
log.error("Unable to read farm deploy file message.", x);
}
}
/**
* create factory for all transported war files
*
* @param msg
* @return Factory for all app message (war files)
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public synchronized FileMessageFactory getFactory(FileMessage msg)
throws java.io.FileNotFoundException, java.io.IOException {
File tmpFile = new File(msg.getFileName());
File writeToFile = new File(getTempDir(), tmpFile.getName());
FileMessageFactory factory = fileFactories.get(msg.getFileName());
if (factory == null) {
factory = FileMessageFactory.getInstance(writeToFile, true);
fileFactories.put(msg.getFileName(), factory);
}
return factory;
}
/**
* Remove file (war) from messages)
*
* @param msg
*/
public void removeFactory(FileMessage msg) {
fileFactories.remove(msg.getFileName());
}
/**
* Before the cluster invokes messageReceived the cluster will ask the
* receiver to accept or decline the message, In the future, when messages
* get big, the accept method will only take a message header
*
* @param msg
* ClusterMessage
* @return boolean - returns true to indicate that messageReceived should be
* invoked. If false is returned, the messageReceived method will
* not be invoked.
*/
@Override
public boolean accept(ClusterMessage msg) {
return (msg instanceof FileMessage) || (msg instanceof UndeployMessage);
}
/**
* Install a new web application, whose web application archive is at the
* specified URL, into this container and all the other members of the
* cluster with the specified context path. A context path of "" (the empty
* string) should be used for the root application for this container.
* Otherwise, the context path must start with a slash.
* <p>
* If this application is successfully installed locally, a ContainerEvent
* of type <code>INSTALL_EVENT</code> will be sent to all registered
* listeners, with the newly created <code>Context</code> as an argument.
*
* @param contextPath
* The context path to which this application should be installed
* (must be unique)
* @param war
* A URL of type "jar:" that points to a WAR file, or type
* "file:" that points to an unpacked directory structure
* containing the web application to be installed
*
* @exception IllegalArgumentException
* if the specified context path is malformed (it must be ""
* or start with a slash)
* @exception IllegalStateException
* if the specified context path is already attached to an
* existing web application
* @exception IOException
* if an input/output error was encountered during
* installation
*/
@Override
public void install(String contextPath, URL war) throws IOException {
Member[] members = getCluster().getMembers();
Member localMember = getCluster().getLocalMember();
FileMessageFactory factory = FileMessageFactory.getInstance(new File(
war.getFile()), false);
FileMessage msg = new FileMessage(localMember, war.getFile(),
contextPath);
if(log.isDebugEnabled())
log.debug("Send cluster war deployment [ path:"
+ contextPath + " war: " + war + " ] started.");
msg = factory.readMessage(msg);
while (msg != null) {
for (int i = 0; i < members.length; i++) {
if (log.isDebugEnabled())
log.debug("Send cluster war fragment [ path: "
+ contextPath + " war: " + war + " to: " + members[i] + " ]");
getCluster().send(msg, members[i]);
}
msg = factory.readMessage(msg);
}
if(log.isDebugEnabled())
log.debug("Send cluster war deployment [ path: "
+ contextPath + " war: " + war + " ] finished.");
}
/**
* Remove an existing web application, attached to the specified context
* path. If this application is successfully removed, a ContainerEvent of
* type <code>REMOVE_EVENT</code> will be sent to all registered
* listeners, with the removed <code>Context</code> as an argument.
* Deletes the web application war file and/or directory if they exist in
* the Host's appBase.
*
* @param contextPath
* The context path of the application to be removed
* @param undeploy
* boolean flag to remove web application from server
*
* @exception IllegalArgumentException
* if the specified context path is malformed (it must be ""
* or start with a slash)
* @exception IllegalArgumentException
* if the specified context path does not identify a
* currently installed web application
* @exception IOException
* if an input/output error occurs during removal
*/
@Override
public void remove(String contextPath, boolean undeploy) throws IOException {
if (log.isInfoEnabled())
log.info("Cluster wide remove of web app " + contextPath);
Member localMember = getCluster().getLocalMember();
UndeployMessage msg = new UndeployMessage(localMember, System
.currentTimeMillis(), "Undeploy:" + contextPath + ":"
+ System.currentTimeMillis(), contextPath, undeploy);
if (log.isDebugEnabled())
log.debug("Send cluster wide undeployment from "
+ contextPath );
cluster.send(msg);
// remove locally
if (undeploy) {
try {
if (!isServiced(contextPath)) {
addServiced(contextPath);
try {
remove(contextPath);
} finally {
removeServiced(contextPath);
}
} else
log.error("Local remove from " + contextPath
+ "failed, other manager has app in service!");
} catch (Exception ex) {
log.error("local remove from " + contextPath + " failed", ex);
}
}
}
/*
* Modification from watchDir war detected!
*
* @see org.apache.catalina.ha.deploy.FileChangeListener#fileModified(java.io.File)
*/
@Override
public void fileModified(File newWar) {
try {
File deployWar = new File(getDeployDir(), newWar.getName());
copy(newWar, deployWar);
String contextName = getContextName(deployWar);
if (log.isInfoEnabled())
log.info("Installing webapp[" + contextName + "] from "
+ deployWar.getAbsolutePath());
try {
remove(contextName, false);
} catch (Exception x) {
log.error("No removal", x);
}
install(contextName, deployWar.toURI().toURL());
} catch (Exception x) {
log.error("Unable to install WAR file", x);
}
}
/*
* War remove from watchDir
*
* @see org.apache.catalina.ha.deploy.FileChangeListener#fileRemoved(java.io.File)
*/
@Override
public void fileRemoved(File removeWar) {
try {
String contextName = getContextName(removeWar);
if (log.isInfoEnabled())
log.info("Removing webapp[" + contextName + "]");
remove(contextName, true);
} catch (Exception x) {
log.error("Unable to remove WAR file", x);
}
}
/**
* Create a context path from war
* @param war War filename
* @return '/filename' or if war name is ROOT.war context name is empty string ''
*/
protected String getContextName(File war) {
String contextName = "/"
+ war.getName().substring(0,
war.getName().lastIndexOf(".war"));
if("/ROOT".equals(contextName))
contextName= "" ;
return contextName ;
}
/**
* Return a File object representing the "application root" directory for
* our associated Host.
*/
protected File getAppBase() {
if (appBase != null) {
return appBase;
}
File file = new File(host.getAppBase());
if (!file.isAbsolute())
file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), host
.getAppBase());
try {
appBase = file.getCanonicalFile();
} catch (IOException e) {
appBase = file;
}
return (appBase);
}
/**
* Invoke the remove method on the deployer.
*/
protected void remove(String path) throws Exception {
// TODO Handle remove also work dir content !
// Stop the context first to be nicer
Context context = (Context) host.findChild(path);
if (context != null) {
if(log.isDebugEnabled())
log.debug("Undeploy local context " +path );
context.stop();
String baseName = context.getBaseName();
File war = new File(getAppBase(), baseName + ".war");
File dir = new File(getAppBase(), baseName);
File xml = new File(configBase, baseName + ".xml");
if (war.exists()) {
if (!war.delete()) {
log.error("Failed to delete [" + war + "]");
}
} else if (dir.exists()) {
undeployDir(dir);
} else {
if (!xml.delete()) {
log.error("Failed to delete [" + xml + "]");
}
}
// Perform new deployment and remove internal HostConfig state
check(path);
}
}
/**
* Delete the specified directory, including all of its contents and
* subdirectories recursively.
*
* @param dir
* File object representing the directory to be deleted
*/
protected void undeployDir(File dir) {
String files[] = dir.list();
if (files == null) {
files = new String[0];
}
for (int i = 0; i < files.length; i++) {
File file = new File(dir, files[i]);
if (file.isDirectory()) {
undeployDir(file);
} else {
if (!file.delete()) {
log.error("Failed to delete [" + file + "]");
}
}
}
if (!dir.delete()) {
log.error("Failed to delete [" + dir + "]");
}
}
/*
* Call watcher to check for deploy changes
*
* @see org.apache.catalina.ha.ClusterDeployer#backgroundProcess()
*/
@Override
public void backgroundProcess() {
if (started) {
count = (count + 1) % processDeployFrequency;
if (count == 0 && watchEnabled) {
watcher.check();
}
}
}
/*--Deployer Operations ------------------------------------*/
/**
* Invoke the check method on the deployer.
*/
protected void check(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
mBeanServer.invoke(oname, "check", params, signature);
}
/**
* Invoke the check method on the deployer.
*/
protected boolean isServiced(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced",
params, signature);
return result.booleanValue();
}
/**
* Invoke the check method on the deployer.
*/
protected void addServiced(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
mBeanServer.invoke(oname, "addServiced", params, signature);
}
/**
* Invoke the check method on the deployer.
*/
protected void removeServiced(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
mBeanServer.invoke(oname, "removeServiced", params, signature);
}
/*--Instance Getters/Setters--------------------------------*/
@Override
public boolean equals(Object listener) {
return super.equals(listener);
}
@Override
public int hashCode() {
return super.hashCode();
}
public String getDeployDir() {
return deployDir;
}
public void setDeployDir(String deployDir) {
this.deployDir = deployDir;
}
public String getTempDir() {
return tempDir;
}
public void setTempDir(String tempDir) {
this.tempDir = tempDir;
}
public String getWatchDir() {
return watchDir;
}
public void setWatchDir(String watchDir) {
this.watchDir = watchDir;
}
public boolean isWatchEnabled() {
return watchEnabled;
}
public boolean getWatchEnabled() {
return watchEnabled;
}
public void setWatchEnabled(boolean watchEnabled) {
this.watchEnabled = watchEnabled;
}
/**
* Return the frequency of watcher checks.
*/
public int getProcessDeployFrequency() {
return (this.processDeployFrequency);
}
/**
* Set the watcher checks frequency.
*
* @param processExpiresFrequency
* the new manager checks frequency
*/
public void setProcessDeployFrequency(int processExpiresFrequency) {
if (processExpiresFrequency <= 0) {
return;
}
this.processDeployFrequency = processExpiresFrequency;
}
/**
* Copy a file to the specified temp directory.
* @param from copy from temp
* @param to to host appBase directory
* @return true, copy successful
*/
protected boolean copy(File from, File to) {
try {
if (!to.exists()) {
if (!to.createNewFile()) {
log.error("Unable to create [" + to + "]");
return false;
}
}
java.io.FileInputStream is = new java.io.FileInputStream(from);
java.io.FileOutputStream os = new java.io.FileOutputStream(to,
false);
byte[] buf = new byte[4096];
while (true) {
int len = is.read(buf);
if (len < 0)
break;
os.write(buf, 0, len);
}
is.close();
os.close();
} catch (IOException e) {
log.error("Unable to copy file from:" + from + " to:" + to, e);
return false;
}
return true;
}
}
| java/org/apache/catalina/ha/deploy/FarmWarDeployer.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.catalina.ha.deploy;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Globals;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.ha.CatalinaCluster;
import org.apache.catalina.ha.ClusterDeployer;
import org.apache.catalina.ha.ClusterListener;
import org.apache.catalina.ha.ClusterMessage;
import org.apache.catalina.tribes.Member;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.modeler.Registry;
/**
* <p>
* A farm war deployer is a class that is able to deploy/undeploy web
* applications in WAR form within the cluster.
* </p>
* Any host can act as the admin, and will have three directories
* <ul>
* <li>deployDir - the directory where we watch for changes</li>
* <li>applicationDir - the directory where we install applications</li>
* <li>tempDir - a temporaryDirectory to store binary data when downloading a
* war from the cluster</li>
* </ul>
* Currently we only support deployment of WAR files since they are easier to
* send across the wire.
*
* @author Filip Hanik
* @author Peter Rossbach
* @version $Revision$
*/
public class FarmWarDeployer extends ClusterListener implements ClusterDeployer, FileChangeListener {
/*--Static Variables----------------------------------------*/
private static final Log log = LogFactory.getLog(FarmWarDeployer.class);
/**
* The descriptive information about this implementation.
*/
private static final String info = "FarmWarDeployer/1.2";
/*--Instance Variables--------------------------------------*/
protected CatalinaCluster cluster = null;
protected boolean started = false; //default 5 seconds
protected HashMap<String, FileMessageFactory> fileFactories =
new HashMap<String, FileMessageFactory>();
protected String deployDir;
protected String tempDir;
protected String watchDir;
protected boolean watchEnabled = false;
protected WarWatcher watcher = null;
/**
* Iteration count for background processing.
*/
private int count = 0;
/**
* Frequency of the Farm watchDir check. Cluster wide deployment will be
* done once for the specified amount of backgrondProcess calls (ie, the
* lower the amount, the most often the checks will occur).
*/
protected int processDeployFrequency = 2;
/**
* Path where context descriptors should be deployed.
*/
protected File configBase = null;
/**
* The associated host.
*/
protected Host host = null;
/**
* The host appBase.
*/
protected File appBase = null;
/**
* MBean server.
*/
protected MBeanServer mBeanServer = null;
/**
* The associated deployer ObjectName.
*/
protected ObjectName oname = null;
/*--Constructor---------------------------------------------*/
public FarmWarDeployer() {
}
/**
* Return descriptive information about this deployer implementation and the
* corresponding version number, in the format
* <code><description>/<version></code>.
*/
public String getInfo() {
return (info);
}
/*--Logic---------------------------------------------------*/
@Override
public void start() throws Exception {
if (started)
return;
Container hcontainer = getCluster().getContainer();
if(!(hcontainer instanceof Host)) {
log.error("FarmWarDeployer can only work as host cluster subelement!");
return ;
}
host = (Host) hcontainer;
// Check to correct engine and host setup
Container econtainer = host.getParent();
if(!(econtainer instanceof Engine)) {
log.error("FarmWarDeployer can only work if parent of " + host.getName()+ " is an engine!");
return ;
}
Engine engine = (Engine) econtainer;
String hostname = null;
hostname = host.getName();
try {
oname = new ObjectName(engine.getName() + ":type=Deployer,host="
+ hostname);
} catch (Exception e) {
log.error("Can't construct MBean object name" + e);
return;
}
if (watchEnabled) {
watcher = new WarWatcher(this, new File(getWatchDir()));
if (log.isInfoEnabled()) {
log.info("Cluster deployment is watching " + getWatchDir()
+ " for changes.");
}
}
configBase = new File(System.getProperty(Globals.CATALINA_BASE_PROP), "conf");
configBase = new File(configBase, engine.getName());
configBase = new File(configBase, hostname);
// Retrieve the MBean server
mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
started = true;
count = 0;
getCluster().addClusterListener(this);
if (log.isInfoEnabled())
log.info("Cluster FarmWarDeployer started.");
}
/*
* stop cluster wide deployments
*
* @see org.apache.catalina.ha.ClusterDeployer#stop()
*/
@Override
public void stop() throws LifecycleException {
started = false;
getCluster().removeClusterListener(this);
count = 0;
if (watcher != null) {
watcher.clear();
watcher = null;
}
if (log.isInfoEnabled())
log.info("Cluster FarmWarDeployer stopped.");
}
public void cleanDeployDir() {
throw new java.lang.UnsupportedOperationException(
"Method cleanDeployDir() not yet implemented.");
}
/**
* Callback from the cluster, when a message is received, The cluster will
* broadcast it invoking the messageReceived on the receiver.
*
* @param msg
* ClusterMessage - the message received from the cluster
*/
@Override
public void messageReceived(ClusterMessage msg) {
try {
if (msg instanceof FileMessage) {
FileMessage fmsg = (FileMessage) msg;
if (log.isDebugEnabled())
log.debug("receive cluster deployment [ path: "
+ fmsg.getContextPath() + " war: "
+ fmsg.getFileName() + " ]");
FileMessageFactory factory = getFactory(fmsg);
// TODO correct second try after app is in service!
if (factory.writeMessage(fmsg)) {
//last message received war file is completed
String name = factory.getFile().getName();
if (!name.endsWith(".war"))
name = name + ".war";
File deployable = new File(getDeployDir(), name);
try {
String path = fmsg.getContextPath();
if (!isServiced(path)) {
addServiced(path);
try {
remove(path);
factory.getFile().renameTo(deployable);
check(path);
} finally {
removeServiced(path);
}
if (log.isDebugEnabled())
log.debug("deployment from " + path
+ " finished.");
} else
log.error("Application " + path
+ " in used. touch war file " + name
+ " again!");
} catch (Exception ex) {
log.error(ex);
} finally {
removeFactory(fmsg);
}
}
} else if (msg instanceof UndeployMessage) {
try {
UndeployMessage umsg = (UndeployMessage) msg;
String path = umsg.getContextPath();
if (log.isDebugEnabled())
log.debug("receive cluster undeployment from " + path);
if (!isServiced(path)) {
addServiced(path);
try {
remove(path);
} finally {
removeServiced(path);
}
if (log.isDebugEnabled())
log.debug("undeployment from " + path
+ " finished.");
} else
log.error("Application "
+ path
+ " in used. Sorry not remove from backup cluster nodes!");
} catch (Exception ex) {
log.error(ex);
}
}
} catch (java.io.IOException x) {
log.error("Unable to read farm deploy file message.", x);
}
}
/**
* create factory for all transported war files
*
* @param msg
* @return Factory for all app message (war files)
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public synchronized FileMessageFactory getFactory(FileMessage msg)
throws java.io.FileNotFoundException, java.io.IOException {
File tmpFile = new File(msg.getFileName());
File writeToFile = new File(getTempDir(), tmpFile.getName());
FileMessageFactory factory = fileFactories.get(msg.getFileName());
if (factory == null) {
factory = FileMessageFactory.getInstance(writeToFile, true);
fileFactories.put(msg.getFileName(), factory);
}
return factory;
}
/**
* Remove file (war) from messages)
*
* @param msg
*/
public void removeFactory(FileMessage msg) {
fileFactories.remove(msg.getFileName());
}
/**
* Before the cluster invokes messageReceived the cluster will ask the
* receiver to accept or decline the message, In the future, when messages
* get big, the accept method will only take a message header
*
* @param msg
* ClusterMessage
* @return boolean - returns true to indicate that messageReceived should be
* invoked. If false is returned, the messageReceived method will
* not be invoked.
*/
@Override
public boolean accept(ClusterMessage msg) {
return (msg instanceof FileMessage) || (msg instanceof UndeployMessage);
}
/**
* Install a new web application, whose web application archive is at the
* specified URL, into this container and all the other members of the
* cluster with the specified context path. A context path of "" (the empty
* string) should be used for the root application for this container.
* Otherwise, the context path must start with a slash.
* <p>
* If this application is successfully installed locally, a ContainerEvent
* of type <code>INSTALL_EVENT</code> will be sent to all registered
* listeners, with the newly created <code>Context</code> as an argument.
*
* @param contextPath
* The context path to which this application should be installed
* (must be unique)
* @param war
* A URL of type "jar:" that points to a WAR file, or type
* "file:" that points to an unpacked directory structure
* containing the web application to be installed
*
* @exception IllegalArgumentException
* if the specified context path is malformed (it must be ""
* or start with a slash)
* @exception IllegalStateException
* if the specified context path is already attached to an
* existing web application
* @exception IOException
* if an input/output error was encountered during
* installation
*/
@Override
public void install(String contextPath, URL war) throws IOException {
Member[] members = getCluster().getMembers();
Member localMember = getCluster().getLocalMember();
FileMessageFactory factory = FileMessageFactory.getInstance(new File(
war.getFile()), false);
FileMessage msg = new FileMessage(localMember, war.getFile(),
contextPath);
if(log.isDebugEnabled())
log.debug("Send cluster war deployment [ path:"
+ contextPath + " war: " + war + " ] started.");
msg = factory.readMessage(msg);
while (msg != null) {
for (int i = 0; i < members.length; i++) {
if (log.isDebugEnabled())
log.debug("Send cluster war fragment [ path: "
+ contextPath + " war: " + war + " to: " + members[i] + " ]");
getCluster().send(msg, members[i]);
}
msg = factory.readMessage(msg);
}
if(log.isDebugEnabled())
log.debug("Send cluster war deployment [ path: "
+ contextPath + " war: " + war + " ] finished.");
}
/**
* Remove an existing web application, attached to the specified context
* path. If this application is successfully removed, a ContainerEvent of
* type <code>REMOVE_EVENT</code> will be sent to all registered
* listeners, with the removed <code>Context</code> as an argument.
* Deletes the web application war file and/or directory if they exist in
* the Host's appBase.
*
* @param contextPath
* The context path of the application to be removed
* @param undeploy
* boolean flag to remove web application from server
*
* @exception IllegalArgumentException
* if the specified context path is malformed (it must be ""
* or start with a slash)
* @exception IllegalArgumentException
* if the specified context path does not identify a
* currently installed web application
* @exception IOException
* if an input/output error occurs during removal
*/
@Override
public void remove(String contextPath, boolean undeploy) throws IOException {
if (log.isInfoEnabled())
log.info("Cluster wide remove of web app " + contextPath);
Member localMember = getCluster().getLocalMember();
UndeployMessage msg = new UndeployMessage(localMember, System
.currentTimeMillis(), "Undeploy:" + contextPath + ":"
+ System.currentTimeMillis(), contextPath, undeploy);
if (log.isDebugEnabled())
log.debug("Send cluster wide undeployment from "
+ contextPath );
cluster.send(msg);
// remove locally
if (undeploy) {
try {
if (!isServiced(contextPath)) {
addServiced(contextPath);
try {
remove(contextPath);
} finally {
removeServiced(contextPath);
}
} else
log.error("Local remove from " + contextPath
+ "failed, other manager has app in service!");
} catch (Exception ex) {
log.error("local remove from " + contextPath + " failed", ex);
}
}
}
/*
* Modification from watchDir war detected!
*
* @see org.apache.catalina.ha.deploy.FileChangeListener#fileModified(java.io.File)
*/
@Override
public void fileModified(File newWar) {
try {
File deployWar = new File(getDeployDir(), newWar.getName());
copy(newWar, deployWar);
String contextName = getContextName(deployWar);
if (log.isInfoEnabled())
log.info("Installing webapp[" + contextName + "] from "
+ deployWar.getAbsolutePath());
try {
remove(contextName, false);
} catch (Exception x) {
log.error("No removal", x);
}
install(contextName, deployWar.toURI().toURL());
} catch (Exception x) {
log.error("Unable to install WAR file", x);
}
}
/*
* War remove from watchDir
*
* @see org.apache.catalina.ha.deploy.FileChangeListener#fileRemoved(java.io.File)
*/
@Override
public void fileRemoved(File removeWar) {
try {
String contextName = getContextName(removeWar);
if (log.isInfoEnabled())
log.info("Removing webapp[" + contextName + "]");
remove(contextName, true);
} catch (Exception x) {
log.error("Unable to remove WAR file", x);
}
}
/**
* Create a context path from war
* @param war War filename
* @return '/filename' or if war name is ROOT.war context name is empty string ''
*/
protected String getContextName(File war) {
String contextName = "/"
+ war.getName().substring(0,
war.getName().lastIndexOf(".war"));
if("/ROOT".equals(contextName))
contextName= "" ;
return contextName ;
}
/**
* Return a File object representing the "application root" directory for
* our associated Host.
*/
protected File getAppBase() {
if (appBase != null) {
return appBase;
}
File file = new File(host.getAppBase());
if (!file.isAbsolute())
file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), host
.getAppBase());
try {
appBase = file.getCanonicalFile();
} catch (IOException e) {
appBase = file;
}
return (appBase);
}
/**
* Invoke the remove method on the deployer.
*/
protected void remove(String path) throws Exception {
// TODO Handle remove also work dir content !
// Stop the context first to be nicer
Context context = (Context) host.findChild(path);
if (context != null) {
if(log.isDebugEnabled())
log.debug("Undeploy local context " +path );
context.stop();
String baseName = context.getBaseName();
File war = new File(getAppBase(), baseName + ".war");
File dir = new File(getAppBase(), baseName);
File xml = new File(configBase, baseName + ".xml");
if (war.exists()) {
war.delete();
} else if (dir.exists()) {
undeployDir(dir);
} else {
xml.delete();
}
// Perform new deployment and remove internal HostConfig state
check(path);
}
}
/**
* Delete the specified directory, including all of its contents and
* subdirectories recursively.
*
* @param dir
* File object representing the directory to be deleted
*/
protected void undeployDir(File dir) {
String files[] = dir.list();
if (files == null) {
files = new String[0];
}
for (int i = 0; i < files.length; i++) {
File file = new File(dir, files[i]);
if (file.isDirectory()) {
undeployDir(file);
} else {
file.delete();
}
}
dir.delete();
}
/*
* Call watcher to check for deploy changes
*
* @see org.apache.catalina.ha.ClusterDeployer#backgroundProcess()
*/
@Override
public void backgroundProcess() {
if (started) {
count = (count + 1) % processDeployFrequency;
if (count == 0 && watchEnabled) {
watcher.check();
}
}
}
/*--Deployer Operations ------------------------------------*/
/**
* Invoke the check method on the deployer.
*/
protected void check(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
mBeanServer.invoke(oname, "check", params, signature);
}
/**
* Invoke the check method on the deployer.
*/
protected boolean isServiced(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced",
params, signature);
return result.booleanValue();
}
/**
* Invoke the check method on the deployer.
*/
protected void addServiced(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
mBeanServer.invoke(oname, "addServiced", params, signature);
}
/**
* Invoke the check method on the deployer.
*/
protected void removeServiced(String name) throws Exception {
String[] params = { name };
String[] signature = { "java.lang.String" };
mBeanServer.invoke(oname, "removeServiced", params, signature);
}
/*--Instance Getters/Setters--------------------------------*/
@Override
public CatalinaCluster getCluster() {
return cluster;
}
@Override
public void setCluster(CatalinaCluster cluster) {
this.cluster = cluster;
}
@Override
public boolean equals(Object listener) {
return super.equals(listener);
}
@Override
public int hashCode() {
return super.hashCode();
}
public String getDeployDir() {
return deployDir;
}
public void setDeployDir(String deployDir) {
this.deployDir = deployDir;
}
public String getTempDir() {
return tempDir;
}
public void setTempDir(String tempDir) {
this.tempDir = tempDir;
}
public String getWatchDir() {
return watchDir;
}
public void setWatchDir(String watchDir) {
this.watchDir = watchDir;
}
public boolean isWatchEnabled() {
return watchEnabled;
}
public boolean getWatchEnabled() {
return watchEnabled;
}
public void setWatchEnabled(boolean watchEnabled) {
this.watchEnabled = watchEnabled;
}
/**
* Return the frequency of watcher checks.
*/
public int getProcessDeployFrequency() {
return (this.processDeployFrequency);
}
/**
* Set the watcher checks frequency.
*
* @param processExpiresFrequency
* the new manager checks frequency
*/
public void setProcessDeployFrequency(int processExpiresFrequency) {
if (processExpiresFrequency <= 0) {
return;
}
this.processDeployFrequency = processExpiresFrequency;
}
/**
* Copy a file to the specified temp directory.
* @param from copy from temp
* @param to to host appBase directory
* @return true, copy successful
*/
protected boolean copy(File from, File to) {
try {
if (!to.exists())
to.createNewFile();
java.io.FileInputStream is = new java.io.FileInputStream(from);
java.io.FileOutputStream os = new java.io.FileOutputStream(to,
false);
byte[] buf = new byte[4096];
while (true) {
int len = is.read(buf);
if (len < 0)
break;
os.write(buf, 0, len);
}
is.close();
os.close();
} catch (IOException e) {
log.error("Unable to copy file from:" + from + " to:" + to, e);
return false;
}
return true;
}
}
| Fix FindBugs warning
Remove unnecessary code
Better error handling
git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1058556 13f79535-47bb-0310-9956-ffa450edef68
| java/org/apache/catalina/ha/deploy/FarmWarDeployer.java | Fix FindBugs warning Remove unnecessary code Better error handling |
|
Java | apache-2.0 | cbae8fbe3442142f48f8dc401c3e512583c88fad | 0 | Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces | /*
* Copyright 2006-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.openspaces.maven.support;
import com.j_spaces.kernel.PlatformVersion;
/**
* @author kimchy
*/
public class OutputVersion {
public static void main(String[] args) throws Exception {
String version;
if (PlatformVersion.MILESTONE.equals("GA")) {
version = PlatformVersion.VERSION;
} else {
version = PlatformVersion.VERSION + "-" + PlatformVersion.MILESTONE + PlatformVersion.BUILD_NUM;
}
System.out.println(version);
}
}
| src/main/src/org/openspaces/maven/support/OutputVersion.java | /*
* Copyright 2006-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.openspaces.maven.support;
import com.j_spaces.kernel.PlatformVersion;
/**
* @author kimchy
*/
public class OutputVersion {
public static final String VERSION;
static {
if (PlatformVersion.MILESTONE.equals("GA")) {
VERSION = PlatformVersion.VERSION;
} else {
VERSION = PlatformVersion.VERSION + "-" + PlatformVersion.MILESTONE + PlatformVersion.BUILD_NUM;
}
}
public static void main(String[] args) throws Exception {
System.out.println(VERSION);
}
}
| make the vesrion concatanation done in runtime and not static construction time
svn path=/trunk/openspaces/; revision=25808
Former-commit-id: 0f26163228ecceedc661056bc12ce8be6e897577 | src/main/src/org/openspaces/maven/support/OutputVersion.java | make the vesrion concatanation done in runtime and not static construction time |
|
Java | apache-2.0 | 13fb7d60813931e6181675e219cc7aa660d6c0b9 | 0 | sebasbaumh/gwt-three.js,sebasbaumh/gwt-three.js,sebasbaumh/gwt-three.js | package com.akjava.gwt.three.client.js.extras.controls;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.HasEnabled;
/**
* Controls for changing the position and angle of an object, e.g. a camera.
* @author sbaumhekel
*/
public class TrackballControls extends JavaScriptObject implements HasEnabled
{
/**
* Do not use.
*/
@Deprecated
protected TrackballControls()
{
}
/**
* Gets whether panning is allowed.
* @return true on success, else false
*/
public final native double getAllowPan()/*-{
return !this.noPan;
}-*/;
/**
* Gets whether rolling is allowed.
* @return true on success, else false
*/
public final native double getAllowRoll()/*-{
return !this.noRoll;
}-*/;
/**
* Gets whether rotation is allowed.
* @return true on success, else false
*/
public final native double getAllowRotate()/*-{
return !this.noRotate;
}-*/;
/**
* Gets whether zoom is allowed.
* @return true on success, else false
*/
public final native double getAllowZoom()/*-{
return !this.noZoom;
}-*/;
/**
* Gets the maximum distance of objects to be shown.
* @return maximum distance (default: {@link Double#POSITIVE_INFINITY} )
*/
public final native double getMaxDistance()/*-{
return this.maxDistance;
}-*/;
/**
* Gets the minimum distance of objects to be shown.
* @return minimum distance (default: 0)
*/
public final native double getMinDistance()/*-{
return this.minDistance;
}-*/;
/**
* Handles resizes of the parent element.
*/
public final native void handleResize()/*-{
this.handleResize();
}-*/;
/*
* (non-Javadoc)
* @see com.google.gwt.user.client.ui.HasEnabled#isEnabled()
*/
@Override
public final native boolean isEnabled()/*-{
return this.enabled;
}-*/;
/**
* Resets the current control state.
*/
public final native void reset()/*-{
this.reset();
}-*/;
/**
* Sets whether panning is allowed.
* @param allow allow panning
*/
public final native void setAllowPan(boolean allow)/*-{
this.noPan = !allow;
}-*/;
/**
* Sets whether rolling is allowed.
* @param allow allow rolling
*/
public final native void setAllowRoll(boolean allow)/*-{
this.noRoll = !allow;
}-*/;
/**
* Sets whether rotation is allowed.
* @param allow allow rotation
*/
public final native void setAllowRotate(boolean allow)/*-{
this.noRotate = !allow;
}-*/;
/**
* Sets whether zoom is allowed.
* @param allow allow zoom
*/
public final native void setAllowZoom(boolean allow)/*-{
this.noZoom = !allow;
}-*/;
/*
* (non-Javadoc)
* @see com.google.gwt.user.client.ui.HasEnabled#setEnabled(boolean)
*/
@Override
public final native void setEnabled(boolean enabled)/*-{
this.enabled = enabled;
}-*/;
/**
* Sets the maximum distance of objects to be shown.
* @param maxDistance maximum distance {@link Double#POSITIVE_INFINITY}
*/
public final native void setMaxDistance(double maxDistance)/*-{
this.maxDistance = maxDistance;
}-*/;
/**
* Sets the minimum distance of objects to be shown.
* @param minDistance minimum distance (default: 0)
*/
public final native void setMinDistance(double minDistance)/*-{
this.minDistance = minDistance;
}-*/;
/**
* Updates the current control state.
*/
public final native void update()/*-{
this.update();
}-*/;
}
| src/com/akjava/gwt/three/client/js/extras/controls/TrackballControls.java | package com.akjava.gwt.three.client.js.extras.controls;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.ui.HasEnabled;
/**
* Controls for changing the position and angle of an object, e.g. a camera.
* @author sbaumhekel
*/
public class TrackballControls extends JavaScriptObject implements HasEnabled
{
/**
* Do not use.
*/
@Deprecated
protected TrackballControls()
{
}
/**
* Gets whether panning is allowed.
* @return true on success, else false
*/
public final native double getAllowPan()/*-{
return !this.noPan;
}-*/;
/**
* Gets whether rotation is allowed.
* @return true on success, else false
*/
public final native double getAllowRotate()/*-{
return !this.noRotate;
}-*/;
/**
* Gets whether zoom is allowed.
* @return true on success, else false
*/
public final native double getAllowZoom()/*-{
return !this.noZoom;
}-*/;
/**
* Gets the maximum distance of objects to be shown.
* @return maximum distance (default: {@link Double#POSITIVE_INFINITY} )
*/
public final native double getMaxDistance()/*-{
return this.maxDistance;
}-*/;
/**
* Gets the minimum distance of objects to be shown.
* @return minimum distance (default: 0)
*/
public final native double getMinDistance()/*-{
return this.minDistance;
}-*/;
/**
* Handles resizes of the parent element.
*/
public final native void handleResize()/*-{
this.handleResize();
}-*/;
/*
* (non-Javadoc)
* @see com.google.gwt.user.client.ui.HasEnabled#isEnabled()
*/
@Override
public final native boolean isEnabled()/*-{
return this.enabled;
}-*/;
/**
* Resets the current control state.
*/
public final native void reset()/*-{
this.reset();
}-*/;
/**
* Sets whether panning is allowed.
* @param allow allow panning
*/
public final native void setAllowPan(boolean allow)/*-{
this.noPan = !allow;
}-*/;
/**
* Sets whether rotation is allowed.
* @param allow allow rotation
*/
public final native void setAllowRotate(boolean allow)/*-{
this.noRotate = !allow;
}-*/;
/**
* Sets whether zoom is allowed.
* @param allow allow zoom
*/
public final native void setAllowZoom(boolean allow)/*-{
this.noZoom = !allow;
}-*/;
/*
* (non-Javadoc)
* @see com.google.gwt.user.client.ui.HasEnabled#setEnabled(boolean)
*/
@Override
public final native void setEnabled(boolean enabled)/*-{
this.enabled = enabled;
}-*/;
/**
* Sets the maximum distance of objects to be shown.
* @param maxDistance maximum distance {@link Double#POSITIVE_INFINITY}
*/
public final native void setMaxDistance(double maxDistance)/*-{
this.maxDistance = maxDistance;
}-*/;
/**
* Sets the minimum distance of objects to be shown.
* @param minDistance minimum distance (default: 0)
*/
public final native void setMinDistance(double minDistance)/*-{
this.minDistance = minDistance;
}-*/;
/**
* Updates the current control state.
*/
public final native void update()/*-{
this.update();
}-*/;
}
| allow rolling with latest three.js.
| src/com/akjava/gwt/three/client/js/extras/controls/TrackballControls.java | allow rolling with latest three.js. |
|
Java | apache-2.0 | 2383a838fc74d444df128fe6bf5e7d0a2b33a573 | 0 | protyposis/Spectaculum,protyposis/MediaPlayer-Extended,protyposis/MediaPlayer-Extended,protyposis/Spectaculum | /*
* Copyright (c) 2014 Mario Guggenberger <[email protected]>
*
* This file is part of ITEC MediaPlayer.
*
* ITEC MediaPlayer 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.
*
* ITEC MediaPlayer 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 ITEC MediaPlayer. If not, see <http://www.gnu.org/licenses/>.
*/
package at.aau.itec.android.mediaplayer;
import android.content.Context;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
/**
* Created by maguggen on 04.06.2014.
*/
public class MediaPlayer {
private static final String TAG = MediaPlayer.class.getSimpleName();
public enum SeekMode {
/**
* Seeks to the previous sync point. Fastest seek mode.
*/
FAST,
/**
* Seeks to the exact frame if the seek time equals the frame time, else
* to the following frame; this means that it will often seek one frame too far.
*/
PRECISE,
/**
* Always seeks to the exact frame. Can cost maximally twice the time than the PRECISE mode.
*/
EXACT,
/**
* Always seeks to the exact frame by skipping the decoding of all frames between the sync
* and target frame, because of which it can result in block artifacts.
*/
FAST_EXACT
}
private SeekMode mSeekMode = SeekMode.EXACT;
private Surface mSurface;
private SurfaceHolder mSurfaceHolder;
private MediaExtractor mVideoExtractor;
private MediaExtractor mAudioExtractor;
private int mVideoTrackIndex;
private MediaFormat mVideoFormat;
private long mVideoMinPTS;
private MediaCodec mVideoCodec;
private int mAudioTrackIndex;
private MediaFormat mAudioFormat;
private long mAudioMinPTS;
private MediaCodec mAudioCodec;
private int mAudioSessionId;
private PlaybackThread mPlaybackThread;
private long mCurrentPosition;
private boolean mSeeking;
private long mSeekTargetTime;
private boolean mSeekPrepare;
private int mBufferPercentage;
private TimeBase mTimeBase;
private EventHandler mEventHandler;
private OnPreparedListener mOnPreparedListener;
private OnCompletionListener mOnCompletionListener;
private OnSeekListener mOnSeekListener;
private OnSeekCompleteListener mOnSeekCompleteListener;
private OnErrorListener mOnErrorListener;
private OnInfoListener mOnInfoListener;
private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
private OnBufferingUpdateListener mOnBufferingUpdateListener;
private PowerManager.WakeLock mWakeLock = null;
private boolean mScreenOnWhilePlaying;
private boolean mStayAwake;
private boolean mIsStopping;
public MediaPlayer() {
mPlaybackThread = null;
mEventHandler = new EventHandler();
mTimeBase = new TimeBase();
}
public void setDataSource(MediaSource source) throws IOException {
mVideoExtractor = source.getVideoExtractor();
mAudioExtractor = source.getAudioExtractor();
mVideoTrackIndex = -1;
mAudioTrackIndex = -1;
for (int i = 0; i < mVideoExtractor.getTrackCount(); ++i) {
MediaFormat format = mVideoExtractor.getTrackFormat(i);
Log.d(TAG, format.toString());
String mime = format.getString(MediaFormat.KEY_MIME);
if (mVideoTrackIndex < 0 && mime.startsWith("video/")) {
mVideoExtractor.selectTrack(i);
mVideoTrackIndex = i;
mVideoFormat = format;
mVideoMinPTS = mVideoExtractor.getSampleTime();
} else if (mAudioExtractor == null && mAudioTrackIndex < 0 && mime.startsWith("audio/")) {
mVideoExtractor.selectTrack(i);
mAudioTrackIndex = i;
mAudioFormat = format;
mAudioMinPTS = mVideoExtractor.getSampleTime();
}
}
if(mAudioExtractor != null) {
for (int i = 0; i < mAudioExtractor.getTrackCount(); ++i) {
MediaFormat format = mAudioExtractor.getTrackFormat(i);
Log.d(TAG, format.toString());
String mime = format.getString(MediaFormat.KEY_MIME);
if (mAudioTrackIndex < 0 && mime.startsWith("audio/")) {
mAudioExtractor.selectTrack(i);
mAudioTrackIndex = i;
mAudioFormat = format;
mAudioMinPTS = mAudioExtractor.getSampleTime();
}
}
}
if(mVideoFormat == null) {
throw new IOException("no video track found");
} else {
if(mAudioFormat == null) {
Log.i(TAG, "no audio track found");
}
if(mPlaybackThread == null) {
if (mSurface == null) {
Log.i(TAG, "no video output surface specified");
}
mPlaybackThread = new PlaybackThread();
mPlaybackThread.start();
}
}
}
/**
* @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri, java.util.Map)
* @deprecated only for compatibility with Android API
*/
@Deprecated
public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException {
setDataSource(new UriSource(context, uri, headers));
}
/**
* @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri)
* @deprecated only for compatibility with Android API
*/
@Deprecated
public void setDataSource(Context context, Uri uri) throws IOException {
setDataSource(context, uri, null);
}
/**
* @see android.media.MediaPlayer#setDisplay(android.view.SurfaceHolder)
*/
public void setDisplay(SurfaceHolder sh) {
mSurfaceHolder = sh;
if (sh != null) {
mSurface = sh.getSurface();
} else {
mSurface = null;
}
updateSurfaceScreenOn();
}
/**
* @see android.media.MediaPlayer#setSurface(android.view.Surface)
*/
public void setSurface(Surface surface) {
mSurface = surface;
if (mScreenOnWhilePlaying && surface != null) {
Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
}
mSurfaceHolder = null;
updateSurfaceScreenOn();
}
public void start() {
mPlaybackThread.play();
stayAwake(true);
}
public void pause() {
mPlaybackThread.pause();
stayAwake(false);
}
public SeekMode getSeekMode() {
return mSeekMode;
}
public void setSeekMode(SeekMode seekMode) {
this.mSeekMode = seekMode;
}
private void seekToInternal(long usec) {
/* A seek needs to be performed in the decoding thread to execute commands in the correct
* order. Otherwise it can happen that, after a seek in the media decoder, seeking procedure
* starts, then a frame is decoded, and then the codec is flushed; the PTS of the decoded frame
* then interferes the seeking procedure, the seek stops prematurely and a wrong waiting time
* gets calculated. */
Log.d(TAG, "seekTo " + usec);
// inform the decoder thread of an upcoming seek
mSeekPrepare = true;
mSeekTargetTime = Math.max(mVideoMinPTS, usec);
// if the decoder is paused, wake it up for the seek
if(mPlaybackThread.isPaused()) {
mPlaybackThread.play();
mPlaybackThread.pause();
}
}
public void seekTo(long usec) {
if (mOnSeekListener != null) {
mOnSeekListener.onSeek(MediaPlayer.this);
}
seekToInternal(usec);
}
public void seekTo(int msec) {
seekTo(msec * 1000L);
}
/**
* Sets the playback speed. Can be used for fast forward and slow motion.
* speed 0.5 = half speed / slow motion
* speed 2.0 = double speed / fast forward
*/
public void setPlaybackSpeed(float speed) {
mTimeBase.setSpeed(speed);
mTimeBase.startAt(mCurrentPosition);
}
public float getPlaybackSpeed() {
return (float)mTimeBase.getSpeed();
}
public boolean isPlaying() {
return mPlaybackThread != null && !mPlaybackThread.isPaused();
}
public void stop() {
if(mPlaybackThread != null) {
mIsStopping = true;
mPlaybackThread.interrupt();
try {
mPlaybackThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "error waiting for playback thread to die", e);
}
mPlaybackThread = null;
}
stayAwake(false);
}
public void release() {
stop();
}
public void reset() {
stop();
}
/**
* @see android.media.MediaPlayer#setWakeMode(android.content.Context, int)
*/
public void setWakeMode(Context context, int mode) {
boolean washeld = false;
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
washeld = true;
mWakeLock.release();
}
mWakeLock = null;
}
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
mWakeLock.setReferenceCounted(false);
if (washeld) {
mWakeLock.acquire();
}
}
/**
* @see android.media.MediaPlayer#setScreenOnWhilePlaying(boolean)
*/
public void setScreenOnWhilePlaying(boolean screenOn) {
if (mScreenOnWhilePlaying != screenOn) {
if (screenOn && mSurfaceHolder == null) {
Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
}
mScreenOnWhilePlaying = screenOn;
updateSurfaceScreenOn();
}
}
private void stayAwake(boolean awake) {
if (mWakeLock != null) {
if (awake && !mWakeLock.isHeld()) {
mWakeLock.acquire();
} else if (!awake && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
mStayAwake = awake;
updateSurfaceScreenOn();
}
private void updateSurfaceScreenOn() {
if (mSurfaceHolder != null) {
mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
}
}
public int getDuration() {
return mVideoFormat != null ? (int)(mVideoFormat.getLong(MediaFormat.KEY_DURATION)/1000) : 0;
}
public int getCurrentPosition() {
/* During a seek, return the temporary seek target time; otherwise a seek bar doesn't
* update to the selected seek position until the seek is finished (which can take a
* while in exact mode). */
return (int)((mSeekPrepare || mSeeking ? mSeekTargetTime : mCurrentPosition)/1000);
}
public int getBufferPercentage() {
return mBufferPercentage;
}
public int getVideoWidth() {
return mVideoFormat != null ? (int)(mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT)
* mVideoFormat.getFloat(MediaExtractor.MEDIA_FORMAT_EXTENSION_KEY_DAR)) : 0;
}
public int getVideoHeight() {
return mVideoFormat != null ? mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT) : 0;
}
/**
* @see android.media.MediaPlayer#setAudioSessionId(int)
*/
public void setAudioSessionId(int sessionId) {
mAudioSessionId = sessionId;
}
/**
* @see android.media.MediaPlayer#getAudioSessionId()
*/
public int getAudioSessionId() {
return mAudioSessionId;
}
private class PlaybackThread extends Thread {
private final long mTimeOutUs = 500000;
private ByteBuffer[] mVideoCodecInputBuffers;
private ByteBuffer[] mVideoCodecOutputBuffers;
private ByteBuffer[] mAudioCodecInputBuffers;
private ByteBuffer[] mAudioCodecOutputBuffers;
private MediaCodec.BufferInfo mVideoInfo;
private MediaCodec.BufferInfo mAudioInfo;
private boolean mPaused;
private boolean mVideoInputEos;
private boolean mVideoOutputEos;
private boolean mAudioInputEos;
private boolean mAudioOutputEos;
private boolean mBuffering;
private AudioPlayback mAudioPlayback;
/* Flag notifying that the representation has changed in the extractor and needs to be passed
* to the decoder. This transition state is only needed in playback, not when seeking. */
private boolean mRepresentationChanging;
/* Flag notifying that the decoder has changed to a new representation, post-actions need to
* be carried out. */
private boolean mRepresentationChanged;
private PlaybackThread() {
super(TAG);
mPaused = true;
}
public void pause() {
mPaused = true;
}
public void play() {
mPaused = false;
synchronized (this) {
notify();
}
}
public boolean isPaused() {
return mPaused;
}
@Override
public void run() {
try {
mVideoCodec = MediaCodec.createDecoderByType(mVideoFormat.getString(MediaFormat.KEY_MIME));
mVideoCodec.configure(mVideoFormat, mSurface, null, 0);
mVideoCodec.start();
mVideoCodecInputBuffers = mVideoCodec.getInputBuffers();
mVideoCodecOutputBuffers = mVideoCodec.getOutputBuffers();
mVideoInfo = new MediaCodec.BufferInfo();
mVideoInputEos = false;
mVideoOutputEos = false;
if(mAudioFormat != null) {
mAudioCodec = MediaCodec.createDecoderByType(mAudioFormat.getString(MediaFormat.KEY_MIME));
mAudioCodec.configure(mAudioFormat, null, null, 0);
mAudioCodec.start();
mAudioCodecInputBuffers = mAudioCodec.getInputBuffers();
mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
mAudioInfo = new MediaCodec.BufferInfo();
mAudioInputEos = false;
mAudioOutputEos = false;
mAudioPlayback = new AudioPlayback();
mAudioPlayback.setAudioSessionId(mAudioSessionId);
mAudioPlayback.init(mAudioFormat);
mAudioSessionId = mAudioPlayback.getAudioSessionId();
}
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE,
getVideoWidth(), getVideoHeight()));
mBuffering = false;
boolean preparing = true; // used on startup to process stream until the first frame
int frameSkipCount = 0;
long lastPTS = 0;
// Initialize the time base with the first PTS that must not necessarily be 0
mTimeBase.startAt(mVideoMinPTS);
while (!mVideoOutputEos) {
if (mPaused && !mSeekPrepare && !mSeeking && !preparing) {
if(mAudioPlayback != null) mAudioPlayback.pause();
synchronized (this) {
while (mPaused && !mSeekPrepare && !mSeeking) {
this.wait();
}
}
if(mAudioPlayback != null) mAudioPlayback.play();
// reset time (otherwise playback tries to "catch up" time after a pause)
mTimeBase.startAt(mVideoInfo.presentationTimeUs);
}
// For a seek, first prepare by seeking the media extractor and flushing the codec.
/* This needs to be in a loop, because the seek inside this block can take some
* time, meanwhile another seek can be issued. The following seek can update the seek
* target while the video extractor is still seeking, which can turn into a problem
* with DASH when the second target is not within the first requested segment - in
* which case the seek cannot find the new target in the old segment. By checking
* if a seek needs to be prepared after the video extractor seek has finished (which
* means another seek hat been issued), it can be run again and again while new
* seek targets come in, until the target finally stays the same during a seek.
*/
while (mSeekPrepare) {
mSeekPrepare = false;
mSeeking = true;
Log.d(TAG, "seeking to: " + mSeekTargetTime);
Log.d(TAG, "frame current position: " + mCurrentPosition);
Log.d(TAG, "extractor current position: " + mVideoExtractor.getSampleTime());
mVideoExtractor.seekTo(mSeekTargetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
mCurrentPosition = mSeekTargetTime;
Log.d(TAG, "extractor new position: " + mVideoExtractor.getSampleTime());
if(mSeekPrepare) {
// Another seek has been issued in the meantime, repeat this block
continue;
}
mVideoInputEos = false;
mVideoOutputEos = false;
mAudioInputEos = false;
mAudioOutputEos = false;
mVideoCodec.flush();
if (mAudioFormat != null) mAudioCodec.flush();
if(mVideoExtractor.hasTrackFormatChanged()) {
reinitCodecs();
mRepresentationChanged = true;
}
if(mSeekMode == SeekMode.FAST_EXACT) {
/* Check if the seek target time after the seek is the same as before the
* seek. If not, a new seek has been issued in the meantime; the current
* one must be discarded and a new seek with the new target time started.
*/
long in;
long out;
do {
in = mSeekTargetTime;
out = fastSeek(in);
} while (in != mSeekTargetTime);
mSeekTargetTime = out;
mSeekPrepare = false;
}
}
if (!mVideoInputEos && !mRepresentationChanging) {
queueMediaSampleToCodec(mSeeking);
}
lastPTS = mVideoInfo.presentationTimeUs;
int res = mVideoCodec.dequeueOutputBuffer(mVideoInfo, mTimeOutUs);
mVideoOutputEos = res >= 0 && (mVideoInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
if(mVideoOutputEos && mRepresentationChanging) {
/* Here, the video output is not really at its end, it's just the end of the
* current representation segment, and the codec needs to be reconfigured to
* the following representation format to carry on.
*/
reinitCodecs();
mVideoOutputEos = false;
mRepresentationChanging = false;
mRepresentationChanged = true;
}
else if (res >= 0) {
int outputBufIndex = res;
boolean render = true;
//ByteBuffer buf = codecOutputBuffers[outputBufIndex];
//Log.d(TAG, "pts=" + info.presentationTimeUs);
if (mSeeking) {
if(mVideoOutputEos) {
/* When the end of stream is reached while seeking, the seek target
* time is set to the last frame's PTS, else the seek skips the last
* frame which then does not get rendered, and it might end up in a
* loop trying to reach the unreachable target time. */
mSeekTargetTime = mVideoInfo.presentationTimeUs;
}
/* NOTE
* This code seeks one frame too far, except if the seek time equals the
* frame PTS:
* (F1.....)(F2.....)(F3.....) ... (Fn.....)
* A frame is shown for an interval, e.g. (1/fps seconds). Now if the seek
* target time is somewhere in frame 2's interval, we end up with frame 3
* because we need to decode it to know if the seek target time lies in
* frame 2's interval (because we don't know the frame rate of the video,
* and neither if it's a fixed frame rate or a variable one - even when
* deriving it from the PTS series we cannot be sure about it). This means
* we always end up one frame too far, because the MediaCodec does not allow
* to go back, except when starting at a sync frame.
*
* Solution for fixed frame rate could be to subtract the frame interval
* time (1/fps secs) from the seek target time.
*
* Solution for variable frame rate and unknown frame rate: go back to sync
* frame and re-seek to the now known exact PTS of the desired frame.
* See EXACT mode handling below.
*/
/* Android API compatibility:
* Use millisecond precision to stay compatible with VideoView API that works
* in millisecond precision only. Else, exact seek matches are missed if frames
* are positioned at fractions of a millisecond. */
long presentationTimeMs = mVideoInfo.presentationTimeUs / 1000;
long seekTargetTimeMs = mSeekTargetTime / 1000;
if ((mSeekMode == SeekMode.PRECISE || mSeekMode == SeekMode.EXACT) && presentationTimeMs < seekTargetTimeMs) {
// this is not yet the aimed time so we skip rendering of this frame
render = false;
if(frameSkipCount == 0) {
Log.d(TAG, "skipping frames...");
}
frameSkipCount++;
} else {
Log.d(TAG, "frame new position: " + mVideoInfo.presentationTimeUs);
Log.d(TAG, "seeking finished, skipped " + frameSkipCount + " frames");
frameSkipCount = 0;
if(mSeekMode == SeekMode.EXACT && presentationTimeMs > seekTargetTimeMs) {
/* If the current frame's PTS it after the seek target time, we're
* one frame too far into the stream. This is because we do not know
* the frame rate of the video and therefore can't decide for a frame
* if its interval covers the seek target time of if there's already
* another frame coming. We know after the next frame has been
* decoded though if we're too far into the stream, and if so, and if
* EXACT mode is desired, we need to take the previous frame's PTS
* and repeat the seek with that PTS to arrive at the desired frame.
*/
Log.d(TAG, "exact seek: repeat seek for previous frame at " + lastPTS);
render = false;
seekToInternal(lastPTS);
} else {
if(presentationTimeMs == seekTargetTimeMs) {
Log.d(TAG, "exact seek match!");
}
if(mSeekMode == SeekMode.FAST_EXACT && mVideoInfo.presentationTimeUs < mSeekTargetTime) {
// this should only ever happen in fastseek mode, else it FFWs in fast mode
Log.d(TAG, "presentation is behind, another try...");
} else {
// reset time to keep frame rate constant (otherwise it's too fast on back seeks and waits for the PTS time on fw seeks)
mTimeBase.startAt(mVideoInfo.presentationTimeUs);
mCurrentPosition = mVideoInfo.presentationTimeUs;
mSeeking = false;
if(mAudioExtractor != null) {
mAudioExtractor.seekTo(mVideoInfo.presentationTimeUs, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
mAudioPlayback.flush();
}
mEventHandler.sendEmptyMessage(MEDIA_SEEK_COMPLETE);
}
}
}
} else {
mCurrentPosition = mVideoInfo.presentationTimeUs;
long waitingTime = mTimeBase.getOffsetFrom(mVideoInfo.presentationTimeUs);
if(mAudioFormat != null) {
long audioOffsetUs = mAudioPlayback.getLastPresentationTimeUs() - mCurrentPosition;
// Log.d(TAG, "VideoPTS=" + mCurrentPosition
// + " AudioPTS=" + mAudioPlayback.getLastPresentationTimeUs()
// + " offset=" + audioOffsetUs);
/* Synchronize the video frame PTS to the audio PTS by slowly adjusting
* the video frame waiting time towards a better synchronization.
* Directly correcting the video waiting time by the audio offset
* introduces too much jitter and leads to juddering video playback.
*/
long audioOffsetCorrectionUs = 10000;
if (audioOffsetUs > audioOffsetCorrectionUs) {
waitingTime -= audioOffsetCorrectionUs;
} else if(audioOffsetUs < -audioOffsetCorrectionUs) {
waitingTime += audioOffsetCorrectionUs;
}
mAudioPlayback.setPlaybackSpeed((float)mTimeBase.getSpeed());
}
//Log.d(TAG, "waiting time = " + waitingTime);
/* If this is an online stream, notify the client of the buffer fill level.
* The cached duration from the MediaExtractor returns the cached time from
* the current position onwards, but the Android mediaPlayer returns the
* total time consisting fo the current playback point and the length of
* the prefetched data.
*/
long cachedDuration = mVideoExtractor.getCachedDuration();
if(cachedDuration != -1) {
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_BUFFERING_UPDATE,
(int) (100d / mVideoFormat.getLong(MediaFormat.KEY_DURATION) * (mCurrentPosition + cachedDuration)), 0));
}
// slow down playback, if necessary, to keep frame rate
if (!preparing && waitingTime > 5000) {
// sleep until it's time to render the next frame
// TODO find better alternative to sleep
// The sleep takes much longer than expected, leading to playback
// jitter, and depending on the structure of a container and the
// data sequence, dropouts in the audio playback stream.
Thread.sleep(waitingTime / 1000);
} else if(!preparing && waitingTime < 0) {
// we weed to catch up time by skipping rendering of this frame
// this doesn't gain enough time if playback speed is too high and decoder at full load
// TODO improve fast forward mode
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_VIDEO_TRACK_LAGGING, 0));
mTimeBase.startAt(mVideoInfo.presentationTimeUs);
}
}
if(mBuffering) {
mBuffering = false;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_BUFFERING_END, 0));
}
/* Defer the video size changed message until the first frame of the new
* size is being rendered. */
if(mRepresentationChanged && render) {
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE,
getVideoWidth(), getVideoHeight()));
mRepresentationChanged = false;
}
mVideoCodec.releaseOutputBuffer(outputBufIndex, render); // render picture
if (mAudioFormat != null & mAudioExtractor != null && !mSeeking && !mPaused) {
// TODO rewrite; this is just a quick and dirty hack
long start = SystemClock.elapsedRealtime();
while (mAudioPlayback.getBufferTimeUs() < 100000) {
if (queueAudioSampleToCodec(mAudioExtractor)) {
decodeAudioSample();
} else {
break;
}
}
//Log.d(TAG, "audio stream decode time " + (SystemClock.elapsedRealtime() - start));
}
if (preparing) {
mEventHandler.sendEmptyMessage(MEDIA_PREPARED);
preparing = false;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_VIDEO_RENDERING_START, 0));
}
if (mVideoOutputEos) {
Log.d(TAG, "EOS video output");
mEventHandler.sendEmptyMessage(MEDIA_PLAYBACK_COMPLETE);
/* When playback reached the end of the stream and the last frame is
* displayed, we go into paused state instead of finishing the thread
* and wait until a new start or seek command is arriving. If no
* command arrives, the thread stays sleeping until the player is
* stopped.
*/
mPaused = true;
synchronized (this) {
if(mAudioPlayback != null) mAudioPlayback.pause();
while (mPaused && !mSeeking && !mSeekPrepare) {
this.wait();
}
if(mAudioPlayback != null) mAudioPlayback.play();
// reset these flags so playback can continue
mVideoInputEos = false;
mVideoOutputEos = false;
mAudioInputEos = false;
mAudioOutputEos = false;
// if no seek command but a start command arrived, seek to the start
if(!mSeeking && !mSeekPrepare) {
seekToInternal(0);
}
}
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
mVideoCodecOutputBuffers = mVideoCodec.getOutputBuffers();
Log.d(TAG, "output buffers have changed.");
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
// NOTE: this is the format of the raw video output, not the video format as specified by the container
MediaFormat oformat = mVideoCodec.getOutputFormat();
Log.d(TAG, "output format has changed to " + oformat);
} else if (res == MediaCodec.INFO_TRY_AGAIN_LATER) {
Log.d(TAG, "dequeueOutputBuffer timed out");
}
}
} catch (InterruptedException e) {
Log.d(TAG, "decoder interrupted");
interrupt();
if(mIsStopping) {
// An intentional stop does not trigger an error message
mIsStopping = false;
} else {
// Unexpected interruption, send error message
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR,
MEDIA_ERROR_UNKNOWN, 0));
}
} catch (IllegalStateException e) {
Log.e(TAG, "decoder error, too many instances?", e);
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR,
MEDIA_ERROR_UNKNOWN, 0));
} catch (IOException e) {
Log.e(TAG, "decoder error, codec can not be created", e);
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR,
MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_IO));
}
if(mAudioPlayback != null) mAudioPlayback.stopAndRelease();
mVideoCodec.stop();
mVideoCodec.release();
if(mAudioFormat != null) {
mAudioCodec.stop();
mAudioCodec.release();
}
mVideoExtractor.release();
Log.d(TAG, "decoder released");
}
private boolean queueVideoSampleToCodec() {
/* NOTE the track index checks only for debugging
* when enabled, they prevent the EOS detection and handling below */
// int trackIndex = mVideoExtractor.getSampleTrackIndex();
// if(trackIndex == -1) {
// throw new IllegalStateException("EOS");
// }
// if(trackIndex != mVideoTrackIndex) {
// throw new IllegalStateException("wrong track index: " + trackIndex);
// }
boolean sampleQueued = false;
int inputBufIndex = mVideoCodec.dequeueInputBuffer(mTimeOutUs);
if (inputBufIndex >= 0) {
ByteBuffer inputBuffer = mVideoCodecInputBuffers[inputBufIndex];
int sampleSize = mVideoExtractor.readSampleData(inputBuffer, 0);
long presentationTimeUs = 0;
if(sampleSize == 0) {
if(mVideoExtractor.getCachedDuration() == 0) {
mBuffering = true;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_BUFFERING_START, 0));
}
if(mVideoExtractor.hasTrackFormatChanged()) {
/* The mRepresentationChanging flag and BUFFER_FLAG_END_OF_STREAM flag together
* notify the decoding loop that the representation changes and the codec
* needs to be reconfigured.
*/
mRepresentationChanging = true;
mVideoCodec.queueInputBuffer(inputBufIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
}
} else {
if (sampleSize < 0) {
Log.d(TAG, "EOS video input");
mVideoInputEos = true;
sampleSize = 0;
} else {
presentationTimeUs = mVideoExtractor.getSampleTime();
sampleQueued = true;
}
mVideoCodec.queueInputBuffer(
inputBufIndex,
0,
sampleSize,
presentationTimeUs,
mVideoInputEos ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!mVideoInputEos) {
mVideoExtractor.advance();
}
}
}
return sampleQueued;
}
private boolean queueAudioSampleToCodec(MediaExtractor extractor) {
if(mAudioCodec == null) {
throw new IllegalStateException("no audio track configured");
}
/* NOTE the track index checks only for debugging
* when enabled, they prevent the EOS detection and handling below */
// int trackIndex = extractor.getSampleTrackIndex();
// if(trackIndex == -1) {
// throw new IllegalStateException("EOS");
// }
// if(trackIndex != mAudioTrackIndex) {
// throw new IllegalStateException("wrong track index: " + trackIndex);
// }
boolean sampleQueued = false;
int inputBufIndex = mAudioCodec.dequeueInputBuffer(mTimeOutUs);
if (inputBufIndex >= 0) {
ByteBuffer inputBuffer = mAudioCodecInputBuffers[inputBufIndex];
int sampleSize = extractor.readSampleData(inputBuffer, 0);
long presentationTimeUs = 0;
if (sampleSize < 0) {
Log.d(TAG, "EOS audio input");
mAudioInputEos = true;
sampleSize = 0;
} else if(sampleSize == 0) {
if(extractor.getCachedDuration() == 0) {
mBuffering = true;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_BUFFERING_START, 0));
}
} else {
presentationTimeUs = extractor.getSampleTime();
sampleQueued = true;
}
mAudioCodec.queueInputBuffer(
inputBufIndex,
0,
sampleSize,
presentationTimeUs,
mAudioInputEos ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!mAudioInputEos) {
extractor.advance();
}
}
return sampleQueued;
}
private void decodeAudioSample() {
int output = mAudioCodec.dequeueOutputBuffer(mAudioInfo, mTimeOutUs);
if (output >= 0) {
// http://bigflake.com/mediacodec/#q11
ByteBuffer outputData = mAudioCodecOutputBuffers[output];
if (mAudioInfo.size != 0) {
outputData.position(mAudioInfo.offset);
outputData.limit(mAudioInfo.offset + mAudioInfo.size);
//Log.d(TAG, "raw audio data bytes: " + mVideoInfo.size);
}
mAudioPlayback.write(outputData, mAudioInfo.presentationTimeUs);
mAudioCodec.releaseOutputBuffer(output, false);
if ((mAudioInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
mAudioOutputEos = true;
Log.d(TAG, "EOS audio output");
}
} else if (output == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
Log.d(TAG, "audio output buffers have changed.");
mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
} else if (output == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
MediaFormat format = mAudioCodec.getOutputFormat();
Log.d(TAG, "audio output format has changed to " + format);
mAudioPlayback.init(format);
} else if (output == MediaCodec.INFO_TRY_AGAIN_LATER) {
Log.d(TAG, "audio dequeueOutputBuffer timed out");
}
}
private boolean queueMediaSampleToCodec(boolean videoOnly) {
boolean result = false;
if(mAudioCodec != null) {
if (videoOnly) {
/* VideoOnly mode skips audio samples, e.g. while doing a seek operation. */
int trackIndex;
while ((trackIndex = mVideoExtractor.getSampleTrackIndex()) != -1 && trackIndex != mVideoTrackIndex && !mVideoInputEos) {
mVideoExtractor.advance();
}
} else {
while (mAudioExtractor == null && mVideoExtractor.getSampleTrackIndex() == mAudioTrackIndex) {
result = queueAudioSampleToCodec(mVideoExtractor);
decodeAudioSample();
}
}
}
if(!mVideoInputEos) {
result = queueVideoSampleToCodec();
}
return result;
}
private long fastSeek(long targetTime) throws IOException {
mVideoCodec.flush();
if(mAudioFormat != null) mAudioCodec.flush();
mVideoExtractor.seekTo(targetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
if(mVideoExtractor.getSampleTime() == targetTime) {
Log.d(TAG, "skip fastseek, already there");
return targetTime;
}
// 1. Queue first sample which should be the sync/I frame
queueMediaSampleToCodec(true);
// 2. Then, fast forward to target frame
/* 2.1 Search for the best candidate frame, which is the one whose
* right/positive/future distance is minimized
*/
mVideoExtractor.seekTo(targetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
/* Specifies how many frames we continue to check after the first candidate,
* to account for DTS picture reordering (this value is arbitrarily chosen) */
int maxFrameLookahead = 20;
long candidatePTS = 0;
long candidateDistance = Long.MAX_VALUE;
int lookaheadCount = 0;
while (mVideoExtractor.advance() && lookaheadCount < maxFrameLookahead) {
long distance = targetTime - mVideoExtractor.getSampleTime();
if (distance >= 0 && distance < candidateDistance) {
candidateDistance = distance;
candidatePTS = mVideoExtractor.getSampleTime();
//Log.d(TAG, "candidate " + candidatePTS + " d=" + candidateDistance);
}
if (distance < 0) {
lookaheadCount++;
}
}
targetTime = candidatePTS; // set best candidate frame as exact seek target
// 2.2 Fast forward to chosen candidate frame
mVideoExtractor.seekTo(targetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
while (mVideoExtractor.getSampleTime() != targetTime) {
mVideoExtractor.advance();
}
Log.d(TAG, "exact fastseek match: " + mVideoExtractor.getSampleTime());
return targetTime;
}
/**
* Restarts the codecs with a new format, e.g. after a representation change.
*/
private void reinitCodecs() {
long t1 = SystemClock.elapsedRealtime();
// Get new video format and restart video codec with this format
mVideoFormat = mVideoExtractor.getTrackFormat(mVideoTrackIndex);
mVideoCodec.stop();
mVideoCodec.configure(mVideoFormat, mSurface, null, 0);
mVideoCodec.start();
mVideoCodecInputBuffers = mVideoCodec.getInputBuffers();
mVideoCodecOutputBuffers = mVideoCodec.getOutputBuffers();
if(mAudioFormat != null) {
mAudioCodec.stop();
mAudioCodec.configure(mAudioFormat, null, null, 0);
mAudioCodec.start();
mAudioCodecInputBuffers = mAudioCodec.getInputBuffers();
mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
}
Log.d(TAG, "reinitCodecs " + (SystemClock.elapsedRealtime() - t1) + "ms");
}
}
/**
* Interface definition for a callback to be invoked when the media
* source is ready for playback.
*/
public interface OnPreparedListener {
/**
* Called when the media file is ready for playback.
* @param mp the MediaPlayer that is ready for playback
*/
void onPrepared(MediaPlayer mp);
}
/**
* Register a callback to be invoked when the media source is ready
* for playback.
*
* @param listener the callback that will be run
*/
public void setOnPreparedListener(OnPreparedListener listener) {
mOnPreparedListener = listener;
}
/**
* Interface definition for a callback to be invoked when playback of
* a media source has completed.
*/
public interface OnCompletionListener {
/**
* Called when the end of a media source is reached during playback.
* @param mp the MediaPlayer that reached the end of the file
*/
void onCompletion(MediaPlayer mp);
}
/**
* Register a callback to be invoked when the end of a media source
* has been reached during playback.
*
* @param listener the callback that will be run
*/
public void setOnCompletionListener(OnCompletionListener listener) {
mOnCompletionListener = listener;
}
/**
* Interface definition of a callback to be invoked when a seek
* is issued.
*/
public interface OnSeekListener {
/**
* Called to indicate that a seek operation has been started.
* @param mp the mediaPlayer that the seek was called on
*/
public void onSeek(MediaPlayer mp);
}
/**
* Register a calback to be invoked when a seek operation has been started.
* @param listener the callback that will be run
*/
public void setOnSeekListener(OnSeekListener listener) {
mOnSeekListener = listener;
}
/**
* Interface definition of a callback to be invoked indicating
* the completion of a seek operation.
*/
public interface OnSeekCompleteListener {
/**
* Called to indicate the completion of a seek operation.
* @param mp the MediaPlayer that issued the seek operation
*/
public void onSeekComplete(MediaPlayer mp);
}
/**
* Register a callback to be invoked when a seek operation has been
* completed.
*
* @param listener the callback that will be run
*/
public void setOnSeekCompleteListener(OnSeekCompleteListener listener) {
mOnSeekCompleteListener = listener;
}
/**
* Interface definition of a callback to be invoked when the
* video size is first known or updated
*/
public interface OnVideoSizeChangedListener
{
/**
* Called to indicate the video size
*
* The video size (width and height) could be 0 if there was no video,
* no display surface was set, or the value was not determined yet.
*
* @param mp the MediaPlayer associated with this callback
* @param width the width of the video
* @param height the height of the video
*/
public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
}
/**
* Register a callback to be invoked when the video size is
* known or updated.
*
* @param listener the callback that will be run
*/
public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) {
mOnVideoSizeChangedListener = listener;
}
/**
* Interface definition of a callback to be invoked indicating buffering
* status of a media resource being streamed over the network.
*/
public interface OnBufferingUpdateListener {
/**
* Called to update status in buffering a media stream received through
* progressive HTTP download. The received buffering percentage
* indicates how much of the content has been buffered or played.
* For example a buffering update of 80 percent when half the content
* has already been played indicates that the next 30 percent of the
* content to play has been buffered.
*
* @param mp the MediaPlayer the update pertains to
* @param percent the percentage (0-100) of the content
* that has been buffered or played thus far
*/
void onBufferingUpdate(MediaPlayer mp, int percent);
}
/**
* Register a callback to be invoked when the status of a network
* stream's buffer has changed.
*
* @param listener the callback that will be run.
*/
public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) {
mOnBufferingUpdateListener = listener;
}
/** Unspecified media player error.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnErrorListener
*/
public static final int MEDIA_ERROR_UNKNOWN = 1;
/** Media server died. In this case, the application must release the
* MediaPlayer object and instantiate a new one.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnErrorListener
*/
public static final int MEDIA_ERROR_SERVER_DIED = 100;
/** The video is streamed and its container is not valid for progressive
* playback i.e the video's index (e.g moov atom) is not at the start of the
* file.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnErrorListener
*/
public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
/** File or network related operation errors. */
public static final int MEDIA_ERROR_IO = -1004;
/** Bitstream is not conforming to the related coding standard or file spec. */
public static final int MEDIA_ERROR_MALFORMED = -1007;
/** Bitstream is conforming to the related coding standard or file spec, but
* the media framework does not support the feature. */
public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
/** Some operation takes too long to complete, usually more than 3-5 seconds. */
public static final int MEDIA_ERROR_TIMED_OUT = -110;
/**
* Interface definition of a callback to be invoked when there
* has been an error during an asynchronous operation (other errors
* will throw exceptions at method call time).
*/
public interface OnErrorListener
{
/**
* Called to indicate an error.
*
* @param mp the MediaPlayer the error pertains to
* @param what the type of error that has occurred:
* <ul>
* <li>{@link #MEDIA_ERROR_UNKNOWN}
* <li>{@link #MEDIA_ERROR_SERVER_DIED}
* </ul>
* @param extra an extra code, specific to the error. Typically
* implementation dependent.
* <ul>
* <li>{@link #MEDIA_ERROR_IO}
* <li>{@link #MEDIA_ERROR_MALFORMED}
* <li>{@link #MEDIA_ERROR_UNSUPPORTED}
* <li>{@link #MEDIA_ERROR_TIMED_OUT}
* </ul>
* @return True if the method handled the error, false if it didn't.
* Returning false, or not having an OnErrorListener at all, will
* cause the OnCompletionListener to be called.
*/
boolean onError(MediaPlayer mp, int what, int extra);
}
/**
* Register a callback to be invoked when an error has happened
* during an asynchronous operation.
*
* @param listener the callback that will be run
*/
public void setOnErrorListener(OnErrorListener listener)
{
mOnErrorListener = listener;
}
/** The player just pushed the very first video frame for rendering.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
/** The video is too complex for the decoder: it can't decode frames fast
* enough. Possibly only the audio plays fine at this stage.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
/** MediaPlayer is temporarily pausing playback internally in order to
* buffer more data.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_BUFFERING_START = 701;
/** MediaPlayer is resuming playback after filling buffers.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_BUFFERING_END = 702;
/**
* Interface definition of a callback to be invoked to communicate some
* info and/or warning about the media or its playback.
*/
public interface OnInfoListener {
/**
* Called to indicate an info or a warning.
*
* @param mp the MediaPlayer the info pertains to.
* @param what the type of info or warning.
* <ul>
* <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
* <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
* <li>{@link #MEDIA_INFO_BUFFERING_START}
* <li>{@link #MEDIA_INFO_BUFFERING_END}
* </ul>
* @param extra an extra code, specific to the info. Typically
* implementation dependent.
* @return True if the method handled the info, false if it didn't.
* Returning false, or not having an OnErrorListener at all, will
* cause the info to be discarded.
*/
boolean onInfo(MediaPlayer mp, int what, int extra);
}
/**
* Register a callback to be invoked when an info/warning is available.
* @param listener the callback that will be run
*/
public void setOnInfoListener(OnInfoListener listener) {
mOnInfoListener = listener;
}
private static final int MEDIA_PREPARED = 1;
private static final int MEDIA_PLAYBACK_COMPLETE = 2;
private static final int MEDIA_BUFFERING_UPDATE = 3;
private static final int MEDIA_SEEK_COMPLETE = 4;
private static final int MEDIA_SET_VIDEO_SIZE = 5;
private static final int MEDIA_ERROR = 100;
private static final int MEDIA_INFO = 200;
private class EventHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case MEDIA_PREPARED:
Log.d(TAG, "onPrepared");
if(mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(MediaPlayer.this);
}
return;
case MEDIA_SEEK_COMPLETE:
Log.d(TAG, "onSeekComplete");
if (mOnSeekCompleteListener != null) {
mOnSeekCompleteListener.onSeekComplete(MediaPlayer.this);
}
return;
case MEDIA_PLAYBACK_COMPLETE:
Log.d(TAG, "onPlaybackComplete");
if(mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(MediaPlayer.this);
}
stayAwake(false);
return;
case MEDIA_SET_VIDEO_SIZE:
Log.d(TAG, "onVideoSizeChanged");
if(mOnVideoSizeChangedListener != null) {
mOnVideoSizeChangedListener.onVideoSizeChanged(MediaPlayer.this, msg.arg1, msg.arg2);
}
return;
case MEDIA_ERROR:
Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
boolean error_was_handled = false;
if (mOnErrorListener != null) {
error_was_handled = mOnErrorListener.onError(MediaPlayer.this, msg.arg1, msg.arg2);
}
if (mOnCompletionListener != null && !error_was_handled) {
mOnCompletionListener.onCompletion(MediaPlayer.this);
}
stayAwake(false);
return;
case MEDIA_INFO:
Log.d(TAG, "onInfo");
if(mOnInfoListener != null) {
mOnInfoListener.onInfo(MediaPlayer.this, msg.arg1, msg.arg2);
}
return;
case MEDIA_BUFFERING_UPDATE:
//Log.d(TAG, "onBufferingUpdate");
if (mOnBufferingUpdateListener != null)
mOnBufferingUpdateListener.onBufferingUpdate(MediaPlayer.this, msg.arg1);
mBufferPercentage = msg.arg1;
return;
default:
// nothing
}
}
}
}
| MediaPlayer/src/main/java/at/aau/itec/android/mediaplayer/MediaPlayer.java | /*
* Copyright (c) 2014 Mario Guggenberger <[email protected]>
*
* This file is part of ITEC MediaPlayer.
*
* ITEC MediaPlayer 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.
*
* ITEC MediaPlayer 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 ITEC MediaPlayer. If not, see <http://www.gnu.org/licenses/>.
*/
package at.aau.itec.android.mediaplayer;
import android.content.Context;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
/**
* Created by maguggen on 04.06.2014.
*/
public class MediaPlayer {
private static final String TAG = MediaPlayer.class.getSimpleName();
public enum SeekMode {
/**
* Seeks to the previous sync point. Fastest seek mode.
*/
FAST,
/**
* Seeks to the exact frame if the seek time equals the frame time, else
* to the following frame; this means that it will often seek one frame too far.
*/
PRECISE,
/**
* Always seeks to the exact frame. Can cost maximally twice the time than the PRECISE mode.
*/
EXACT,
/**
* Always seeks to the exact frame by skipping the decoding of all frames between the sync
* and target frame, because of which it can result in block artifacts.
*/
FAST_EXACT
}
private SeekMode mSeekMode = SeekMode.EXACT;
private Surface mSurface;
private SurfaceHolder mSurfaceHolder;
private MediaExtractor mVideoExtractor;
private MediaExtractor mAudioExtractor;
private int mVideoTrackIndex;
private MediaFormat mVideoFormat;
private long mVideoMinPTS;
private MediaCodec mVideoCodec;
private int mAudioTrackIndex;
private MediaFormat mAudioFormat;
private long mAudioMinPTS;
private MediaCodec mAudioCodec;
private int mAudioSessionId;
private PlaybackThread mPlaybackThread;
private long mCurrentPosition;
private boolean mSeeking;
private long mSeekTargetTime;
private boolean mSeekPrepare;
private int mBufferPercentage;
private TimeBase mTimeBase;
private EventHandler mEventHandler;
private OnPreparedListener mOnPreparedListener;
private OnCompletionListener mOnCompletionListener;
private OnSeekListener mOnSeekListener;
private OnSeekCompleteListener mOnSeekCompleteListener;
private OnErrorListener mOnErrorListener;
private OnInfoListener mOnInfoListener;
private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
private OnBufferingUpdateListener mOnBufferingUpdateListener;
private PowerManager.WakeLock mWakeLock = null;
private boolean mScreenOnWhilePlaying;
private boolean mStayAwake;
private boolean mIsStopping;
public MediaPlayer() {
mPlaybackThread = null;
mEventHandler = new EventHandler();
mTimeBase = new TimeBase();
}
public void setDataSource(MediaSource source) throws IOException {
mVideoExtractor = source.getVideoExtractor();
mAudioExtractor = source.getAudioExtractor();
mVideoTrackIndex = -1;
mAudioTrackIndex = -1;
for (int i = 0; i < mVideoExtractor.getTrackCount(); ++i) {
MediaFormat format = mVideoExtractor.getTrackFormat(i);
Log.d(TAG, format.toString());
String mime = format.getString(MediaFormat.KEY_MIME);
if (mVideoTrackIndex < 0 && mime.startsWith("video/")) {
mVideoExtractor.selectTrack(i);
mVideoTrackIndex = i;
mVideoFormat = format;
mVideoMinPTS = mVideoExtractor.getSampleTime();
} else if (mAudioExtractor == null && mAudioTrackIndex < 0 && mime.startsWith("audio/")) {
mVideoExtractor.selectTrack(i);
mAudioTrackIndex = i;
mAudioFormat = format;
mAudioMinPTS = mVideoExtractor.getSampleTime();
}
}
if(mAudioExtractor != null) {
for (int i = 0; i < mAudioExtractor.getTrackCount(); ++i) {
MediaFormat format = mAudioExtractor.getTrackFormat(i);
Log.d(TAG, format.toString());
String mime = format.getString(MediaFormat.KEY_MIME);
if (mAudioTrackIndex < 0 && mime.startsWith("audio/")) {
mAudioExtractor.selectTrack(i);
mAudioTrackIndex = i;
mAudioFormat = format;
mAudioMinPTS = mAudioExtractor.getSampleTime();
}
}
}
if(mVideoFormat == null) {
throw new IOException("no video track found");
} else {
if(mAudioFormat == null) {
Log.i(TAG, "no audio track found");
}
if(mPlaybackThread == null) {
if (mSurface == null) {
Log.i(TAG, "no video output surface specified");
}
mPlaybackThread = new PlaybackThread();
mPlaybackThread.start();
}
}
}
/**
* @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri, java.util.Map)
* @deprecated only for compatibility with Android API
*/
@Deprecated
public void setDataSource(Context context, Uri uri, Map<String, String> headers) throws IOException {
setDataSource(new UriSource(context, uri, headers));
}
/**
* @see android.media.MediaPlayer#setDataSource(android.content.Context, android.net.Uri)
* @deprecated only for compatibility with Android API
*/
@Deprecated
public void setDataSource(Context context, Uri uri) throws IOException {
setDataSource(context, uri, null);
}
/**
* @see android.media.MediaPlayer#setDisplay(android.view.SurfaceHolder)
*/
public void setDisplay(SurfaceHolder sh) {
mSurfaceHolder = sh;
if (sh != null) {
mSurface = sh.getSurface();
} else {
mSurface = null;
}
updateSurfaceScreenOn();
}
/**
* @see android.media.MediaPlayer#setSurface(android.view.Surface)
*/
public void setSurface(Surface surface) {
mSurface = surface;
if (mScreenOnWhilePlaying && surface != null) {
Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
}
mSurfaceHolder = null;
updateSurfaceScreenOn();
}
public void start() {
mPlaybackThread.play();
stayAwake(true);
}
public void pause() {
mPlaybackThread.pause();
stayAwake(false);
}
public SeekMode getSeekMode() {
return mSeekMode;
}
public void setSeekMode(SeekMode seekMode) {
this.mSeekMode = seekMode;
}
private void seekToInternal(long usec) {
/* A seek needs to be performed in the decoding thread to execute commands in the correct
* order. Otherwise it can happen that, after a seek in the media decoder, seeking procedure
* starts, then a frame is decoded, and then the codec is flushed; the PTS of the decoded frame
* then interferes the seeking procedure, the seek stops prematurely and a wrong waiting time
* gets calculated. */
Log.d(TAG, "seekTo " + usec);
// inform the decoder thread of an upcoming seek
mSeekPrepare = true;
mSeekTargetTime = Math.max(mVideoMinPTS, usec);
// if the decoder is paused, wake it up for the seek
if(mPlaybackThread.isPaused()) {
mPlaybackThread.play();
mPlaybackThread.pause();
}
}
public void seekTo(long usec) {
if (mOnSeekListener != null) {
mOnSeekListener.onSeek(MediaPlayer.this);
}
seekToInternal(usec);
}
public void seekTo(int msec) {
seekTo(msec * 1000L);
}
/**
* Sets the playback speed. Can be used for fast forward and slow motion.
* speed 0.5 = half speed / slow motion
* speed 2.0 = double speed / fast forward
*/
public void setPlaybackSpeed(float speed) {
mTimeBase.setSpeed(speed);
mTimeBase.startAt(mCurrentPosition);
}
public float getPlaybackSpeed() {
return (float)mTimeBase.getSpeed();
}
public boolean isPlaying() {
return mPlaybackThread != null && !mPlaybackThread.isPaused();
}
public void stop() {
if(mPlaybackThread != null) {
mIsStopping = true;
mPlaybackThread.interrupt();
try {
mPlaybackThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "error waiting for playback thread to die", e);
}
mPlaybackThread = null;
}
stayAwake(false);
}
public void release() {
stop();
}
public void reset() {
stop();
}
/**
* @see android.media.MediaPlayer#setWakeMode(android.content.Context, int)
*/
public void setWakeMode(Context context, int mode) {
boolean washeld = false;
if (mWakeLock != null) {
if (mWakeLock.isHeld()) {
washeld = true;
mWakeLock.release();
}
mWakeLock = null;
}
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
mWakeLock.setReferenceCounted(false);
if (washeld) {
mWakeLock.acquire();
}
}
/**
* @see android.media.MediaPlayer#setScreenOnWhilePlaying(boolean)
*/
public void setScreenOnWhilePlaying(boolean screenOn) {
if (mScreenOnWhilePlaying != screenOn) {
if (screenOn && mSurfaceHolder == null) {
Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
}
mScreenOnWhilePlaying = screenOn;
updateSurfaceScreenOn();
}
}
private void stayAwake(boolean awake) {
if (mWakeLock != null) {
if (awake && !mWakeLock.isHeld()) {
mWakeLock.acquire();
} else if (!awake && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
mStayAwake = awake;
updateSurfaceScreenOn();
}
private void updateSurfaceScreenOn() {
if (mSurfaceHolder != null) {
mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
}
}
public int getDuration() {
return mVideoFormat != null ? (int)(mVideoFormat.getLong(MediaFormat.KEY_DURATION)/1000) : 0;
}
public int getCurrentPosition() {
/* During a seek, return the temporary seek target time; otherwise a seek bar doesn't
* update to the selected seek position until the seek is finished (which can take a
* while in exact mode). */
return (int)((mSeekPrepare || mSeeking ? mSeekTargetTime : mCurrentPosition)/1000);
}
public int getBufferPercentage() {
return mBufferPercentage;
}
public int getVideoWidth() {
return mVideoFormat != null ? (int)(mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT)
* mVideoFormat.getFloat(MediaExtractor.MEDIA_FORMAT_EXTENSION_KEY_DAR)) : 0;
}
public int getVideoHeight() {
return mVideoFormat != null ? mVideoFormat.getInteger(MediaFormat.KEY_HEIGHT) : 0;
}
/**
* @see android.media.MediaPlayer#setAudioSessionId(int)
*/
public void setAudioSessionId(int sessionId) {
mAudioSessionId = sessionId;
}
/**
* @see android.media.MediaPlayer#getAudioSessionId()
*/
public int getAudioSessionId() {
return mAudioSessionId;
}
private class PlaybackThread extends Thread {
private final long mTimeOutUs = 500000;
private ByteBuffer[] mVideoCodecInputBuffers;
private ByteBuffer[] mVideoCodecOutputBuffers;
private ByteBuffer[] mAudioCodecInputBuffers;
private ByteBuffer[] mAudioCodecOutputBuffers;
private MediaCodec.BufferInfo mVideoInfo;
private MediaCodec.BufferInfo mAudioInfo;
private boolean mPaused;
private boolean mVideoInputEos;
private boolean mVideoOutputEos;
private boolean mAudioInputEos;
private boolean mAudioOutputEos;
private boolean mBuffering;
private AudioPlayback mAudioPlayback;
/* Flag notifying that the representation has changed in the extractor and needs to be passed
* to the decoder. This transition state is only needed in playback, not when seeking. */
private boolean mRepresentationChanging;
/* Flag notifying that the decoder has changed to a new representation, post-actions need to
* be carried out. */
private boolean mRepresentationChanged;
private PlaybackThread() {
super(TAG);
mPaused = true;
}
public void pause() {
mPaused = true;
}
public void play() {
mPaused = false;
synchronized (this) {
notify();
}
}
public boolean isPaused() {
return mPaused;
}
@Override
public void run() {
try {
mVideoCodec = MediaCodec.createDecoderByType(mVideoFormat.getString(MediaFormat.KEY_MIME));
mVideoCodec.configure(mVideoFormat, mSurface, null, 0);
mVideoCodec.start();
mVideoCodecInputBuffers = mVideoCodec.getInputBuffers();
mVideoCodecOutputBuffers = mVideoCodec.getOutputBuffers();
mVideoInfo = new MediaCodec.BufferInfo();
mVideoInputEos = false;
mVideoOutputEos = false;
if(mAudioFormat != null) {
mAudioCodec = MediaCodec.createDecoderByType(mAudioFormat.getString(MediaFormat.KEY_MIME));
mAudioCodec.configure(mAudioFormat, null, null, 0);
mAudioCodec.start();
mAudioCodecInputBuffers = mAudioCodec.getInputBuffers();
mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
mAudioInfo = new MediaCodec.BufferInfo();
mAudioInputEos = false;
mAudioOutputEos = false;
mAudioPlayback = new AudioPlayback();
mAudioPlayback.setAudioSessionId(mAudioSessionId);
mAudioPlayback.init(mAudioFormat);
mAudioSessionId = mAudioPlayback.getAudioSessionId();
}
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE,
getVideoWidth(), getVideoHeight()));
mBuffering = false;
boolean preparing = true; // used on startup to process stream until the first frame
int frameSkipCount = 0;
long lastPTS = 0;
// Initialize the time base with the first PTS that must not necessarily be 0
mTimeBase.startAt(mVideoMinPTS);
while (!mVideoOutputEos) {
if (mPaused && !mSeekPrepare && !mSeeking && !preparing) {
if(mAudioPlayback != null) mAudioPlayback.pause();
synchronized (this) {
while (mPaused && !mSeekPrepare && !mSeeking) {
this.wait();
}
}
if(mAudioPlayback != null) mAudioPlayback.play();
// reset time (otherwise playback tries to "catch up" time after a pause)
mTimeBase.startAt(mVideoInfo.presentationTimeUs);
}
// For a seek, first prepare by seeking the media extractor and flushing the codec.
/* This needs to be in a loop, because the seek inside this block can take some
* time, meanwhile another seek can be issued. The following seek can update the seek
* target while the video extractor is still seeking, which can turn into a problem
* with DASH when the second target is not within the first requested segment - in
* which case the seek cannot find the new target in the old segment. By checking
* if a seek needs to be prepared after the video extractor seek has finished (which
* means another seek hat been issued), it can be run again and again while new
* seek targets come in, until the target finally stays the same during a seek.
*/
while (mSeekPrepare) {
mSeekPrepare = false;
mSeeking = true;
Log.d(TAG, "seeking to: " + mSeekTargetTime);
Log.d(TAG, "frame current position: " + mCurrentPosition);
Log.d(TAG, "extractor current position: " + mVideoExtractor.getSampleTime());
mVideoExtractor.seekTo(mSeekTargetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
mCurrentPosition = mSeekTargetTime;
Log.d(TAG, "extractor new position: " + mVideoExtractor.getSampleTime());
if(mSeekPrepare) {
// Another seek has been issued in the meantime, repeat this block
continue;
}
mVideoCodec.flush();
if (mAudioFormat != null) mAudioCodec.flush();
if(mVideoExtractor.hasTrackFormatChanged()) {
reinitCodecs();
mRepresentationChanged = true;
}
if(mSeekMode == SeekMode.FAST_EXACT) {
/* Check if the seek target time after the seek is the same as before the
* seek. If not, a new seek has been issued in the meantime; the current
* one must be discarded and a new seek with the new target time started.
*/
long in;
long out;
do {
in = mSeekTargetTime;
out = fastSeek(in);
} while (in != mSeekTargetTime);
mSeekTargetTime = out;
mSeekPrepare = false;
}
}
if (!mVideoInputEos && !mRepresentationChanging) {
queueMediaSampleToCodec(mSeeking);
}
lastPTS = mVideoInfo.presentationTimeUs;
int res = mVideoCodec.dequeueOutputBuffer(mVideoInfo, mTimeOutUs);
mVideoOutputEos = res >= 0 && (mVideoInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0;
if(mVideoOutputEos && mRepresentationChanging) {
/* Here, the video output is not really at its end, it's just the end of the
* current representation segment, and the codec needs to be reconfigured to
* the following representation format to carry on.
*/
reinitCodecs();
mVideoOutputEos = false;
mRepresentationChanging = false;
mRepresentationChanged = true;
}
else if (res >= 0) {
int outputBufIndex = res;
boolean render = true;
//ByteBuffer buf = codecOutputBuffers[outputBufIndex];
//Log.d(TAG, "pts=" + info.presentationTimeUs);
if (mSeeking) {
if(mVideoOutputEos) {
/* When the end of stream is reached while seeking, the seek target
* time is set to the last frame's PTS, else the seek skips the last
* frame which then does not get rendered, and it might end up in a
* loop trying to reach the unreachable target time. */
mSeekTargetTime = mVideoInfo.presentationTimeUs;
}
/* NOTE
* This code seeks one frame too far, except if the seek time equals the
* frame PTS:
* (F1.....)(F2.....)(F3.....) ... (Fn.....)
* A frame is shown for an interval, e.g. (1/fps seconds). Now if the seek
* target time is somewhere in frame 2's interval, we end up with frame 3
* because we need to decode it to know if the seek target time lies in
* frame 2's interval (because we don't know the frame rate of the video,
* and neither if it's a fixed frame rate or a variable one - even when
* deriving it from the PTS series we cannot be sure about it). This means
* we always end up one frame too far, because the MediaCodec does not allow
* to go back, except when starting at a sync frame.
*
* Solution for fixed frame rate could be to subtract the frame interval
* time (1/fps secs) from the seek target time.
*
* Solution for variable frame rate and unknown frame rate: go back to sync
* frame and re-seek to the now known exact PTS of the desired frame.
* See EXACT mode handling below.
*/
/* Android API compatibility:
* Use millisecond precision to stay compatible with VideoView API that works
* in millisecond precision only. Else, exact seek matches are missed if frames
* are positioned at fractions of a millisecond. */
long presentationTimeMs = mVideoInfo.presentationTimeUs / 1000;
long seekTargetTimeMs = mSeekTargetTime / 1000;
if ((mSeekMode == SeekMode.PRECISE || mSeekMode == SeekMode.EXACT) && presentationTimeMs < seekTargetTimeMs) {
// this is not yet the aimed time so we skip rendering of this frame
render = false;
if(frameSkipCount == 0) {
Log.d(TAG, "skipping frames...");
}
frameSkipCount++;
} else {
Log.d(TAG, "frame new position: " + mVideoInfo.presentationTimeUs);
Log.d(TAG, "seeking finished, skipped " + frameSkipCount + " frames");
frameSkipCount = 0;
if(mSeekMode == SeekMode.EXACT && presentationTimeMs > seekTargetTimeMs) {
/* If the current frame's PTS it after the seek target time, we're
* one frame too far into the stream. This is because we do not know
* the frame rate of the video and therefore can't decide for a frame
* if its interval covers the seek target time of if there's already
* another frame coming. We know after the next frame has been
* decoded though if we're too far into the stream, and if so, and if
* EXACT mode is desired, we need to take the previous frame's PTS
* and repeat the seek with that PTS to arrive at the desired frame.
*/
Log.d(TAG, "exact seek: repeat seek for previous frame at " + lastPTS);
render = false;
seekToInternal(lastPTS);
} else {
if(presentationTimeMs == seekTargetTimeMs) {
Log.d(TAG, "exact seek match!");
}
if(mSeekMode == SeekMode.FAST_EXACT && mVideoInfo.presentationTimeUs < mSeekTargetTime) {
// this should only ever happen in fastseek mode, else it FFWs in fast mode
Log.d(TAG, "presentation is behind, another try...");
} else {
// reset time to keep frame rate constant (otherwise it's too fast on back seeks and waits for the PTS time on fw seeks)
mTimeBase.startAt(mVideoInfo.presentationTimeUs);
mCurrentPosition = mVideoInfo.presentationTimeUs;
mSeeking = false;
if(mAudioExtractor != null) {
mAudioExtractor.seekTo(mVideoInfo.presentationTimeUs, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
mAudioPlayback.flush();
}
mEventHandler.sendEmptyMessage(MEDIA_SEEK_COMPLETE);
}
}
}
} else {
mCurrentPosition = mVideoInfo.presentationTimeUs;
long waitingTime = mTimeBase.getOffsetFrom(mVideoInfo.presentationTimeUs);
if(mAudioFormat != null) {
long audioOffsetUs = mAudioPlayback.getLastPresentationTimeUs() - mCurrentPosition;
// Log.d(TAG, "VideoPTS=" + mCurrentPosition
// + " AudioPTS=" + mAudioPlayback.getLastPresentationTimeUs()
// + " offset=" + audioOffsetUs);
/* Synchronize the video frame PTS to the audio PTS by slowly adjusting
* the video frame waiting time towards a better synchronization.
* Directly correcting the video waiting time by the audio offset
* introduces too much jitter and leads to juddering video playback.
*/
long audioOffsetCorrectionUs = 10000;
if (audioOffsetUs > audioOffsetCorrectionUs) {
waitingTime -= audioOffsetCorrectionUs;
} else if(audioOffsetUs < -audioOffsetCorrectionUs) {
waitingTime += audioOffsetCorrectionUs;
}
mAudioPlayback.setPlaybackSpeed((float)mTimeBase.getSpeed());
}
//Log.d(TAG, "waiting time = " + waitingTime);
/* If this is an online stream, notify the client of the buffer fill level.
* The cached duration from the MediaExtractor returns the cached time from
* the current position onwards, but the Android mediaPlayer returns the
* total time consisting fo the current playback point and the length of
* the prefetched data.
*/
long cachedDuration = mVideoExtractor.getCachedDuration();
if(cachedDuration != -1) {
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_BUFFERING_UPDATE,
(int) (100d / mVideoFormat.getLong(MediaFormat.KEY_DURATION) * (mCurrentPosition + cachedDuration)), 0));
}
// slow down playback, if necessary, to keep frame rate
if (!preparing && waitingTime > 5000) {
// sleep until it's time to render the next frame
// TODO find better alternative to sleep
// The sleep takes much longer than expected, leading to playback
// jitter, and depending on the structure of a container and the
// data sequence, dropouts in the audio playback stream.
Thread.sleep(waitingTime / 1000);
} else if(!preparing && waitingTime < 0) {
// we weed to catch up time by skipping rendering of this frame
// this doesn't gain enough time if playback speed is too high and decoder at full load
// TODO improve fast forward mode
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_VIDEO_TRACK_LAGGING, 0));
mTimeBase.startAt(mVideoInfo.presentationTimeUs);
}
}
if(mBuffering) {
mBuffering = false;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_BUFFERING_END, 0));
}
/* Defer the video size changed message until the first frame of the new
* size is being rendered. */
if(mRepresentationChanged && render) {
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_SET_VIDEO_SIZE,
getVideoWidth(), getVideoHeight()));
mRepresentationChanged = false;
}
mVideoCodec.releaseOutputBuffer(outputBufIndex, render); // render picture
if (mAudioFormat != null & mAudioExtractor != null && !mSeeking && !mPaused) {
// TODO rewrite; this is just a quick and dirty hack
long start = SystemClock.elapsedRealtime();
while (mAudioPlayback.getBufferTimeUs() < 100000) {
if (queueAudioSampleToCodec(mAudioExtractor)) {
decodeAudioSample();
} else {
break;
}
}
//Log.d(TAG, "audio stream decode time " + (SystemClock.elapsedRealtime() - start));
}
if (preparing) {
mEventHandler.sendEmptyMessage(MEDIA_PREPARED);
preparing = false;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_VIDEO_RENDERING_START, 0));
}
if (mVideoOutputEos) {
Log.d(TAG, "EOS video output");
mEventHandler.sendEmptyMessage(MEDIA_PLAYBACK_COMPLETE);
/* When playback reached the end of the stream and the last frame is
* displayed, we go into paused state instead of finishing the thread
* and wait until a new start or seek command is arriving. If no
* command arrives, the thread stays sleeping until the player is
* stopped.
*/
mPaused = true;
synchronized (this) {
if(mAudioPlayback != null) mAudioPlayback.pause();
while (mPaused && !mSeeking && !mSeekPrepare) {
this.wait();
}
if(mAudioPlayback != null) mAudioPlayback.play();
// reset these flags so playback can continue
mVideoInputEos = false;
mVideoOutputEos = false;
mAudioInputEos = false;
mAudioOutputEos = false;
// if no seek command but a start command arrived, seek to the start
if(!mSeeking && !mSeekPrepare) {
seekToInternal(0);
}
}
}
} else if (res == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
mVideoCodecOutputBuffers = mVideoCodec.getOutputBuffers();
Log.d(TAG, "output buffers have changed.");
} else if (res == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
// NOTE: this is the format of the raw video output, not the video format as specified by the container
MediaFormat oformat = mVideoCodec.getOutputFormat();
Log.d(TAG, "output format has changed to " + oformat);
} else if (res == MediaCodec.INFO_TRY_AGAIN_LATER) {
Log.d(TAG, "dequeueOutputBuffer timed out");
}
}
} catch (InterruptedException e) {
Log.d(TAG, "decoder interrupted");
interrupt();
if(mIsStopping) {
// An intentional stop does not trigger an error message
mIsStopping = false;
} else {
// Unexpected interruption, send error message
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR,
MEDIA_ERROR_UNKNOWN, 0));
}
} catch (IllegalStateException e) {
Log.e(TAG, "decoder error, too many instances?", e);
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR,
MEDIA_ERROR_UNKNOWN, 0));
} catch (IOException e) {
Log.e(TAG, "decoder error, codec can not be created", e);
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_ERROR,
MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_IO));
}
if(mAudioPlayback != null) mAudioPlayback.stopAndRelease();
mVideoCodec.stop();
mVideoCodec.release();
if(mAudioFormat != null) {
mAudioCodec.stop();
mAudioCodec.release();
}
mVideoExtractor.release();
Log.d(TAG, "decoder released");
}
private boolean queueVideoSampleToCodec() {
/* NOTE the track index checks only for debugging
* when enabled, they prevent the EOS detection and handling below */
// int trackIndex = mVideoExtractor.getSampleTrackIndex();
// if(trackIndex == -1) {
// throw new IllegalStateException("EOS");
// }
// if(trackIndex != mVideoTrackIndex) {
// throw new IllegalStateException("wrong track index: " + trackIndex);
// }
boolean sampleQueued = false;
int inputBufIndex = mVideoCodec.dequeueInputBuffer(mTimeOutUs);
if (inputBufIndex >= 0) {
ByteBuffer inputBuffer = mVideoCodecInputBuffers[inputBufIndex];
int sampleSize = mVideoExtractor.readSampleData(inputBuffer, 0);
long presentationTimeUs = 0;
if(sampleSize == 0) {
if(mVideoExtractor.getCachedDuration() == 0) {
mBuffering = true;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_BUFFERING_START, 0));
}
if(mVideoExtractor.hasTrackFormatChanged()) {
/* The mRepresentationChanging flag and BUFFER_FLAG_END_OF_STREAM flag together
* notify the decoding loop that the representation changes and the codec
* needs to be reconfigured.
*/
mRepresentationChanging = true;
mVideoCodec.queueInputBuffer(inputBufIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
}
} else {
if (sampleSize < 0) {
Log.d(TAG, "EOS video input");
mVideoInputEos = true;
sampleSize = 0;
} else {
presentationTimeUs = mVideoExtractor.getSampleTime();
sampleQueued = true;
}
mVideoCodec.queueInputBuffer(
inputBufIndex,
0,
sampleSize,
presentationTimeUs,
mVideoInputEos ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!mVideoInputEos) {
mVideoExtractor.advance();
}
}
}
return sampleQueued;
}
private boolean queueAudioSampleToCodec(MediaExtractor extractor) {
if(mAudioCodec == null) {
throw new IllegalStateException("no audio track configured");
}
/* NOTE the track index checks only for debugging
* when enabled, they prevent the EOS detection and handling below */
// int trackIndex = extractor.getSampleTrackIndex();
// if(trackIndex == -1) {
// throw new IllegalStateException("EOS");
// }
// if(trackIndex != mAudioTrackIndex) {
// throw new IllegalStateException("wrong track index: " + trackIndex);
// }
boolean sampleQueued = false;
int inputBufIndex = mAudioCodec.dequeueInputBuffer(mTimeOutUs);
if (inputBufIndex >= 0) {
ByteBuffer inputBuffer = mAudioCodecInputBuffers[inputBufIndex];
int sampleSize = extractor.readSampleData(inputBuffer, 0);
long presentationTimeUs = 0;
if (sampleSize < 0) {
Log.d(TAG, "EOS audio input");
mAudioInputEos = true;
sampleSize = 0;
} else if(sampleSize == 0) {
if(extractor.getCachedDuration() == 0) {
mBuffering = true;
mEventHandler.sendMessage(mEventHandler.obtainMessage(MEDIA_INFO,
MEDIA_INFO_BUFFERING_START, 0));
}
} else {
presentationTimeUs = extractor.getSampleTime();
sampleQueued = true;
}
mAudioCodec.queueInputBuffer(
inputBufIndex,
0,
sampleSize,
presentationTimeUs,
mAudioInputEos ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
if (!mAudioInputEos) {
extractor.advance();
}
}
return sampleQueued;
}
private void decodeAudioSample() {
int output = mAudioCodec.dequeueOutputBuffer(mAudioInfo, mTimeOutUs);
if (output >= 0) {
// http://bigflake.com/mediacodec/#q11
ByteBuffer outputData = mAudioCodecOutputBuffers[output];
if (mAudioInfo.size != 0) {
outputData.position(mAudioInfo.offset);
outputData.limit(mAudioInfo.offset + mAudioInfo.size);
//Log.d(TAG, "raw audio data bytes: " + mVideoInfo.size);
}
mAudioPlayback.write(outputData, mAudioInfo.presentationTimeUs);
mAudioCodec.releaseOutputBuffer(output, false);
if ((mAudioInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
mAudioOutputEos = true;
Log.d(TAG, "EOS audio output");
}
} else if (output == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
Log.d(TAG, "audio output buffers have changed.");
mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
} else if (output == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
MediaFormat format = mAudioCodec.getOutputFormat();
Log.d(TAG, "audio output format has changed to " + format);
mAudioPlayback.init(format);
} else if (output == MediaCodec.INFO_TRY_AGAIN_LATER) {
Log.d(TAG, "audio dequeueOutputBuffer timed out");
}
}
private boolean queueMediaSampleToCodec(boolean videoOnly) {
boolean result = false;
if(mAudioCodec != null) {
if (videoOnly) {
/* VideoOnly mode skips audio samples, e.g. while doing a seek operation. */
int trackIndex;
while ((trackIndex = mVideoExtractor.getSampleTrackIndex()) != -1 && trackIndex != mVideoTrackIndex && !mVideoInputEos) {
mVideoExtractor.advance();
}
} else {
while (mAudioExtractor == null && mVideoExtractor.getSampleTrackIndex() == mAudioTrackIndex) {
result = queueAudioSampleToCodec(mVideoExtractor);
decodeAudioSample();
}
}
}
if(!mVideoInputEos) {
result = queueVideoSampleToCodec();
}
return result;
}
private long fastSeek(long targetTime) throws IOException {
mVideoCodec.flush();
if(mAudioFormat != null) mAudioCodec.flush();
mVideoExtractor.seekTo(targetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
if(mVideoExtractor.getSampleTime() == targetTime) {
Log.d(TAG, "skip fastseek, already there");
return targetTime;
}
// 1. Queue first sample which should be the sync/I frame
queueMediaSampleToCodec(true);
// 2. Then, fast forward to target frame
/* 2.1 Search for the best candidate frame, which is the one whose
* right/positive/future distance is minimized
*/
mVideoExtractor.seekTo(targetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
/* Specifies how many frames we continue to check after the first candidate,
* to account for DTS picture reordering (this value is arbitrarily chosen) */
int maxFrameLookahead = 20;
long candidatePTS = 0;
long candidateDistance = Long.MAX_VALUE;
int lookaheadCount = 0;
while (mVideoExtractor.advance() && lookaheadCount < maxFrameLookahead) {
long distance = targetTime - mVideoExtractor.getSampleTime();
if (distance >= 0 && distance < candidateDistance) {
candidateDistance = distance;
candidatePTS = mVideoExtractor.getSampleTime();
//Log.d(TAG, "candidate " + candidatePTS + " d=" + candidateDistance);
}
if (distance < 0) {
lookaheadCount++;
}
}
targetTime = candidatePTS; // set best candidate frame as exact seek target
// 2.2 Fast forward to chosen candidate frame
mVideoExtractor.seekTo(targetTime, MediaExtractor.SEEK_TO_PREVIOUS_SYNC);
while (mVideoExtractor.getSampleTime() != targetTime) {
mVideoExtractor.advance();
}
Log.d(TAG, "exact fastseek match: " + mVideoExtractor.getSampleTime());
return targetTime;
}
/**
* Restarts the codecs with a new format, e.g. after a representation change.
*/
private void reinitCodecs() {
long t1 = SystemClock.elapsedRealtime();
// Get new video format and restart video codec with this format
mVideoFormat = mVideoExtractor.getTrackFormat(mVideoTrackIndex);
mVideoCodec.stop();
mVideoCodec.configure(mVideoFormat, mSurface, null, 0);
mVideoCodec.start();
mVideoCodecInputBuffers = mVideoCodec.getInputBuffers();
mVideoCodecOutputBuffers = mVideoCodec.getOutputBuffers();
if(mAudioFormat != null) {
mAudioCodec.stop();
mAudioCodec.configure(mAudioFormat, null, null, 0);
mAudioCodec.start();
mAudioCodecInputBuffers = mAudioCodec.getInputBuffers();
mAudioCodecOutputBuffers = mAudioCodec.getOutputBuffers();
}
Log.d(TAG, "reinitCodecs " + (SystemClock.elapsedRealtime() - t1) + "ms");
}
}
/**
* Interface definition for a callback to be invoked when the media
* source is ready for playback.
*/
public interface OnPreparedListener {
/**
* Called when the media file is ready for playback.
* @param mp the MediaPlayer that is ready for playback
*/
void onPrepared(MediaPlayer mp);
}
/**
* Register a callback to be invoked when the media source is ready
* for playback.
*
* @param listener the callback that will be run
*/
public void setOnPreparedListener(OnPreparedListener listener) {
mOnPreparedListener = listener;
}
/**
* Interface definition for a callback to be invoked when playback of
* a media source has completed.
*/
public interface OnCompletionListener {
/**
* Called when the end of a media source is reached during playback.
* @param mp the MediaPlayer that reached the end of the file
*/
void onCompletion(MediaPlayer mp);
}
/**
* Register a callback to be invoked when the end of a media source
* has been reached during playback.
*
* @param listener the callback that will be run
*/
public void setOnCompletionListener(OnCompletionListener listener) {
mOnCompletionListener = listener;
}
/**
* Interface definition of a callback to be invoked when a seek
* is issued.
*/
public interface OnSeekListener {
/**
* Called to indicate that a seek operation has been started.
* @param mp the mediaPlayer that the seek was called on
*/
public void onSeek(MediaPlayer mp);
}
/**
* Register a calback to be invoked when a seek operation has been started.
* @param listener the callback that will be run
*/
public void setOnSeekListener(OnSeekListener listener) {
mOnSeekListener = listener;
}
/**
* Interface definition of a callback to be invoked indicating
* the completion of a seek operation.
*/
public interface OnSeekCompleteListener {
/**
* Called to indicate the completion of a seek operation.
* @param mp the MediaPlayer that issued the seek operation
*/
public void onSeekComplete(MediaPlayer mp);
}
/**
* Register a callback to be invoked when a seek operation has been
* completed.
*
* @param listener the callback that will be run
*/
public void setOnSeekCompleteListener(OnSeekCompleteListener listener) {
mOnSeekCompleteListener = listener;
}
/**
* Interface definition of a callback to be invoked when the
* video size is first known or updated
*/
public interface OnVideoSizeChangedListener
{
/**
* Called to indicate the video size
*
* The video size (width and height) could be 0 if there was no video,
* no display surface was set, or the value was not determined yet.
*
* @param mp the MediaPlayer associated with this callback
* @param width the width of the video
* @param height the height of the video
*/
public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
}
/**
* Register a callback to be invoked when the video size is
* known or updated.
*
* @param listener the callback that will be run
*/
public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) {
mOnVideoSizeChangedListener = listener;
}
/**
* Interface definition of a callback to be invoked indicating buffering
* status of a media resource being streamed over the network.
*/
public interface OnBufferingUpdateListener {
/**
* Called to update status in buffering a media stream received through
* progressive HTTP download. The received buffering percentage
* indicates how much of the content has been buffered or played.
* For example a buffering update of 80 percent when half the content
* has already been played indicates that the next 30 percent of the
* content to play has been buffered.
*
* @param mp the MediaPlayer the update pertains to
* @param percent the percentage (0-100) of the content
* that has been buffered or played thus far
*/
void onBufferingUpdate(MediaPlayer mp, int percent);
}
/**
* Register a callback to be invoked when the status of a network
* stream's buffer has changed.
*
* @param listener the callback that will be run.
*/
public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) {
mOnBufferingUpdateListener = listener;
}
/** Unspecified media player error.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnErrorListener
*/
public static final int MEDIA_ERROR_UNKNOWN = 1;
/** Media server died. In this case, the application must release the
* MediaPlayer object and instantiate a new one.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnErrorListener
*/
public static final int MEDIA_ERROR_SERVER_DIED = 100;
/** The video is streamed and its container is not valid for progressive
* playback i.e the video's index (e.g moov atom) is not at the start of the
* file.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnErrorListener
*/
public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
/** File or network related operation errors. */
public static final int MEDIA_ERROR_IO = -1004;
/** Bitstream is not conforming to the related coding standard or file spec. */
public static final int MEDIA_ERROR_MALFORMED = -1007;
/** Bitstream is conforming to the related coding standard or file spec, but
* the media framework does not support the feature. */
public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
/** Some operation takes too long to complete, usually more than 3-5 seconds. */
public static final int MEDIA_ERROR_TIMED_OUT = -110;
/**
* Interface definition of a callback to be invoked when there
* has been an error during an asynchronous operation (other errors
* will throw exceptions at method call time).
*/
public interface OnErrorListener
{
/**
* Called to indicate an error.
*
* @param mp the MediaPlayer the error pertains to
* @param what the type of error that has occurred:
* <ul>
* <li>{@link #MEDIA_ERROR_UNKNOWN}
* <li>{@link #MEDIA_ERROR_SERVER_DIED}
* </ul>
* @param extra an extra code, specific to the error. Typically
* implementation dependent.
* <ul>
* <li>{@link #MEDIA_ERROR_IO}
* <li>{@link #MEDIA_ERROR_MALFORMED}
* <li>{@link #MEDIA_ERROR_UNSUPPORTED}
* <li>{@link #MEDIA_ERROR_TIMED_OUT}
* </ul>
* @return True if the method handled the error, false if it didn't.
* Returning false, or not having an OnErrorListener at all, will
* cause the OnCompletionListener to be called.
*/
boolean onError(MediaPlayer mp, int what, int extra);
}
/**
* Register a callback to be invoked when an error has happened
* during an asynchronous operation.
*
* @param listener the callback that will be run
*/
public void setOnErrorListener(OnErrorListener listener)
{
mOnErrorListener = listener;
}
/** The player just pushed the very first video frame for rendering.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
/** The video is too complex for the decoder: it can't decode frames fast
* enough. Possibly only the audio plays fine at this stage.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
/** MediaPlayer is temporarily pausing playback internally in order to
* buffer more data.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_BUFFERING_START = 701;
/** MediaPlayer is resuming playback after filling buffers.
* @see at.aau.itec.android.mediaplayer.MediaPlayer.OnInfoListener
*/
public static final int MEDIA_INFO_BUFFERING_END = 702;
/**
* Interface definition of a callback to be invoked to communicate some
* info and/or warning about the media or its playback.
*/
public interface OnInfoListener {
/**
* Called to indicate an info or a warning.
*
* @param mp the MediaPlayer the info pertains to.
* @param what the type of info or warning.
* <ul>
* <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
* <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
* <li>{@link #MEDIA_INFO_BUFFERING_START}
* <li>{@link #MEDIA_INFO_BUFFERING_END}
* </ul>
* @param extra an extra code, specific to the info. Typically
* implementation dependent.
* @return True if the method handled the info, false if it didn't.
* Returning false, or not having an OnErrorListener at all, will
* cause the info to be discarded.
*/
boolean onInfo(MediaPlayer mp, int what, int extra);
}
/**
* Register a callback to be invoked when an info/warning is available.
* @param listener the callback that will be run
*/
public void setOnInfoListener(OnInfoListener listener) {
mOnInfoListener = listener;
}
private static final int MEDIA_PREPARED = 1;
private static final int MEDIA_PLAYBACK_COMPLETE = 2;
private static final int MEDIA_BUFFERING_UPDATE = 3;
private static final int MEDIA_SEEK_COMPLETE = 4;
private static final int MEDIA_SET_VIDEO_SIZE = 5;
private static final int MEDIA_ERROR = 100;
private static final int MEDIA_INFO = 200;
private class EventHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case MEDIA_PREPARED:
Log.d(TAG, "onPrepared");
if(mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(MediaPlayer.this);
}
return;
case MEDIA_SEEK_COMPLETE:
Log.d(TAG, "onSeekComplete");
if (mOnSeekCompleteListener != null) {
mOnSeekCompleteListener.onSeekComplete(MediaPlayer.this);
}
return;
case MEDIA_PLAYBACK_COMPLETE:
Log.d(TAG, "onPlaybackComplete");
if(mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(MediaPlayer.this);
}
stayAwake(false);
return;
case MEDIA_SET_VIDEO_SIZE:
Log.d(TAG, "onVideoSizeChanged");
if(mOnVideoSizeChangedListener != null) {
mOnVideoSizeChangedListener.onVideoSizeChanged(MediaPlayer.this, msg.arg1, msg.arg2);
}
return;
case MEDIA_ERROR:
Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
boolean error_was_handled = false;
if (mOnErrorListener != null) {
error_was_handled = mOnErrorListener.onError(MediaPlayer.this, msg.arg1, msg.arg2);
}
if (mOnCompletionListener != null && !error_was_handled) {
mOnCompletionListener.onCompletion(MediaPlayer.this);
}
stayAwake(false);
return;
case MEDIA_INFO:
Log.d(TAG, "onInfo");
if(mOnInfoListener != null) {
mOnInfoListener.onInfo(MediaPlayer.this, msg.arg1, msg.arg2);
}
return;
case MEDIA_BUFFERING_UPDATE:
//Log.d(TAG, "onBufferingUpdate");
if (mOnBufferingUpdateListener != null)
mOnBufferingUpdateListener.onBufferingUpdate(MediaPlayer.this, msg.arg1);
mBufferPercentage = msg.arg1;
return;
default:
// nothing
}
}
}
}
| Fix seeking from the end of the input stream
When seeking to the end of a stream and the end of the input stream is reached, the mVideoInputEos flag gets set to true. A following seek then resulted in an infinite loop of the media player waiting for a decoded frame, because due to the flag, no more sample data was read from the extractor and fed to the decoder, and the decoder therefore never emitted a decoded frame. Fixes GitHub issue #9.
| MediaPlayer/src/main/java/at/aau/itec/android/mediaplayer/MediaPlayer.java | Fix seeking from the end of the input stream |
|
Java | apache-2.0 | 67479043a372b27be40951b36a621c981577ae62 | 0 | deesebc/conmigo,deesebc/conmigo,deesebc/conmigo | package com.conmigo.app.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.conmigo.app.util.SecurityUtil;
@Controller
public class LoginController {
private final static Logger LOGGER = LoggerFactory.getLogger( LoginController.class );
private final static String REDIRECT_INDEX = "redirect:/";
private final static String PAGE = "site.login";
public LoginController() {
super();
}
@RequestMapping( value = "/login", method = RequestMethod.GET )
public String login( @RequestParam( value = "error", required = false ) final String error ) {
String retorno = PAGE;
if( SecurityUtil.isFullyAuthenticated() ) {
retorno = REDIRECT_INDEX;
}
return retorno;
}
}
| src/main/java/com/conmigo/app/controller/LoginController.java | package com.conmigo.app.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.conmigo.app.util.SecurityUtil;
@Controller
public class LoginController {
private final static Logger LOGGER = LoggerFactory.getLogger( LoginController.class );
private final static String REDIRECT_INDEX = "redirect:/";
public LoginController() {
super();
}
@RequestMapping( value = "/login", method = RequestMethod.GET )
public String login( @RequestParam( value = "error", required = false ) final String error ) {
String retorno = "site.login";
if( SecurityUtil.isFullyAuthenticated() ) {
retorno = REDIRECT_INDEX;
}
return retorno;
}
@RequestMapping( value = "/logout", method = RequestMethod.GET )
public String logout( final HttpServletRequest request, final HttpServletResponse response ) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if( auth != null ) {
new SecurityContextLogoutHandler().logout( request, response, auth );
}
return REDIRECT_INDEX;
}
}
| DSBC: QUitamos metodo duplicado
| src/main/java/com/conmigo/app/controller/LoginController.java | DSBC: QUitamos metodo duplicado |
|
Java | apache-2.0 | 6648c412a6463a898bb8660c51a7c7c6851a4ff0 | 0 | yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,jmt4/Selenium2,yumingjuan/selenium,jmt4/Selenium2,yumingjuan/selenium,yumingjuan/selenium,jmt4/Selenium2 | /*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Portions copyright 2011 Software Freedom Conservancy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium;
import java.io.Serializable;
public class UnhandledAlertException extends WebDriverException {
private final Alert locallyStoredAlert;
public UnhandledAlertException(String commandName) {
this(commandName, null);
}
public UnhandledAlertException(String commandName, String alertText) {
super(commandName);
this.locallyStoredAlert = alertText == null ? null : new LocallyStoredAlert(alertText);
}
/*
* Returns null if alert text could not be retrieved.
*/
public Alert getAlert() {
return this.locallyStoredAlert;
}
private static class LocallyStoredAlert implements Alert, Serializable {
private static final long serialVersionUID = 1L;
private final String alertText;
public LocallyStoredAlert(String alertText) {
this.alertText = alertText;
}
public void dismiss() {
throwAlreadyDismissed();
}
public void accept() {
throwAlreadyDismissed();
}
public String getText() {
return this.alertText;
}
public void sendKeys(String keysToSend) {
throwAlreadyDismissed();
}
private void throwAlreadyDismissed() {
throw new UnsupportedOperationException("Alert was already dismissed");
}
}
}
| java/client/src/org/openqa/selenium/UnhandledAlertException.java | /*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Portions copyright 2011 Software Freedom Conservancy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium;
public class UnhandledAlertException extends WebDriverException {
private final Alert locallyStoredAlert;
public UnhandledAlertException(String commandName) {
this(commandName, null);
}
public UnhandledAlertException(String commandName, String alertText) {
super(commandName);
this.locallyStoredAlert = alertText == null ? null : new LocallyStoredAlert(alertText);
}
/*
* Returns null if alert text could not be retrieved.
*/
public Alert getAlert() {
return this.locallyStoredAlert;
}
private static class LocallyStoredAlert implements Alert {
private final String alertText;
public LocallyStoredAlert(String alertText) {
this.alertText = alertText;
}
public void dismiss() {
throwAlreadyDismissed();
}
public void accept() {
throwAlreadyDismissed();
}
public String getText() {
return this.alertText;
}
public void sendKeys(String keysToSend) {
throwAlreadyDismissed();
}
private void throwAlreadyDismissed() {
throw new UnsupportedOperationException("Alert was already dismissed");
}
}
}
| DanielWagnerHall: Mark LocallyStoredAlert as Serializable, which hopefully will make it pass on Sauce
git-svn-id: aa1aa1384423cb28c2b1e29129bb3a91de1d9196@15826 07704840-8298-11de-bf8c-fd130f914ac9
| java/client/src/org/openqa/selenium/UnhandledAlertException.java | DanielWagnerHall: Mark LocallyStoredAlert as Serializable, which hopefully will make it pass on Sauce |
|
Java | apache-2.0 | 5c2cb2d668f5ff8fe0694ca9fea9c2daf1657d61 | 0 | GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,GerritCodeReview/gerrit | // Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.permissions;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.stream.Collectors.toSet;
import com.google.auto.value.AutoValue;
import com.google.common.collect.Sets;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.extensions.api.access.GlobalOrPluginPermission;
import com.google.gerrit.extensions.conditions.BooleanCondition;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
import com.google.inject.ImplementedBy;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Checks authorization to perform an action on a project, reference, or change.
*
* <p>{@code check} methods should be used during action handlers to verify the user is allowed to
* exercise the specified permission. For convenience in implementation {@code check} methods throw
* {@link AuthException} if the permission is denied.
*
* <p>{@code test} methods should be used when constructing replies to the client and the result
* object needs to include a true/false hint indicating the user's ability to exercise the
* permission. This is suitable for configuring UI button state, but should not be relied upon to
* guard handlers before making state changes.
*
* <p>{@code PermissionBackend} is a singleton for the server, acting as a factory for lightweight
* request instances. Implementation classes may cache supporting data inside of {@link WithUser},
* {@link ForProject}, {@link ForRef}, and {@link ForChange} instances, in addition to storing
* within {@link CurrentUser} using a {@link com.google.gerrit.server.CurrentUser.PropertyKey}.
* {@link GlobalPermission} caching for {@link WithUser} may best cached inside {@link CurrentUser}
* as {@link WithUser} instances are frequently created.
*
* <p>Example use:
*
* <pre>
* private final PermissionBackend permissions;
* private final Provider<CurrentUser> user;
*
* @Inject
* Foo(PermissionBackend permissions, Provider<CurrentUser> user) {
* this.permissions = permissions;
* this.user = user;
* }
*
* public void apply(...) {
* permissions.user(user).change(cd).check(ChangePermission.SUBMIT);
* }
*
* public UiAction.Description getDescription(ChangeResource rsrc) {
* return new UiAction.Description()
* .setLabel("Submit")
* .setVisible(rsrc.permissions().testCond(ChangePermission.SUBMIT));
* }
* </pre>
*/
@ImplementedBy(DefaultPermissionBackend.class)
public abstract class PermissionBackend {
private static final Logger logger = LoggerFactory.getLogger(PermissionBackend.class);
/** Returns an instance scoped to the current user. */
public abstract WithUser currentUser();
/**
* Returns an instance scoped to the specified user. Should be used in cases where the user could
* either be the issuer of the current request or an impersonated user. PermissionBackends that do
* not support impersonation can fail with an {@code IllegalStateException}.
*
* <p>If an instance scoped to the current user is desired, use {@code currentUser()} instead.
*/
public abstract WithUser user(CurrentUser user);
/**
* Returns an instance scoped to the provided user. Should be used in cases where the caller wants
* to check the permissions of a user who is not the issuer of the current request and not the
* target of impersonation.
*
* <p>Usage should be very limited as this can expose a group-oracle.
*/
public abstract WithUser absentUser(Account.Id user);
/**
* Check whether this {@code PermissionBackend} respects the same global capabilities as the
* {@link DefaultPermissionBackend}.
*
* <p>If true, then it makes sense for downstream callers to refer to built-in Gerrit capability
* names in user-facing error messages, for example.
*
* @return whether this is the default permission backend.
*/
public boolean usesDefaultCapabilities() {
return false;
}
/**
* Throw {@link ResourceNotFoundException} if this backend does not use the default global
* capabilities.
*/
public void checkUsesDefaultCapabilities() throws ResourceNotFoundException {
if (!usesDefaultCapabilities()) {
throw new ResourceNotFoundException("Gerrit capabilities not used on this server");
}
}
/**
* Bulk evaluate a set of {@link PermissionBackendCondition} for view handling.
*
* <p>Overridden implementations should call {@link PermissionBackendCondition#set(boolean)} to
* cache the result of {@code testOrFalse} in the condition for later evaluation. Caching the
* result will bypass the usual invocation of {@code testOrFalse}.
*
* @param conds conditions to consider.
*/
public void bulkEvaluateTest(Set<PermissionBackendCondition> conds) {
// Do nothing by default. The default implementation of PermissionBackendCondition
// delegates to the appropriate testOrFalse method in PermissionBackend.
}
/** PermissionBackend with an optional per-request ReviewDb handle. */
public abstract static class AcceptsReviewDb<T> {
protected Provider<ReviewDb> db;
public T database(Provider<ReviewDb> db) {
if (db != null) {
this.db = db;
}
return self();
}
public T database(ReviewDb db) {
return database(Providers.of(checkNotNull(db, "ReviewDb")));
}
@SuppressWarnings("unchecked")
private T self() {
return (T) this;
}
}
/** PermissionBackend scoped to a specific user. */
public abstract static class WithUser extends AcceptsReviewDb<WithUser> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns an instance scoped for the specified project. */
public abstract ForProject project(Project.NameKey project);
/** Returns an instance scoped for the {@code ref}, and its parent project. */
public ForRef ref(Branch.NameKey ref) {
return project(ref.getParentKey()).ref(ref.get()).database(db);
}
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeData cd) {
try {
return ref(cd.change().getDest()).change(cd);
} catch (OrmException e) {
return FailedPermissionBackend.change("unavailable", e);
}
}
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeNotes notes) {
return ref(notes.getChange().getDest()).change(notes);
}
/**
* Returns an instance scoped for the change loaded from index, and its destination ref and
* project. This method should only be used when database access is harmful and potentially
* stale data from the index is acceptable.
*/
public ForChange indexedChange(ChangeData cd, ChangeNotes notes) {
return ref(notes.getChange().getDest()).indexedChange(cd, notes);
}
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(GlobalOrPluginPermission perm)
throws AuthException, PermissionBackendException;
/**
* Verify scoped user can perform at least one listed permission.
*
* <p>If {@code any} is empty, the method completes normally and allows the caller to continue.
* Since no permissions were supplied to check, its assumed no permissions are necessary to
* continue with the caller's operation.
*
* <p>If the user has at least one of the permissions in {@code any}, the method completes
* normally, possibly without checking all listed permissions.
*
* <p>If {@code any} is non-empty and the user has none, {@link AuthException} is thrown for one
* of the failed permissions.
*
* @param any set of permissions to check.
*/
public void checkAny(Set<GlobalOrPluginPermission> any)
throws PermissionBackendException, AuthException {
for (Iterator<GlobalOrPluginPermission> itr = any.iterator(); itr.hasNext(); ) {
try {
check(itr.next());
return;
} catch (AuthException err) {
if (!itr.hasNext()) {
throw err;
}
}
}
}
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract <T extends GlobalOrPluginPermission> Set<T> test(Collection<T> permSet)
throws PermissionBackendException;
public boolean test(GlobalOrPluginPermission perm) throws PermissionBackendException {
return test(Collections.singleton(perm)).contains(perm);
}
public boolean testOrFalse(GlobalOrPluginPermission perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(GlobalOrPluginPermission perm) {
return new PermissionBackendCondition.WithUser(this, perm);
}
/**
* Filter a set of projects using {@code check(perm)}.
*
* @param perm required permission in a project to be included in result.
* @param projects candidate set of projects; may be empty.
* @return filtered set of {@code projects} where {@code check(perm)} was successful.
* @throws PermissionBackendException backend cannot access its internal state.
*/
public Set<Project.NameKey> filter(ProjectPermission perm, Collection<Project.NameKey> projects)
throws PermissionBackendException {
checkNotNull(perm, "ProjectPermission");
checkNotNull(projects, "projects");
Set<Project.NameKey> allowed = Sets.newHashSetWithExpectedSize(projects.size());
for (Project.NameKey project : projects) {
try {
project(project).check(perm);
allowed.add(project);
} catch (AuthException e) {
// Do not include this project in allowed.
} catch (PermissionBackendException e) {
if (e.getCause() instanceof RepositoryNotFoundException) {
logger.warn("Could not find repository of the project {} : ", project.get(), e);
// Do not include this project because doesn't exist
} else {
throw e;
}
}
}
return allowed;
}
}
/** PermissionBackend scoped to a user and project. */
public abstract static class ForProject extends AcceptsReviewDb<ForProject> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns the fully qualified resource path that this instance is scoped to. */
public abstract String resourcePath();
/** Returns a new instance rescoped to same project, but different {@code user}. */
public abstract ForProject user(CurrentUser user);
/** Returns an instance scoped for {@code ref} in this project. */
public abstract ForRef ref(String ref);
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeData cd) {
try {
return ref(cd.change().getDest().get()).change(cd);
} catch (OrmException e) {
return FailedPermissionBackend.change("unavailable", e);
}
}
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeNotes notes) {
return ref(notes.getChange().getDest().get()).change(notes);
}
/**
* Returns an instance scoped for the change loaded from index, and its destination ref and
* project. This method should only be used when database access is harmful and potentially
* stale data from the index is acceptable.
*/
public ForChange indexedChange(ChangeData cd, ChangeNotes notes) {
return ref(notes.getChange().getDest().get()).indexedChange(cd, notes);
}
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(ProjectPermission perm)
throws AuthException, PermissionBackendException;
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract Set<ProjectPermission> test(Collection<ProjectPermission> permSet)
throws PermissionBackendException;
public boolean test(ProjectPermission perm) throws PermissionBackendException {
return test(EnumSet.of(perm)).contains(perm);
}
public boolean testOrFalse(ProjectPermission perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(ProjectPermission perm) {
return new PermissionBackendCondition.ForProject(this, perm);
}
/**
* Filter a map of references by visibility.
*
* @param refs a map of references to filter.
* @param repo an open {@link Repository} handle for this instance's project
* @param opts further options for filtering.
* @return a partition of the provided refs that are visible to the user that this instance is
* scoped to.
* @throws PermissionBackendException if failure consulting backend configuration.
*/
public abstract Map<String, Ref> filter(
Map<String, Ref> refs, Repository repo, RefFilterOptions opts)
throws PermissionBackendException;
}
/** Options for filtering refs using {@link ForProject}. */
@AutoValue
public abstract static class RefFilterOptions {
/** Remove all NoteDb refs (refs/changes/*, refs/users/*, edit refs) from the result. */
public abstract boolean filterMeta();
/** Separately add reachable tags. */
public abstract boolean filterTagsSeparately();
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_PermissionBackend_RefFilterOptions.Builder()
.setFilterMeta(false)
.setFilterTagsSeparately(false);
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder setFilterMeta(boolean val);
public abstract Builder setFilterTagsSeparately(boolean val);
public abstract RefFilterOptions build();
}
public static RefFilterOptions defaults() {
return builder().build();
}
}
/** PermissionBackend scoped to a user, project and reference. */
public abstract static class ForRef extends AcceptsReviewDb<ForRef> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns a fully qualified resource path that this instance is scoped to. */
public abstract String resourcePath();
/** Returns a new instance rescoped to same reference, but different {@code user}. */
public abstract ForRef user(CurrentUser user);
/** Returns an instance scoped to change. */
public abstract ForChange change(ChangeData cd);
/** Returns an instance scoped to change. */
public abstract ForChange change(ChangeNotes notes);
/**
* @return instance scoped to change loaded from index. This method should only be used when
* database access is harmful and potentially stale data from the index is acceptable.
*/
public abstract ForChange indexedChange(ChangeData cd, ChangeNotes notes);
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(RefPermission perm) throws AuthException, PermissionBackendException;
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract Set<RefPermission> test(Collection<RefPermission> permSet)
throws PermissionBackendException;
public boolean test(RefPermission perm) throws PermissionBackendException {
return test(EnumSet.of(perm)).contains(perm);
}
/**
* Test if user may be able to perform the permission.
*
* <p>Similar to {@link #test(RefPermission)} except this method returns {@code false} instead
* of throwing an exception.
*
* @param perm the permission to test.
* @return true if the user might be able to perform the permission; false if the user may be
* missing the necessary grants or state, or if the backend threw an exception.
*/
public boolean testOrFalse(RefPermission perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(RefPermission perm) {
return new PermissionBackendCondition.ForRef(this, perm);
}
}
/** PermissionBackend scoped to a user, project, reference and change. */
public abstract static class ForChange extends AcceptsReviewDb<ForChange> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns the fully qualified resource path that this instance is scoped to. */
public abstract String resourcePath();
/** Returns a new instance rescoped to same change, but different {@code user}. */
public abstract ForChange user(CurrentUser user);
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(ChangePermissionOrLabel perm)
throws AuthException, PermissionBackendException;
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract <T extends ChangePermissionOrLabel> Set<T> test(Collection<T> permSet)
throws PermissionBackendException;
public boolean test(ChangePermissionOrLabel perm) throws PermissionBackendException {
return test(Collections.singleton(perm)).contains(perm);
}
/**
* Test if user may be able to perform the permission.
*
* <p>Similar to {@link #test(ChangePermissionOrLabel)} except this method returns {@code false}
* instead of throwing an exception.
*
* @param perm the permission to test.
* @return true if the user might be able to perform the permission; false if the user may be
* missing the necessary grants or state, or if the backend threw an exception.
*/
public boolean testOrFalse(ChangePermissionOrLabel perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(ChangePermissionOrLabel perm) {
return new PermissionBackendCondition.ForChange(this, perm);
}
/**
* Test which values of a label the user may be able to set.
*
* @param label definition of the label to test values of.
* @return set containing values the user may be able to use; may be empty if none.
* @throws PermissionBackendException if failure consulting backend configuration.
*/
public Set<LabelPermission.WithValue> test(LabelType label) throws PermissionBackendException {
return test(valuesOf(checkNotNull(label, "LabelType")));
}
/**
* Test which values of a group of labels the user may be able to set.
*
* @param types definition of the labels to test values of.
* @return set containing values the user may be able to use; may be empty if none.
* @throws PermissionBackendException if failure consulting backend configuration.
*/
public Set<LabelPermission.WithValue> testLabels(Collection<LabelType> types)
throws PermissionBackendException {
checkNotNull(types, "LabelType");
return test(types.stream().flatMap((t) -> valuesOf(t).stream()).collect(toSet()));
}
private static Set<LabelPermission.WithValue> valuesOf(LabelType label) {
return label
.getValues()
.stream()
.map((v) -> new LabelPermission.WithValue(label, v))
.collect(toSet());
}
}
}
| java/com/google/gerrit/server/permissions/PermissionBackend.java | // Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.permissions;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.stream.Collectors.toSet;
import com.google.auto.value.AutoValue;
import com.google.common.collect.Sets;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.extensions.api.access.GlobalOrPluginPermission;
import com.google.gerrit.extensions.conditions.BooleanCondition;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Branch;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gwtorm.server.OrmException;
import com.google.inject.ImplementedBy;
import com.google.inject.Provider;
import com.google.inject.util.Providers;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Checks authorization to perform an action on a project, reference, or change.
*
* <p>{@code check} methods should be used during action handlers to verify the user is allowed to
* exercise the specified permission. For convenience in implementation {@code check} methods throw
* {@link AuthException} if the permission is denied.
*
* <p>{@code test} methods should be used when constructing replies to the client and the result
* object needs to include a true/false hint indicating the user's ability to exercise the
* permission. This is suitable for configuring UI button state, but should not be relied upon to
* guard handlers before making state changes.
*
* <p>{@code PermissionBackend} is a singleton for the server, acting as a factory for lightweight
* request instances. Implementation classes may cache supporting data inside of {@link WithUser},
* {@link ForProject}, {@link ForRef}, and {@link ForChange} instances, in addition to storing
* within {@link CurrentUser} using a {@link com.google.gerrit.server.CurrentUser.PropertyKey}.
* {@link GlobalPermission} caching for {@link WithUser} may best cached inside {@link CurrentUser}
* as {@link WithUser} instances are frequently created.
*
* <p>Example use:
*
* <pre>
* private final PermissionBackend permissions;
* private final Provider<CurrentUser> user;
*
* @Inject
* Foo(PermissionBackend permissions, Provider<CurrentUser> user) {
* this.permissions = permissions;
* this.user = user;
* }
*
* public void apply(...) {
* permissions.user(user).change(cd).check(ChangePermission.SUBMIT);
* }
*
* public UiAction.Description getDescription(ChangeResource rsrc) {
* return new UiAction.Description()
* .setLabel("Submit")
* .setVisible(rsrc.permissions().testCond(ChangePermission.SUBMIT));
* }
* </pre>
*/
@ImplementedBy(DefaultPermissionBackend.class)
public abstract class PermissionBackend {
private static final Logger logger = LoggerFactory.getLogger(PermissionBackend.class);
/** Returns an instance scoped to the current user. */
public abstract WithUser currentUser();
/**
* Returns an instance scoped to the specified user. Should be used in cases where the user could
* either be the issuer of the current request or an impersonated user. PermissionBackends that do
* not support impersonation can fail with an {@code IllegalStateException}.
*
* <p>If an instance scoped to the current user is desired, use {@code currentUser()} instead.
*/
public abstract WithUser user(CurrentUser user);
/**
* Returns an instance scoped to the provided user. Should be used in cases where the caller wants
* to check the permissions of a user who is not the issuer of the current request and not the
* target of impersonation.
*
* <p>Usage should be very limited as this can expose a group-oracle.
*/
public abstract WithUser absentUser(Account.Id user);
/**
* Check whether this {@code PermissionBackend} respects the same global capabilities as the
* {@link DefaultPermissionBackend}.
*
* <p>If true, then it makes sense for downstream callers to refer to built-in Gerrit capability
* names in user-facing error messages, for example.
*
* @return whether this is the default permission backend.
*/
public boolean usesDefaultCapabilities() {
return false;
}
/**
* Throw {@link ResourceNotFoundException} if this backend does not use the default global
* capabilities.
*/
public void checkUsesDefaultCapabilities() throws ResourceNotFoundException {
if (!usesDefaultCapabilities()) {
throw new ResourceNotFoundException("Gerrit capabilities not used on this server");
}
}
/**
* Bulk evaluate a set of {@link PermissionBackendCondition} for view handling.
*
* <p>Overridden implementations should call {@link PermissionBackendCondition#set(boolean)} to
* cache the result of {@code testOrFalse} in the condition for later evaluation. Caching the
* result will bypass the usual invocation of {@code testOrFalse}.
*
* @param conds conditions to consider.
*/
public void bulkEvaluateTest(Set<PermissionBackendCondition> conds) {
// Do nothing by default. The default implementation of PermissionBackendCondition
// delegates to the appropriate testOrFalse method in PermissionBackend.
}
/** PermissionBackend with an optional per-request ReviewDb handle. */
public abstract static class AcceptsReviewDb<T> {
protected Provider<ReviewDb> db;
public T database(Provider<ReviewDb> db) {
if (db != null) {
this.db = db;
}
return self();
}
public T database(ReviewDb db) {
return database(Providers.of(checkNotNull(db, "ReviewDb")));
}
@SuppressWarnings("unchecked")
private T self() {
return (T) this;
}
}
/** PermissionBackend scoped to a specific user. */
public abstract static class WithUser extends AcceptsReviewDb<WithUser> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns an instance scoped for the specified project. */
public abstract ForProject project(Project.NameKey project);
/** Returns an instance scoped for the {@code ref}, and its parent project. */
public ForRef ref(Branch.NameKey ref) {
return project(ref.getParentKey()).ref(ref.get()).database(db);
}
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeData cd) {
try {
return ref(cd.change().getDest()).change(cd);
} catch (OrmException e) {
return FailedPermissionBackend.change("unavailable", e);
}
}
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeNotes notes) {
return ref(notes.getChange().getDest()).change(notes);
}
/**
* Returns an instance scoped for the change loaded from index, and its destination ref and
* project. This method should only be used when database access is harmful and potentially
* stale data from the index is acceptable.
*/
public ForChange indexedChange(ChangeData cd, ChangeNotes notes) {
return ref(notes.getChange().getDest()).indexedChange(cd, notes);
}
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(GlobalOrPluginPermission perm)
throws AuthException, PermissionBackendException;
/**
* Verify scoped user can perform at least one listed permission.
*
* <p>If {@code any} is empty, the method completes normally and allows the caller to continue.
* Since no permissions were supplied to check, its assumed no permissions are necessary to
* continue with the caller's operation.
*
* <p>If the user has at least one of the permissions in {@code any}, the method completes
* normally, possibly without checking all listed permissions.
*
* <p>If {@code any} is non-empty and the user has none, {@link AuthException} is thrown for one
* of the failed permissions.
*
* @param any set of permissions to check.
*/
public void checkAny(Set<GlobalOrPluginPermission> any)
throws PermissionBackendException, AuthException {
for (Iterator<GlobalOrPluginPermission> itr = any.iterator(); itr.hasNext(); ) {
try {
check(itr.next());
return;
} catch (AuthException err) {
if (!itr.hasNext()) {
throw err;
}
}
}
}
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract <T extends GlobalOrPluginPermission> Set<T> test(Collection<T> permSet)
throws PermissionBackendException;
public boolean test(GlobalOrPluginPermission perm) throws PermissionBackendException {
return test(Collections.singleton(perm)).contains(perm);
}
public boolean testOrFalse(GlobalOrPluginPermission perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(GlobalOrPluginPermission perm) {
return new PermissionBackendCondition.WithUser(this, perm);
}
/**
* Filter a set of projects using {@code check(perm)}.
*
* @param perm required permission in a project to be included in result.
* @param projects candidate set of projects; may be empty.
* @return filtered set of {@code projects} where {@code check(perm)} was successful.
* @throws PermissionBackendException backend cannot access its internal state.
*/
public Set<Project.NameKey> filter(ProjectPermission perm, Collection<Project.NameKey> projects)
throws PermissionBackendException {
checkNotNull(perm, "ProjectPermission");
checkNotNull(projects, "projects");
Set<Project.NameKey> allowed = Sets.newHashSetWithExpectedSize(projects.size());
for (Project.NameKey project : projects) {
try {
project(project).check(perm);
allowed.add(project);
} catch (AuthException e) {
// Do not include this project in allowed.
} catch (PermissionBackendException e) {
if (e.getCause() instanceof RepositoryNotFoundException) {
logger.warn("Could not find repository of the project {} : ", project.get(), e);
// Do not include this project because doesn't exist
} else {
throw e;
}
}
}
return allowed;
}
}
/** PermissionBackend scoped to a user and project. */
public abstract static class ForProject extends AcceptsReviewDb<ForProject> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns the fully qualified resource path that this instance is scoped to. */
public abstract String resourcePath();
/** Returns a new instance rescoped to same project, but different {@code user}. */
public abstract ForProject user(CurrentUser user);
/** Returns an instance scoped for {@code ref} in this project. */
public abstract ForRef ref(String ref);
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeData cd) {
try {
return ref(cd.change().getDest().get()).change(cd);
} catch (OrmException e) {
return FailedPermissionBackend.change("unavailable", e);
}
}
/** Returns an instance scoped for the change, and its destination ref and project. */
public ForChange change(ChangeNotes notes) {
return ref(notes.getChange().getDest().get()).change(notes);
}
/**
* Returns an instance scoped for the change loaded from index, and its destination ref and
* project. This method should only be used when database access is harmful and potentially
* stale data from the index is acceptable.
*/
public ForChange indexedChange(ChangeData cd, ChangeNotes notes) {
return ref(notes.getChange().getDest().get()).indexedChange(cd, notes);
}
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(ProjectPermission perm)
throws AuthException, PermissionBackendException;
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract Set<ProjectPermission> test(Collection<ProjectPermission> permSet)
throws PermissionBackendException;
public boolean test(ProjectPermission perm) throws PermissionBackendException {
return test(EnumSet.of(perm)).contains(perm);
}
public boolean testOrFalse(ProjectPermission perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(ProjectPermission perm) {
return new PermissionBackendCondition.ForProject(this, perm);
}
/**
* Returns a partition of the provided refs that are visible to the user that this instance is
* scoped to.
*/
public abstract Map<String, Ref> filter(
Map<String, Ref> refs, Repository repo, RefFilterOptions opts)
throws PermissionBackendException;
}
/** Options for filtering refs using {@link ForProject}. */
@AutoValue
public abstract static class RefFilterOptions {
/** Remove all NoteDb refs (refs/changes/*, refs/users/*, edit refs) from the result. */
public abstract boolean filterMeta();
/** Separately add reachable tags. */
public abstract boolean filterTagsSeparately();
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_PermissionBackend_RefFilterOptions.Builder()
.setFilterMeta(false)
.setFilterTagsSeparately(false);
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder setFilterMeta(boolean val);
public abstract Builder setFilterTagsSeparately(boolean val);
public abstract RefFilterOptions build();
}
public static RefFilterOptions defaults() {
return builder().build();
}
}
/** PermissionBackend scoped to a user, project and reference. */
public abstract static class ForRef extends AcceptsReviewDb<ForRef> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns a fully qualified resource path that this instance is scoped to. */
public abstract String resourcePath();
/** Returns a new instance rescoped to same reference, but different {@code user}. */
public abstract ForRef user(CurrentUser user);
/** Returns an instance scoped to change. */
public abstract ForChange change(ChangeData cd);
/** Returns an instance scoped to change. */
public abstract ForChange change(ChangeNotes notes);
/**
* @return instance scoped to change loaded from index. This method should only be used when
* database access is harmful and potentially stale data from the index is acceptable.
*/
public abstract ForChange indexedChange(ChangeData cd, ChangeNotes notes);
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(RefPermission perm) throws AuthException, PermissionBackendException;
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract Set<RefPermission> test(Collection<RefPermission> permSet)
throws PermissionBackendException;
public boolean test(RefPermission perm) throws PermissionBackendException {
return test(EnumSet.of(perm)).contains(perm);
}
/**
* Test if user may be able to perform the permission.
*
* <p>Similar to {@link #test(RefPermission)} except this method returns {@code false} instead
* of throwing an exception.
*
* @param perm the permission to test.
* @return true if the user might be able to perform the permission; false if the user may be
* missing the necessary grants or state, or if the backend threw an exception.
*/
public boolean testOrFalse(RefPermission perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(RefPermission perm) {
return new PermissionBackendCondition.ForRef(this, perm);
}
}
/** PermissionBackend scoped to a user, project, reference and change. */
public abstract static class ForChange extends AcceptsReviewDb<ForChange> {
/** Returns the user this instance is scoped to. */
public abstract CurrentUser user();
/** Returns the fully qualified resource path that this instance is scoped to. */
public abstract String resourcePath();
/** Returns a new instance rescoped to same change, but different {@code user}. */
public abstract ForChange user(CurrentUser user);
/** Verify scoped user can {@code perm}, throwing if denied. */
public abstract void check(ChangePermissionOrLabel perm)
throws AuthException, PermissionBackendException;
/** Filter {@code permSet} to permissions scoped user might be able to perform. */
public abstract <T extends ChangePermissionOrLabel> Set<T> test(Collection<T> permSet)
throws PermissionBackendException;
public boolean test(ChangePermissionOrLabel perm) throws PermissionBackendException {
return test(Collections.singleton(perm)).contains(perm);
}
/**
* Test if user may be able to perform the permission.
*
* <p>Similar to {@link #test(ChangePermissionOrLabel)} except this method returns {@code false}
* instead of throwing an exception.
*
* @param perm the permission to test.
* @return true if the user might be able to perform the permission; false if the user may be
* missing the necessary grants or state, or if the backend threw an exception.
*/
public boolean testOrFalse(ChangePermissionOrLabel perm) {
try {
return test(perm);
} catch (PermissionBackendException e) {
logger.warn("Cannot test " + perm + "; assuming false", e);
return false;
}
}
public BooleanCondition testCond(ChangePermissionOrLabel perm) {
return new PermissionBackendCondition.ForChange(this, perm);
}
/**
* Test which values of a label the user may be able to set.
*
* @param label definition of the label to test values of.
* @return set containing values the user may be able to use; may be empty if none.
* @throws PermissionBackendException if failure consulting backend configuration.
*/
public Set<LabelPermission.WithValue> test(LabelType label) throws PermissionBackendException {
return test(valuesOf(checkNotNull(label, "LabelType")));
}
/**
* Test which values of a group of labels the user may be able to set.
*
* @param types definition of the labels to test values of.
* @return set containing values the user may be able to use; may be empty if none.
* @throws PermissionBackendException if failure consulting backend configuration.
*/
public Set<LabelPermission.WithValue> testLabels(Collection<LabelType> types)
throws PermissionBackendException {
checkNotNull(types, "LabelType");
return test(types.stream().flatMap((t) -> valuesOf(t).stream()).collect(toSet()));
}
private static Set<LabelPermission.WithValue> valuesOf(LabelType label) {
return label
.getValues()
.stream()
.map((v) -> new LabelPermission.WithValue(label, v))
.collect(toSet());
}
}
}
| Document that repo in ForProject#filter() must be scoped to the project
Change-Id: I874124896029aeae85b946bb1a81410e693b3cd4
| java/com/google/gerrit/server/permissions/PermissionBackend.java | Document that repo in ForProject#filter() must be scoped to the project |
|
Java | apache-2.0 | ae2a82711510d835e61e912f3f5abce73f2a95d4 | 0 | squanchy-dev/squanchy-android,squanchy-dev/squanchy-android,squanchy-dev/squanchy-android | package net.squanchy.schedule.view;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.TextView;
import net.squanchy.R;
import net.squanchy.schedule.domain.view.Event;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class OtherEventItemView extends EventItemView {
private static final int NO_DRAWABLE = 0;
private TextView titleView;
private TextView timestampView;
private ImageView illustrationView;
public OtherEventItemView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.cardViewDefaultStyle);
}
public OtherEventItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
timestampView = (TextView) findViewById(R.id.timestamp);
titleView = (TextView) findViewById(R.id.title);
illustrationView = (ImageView) findViewById(R.id.illustration);
}
@Override
public void updateWith(Event event) {
ensureSupportedType(event.type());
timestampView.setText(startTimeAsFormattedString(event));
titleView.setText(event.title());
illustrationView.setImageResource(illustrationFor(event.type()));
}
private void ensureSupportedType(Event.Type type) {
if (type == Event.Type.COFFEE_BREAK
|| type == Event.Type.LUNCH
|| type == Event.Type.OTHER
|| type == Event.Type.REGISTRATION
|| type == Event.Type.SOCIAL) {
return;
}
throw new IllegalArgumentException("Event with type " + type.name() + " is not supported by this view");
}
private String startTimeAsFormattedString(Event event) {
DateTimeFormatter formatter = DateTimeFormat.shortTime()
.withZone(event.timeZone());
return formatter.print(event.startTime().toDateTime());
}
@DrawableRes
private int illustrationFor(Event.Type type) {
switch (type) {
case COFFEE_BREAK:
return R.drawable.coffee_break;
case LUNCH:
return R.drawable.illustration_lunch;
case REGISTRATION:
return R.drawable.registration;
case OTHER:
return NO_DRAWABLE;
case SOCIAL:
return R.drawable.illustration_lunch; // TODO replace these with the correct images once we have them
default:
throw new IllegalArgumentException("Type not supported: " + type.name());
}
}
}
| app/src/main/java/net/squanchy/schedule/view/OtherEventItemView.java | package net.squanchy.schedule.view;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.TextView;
import net.squanchy.R;
import net.squanchy.schedule.domain.view.Event;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class OtherEventItemView extends EventItemView {
private TextView titleView;
private TextView timestampView;
private ImageView illustrationView;
public OtherEventItemView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.cardViewDefaultStyle);
}
public OtherEventItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
timestampView = (TextView) findViewById(R.id.timestamp);
titleView = (TextView) findViewById(R.id.title);
illustrationView = (ImageView) findViewById(R.id.illustration);
}
@Override
public void updateWith(Event event) {
ensureSupportedType(event.type());
timestampView.setText(startTimeAsFormattedString(event));
titleView.setText(event.title());
illustrationView.setImageResource(illustrationFor(event.type()));
}
private void ensureSupportedType(Event.Type type) {
if (type == Event.Type.COFFEE_BREAK
|| type == Event.Type.LUNCH
|| type == Event.Type.OTHER
|| type == Event.Type.REGISTRATION
|| type == Event.Type.SOCIAL) {
return;
}
throw new IllegalArgumentException("Event with type " + type.name() + " is not supported by this view");
}
private String startTimeAsFormattedString(Event event) {
DateTimeFormatter formatter = DateTimeFormat.shortTime()
.withZone(event.timeZone());
return formatter.print(event.startTime().toDateTime());
}
@DrawableRes
private int illustrationFor(Event.Type type) {
switch (type) {
case COFFEE_BREAK:
case LUNCH:
case OTHER:
case REGISTRATION:
case SOCIAL:
return R.drawable.illustration_lunch; // TODO replace these with the correct images once we have them
default:
throw new IllegalArgumentException("Type not supported: " + type.name());
}
}
}
| Bind coffee break, registration and other to their drawables
| app/src/main/java/net/squanchy/schedule/view/OtherEventItemView.java | Bind coffee break, registration and other to their drawables |
|
Java | apache-2.0 | 7897f718981a82a72fda2cc88f95c1b9f463a8be | 0 | yesil/jackrabbit-oak,francescomari/jackrabbit-oak,ieb/jackrabbit-oak,chetanmeh/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,afilimonov/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,tripodsan/jackrabbit-oak,afilimonov/jackrabbit-oak,meggermo/jackrabbit-oak,tripodsan/jackrabbit-oak,rombert/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,mduerig/jackrabbit-oak,yesil/jackrabbit-oak,tripodsan/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,meggermo/jackrabbit-oak,chetanmeh/jackrabbit-oak,meggermo/jackrabbit-oak,catholicon/jackrabbit-oak,joansmith/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,alexparvulescu/jackrabbit-oak,meggermo/jackrabbit-oak,kwin/jackrabbit-oak,joansmith/jackrabbit-oak,bdelacretaz/jackrabbit-oak,leftouterjoin/jackrabbit-oak,anchela/jackrabbit-oak,davidegiannella/jackrabbit-oak,tripodsan/jackrabbit-oak,stillalex/jackrabbit-oak,bdelacretaz/jackrabbit-oak,kwin/jackrabbit-oak,davidegiannella/jackrabbit-oak,alexkli/jackrabbit-oak,chetanmeh/jackrabbit-oak,catholicon/jackrabbit-oak,afilimonov/jackrabbit-oak,catholicon/jackrabbit-oak,code-distillery/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,stillalex/jackrabbit-oak,ieb/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,yesil/jackrabbit-oak,alexkli/jackrabbit-oak,code-distillery/jackrabbit-oak,code-distillery/jackrabbit-oak,mduerig/jackrabbit-oak,kwin/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,leftouterjoin/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,code-distillery/jackrabbit-oak,rombert/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,ieb/jackrabbit-oak,davidegiannella/jackrabbit-oak,joansmith/jackrabbit-oak,bdelacretaz/jackrabbit-oak,joansmith/jackrabbit-oak,mduerig/jackrabbit-oak,rombert/jackrabbit-oak,alexparvulescu/jackrabbit-oak,davidegiannella/jackrabbit-oak,alexparvulescu/jackrabbit-oak,chetanmeh/jackrabbit-oak,catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,leftouterjoin/jackrabbit-oak,joansmith/jackrabbit-oak,francescomari/jackrabbit-oak,leftouterjoin/jackrabbit-oak,anchela/jackrabbit-oak,kwin/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,ieb/jackrabbit-oak,mduerig/jackrabbit-oak,chetanmeh/jackrabbit-oak,rombert/jackrabbit-oak,kwin/jackrabbit-oak,davidegiannella/jackrabbit-oak,anchela/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,bdelacretaz/jackrabbit-oak,alexparvulescu/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,meggermo/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,mduerig/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,afilimonov/jackrabbit-oak,yesil/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,francescomari/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.oak.core;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.plugins.memory.MemoryChildNodeEntry;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeBuilder;
import org.apache.jackrabbit.oak.spi.state.AbstractNodeState;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
/**
* SecureNodeState...
*
* TODO: clarify if HIDDEN items should be filtered by this NodeState implementation
* TODO: clarify usage of ReadStatus in getChildNodeEntries
*/
class SecureNodeState extends AbstractNodeState {
/**
* Underlying node state.
*/
private final NodeState state;
/**
* Security context of this subtree.
*/
private final SecurityContext context;
/**
* Predicate for testing whether a given property is readable.
*/
private final Predicate<PropertyState> isPropertyReadable = new ReadablePropertyPredicate();
/**
* Predicate for testing whether the node state in a child node entry
* is iterable.
*/
private final Predicate<ChildNodeEntry> isIterableNode = new IterableNodePredicate();
/**
* Function that that adds a security wrapper to node states from
* in child node entries. The {@link #isIterableNode} predicate should be
* used on the result to filter out non-existing/iterable child nodes.
* <p>
* Note that the SecureNodeState wrapper is needed only when the child
* or any of its descendants has read access restrictions. Otherwise
* we can optimize access by skipping the security wrapper entirely.
*/
private final WrapChildEntryFunction wrapChildNodeEntry = new WrapChildEntryFunction();
private long childNodeCount = -1;
private long propertyCount = -1;
SecureNodeState(
@Nonnull NodeState state, @Nonnull SecurityContext context) {
this.state = checkNotNull(state);
this.context = checkNotNull(context);
}
@Override
public boolean exists() {
return context.canReadThisNode();
}
@Override @CheckForNull
public PropertyState getProperty(String name) {
PropertyState property = state.getProperty(name);
if (property != null && context.canReadProperty(property)) {
return property;
} else {
return null;
}
}
@Override
public synchronized long getPropertyCount() {
if (propertyCount == -1) {
if (context.canReadAll()) {
propertyCount = state.getPropertyCount();
} else {
propertyCount = count(filter(state.getProperties(), isPropertyReadable));
}
}
return propertyCount;
}
@Override @Nonnull
public Iterable<? extends PropertyState> getProperties() {
if (context.canReadAll()) {
return state.getProperties();
} else {
return filter(state.getProperties(), isPropertyReadable);
}
}
@Override
public NodeState getChildNode(@Nonnull String name) {
NodeState child = state.getChildNode(checkNotNull(name));
if (child.exists() && !context.canReadAll()) {
ChildNodeEntry entry = new MemoryChildNodeEntry(name, child);
return wrapChildNodeEntry.apply(entry).getNodeState();
} else {
return child;
}
}
@Override
public synchronized long getChildNodeCount() {
if (childNodeCount == -1) {
if (context.canReadAll()) {
childNodeCount = state.getChildNodeCount();
} else {
childNodeCount = super.getChildNodeCount();
}
}
return childNodeCount;
}
@Override @Nonnull
public Iterable<? extends ChildNodeEntry> getChildNodeEntries() {
if (context.canReadAll()) {
// everything is readable including ac-content -> no secure wrapper needed
return state.getChildNodeEntries();
} else {
Iterable<ChildNodeEntry> readable = transform(state.getChildNodeEntries(), wrapChildNodeEntry);
return filter(readable, isIterableNode);
}
}
@Override @Nonnull
public NodeBuilder builder() {
return new MemoryNodeBuilder(this);
}
//-------------------------------------------------------------< Object >---
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
} else if (object instanceof SecureNodeState) {
SecureNodeState that = (SecureNodeState) object;
// TODO: We should be able to do this optimization also across
// different revisions (root states) as long as the path,
// the subtree, and any security-related areas like the
// permission store are equal for both states.
if (state.equals(that.state) && context.equals(that.context)) {
return true;
}
}
return super.equals(object);
}
//------------------------------------------------------< inner classes >---
/**
* Predicate for testing whether a given property is readable.
*/
private class ReadablePropertyPredicate implements Predicate<PropertyState> {
@Override
public boolean apply(@Nonnull PropertyState property) {
return context.canReadProperty(property);
}
}
/**
* Predicate for testing whether the node state in a child node entry is iterable.
*/
private class IterableNodePredicate implements Predicate<ChildNodeEntry> {
@Override
public boolean apply(@Nonnull ChildNodeEntry input) {
return input.getNodeState().exists();
}
}
/**
* Function that that adds a security wrapper to node states from
* in child node entries. The {@link IterableNodePredicate} predicate should be
* used on the result to filter out non-existing/iterable child nodes.
* <p>
* Note that the SecureNodeState wrapper is needed only when the child
* or any of its descendants has read access restrictions. Otherwise
* we can optimize access by skipping the security wrapper entirely.
*/
private class WrapChildEntryFunction implements Function<ChildNodeEntry, ChildNodeEntry> {
@Nonnull
@Override
public ChildNodeEntry apply(@Nonnull ChildNodeEntry input) {
String name = input.getName();
NodeState child = input.getNodeState();
SecurityContext childContext = context.getChildContext(name, child);
SecureNodeState secureChild = new SecureNodeState(child, childContext);
if (child.getChildNodeCount() == 0
&& secureChild.context.canReadThisNode()
&& secureChild.context.canReadAllProperties()) {
// Since this is an accessible leaf node whose all properties
// are readable, we don't need the SecureNodeState wrapper
// TODO: A further optimization would be to return the raw
// underlying node state even for non-leaf nodes if we can
// tell in advance that the full subtree is readable. Then
// we also wouldn't need the above getChildNodeCount() call
// that's somewhat expensive on the MongoMK.
return input;
} else {
return new MemoryChildNodeEntry(name, secureChild);
}
}
}
}
| oak-core/src/main/java/org/apache/jackrabbit/oak/core/SecureNodeState.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.oak.core;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.plugins.memory.MemoryChildNodeEntry;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeBuilder;
import org.apache.jackrabbit.oak.spi.state.AbstractNodeState;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateDiff;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
/**
* SecureNodeState...
*
* TODO: clarify if HIDDEN items should be filtered by this NodeState implementation
* TODO: clarify usage of ReadStatus in getChildNodeEntries
* TODO: add proper equals/hashcode implementation
* TODO: should be package-private
*/
class SecureNodeState extends AbstractNodeState {
/**
* Underlying node state.
*/
private final NodeState state;
/**
* Security context of this subtree.
*/
private final SecurityContext context;
/**
* Predicate for testing whether a given property is readable.
*/
private final Predicate<PropertyState> isPropertyReadable = new ReadablePropertyPredicate();
/**
* Predicate for testing whether the node state in a child node entry
* is iterable.
*/
private final Predicate<ChildNodeEntry> isIterableNode = new IterableNodePredicate();
/**
* Function that that adds a security wrapper to node states from
* in child node entries. The {@link #isIterableNode} predicate should be
* used on the result to filter out non-existing/iterable child nodes.
* <p>
* Note that the SecureNodeState wrapper is needed only when the child
* or any of its descendants has read access restrictions. Otherwise
* we can optimize access by skipping the security wrapper entirely.
*/
private final WrapChildEntryFunction wrapChildNodeEntry = new WrapChildEntryFunction();
private long childNodeCount = -1;
private long propertyCount = -1;
SecureNodeState(
@Nonnull NodeState state, @Nonnull SecurityContext context) {
this.state = checkNotNull(state);
this.context = checkNotNull(context);
}
@Override
public boolean exists() {
return context.canReadThisNode();
}
@Override @CheckForNull
public PropertyState getProperty(String name) {
PropertyState property = state.getProperty(name);
if (property != null && context.canReadProperty(property)) {
return property;
} else {
return null;
}
}
@Override
public synchronized long getPropertyCount() {
if (propertyCount == -1) {
if (context.canReadAll()) {
propertyCount = state.getPropertyCount();
} else {
propertyCount = count(filter(state.getProperties(), isPropertyReadable));
}
}
return propertyCount;
}
@Override @Nonnull
public Iterable<? extends PropertyState> getProperties() {
if (context.canReadAll()) {
return state.getProperties();
} else {
return filter(state.getProperties(), isPropertyReadable);
}
}
@Override
public NodeState getChildNode(@Nonnull String name) {
NodeState child = state.getChildNode(checkNotNull(name));
if (child.exists() && !context.canReadAll()) {
ChildNodeEntry entry = new MemoryChildNodeEntry(name, child);
return wrapChildNodeEntry.apply(entry).getNodeState();
} else {
return child;
}
}
@Override
public synchronized long getChildNodeCount() {
if (childNodeCount == -1) {
if (context.canReadAll()) {
childNodeCount = state.getChildNodeCount();
} else {
childNodeCount = super.getChildNodeCount();
}
}
return childNodeCount;
}
@Override @Nonnull
public Iterable<? extends ChildNodeEntry> getChildNodeEntries() {
if (context.canReadAll()) {
// everything is readable including ac-content -> no secure wrapper needed
return state.getChildNodeEntries();
} else {
Iterable<ChildNodeEntry> readable = transform(state.getChildNodeEntries(), wrapChildNodeEntry);
return filter(readable, isIterableNode);
}
}
@Override @Nonnull
public NodeBuilder builder() {
return new MemoryNodeBuilder(this);
}
@Override
public void compareAgainstBaseState(NodeState base, NodeStateDiff diff) {
// FIXME: decide if comparison during commit should compare the secure
// states or the original node states without ac restrictions
super.compareAgainstBaseState(base, diff);
}
//-------------------------------------------------------------< Object >---
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
} else if (object instanceof SecureNodeState) {
SecureNodeState that = (SecureNodeState) object;
// TODO: We should be able to do this optimization also across
// different revisions (root states) as long as the path,
// the subtree, and any security-related areas like the
// permission store are equal for both states.
if (state.equals(that.state) && context.equals(that.context)) {
return true;
}
}
return super.equals(object);
}
//------------------------------------------------------< inner classes >---
/**
* Predicate for testing whether a given property is readable.
*/
private class ReadablePropertyPredicate implements Predicate<PropertyState> {
@Override
public boolean apply(@Nonnull PropertyState property) {
return context.canReadProperty(property);
}
}
/**
* Predicate for testing whether the node state in a child node entry is iterable.
*/
private class IterableNodePredicate implements Predicate<ChildNodeEntry> {
@Override
public boolean apply(@Nonnull ChildNodeEntry input) {
return input.getNodeState().exists();
}
}
/**
* Function that that adds a security wrapper to node states from
* in child node entries. The {@link IterableNodePredicate} predicate should be
* used on the result to filter out non-existing/iterable child nodes.
* <p>
* Note that the SecureNodeState wrapper is needed only when the child
* or any of its descendants has read access restrictions. Otherwise
* we can optimize access by skipping the security wrapper entirely.
*/
private class WrapChildEntryFunction implements Function<ChildNodeEntry, ChildNodeEntry> {
@Nonnull
@Override
public ChildNodeEntry apply(@Nonnull ChildNodeEntry input) {
String name = input.getName();
NodeState child = input.getNodeState();
SecurityContext childContext = context.getChildContext(name, child);
SecureNodeState secureChild = new SecureNodeState(child, childContext);
if (child.getChildNodeCount() == 0
&& secureChild.context.canReadThisNode()
&& secureChild.context.canReadAllProperties()) {
// Since this is an accessible leaf node whose all properties
// are readable, we don't need the SecureNodeState wrapper
// TODO: A further optimization would be to return the raw
// underlying node state even for non-leaf nodes if we can
// tell in advance that the full subtree is readable. Then
// we also wouldn't need the above getChildNodeCount() call
// that's somewhat expensive on the MongoMK.
return input;
} else {
return new MemoryChildNodeEntry(name, secureChild);
}
}
}
}
| OAK-709: Consider moving permission evaluation to the node state level
- implement rebasing of secure node state differences on top of non secure node state giving transient changes precedence: no need to override compareAgainstBaseState
- remove done TODOs
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1468820 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/main/java/org/apache/jackrabbit/oak/core/SecureNodeState.java | OAK-709: Consider moving permission evaluation to the node state level - implement rebasing of secure node state differences on top of non secure node state giving transient changes precedence: no need to override compareAgainstBaseState - remove done TODOs |
|
Java | apache-2.0 | 35ba26d5c8ac399fefe5d308556fe94e32628891 | 0 | realityforge/arez,realityforge/arez,realityforge/arez | package org.realityforge.arez.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import org.realityforge.arez.annotations.Container;
/**
* Annotation processor that analyzes Arez annotated source and generates Observable models.
*/
@AutoService( Processor.class )
@SupportedAnnotationTypes( { "org.realityforge.arez.annotations.Action",
"org.realityforge.arez.annotations.Computed",
"org.realityforge.arez.annotations.Container",
"org.realityforge.arez.annotations.ContainerId",
"org.realityforge.arez.annotations.Observable" } )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public final class ArezProcessor
extends AbstractJavaPoetProcessor
{
private static final ClassName AREZ_CONTEXT_CLASSNAME = ClassName.get( "org.realityforge.arez", "ArezContext" );
private static final String CONTEXT_FIELD_NAME = "$$arez$$_context";
/**
* {@inheritDoc}
*/
@Override
public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment env )
{
final Set<? extends Element> elements = env.getElementsAnnotatedWith( Container.class );
processElements( elements );
return false;
}
@Override
protected void process( @Nonnull final Element element )
throws IOException, ArezProcessorException
{
final ContainerDescriptor descriptor =
ContainerDescriptorParser.parse( element, processingEnv.getElementUtils(), processingEnv.getTypeUtils() );
emitTypeSpec( descriptor.getPackageElement().getQualifiedName().toString(), builder( descriptor ) );
}
@Nonnull
private TypeSpec builder( @Nonnull final ContainerDescriptor descriptor )
throws ArezProcessorException
{
final TypeElement element = descriptor.getElement();
final AnnotationSpec generatedAnnotation =
AnnotationSpec.builder( Generated.class ).addMember( "value", "$S", getClass().getName() ).build();
final TypeSpec.Builder builder = TypeSpec.classBuilder( "Arez_" + element.getSimpleName() ).
superclass( TypeName.get( element.asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( descriptor.asDeclaredType() ) ).
addModifiers( Modifier.FINAL ).
addAnnotation( generatedAnnotation );
ProcessorUtil.copyAccessModifiers( element, builder );
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( element ) )
{
builder.addMethod( buildConstructor( constructor ) );
}
return builder.build();
}
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ExecutableElement constructor )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
ProcessorUtil.copyAccessModifiers( constructor, builder );
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
return builder.build();
}
}
| processor/src/main/java/org/realityforge/arez/processor/ArezProcessor.java | package org.realityforge.arez.processor;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import org.realityforge.arez.annotations.Container;
/**
* Annotation processor that analyzes Arez annotated source and generates Observable models.
*/
@AutoService( Processor.class )
@SupportedAnnotationTypes( { "org.realityforge.arez.annotations.Action",
"org.realityforge.arez.annotations.Computed",
"org.realityforge.arez.annotations.Container",
"org.realityforge.arez.annotations.ContainerId",
"org.realityforge.arez.annotations.Observable" } )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public final class ArezProcessor
extends AbstractJavaPoetProcessor
{
private static final ClassName AREZ_CONTEXT_CLASSNAME = ClassName.get( "org.realityforge.arez", "ArezContext" );
/**
* {@inheritDoc}
*/
@Override
public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment env )
{
final Set<? extends Element> elements = env.getElementsAnnotatedWith( Container.class );
processElements( elements );
return false;
}
@Override
protected void process( @Nonnull final Element element )
throws IOException, ArezProcessorException
{
final ContainerDescriptor descriptor =
ContainerDescriptorParser.parse( element, processingEnv.getElementUtils(), processingEnv.getTypeUtils() );
emitTypeSpec( descriptor.getPackageElement().getQualifiedName().toString(), builder( descriptor ) );
}
@Nonnull
private TypeSpec builder( @Nonnull final ContainerDescriptor descriptor )
throws ArezProcessorException
{
final TypeElement element = descriptor.getElement();
final AnnotationSpec generatedAnnotation =
AnnotationSpec.builder( Generated.class ).addMember( "value", "$S", getClass().getName() ).build();
final TypeSpec.Builder builder = TypeSpec.classBuilder( "Arez_" + element.getSimpleName() ).
superclass( TypeName.get( element.asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( descriptor.asDeclaredType() ) ).
addModifiers( Modifier.FINAL ).
addAnnotation( generatedAnnotation );
ProcessorUtil.copyAccessModifiers( element, builder );
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( element ) )
{
builder.addMethod( buildConstructor( constructor ) );
}
return builder.build();
}
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ExecutableElement constructor )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
ProcessorUtil.copyAccessModifiers( constructor, builder );
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyDocumentedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
return builder.build();
}
}
| Extract constant for context field name
| processor/src/main/java/org/realityforge/arez/processor/ArezProcessor.java | Extract constant for context field name |
|
Java | apache-2.0 | e0021ade99fb570d1771ca6721ab812d40cfa033 | 0 | martamarszal/mini-mesos,ContainerSolutions/minimesos,jitpack-io/mini-mesos,mwl/mini-mesos,ContainerSolutions/minimesos,mwl/mini-mesos,ruo91/mini-mesos,puneetguptanitj/mini-mesos,ContainerSolutions/mini-mesos,ContainerSolutions/mini-mesos,ContainerSolutions/minimesos,jitpack-io/mini-mesos,Praqma/mini-mesos,jhftrifork/mini-mesos | package org.apache.mesos.mini.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.jayway.awaitility.core.ConditionTimeoutException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.log4j.Logger;
import org.apache.mesos.mini.MesosCluster;
import org.apache.mesos.mini.util.ContainerEchoResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* Utility for Docker related tasks such as pulling images and reading output.
*/
public class DockerUtil {
private static final ArrayList<String> containerIds = new ArrayList<String>(); // Massive hack. Todo. Static so it shuts down all containers.
public static Logger LOGGER = Logger.getLogger(MesosCluster.class);
private final DockerClient dockerClient;
public DockerUtil(DockerClient dockerClient) {
this.dockerClient = dockerClient;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LOGGER.info("Running shutdown hook");
DockerUtil.this.stop();
}
});
}
public static String consumeInputStream(InputStream response) {
StringWriter logwriter = new StringWriter();
try {
LineIterator itr = IOUtils.lineIterator(response, "UTF-8");
while (itr.hasNext()) {
String line = itr.next();
logwriter.write(line + (itr.hasNext() ? "\n" : ""));
LOGGER.info(line);
}
response.close();
return logwriter.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(response);
}
}
public String getContainerIp(String containerId) {
InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec();
assertThat(inspectContainerResponse.getNetworkSettings().getIpAddress(), notNullValue());
return inspectContainerResponse.getNetworkSettings().getIpAddress();
}
public void buildImageFromFolder(File dir, String tag) {
String fullLog;
assert dir.isDirectory();
InputStream responseBuildImage = dockerClient.buildImageCmd(dir).withTag(tag).exec();
fullLog = consumeInputStream(responseBuildImage);
assertThat(fullLog, containsString("Successfully built"));
}
public void buildImageFromFolder(String name, String tag) {
File folder = new File(Thread.currentThread().getContextClassLoader().getResource(name).getFile());
buildImageFromFolder(folder, tag);
}
public String createAndStart(CreateContainerCmd createCommand) {
LOGGER.debug("***************************** Creating container \"" + createCommand.getName() + "\" *****************************");
CreateContainerResponse r = createCommand.exec(); // we assume that if exec fails no container with that name is created so we don't need to clean up
String containerId = r.getId();
if (createCommand.getName() != null) {
containerIds.add(createCommand.getName()); // for better readability when logging the cleanup/removal of the containers
} else {
containerIds.add(containerId);
}
StartContainerCmd startMesosClusterContainerCmd = dockerClient.startContainerCmd(containerId);
startMesosClusterContainerCmd.exec();
awaitEchoResponse(containerId, createCommand.getName());
return containerId;
}
public void awaitEchoResponse(String containerId) throws ConditionTimeoutException {
awaitEchoResponse(containerId, containerId);
}
public void awaitEchoResponse(String containerId, String containerName) throws ConditionTimeoutException {
await("Waiting for container: " + containerName)
.atMost(10, TimeUnit.SECONDS)
.pollInterval(1, TimeUnit.SECONDS)
.until(new ContainerEchoResponse(dockerClient, containerId), is(true));
}
public void pullImage(String imageName, String registryTag) {
LOGGER.debug("***************************** Pulling image \"" + imageName + ":" + registryTag + "\" *****************************");
InputStream responsePullImages = dockerClient.pullImageCmd(imageName).withTag(registryTag).exec();
String fullLog = DockerUtil.consumeInputStream(responsePullImages);
assertThat(fullLog, anyOf(containsString("Download complete"), containsString("Already exists")));
}
public void stop() {
for (String containerId : containerIds) {
try {
dockerClient.removeContainerCmd(containerId).withForce().exec();
LOGGER.info("***************************** Removing container \"" + containerId + "\" *****************************");
} catch (Exception ignore) {
}
}
containerIds.clear();
}
} | src/main/java/org/apache/mesos/mini/docker/DockerUtil.java | package org.apache.mesos.mini.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.jayway.awaitility.core.ConditionTimeoutException;
import com.sun.tools.doclets.internal.toolkit.util.DocFinder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.log4j.Logger;
import org.apache.mesos.mini.MesosCluster;
import org.apache.mesos.mini.util.ContainerEchoResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* Utility for Docker related tasks such as pulling images and reading output.
*/
public class DockerUtil {
private static final ArrayList<String> containerIds = new ArrayList<String>(); // Massive hack. Todo. Static so it shuts down all containers.
public static Logger LOGGER = Logger.getLogger(MesosCluster.class);
private final DockerClient dockerClient;
public DockerUtil(DockerClient dockerClient) {
this.dockerClient = dockerClient;
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LOGGER.info("Running shutdown hook");
DockerUtil.this.stop();
}
});
}
public static String consumeInputStream(InputStream response) {
StringWriter logwriter = new StringWriter();
try {
LineIterator itr = IOUtils.lineIterator(response, "UTF-8");
while (itr.hasNext()) {
String line = itr.next();
logwriter.write(line + (itr.hasNext() ? "\n" : ""));
LOGGER.info(line);
}
response.close();
return logwriter.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(response);
}
}
public String getContainerIp(String containerId) {
InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(containerId).exec();
assertThat(inspectContainerResponse.getNetworkSettings().getIpAddress(), notNullValue());
return inspectContainerResponse.getNetworkSettings().getIpAddress();
}
public void buildImageFromFolder(File dir, String tag) {
String fullLog;
assert dir.isDirectory();
InputStream responseBuildImage = dockerClient.buildImageCmd(dir).withTag(tag).exec();
fullLog = consumeInputStream(responseBuildImage);
assertThat(fullLog, containsString("Successfully built"));
}
public void buildImageFromFolder(String name, String tag) {
File folder = new File(Thread.currentThread().getContextClassLoader().getResource(name).getFile());
buildImageFromFolder(folder, tag);
}
public String createAndStart(CreateContainerCmd createCommand) {
LOGGER.debug("***************************** Creating container \"" + createCommand.getName() + "\" *****************************");
CreateContainerResponse r = createCommand.exec(); // we assume that if exec fails no container with that name is created so we don't need to clean up
String containerId = r.getId();
if (createCommand.getName() != null) {
containerIds.add(createCommand.getName()); // for better readability when logging the cleanup/removal of the containers
} else {
containerIds.add(containerId);
}
StartContainerCmd startMesosClusterContainerCmd = dockerClient.startContainerCmd(containerId);
startMesosClusterContainerCmd.exec();
awaitEchoResponse(containerId, createCommand.getName());
return containerId;
}
public void awaitEchoResponse(String containerId) throws ConditionTimeoutException {
awaitEchoResponse(containerId, containerId);
}
public void awaitEchoResponse(String containerId, String containerName) throws ConditionTimeoutException {
await("Waiting for container: " + containerName)
.atMost(10, TimeUnit.SECONDS)
.pollInterval(1, TimeUnit.SECONDS)
.until(new ContainerEchoResponse(dockerClient, containerId), is(true));
}
public void pullImage(String imageName, String registryTag) {
LOGGER.debug("***************************** Pulling image \"" + imageName + ":" + registryTag + "\" *****************************");
InputStream responsePullImages = dockerClient.pullImageCmd(imageName).withTag(registryTag).exec();
String fullLog = DockerUtil.consumeInputStream(responsePullImages);
assertThat(fullLog, anyOf(containsString("Download complete"), containsString("Already exists")));
}
public void stop() {
for (String containerId : containerIds) {
try {
dockerClient.removeContainerCmd(containerId).withForce().exec();
LOGGER.info("***************************** Removing container \"" + containerId + "\" *****************************");
} catch (Exception ignore) {
}
}
containerIds.clear();
}
} | Fixed unused import
| src/main/java/org/apache/mesos/mini/docker/DockerUtil.java | Fixed unused import |
|
Java | apache-2.0 | 0f2a9c211cc04d7fb147917909c3b8f48452b4cf | 0 | bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.Abilities.Tech;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.Abilities.Common.CommonSkill;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2014-2016 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class AstroEngineering extends TechSkill
{
@Override
public String ID()
{
return "AstroEngineering";
}
private final static String localizedName = CMLib.lang().L("Astro Engineering");
@Override
public String name()
{
return localizedName;
}
@Override
public String displayText()
{
return "";
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
private static final String[] triggerStrings = I(new String[] { "ASTROENGINEER", "ASTROENGINEERING", "ENGINEER", "AE" });
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT;
}
protected volatile int baseTickSpan = Integer.MAX_VALUE;
protected volatile boolean aborted = false;
protected volatile boolean failure = false;
protected volatile Item targetItem = null;
protected volatile Item targetPanel = null;
protected volatile Room targetRoom = null;
protected volatile Operation op = Operation.REPAIR;
protected volatile String altverb = "";
protected static enum Operation
{
INSTALL("installing"),
REPAIR("repairing"),
ENHANCE("enhancing");
public String verb="";
private Operation(String verb)
{
this.verb=verb;
}
}
public int getBonus(MOB mob, Electronics item, int multiplyBy)
{
if((mob==null)||(item==null))
return 0;
double score = 0.0;
final Manufacturer m=item.getFinalManufacturer();
if(m==null)
score+=0.5;
else
{
final Pair<String,Integer> manuExpertise=mob.fetchExpertise(m.name()+"%");
if(manuExpertise!=null)
score += (0.5 * CMath.div(manuExpertise.second.intValue(), 100.0));
}
final Technical.TechType ttype = item.getTechType();
if(ttype==null)
score+=0.5;
else
{
final Pair<String,Integer> techTypeExpertise=mob.fetchExpertise(ttype.getDisplayName()+"%");
if(techTypeExpertise!=null)
score += (0.5 * CMath.div(techTypeExpertise.second.intValue(), 100.0));
}
return (int)Math.round(CMath.mul(multiplyBy, score));
}
public void giveBonus(MOB mob, Electronics item)
{
if((mob==null)||(item==null))
return;
if((System.currentTimeMillis()-lastCastHelp)<300000)
return;
String experName;
if(CMLib.dice().rollPercentage()>50)
{
final Manufacturer m=item.getFinalManufacturer();
if(m!=null)
{
experName=m.name();
}
else
return;
}
else
{
final Technical.TechType ttype = item.getTechType();
if(ttype!=null)
{
experName=ttype.getDisplayName();
}
else
return;
}
Pair<String,Integer> expertise=mob.fetchExpertise(experName+"%");
final int currentExpertise=(expertise!=null)?expertise.second.intValue():0;
if(((int)Math.round(Math.sqrt((mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)))*34.0*Math.random()))>=currentExpertise)
{
mob.addExpertise(experName+"%"+(currentExpertise+1));
lastCastHelp=System.currentTimeMillis();
AstroEngineering A=(AstroEngineering)mob.fetchAbility(ID());
if(A!=null)
A.lastCastHelp=System.currentTimeMillis();
mob.tell(mob,null,null,L("You gain some new insights about @x1.",CMLib.english().makePlural(experName.toLowerCase())));
}
}
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if((affected instanceof MOB)
&&(((MOB)affected).location()!=null))
{
final MOB mob=(MOB)affected;
final Room room=mob.location();
if((aborted)||(room==null))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> stop(s) @x1.",op.verb));
else
if(failure)
{
mob.location().show(mob,targetItem,CMMsg.MSG_OK_VISUAL,L("<S-NAME> mess(es) up @x1 <T-NAME>.",op.verb));
}
else
if(op==Operation.INSTALL)
{
final CMMsg msg=CMClass.getMsg(mob,targetPanel,targetItem,CMMsg.MSG_INSTALL,L("<S-NAME> install(s) <O-NAME> into <T-NAME>."));
msg.setValue(50+getBonus(mob,(Electronics)targetItem,50));
if(room.okMessage(msg.source(), msg))
{
room.send(msg.source(), msg);
giveBonus(mob,(Electronics)targetItem);
}
}
else
if(op==Operation.REPAIR)
{
final CMMsg msg=CMClass.getMsg(mob,targetItem,this,CMMsg.MSG_REPAIR,L("<S-NAME> <S-IS-ARE> done trying to repair <T-NAME>."));
msg.setValue(CMLib.dice().roll(1, proficiency()/2, getBonus(mob,(Electronics)targetItem,50)));
if(room.okMessage(msg.source(), msg))
{
room.send(msg.source(), msg);
giveBonus(mob,(Electronics)targetItem);
}
}
else
{
String verb=altverb;
final CMMsg msg=CMClass.getMsg(mob,targetItem,this,CMMsg.MSG_ENHANCE,L("<S-NAME> <S-IS-ARE> done @x1 <T-NAME>.",verb));
msg.setValue((proficiency()/2)+getBonus(mob,(Electronics)targetItem,50));
if(room.okMessage(msg.source(), msg))
{
room.send(msg.source(), msg);
giveBonus(mob,(Electronics)targetItem);
}
}
}
aborted = false;
targetItem = null;
targetPanel = null;
targetRoom = null;
}
super.unInvoke();
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
final MOB mob=(MOB)affected;
if((mob.isInCombat())
||(mob.location()!=targetRoom)
||(!CMLib.flags().isAliveAwakeMobileUnbound(mob,true)))
{
aborted=true;
unInvoke();
return false;
}
if(tickDown==4)
{
String verb=op.verb;
if(op==Operation.ENHANCE)
verb=altverb;
mob.location().show(mob,targetItem,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> <S-IS-ARE> almost done @x1 <T-NAME>.",verb));
}
else
if(((baseTickSpan-tickDown)%4)==0)
{
final int total=baseTickSpan;
final int tickUp=(baseTickSpan-tickDown);
final int pct=(int)Math.round(CMath.div(tickUp,total)*100.0);
String verb=op.verb;
if(op==Operation.ENHANCE)
verb=altverb;
mob.location().show(mob,targetItem,this,CMMsg.MSG_NOISYMOVEMENT,
L("<S-NAME> continue(s) @x1 <T-NAME> (@x2% completed).",verb,""+pct),
null,L("<S-NAME> continue(s) @x1 <T-NAME>.",verb));
}
if((mob.soulMate()==null)
&&(mob.playerStats()!=null)
&&(mob.location()!=null)
&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.HYGIENE)))
mob.playerStats().adjHygiene(PlayerStats.HYGIENE_COMMONDIRTY);
}
if(!super.tick(ticking,tickID))
return false;
return true;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((myHost instanceof MOB)&&(myHost == this.affected)&&(((MOB)myHost).location()!=null))
{
if((msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
||((msg.sourceMinor()==CMMsg.TYP_QUIT)&&(msg.amISource((MOB)myHost))))
{
aborted=true;
unInvoke();
}
}
return true;
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(commands.size()<1)
{
mob.tell(L("What would you like to install, repair, or enhance?"));
return false;
}
aborted = false;
failure = false;
targetItem = null;
targetPanel = null;
targetRoom = mob.location();
op=Operation.REPAIR;
int minTicks=8;
if("INSTALL".startsWith((commands.get(0)).toUpperCase()))
{
op=Operation.INSTALL;
commands.remove(0);
if(givenTarget instanceof Item)
{
targetPanel=(Item)givenTarget;
}
else
if(commands.size()<2)
{
mob.tell(L("You need to specify an item to install and a panel to install it into."));
return false;
}
else
{
final String panelName=commands.get(commands.size()-1);
targetPanel=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,panelName);
if(targetPanel==null)
{
targetPanel=targetRoom.findItem(null,panelName);
}
if((targetPanel==null)||(!CMLib.flags().canBeSeenBy(targetPanel,mob)))
{
mob.tell(L("You don't see '@x1' here.",panelName));
return false;
}
if(!(targetPanel instanceof ElecPanel))
{
mob.tell(L("That's not an electronics panel."));
return false;
}
commands.remove(commands.size()-1);
}
}
else
if("REPAIR".startsWith((commands.get(0)).toUpperCase()))
{
op=Operation.REPAIR;
commands.remove(0);
}
else
if("ENHANCE".startsWith((commands.get(0)).toUpperCase()))
{
op=Operation.ENHANCE;
final String[] verbs=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_VERBS);
final String[] adjs1=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_ADJ1);
final String[] adjs2=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_ADJ2);
final String[] adjs12=new String[adjs1.length+adjs2.length];
System.arraycopy(adjs1, 0, adjs12, 0, adjs1.length);
System.arraycopy(adjs2, 0, adjs12, adjs1.length, adjs2.length);
final String[] nouns=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_NOUN);
altverb=verbs[CMLib.dice().roll(1, verbs.length, -1)].trim()+" "
+adjs12[CMLib.dice().roll(1, adjs12.length, -1)].trim()+" "
+adjs2[CMLib.dice().roll(1, adjs2.length, -1)].trim()+" "
+nouns[CMLib.dice().roll(1, nouns.length, -1)].trim()
;
commands.remove(0);
}
final String itemName=CMParms.combine(commands,0);
if(targetItem == null)
targetItem=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,itemName);
if(targetItem==null)
targetItem=targetRoom.findItem(null,itemName);
if((targetItem==null)&&(targetPanel==null))
{
final CMFlagLibrary flagLib=CMLib.flags();
for(int i=0;i<targetRoom.numItems();i++)
{
final Item I=targetRoom.getItem(i);
if((flagLib.isOpenAccessibleContainer(I))
&&(flagLib.canBeSeenBy(I, mob)))
{
targetItem=targetRoom.findItem(I,itemName);
if(targetItem!=null)
break;
}
}
}
if((targetItem==null)||(!CMLib.flags().canBeSeenBy(targetItem,mob)))
{
mob.tell(L("You don't see '@x1' here.",itemName));
return false;
}
if(!(targetItem instanceof Electronics))
{
mob.tell(L("That's not an electronics item."));
return false;
}
if(!(targetItem instanceof TechComponent))
{
mob.tell(L("That's not a space ship component."));
return false;
}
if(mob.isInCombat())
{
mob.tell(mob,null,null,L("<S-NAME> <S-IS-ARE> in combat!"));
return false;
}
if(!CMLib.flags().canBeSeenBy(targetRoom,mob))
{
mob.tell(mob,null,null,L("<S-NAME> can't see to do that!"));
return false;
}
if(CMLib.flags().isSitting(mob)||CMLib.flags().isSleeping(mob))
{
mob.tell(mob,null,null,L("You need to stand up!"));
return false;
}
if(op==Operation.REPAIR)
{
if(!targetItem.subjectToWearAndTear())
{
mob.tell(mob,targetItem,null,L("<T-NAME> can't be repaired!"));
return false;
}
}
else
if(op==Operation.ENHANCE)
{
if((targetItem.subjectToWearAndTear())&&(targetItem.usesRemaining()<100))
{
mob.tell(mob,targetItem,null,L("<T-NAME> must be repaired first!"));
return false;
}
if(targetItem instanceof TechComponent)
{
if(((TechComponent)targetItem).getInstalledFactor()>1.0)
minTicks+=(int)Math.round((((TechComponent)targetItem).getInstalledFactor()-1.0)*0.01);
}
}
for(final Enumeration<Ability> a=mob.personalEffects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)||(A.ID().equalsIgnoreCase("AstroEngineering"))))
{
if(A instanceof AstroEngineering)
((AstroEngineering)A).aborted=true;
A.unInvoke();
}
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
failure=!proficiencyCheck(mob,0,auto);
baseTickSpan = targetItem.basePhyStats().weight()/4;
if(failure)
baseTickSpan=baseTickSpan/2;
if(baseTickSpan<minTicks)
baseTickSpan=minTicks;
mob.location().show(mob,targetItem,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> start(s) @x1 <T-NAME>@x2.",op.verb,((targetPanel!=null)?" into "+targetPanel.name():"")));
beneficialAffect(mob, mob, asLevel, baseTickSpan);
return !failure;
}
}
| com/planet_ink/coffee_mud/Abilities/Tech/AstroEngineering.java | package com.planet_ink.coffee_mud.Abilities.Tech;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.Abilities.Common.CommonSkill;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2014-2016 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class AstroEngineering extends TechSkill
{
@Override public String ID() { return "AstroEngineering"; }
private final static String localizedName = CMLib.lang().L("Astro Engineering");
@Override public String name() { return localizedName; }
@Override public String displayText(){ return "";}
@Override protected int canAffectCode(){return CAN_MOBS;}
@Override protected int canTargetCode(){return CAN_ITEMS;}
@Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;}
private static final String[] triggerStrings =I(new String[] {"ASTROENGINEER","ASTROENGINEERING","ENGINEER","AE"});
@Override public String[] triggerStrings(){return triggerStrings;}
@Override public int usageType(){return USAGE_MOVEMENT;}
protected volatile int baseTickSpan = Integer.MAX_VALUE;
protected volatile boolean aborted = false;
protected volatile boolean failure = false;
protected volatile Item targetItem = null;
protected volatile Item targetPanel = null;
protected volatile Room targetRoom = null;
protected volatile Operation op = Operation.REPAIR;
protected volatile String altverb="";
protected static enum Operation
{
INSTALL("installing"),
REPAIR("repairing"),
ENHANCE("enhancing");
public String verb="";
private Operation(String verb)
{
this.verb=verb;
}
}
public int getBonus(MOB mob, Electronics item, int multiplyBy)
{
if((mob==null)||(item==null))
return 0;
double score = 0.0;
final Manufacturer m=item.getFinalManufacturer();
if(m==null)
score+=0.5;
else
{
final Pair<String,Integer> manuExpertise=mob.fetchExpertise(m.name()+"%");
if(manuExpertise!=null)
score += (0.5 * CMath.div(manuExpertise.second.intValue(), 100.0));
}
final Technical.TechType ttype = item.getTechType();
if(ttype==null)
score+=0.5;
else
{
final Pair<String,Integer> techTypeExpertise=mob.fetchExpertise(ttype.getDisplayName()+"%");
if(techTypeExpertise!=null)
score += (0.5 * CMath.div(techTypeExpertise.second.intValue(), 100.0));
}
return (int)Math.round(CMath.mul(multiplyBy, score));
}
public void giveBonus(MOB mob, Electronics item)
{
if((mob==null)||(item==null))
return;
if((System.currentTimeMillis()-lastCastHelp)<300000)
return;
String experName;
if(CMLib.dice().rollPercentage()>50)
{
final Manufacturer m=item.getFinalManufacturer();
if(m!=null)
{
experName=m.name();
}
else
return;
}
else
{
final Technical.TechType ttype = item.getTechType();
if(ttype!=null)
{
experName=ttype.getDisplayName();
}
else
return;
}
Pair<String,Integer> expertise=mob.fetchExpertise(experName+"%");
final int currentExpertise=(expertise!=null)?expertise.second.intValue():0;
if(((int)Math.round(Math.sqrt((mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)))*34.0*Math.random()))>=currentExpertise)
{
mob.addExpertise(experName+"%"+(currentExpertise+1));
lastCastHelp=System.currentTimeMillis();
AstroEngineering A=(AstroEngineering)mob.fetchAbility(ID());
if(A!=null)
A.lastCastHelp=System.currentTimeMillis();
mob.tell(mob,null,null,L("You gain some new insights about @x1.",CMLib.english().makePlural(experName.toLowerCase())));
}
}
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if((affected instanceof MOB)
&&(((MOB)affected).location()!=null))
{
final MOB mob=(MOB)affected;
final Room room=mob.location();
if((aborted)||(room==null))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> stop(s) @x1.",op.verb));
else
if(failure)
{
mob.location().show(mob,targetItem,CMMsg.MSG_OK_VISUAL,L("<S-NAME> mess(es) up @x1 <T-NAME>.",op.verb));
}
else
if(op==Operation.INSTALL)
{
final CMMsg msg=CMClass.getMsg(mob,targetPanel,targetItem,CMMsg.MSG_INSTALL,L("<S-NAME> install(s) <O-NAME> into <T-NAME>."));
msg.setValue(50+getBonus(mob,(Electronics)targetItem,50));
if(room.okMessage(msg.source(), msg))
{
room.send(msg.source(), msg);
giveBonus(mob,(Electronics)targetItem);
}
}
else
if(op==Operation.REPAIR)
{
final CMMsg msg=CMClass.getMsg(mob,targetItem,this,CMMsg.MSG_REPAIR,L("<S-NAME> <S-IS-ARE> done trying to repair <T-NAME>."));
msg.setValue(CMLib.dice().roll(1, proficiency()/2, getBonus(mob,(Electronics)targetItem,50)));
if(room.okMessage(msg.source(), msg))
{
room.send(msg.source(), msg);
giveBonus(mob,(Electronics)targetItem);
}
}
else
{
String verb=altverb;
final CMMsg msg=CMClass.getMsg(mob,targetItem,this,CMMsg.MSG_ENHANCE,L("<S-NAME> <S-IS-ARE> done @x1 <T-NAME>.",verb));
msg.setValue((proficiency()/2)+getBonus(mob,(Electronics)targetItem,50));
if(room.okMessage(msg.source(), msg))
{
room.send(msg.source(), msg);
giveBonus(mob,(Electronics)targetItem);
}
}
}
aborted = false;
targetItem = null;
targetPanel = null;
targetRoom = null;
}
super.unInvoke();
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
final MOB mob=(MOB)affected;
if((mob.isInCombat())
||(mob.location()!=targetRoom)
||(!CMLib.flags().isAliveAwakeMobileUnbound(mob,true)))
{
aborted=true;
unInvoke();
return false;
}
if(tickDown==4)
{
String verb=op.verb;
if(op==Operation.ENHANCE)
verb=altverb;
mob.location().show(mob,targetItem,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> <S-IS-ARE> almost done @x1 <T-NAME>.",verb));
}
else
if(((baseTickSpan-tickDown)%4)==0)
{
final int total=baseTickSpan;
final int tickUp=(baseTickSpan-tickDown);
final int pct=(int)Math.round(CMath.div(tickUp,total)*100.0);
String verb=op.verb;
if(op==Operation.ENHANCE)
verb=altverb;
mob.location().show(mob,targetItem,this,CMMsg.MSG_NOISYMOVEMENT,
L("<S-NAME> continue(s) @x1 <T-NAME> (@x2% completed).",verb,""+pct),
null,L("<S-NAME> continue(s) @x1 <T-NAME>.",verb));
}
if((mob.soulMate()==null)
&&(mob.playerStats()!=null)
&&(mob.location()!=null)
&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.HYGIENE)))
mob.playerStats().adjHygiene(PlayerStats.HYGIENE_COMMONDIRTY);
}
if(!super.tick(ticking,tickID))
return false;
return true;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((myHost instanceof MOB)&&(myHost == this.affected)&&(((MOB)myHost).location()!=null))
{
if((msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
||((msg.sourceMinor()==CMMsg.TYP_QUIT)&&(msg.amISource((MOB)myHost))))
{
aborted=true;
unInvoke();
}
}
return true;
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(commands.size()<1)
{
mob.tell(L("What would you like to install, repair, or enhance?"));
return false;
}
aborted = false;
failure = false;
targetItem = null;
targetPanel = null;
targetRoom = mob.location();
op=Operation.REPAIR;
int minTicks=8;
if("INSTALL".startsWith((commands.get(0)).toUpperCase()))
{
op=Operation.INSTALL;
commands.remove(0);
if(givenTarget instanceof Item)
{
targetPanel=(Item)givenTarget;
}
else
if(commands.size()<2)
{
mob.tell(L("You need to specify an item to install and a panel to install it into."));
return false;
}
else
{
final String panelName=commands.get(commands.size()-1);
targetPanel=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,panelName);
if(targetPanel==null)
{
targetPanel=targetRoom.findItem(null,panelName);
}
if((targetPanel==null)||(!CMLib.flags().canBeSeenBy(targetPanel,mob)))
{
mob.tell(L("You don't see '@x1' here.",panelName));
return false;
}
if(!(targetPanel instanceof ElecPanel))
{
mob.tell(L("That's not an electronics panel."));
return false;
}
commands.remove(commands.size()-1);
}
}
else
if("REPAIR".startsWith((commands.get(0)).toUpperCase()))
{
op=Operation.REPAIR;
commands.remove(0);
}
else
if("ENHANCE".startsWith((commands.get(0)).toUpperCase()))
{
op=Operation.ENHANCE;
final String[] verbs=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_VERBS);
final String[] adjs1=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_ADJ1);
final String[] adjs2=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_ADJ2);
final String[] adjs12=new String[adjs1.length+adjs2.length];
System.arraycopy(adjs1, 0, adjs12, 0, adjs1.length);
System.arraycopy(adjs2, 0, adjs12, adjs1.length, adjs2.length);
final String[] nouns=CMProps.getListFileStringList(CMProps.ListFile.TECH_BABBLE_NOUN);
altverb=verbs[CMLib.dice().roll(1, verbs.length, -1)].trim()+" "
+adjs12[CMLib.dice().roll(1, adjs12.length, -1)].trim()+" "
+adjs2[CMLib.dice().roll(1, adjs2.length, -1)].trim()+" "
+nouns[CMLib.dice().roll(1, nouns.length, -1)].trim()
;
commands.remove(0);
}
final String itemName=CMParms.combine(commands,0);
if(targetItem == null)
targetItem=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,itemName);
if(targetItem==null)
targetItem=targetRoom.findItem(null,itemName);
if((targetItem==null)&&(targetPanel==null))
{
final CMFlagLibrary flagLib=CMLib.flags();
for(int i=0;i<targetRoom.numItems();i++)
{
final Item I=targetRoom.getItem(i);
if((flagLib.isOpenAccessibleContainer(I))
&&(flagLib.canBeSeenBy(I, mob)))
{
targetItem=targetRoom.findItem(I,itemName);
if(targetItem!=null)
break;
}
}
}
if((targetItem==null)||(!CMLib.flags().canBeSeenBy(targetItem,mob)))
{
mob.tell(L("You don't see '@x1' here.",itemName));
return false;
}
if(!(targetItem instanceof Electronics))
{
mob.tell(L("That's not an electronics item."));
return false;
}
if(!(targetItem instanceof TechComponent))
{
mob.tell(L("That's not a space ship component."));
return false;
}
if(mob.isInCombat())
{
mob.tell(mob,null,null,L("<S-NAME> <S-IS-ARE> in combat!"));
return false;
}
if(!CMLib.flags().canBeSeenBy(targetRoom,mob))
{
mob.tell(mob,null,null,L("<S-NAME> can't see to do that!"));
return false;
}
if(CMLib.flags().isSitting(mob)||CMLib.flags().isSleeping(mob))
{
mob.tell(mob,null,null,L("You need to stand up!"));
return false;
}
if(op==Operation.REPAIR)
{
if(!targetItem.subjectToWearAndTear())
{
mob.tell(mob,targetItem,null,L("<T-NAME> can't be repaired!"));
return false;
}
}
else
if(op==Operation.ENHANCE)
{
if((targetItem.subjectToWearAndTear())&&(targetItem.usesRemaining()<100))
{
mob.tell(mob,targetItem,null,L("<T-NAME> must be repaired first!"));
return false;
}
if(targetItem instanceof TechComponent)
{
if(((TechComponent)targetItem).getInstalledFactor()>1.0)
minTicks+=(int)Math.round((((TechComponent)targetItem).getInstalledFactor()-1.0)*0.01);
}
}
for(final Enumeration<Ability> a=mob.personalEffects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)||(A.ID().equalsIgnoreCase("AstroEngineering"))))
{
if(A instanceof AstroEngineering)
((AstroEngineering)A).aborted=true;
A.unInvoke();
}
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
failure=!proficiencyCheck(mob,0,auto);
baseTickSpan = targetItem.basePhyStats().weight()/4;
if(failure)
baseTickSpan=baseTickSpan/2;
if(baseTickSpan<minTicks)
baseTickSpan=minTicks;
mob.location().show(mob,targetItem,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> start(s) @x1 <T-NAME>@x2.",op.verb,((targetPanel!=null)?" into "+targetPanel.name():"")));
beneficialAffect(mob, mob, asLevel, baseTickSpan);
return !failure;
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@14112 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Abilities/Tech/AstroEngineering.java | ||
Java | apache-2.0 | 1722d20426db7333c4cc485282390e39d165869b | 0 | rcordovano/autopsy,wschaeferB/autopsy,rcordovano/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,wschaeferB/autopsy,millmanorama/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,APriestman/autopsy,millmanorama/autopsy,wschaeferB/autopsy,APriestman/autopsy,millmanorama/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,millmanorama/autopsy,rcordovano/autopsy,esaunders/autopsy,APriestman/autopsy,esaunders/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2011 - 2013 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.modules.hashdatabase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.services.Blackboard;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.ingest.FileIngestModule;
import org.sleuthkit.autopsy.ingest.IngestMessage;
import org.sleuthkit.autopsy.ingest.IngestModuleReferenceCounter;
import org.sleuthkit.autopsy.ingest.IngestServices;
import org.sleuthkit.autopsy.ingest.ModuleDataEvent;
import org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.HashDb;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.HashHitInfo;
import org.sleuthkit.datamodel.HashUtility;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
import org.sleuthkit.datamodel.TskException;
@NbBundle.Messages({
"HashDbIngestModule.noKnownBadHashDbSetMsg=No notable hash database set.",
"HashDbIngestModule.knownBadFileSearchWillNotExecuteWarn=Notable file search will not be executed.",
"HashDbIngestModule.noKnownHashDbSetMsg=No known hash database set.",
"HashDbIngestModule.knownFileSearchWillNotExecuteWarn=Known file search will not be executed."
})
public class HashDbIngestModule implements FileIngestModule {
private static final Logger logger = Logger.getLogger(HashDbIngestModule.class.getName());
private static final int MAX_COMMENT_SIZE = 500;
private final IngestServices services = IngestServices.getInstance();
private final SleuthkitCase skCase = Case.getCurrentCase().getSleuthkitCase();
private final HashDbManager hashDbManager = HashDbManager.getInstance();
private final HashLookupModuleSettings settings;
private List<HashDb> knownBadHashSets = new ArrayList<>();
private List<HashDb> knownHashSets = new ArrayList<>();
private long jobId;
private static final HashMap<Long, IngestJobTotals> totalsForIngestJobs = new HashMap<>();
private static final IngestModuleReferenceCounter refCounter = new IngestModuleReferenceCounter();
private Blackboard blackboard;
private static class IngestJobTotals {
private AtomicLong totalKnownBadCount = new AtomicLong(0);
private AtomicLong totalCalctime = new AtomicLong(0);
private AtomicLong totalLookuptime = new AtomicLong(0);
}
private static synchronized IngestJobTotals getTotalsForIngestJobs(long ingestJobId) {
IngestJobTotals totals = totalsForIngestJobs.get(ingestJobId);
if (totals == null) {
totals = new HashDbIngestModule.IngestJobTotals();
totalsForIngestJobs.put(ingestJobId, totals);
}
return totals;
}
HashDbIngestModule(HashLookupModuleSettings settings) {
this.settings = settings;
}
@Override
public void startUp(org.sleuthkit.autopsy.ingest.IngestJobContext context) throws IngestModuleException {
jobId = context.getJobId();
if (!hashDbManager.verifyAllDatabasesLoadedCorrectly()) {
throw new IngestModuleException("Could not load all hash databases");
}
updateEnabledHashSets(hashDbManager.getKnownBadFileHashSets(), knownBadHashSets);
updateEnabledHashSets(hashDbManager.getKnownFileHashSets(), knownHashSets);
if (refCounter.incrementAndGet(jobId) == 1) {
// initialize job totals
getTotalsForIngestJobs(jobId);
// if first module for this job then post error msgs if needed
if (knownBadHashSets.isEmpty()) {
services.postMessage(IngestMessage.createWarningMessage(
HashLookupModuleFactory.getModuleName(),
Bundle.HashDbIngestModule_noKnownBadHashDbSetMsg(),
Bundle.HashDbIngestModule_knownBadFileSearchWillNotExecuteWarn()));
}
if (knownHashSets.isEmpty()) {
services.postMessage(IngestMessage.createWarningMessage(
HashLookupModuleFactory.getModuleName(),
Bundle.HashDbIngestModule_noKnownHashDbSetMsg(),
Bundle.HashDbIngestModule_knownFileSearchWillNotExecuteWarn()));
}
}
}
/**
* Cycle through list of hashsets and return the subset that is enabled.
*
* @param allHashSets List of all hashsets from DB manager
* @param enabledHashSets List of enabled ones to return.
*/
private void updateEnabledHashSets(List<HashDb> allHashSets, List<HashDb> enabledHashSets) {
enabledHashSets.clear();
for (HashDb db : allHashSets) {
if (settings.isHashSetEnabled(db)) {
try {
if (db.isValid()) {
enabledHashSets.add(db);
}
} catch (TskCoreException ex) {
logger.log(Level.WARNING, "Error getting index status for " + db.getDisplayName()+ " hash database", ex); //NON-NLS
}
}
}
}
@Override
public ProcessResult process(AbstractFile file) {
blackboard = Case.getCurrentCase().getServices().getBlackboard();
// Skip unallocated space files.
if ((file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) ||
file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK))) {
return ProcessResult.OK;
}
/*
* Skip directories. One reason for this is because we won't accurately
* calculate hashes of NTFS directories that have content that spans the
* IDX_ROOT and IDX_ALLOC artifacts. So we disable that until a solution
* for it is developed.
*/
if (file.isDir()) {
return ProcessResult.OK;
}
// bail out if we have no hashes set
if ((knownHashSets.isEmpty()) && (knownBadHashSets.isEmpty()) && (!settings.shouldCalculateHashes())) {
return ProcessResult.OK;
}
// Safely get a reference to the totalsForIngestJobs object
IngestJobTotals totals = getTotalsForIngestJobs(jobId);
// calc hash value
String name = file.getName();
String md5Hash = file.getMd5Hash();
if (md5Hash == null || md5Hash.isEmpty()) {
try {
long calcstart = System.currentTimeMillis();
md5Hash = HashUtility.calculateMd5(file, false);
long delta = (System.currentTimeMillis() - calcstart);
totals.totalCalctime.addAndGet(delta);
} catch (IOException ex) {
logger.log(Level.WARNING, "Error calculating hash of file " + name, ex); //NON-NLS
services.postMessage(IngestMessage.createErrorMessage(
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.fileReadErrorMsg",
name),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.calcHashValueErr",
name)));
return ProcessResult.ERROR;
}
}
// look up in notable first
boolean foundBad = false;
ProcessResult ret = ProcessResult.OK;
for (HashDb db : knownBadHashSets) {
try {
long lookupstart = System.currentTimeMillis();
HashHitInfo hashInfo = db.lookupMD5(file);
if (null != hashInfo) {
foundBad = true;
totals.totalKnownBadCount.incrementAndGet();
file.setKnown(TskData.FileKnown.BAD);
String hashSetName = db.getDisplayName();
String comment = "";
ArrayList<String> comments = hashInfo.getComments();
int i = 0;
for (String c : comments) {
if (++i > 1) {
comment += " ";
}
comment += c;
if (comment.length() > MAX_COMMENT_SIZE) {
comment = comment.substring(0, MAX_COMMENT_SIZE) + "...";
break;
}
}
postHashSetHitToBlackboard(file, md5Hash, hashSetName, comment, db.getSendIngestMessages());
}
long delta = (System.currentTimeMillis() - lookupstart);
totals.totalLookuptime.addAndGet(delta);
} catch (TskException ex) {
logger.log(Level.WARNING, "Couldn't lookup notable hash for file " + name + " - see sleuthkit log for details", ex); //NON-NLS
services.postMessage(IngestMessage.createErrorMessage(
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.hashLookupErrorMsg",
name),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.lookingUpKnownBadHashValueErr",
name)));
ret = ProcessResult.ERROR;
}
}
// If the file is not in the notable sets, search for it in the known sets.
// Any hit is sufficient to classify it as known, and there is no need to create
// a hit artifact or send a message to the application inbox.
if (!foundBad) {
for (HashDb db : knownHashSets) {
try {
long lookupstart = System.currentTimeMillis();
if (db.lookupMD5Quick(file)) {
file.setKnown(TskData.FileKnown.KNOWN);
break;
}
long delta = (System.currentTimeMillis() - lookupstart);
totals.totalLookuptime.addAndGet(delta);
} catch (TskException ex) {
logger.log(Level.WARNING, "Couldn't lookup known hash for file " + name + " - see sleuthkit log for details", ex); //NON-NLS
services.postMessage(IngestMessage.createErrorMessage(
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.hashLookupErrorMsg",
name),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.lookingUpKnownHashValueErr",
name)));
ret = ProcessResult.ERROR;
}
}
}
return ret;
}
@Messages({"HashDbIngestModule.indexError.message=Failed to index hashset hit artifact for keyword search."})
private void postHashSetHitToBlackboard(AbstractFile abstractFile, String md5Hash, String hashSetName, String comment, boolean showInboxMessage) {
try {
String MODULE_NAME = NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.moduleName");
BlackboardArtifact badFile = abstractFile.newArtifact(ARTIFACT_TYPE.TSK_HASHSET_HIT);
Collection<BlackboardAttribute> attributes = new ArrayList<>();
//TODO Revisit usage of deprecated constructor as per TSK-583
//BlackboardAttribute att2 = new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID(), MODULE_NAME, "Known Bad", hashSetName);
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, hashSetName));
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_HASH_MD5, MODULE_NAME, md5Hash));
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_COMMENT, MODULE_NAME, comment));
badFile.addAttributes(attributes);
try {
// index the artifact for keyword search
blackboard.indexArtifact(badFile);
} catch (Blackboard.BlackboardException ex) {
logger.log(Level.SEVERE, "Unable to index blackboard artifact " + badFile.getArtifactID(), ex); //NON-NLS
MessageNotifyUtil.Notify.error(
Bundle.HashDbIngestModule_indexError_message(), badFile.getDisplayName());
}
if (showInboxMessage) {
StringBuilder detailsSb = new StringBuilder();
//details
detailsSb.append("<table border='0' cellpadding='4' width='280'>"); //NON-NLS
//hit
detailsSb.append("<tr>"); //NON-NLS
detailsSb.append("<th>") //NON-NLS
.append(NbBundle.getMessage(this.getClass(), "HashDbIngestModule.postToBB.fileName"))
.append("</th>"); //NON-NLS
detailsSb.append("<td>") //NON-NLS
.append(abstractFile.getName())
.append("</td>"); //NON-NLS
detailsSb.append("</tr>"); //NON-NLS
detailsSb.append("<tr>"); //NON-NLS
detailsSb.append("<th>") //NON-NLS
.append(NbBundle.getMessage(this.getClass(), "HashDbIngestModule.postToBB.md5Hash"))
.append("</th>"); //NON-NLS
detailsSb.append("<td>").append(md5Hash).append("</td>"); //NON-NLS
detailsSb.append("</tr>"); //NON-NLS
detailsSb.append("<tr>"); //NON-NLS
detailsSb.append("<th>") //NON-NLS
.append(NbBundle.getMessage(this.getClass(), "HashDbIngestModule.postToBB.hashsetName"))
.append("</th>"); //NON-NLS
detailsSb.append("<td>").append(hashSetName).append("</td>"); //NON-NLS
detailsSb.append("</tr>"); //NON-NLS
detailsSb.append("</table>"); //NON-NLS
services.postMessage(IngestMessage.createDataMessage(HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.postToBB.knownBadMsg",
abstractFile.getName()),
detailsSb.toString(),
abstractFile.getName() + md5Hash,
badFile));
}
services.fireModuleDataEvent(new ModuleDataEvent(MODULE_NAME, ARTIFACT_TYPE.TSK_HASHSET_HIT, Collections.singletonList(badFile)));
} catch (TskException ex) {
logger.log(Level.WARNING, "Error creating blackboard artifact", ex); //NON-NLS
}
}
private static synchronized void postSummary(long jobId,
List<HashDb> knownBadHashSets, List<HashDb> knownHashSets) {
IngestJobTotals jobTotals = getTotalsForIngestJobs(jobId);
totalsForIngestJobs.remove(jobId);
if ((!knownBadHashSets.isEmpty()) || (!knownHashSets.isEmpty())) {
StringBuilder detailsSb = new StringBuilder();
//details
detailsSb.append("<table border='0' cellpadding='4' width='280'>"); //NON-NLS
detailsSb.append("<tr><td>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.knownBadsFound"))
.append("</td>"); //NON-NLS
detailsSb.append("<td>").append(jobTotals.totalKnownBadCount.get()).append("</td></tr>"); //NON-NLS
detailsSb.append("<tr><td>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.totalCalcTime"))
.append("</td><td>").append(jobTotals.totalCalctime.get()).append("</td></tr>\n"); //NON-NLS
detailsSb.append("<tr><td>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.totalLookupTime"))
.append("</td><td>").append(jobTotals.totalLookuptime.get()).append("</td></tr>\n"); //NON-NLS
detailsSb.append("</table>"); //NON-NLS
detailsSb.append("<p>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.databasesUsed"))
.append("</p>\n<ul>"); //NON-NLS
for (HashDb db : knownBadHashSets) {
detailsSb.append("<li>").append(db.getHashSetName()).append("</li>\n"); //NON-NLS
}
detailsSb.append("</ul>"); //NON-NLS
IngestServices.getInstance().postMessage(IngestMessage.createMessage(
IngestMessage.MessageType.INFO,
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(HashDbIngestModule.class,
"HashDbIngestModule.complete.hashLookupResults"),
detailsSb.toString()));
}
}
@Override
public void shutDown() {
if (refCounter.decrementAndGet(jobId) == 0) {
postSummary(jobId, knownBadHashSets, knownHashSets);
}
}
}
| Core/src/org/sleuthkit/autopsy/modules/hashdatabase/HashDbIngestModule.java | /*
* Autopsy Forensic Browser
*
* Copyright 2011 - 2013 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.modules.hashdatabase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.services.Blackboard;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.ingest.FileIngestModule;
import org.sleuthkit.autopsy.ingest.IngestMessage;
import org.sleuthkit.autopsy.ingest.IngestModuleReferenceCounter;
import org.sleuthkit.autopsy.ingest.IngestServices;
import org.sleuthkit.autopsy.ingest.ModuleDataEvent;
import org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.HashDb;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.HashHitInfo;
import org.sleuthkit.datamodel.HashUtility;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
import org.sleuthkit.datamodel.TskException;
@NbBundle.Messages({
"HashDbIngestModule.noKnownBadHashDbSetMsg=No notable hash database set.",
"HashDbIngestModule.knownBadFileSearchWillNotExecuteWarn=Notable file search will not be executed.",
"HashDbIngestModule.noKnownHashDbSetMsg=No known hash database set.",
"HashDbIngestModule.knownFileSearchWillNotExecuteWarn=Known file search will not be executed."
})
public class HashDbIngestModule implements FileIngestModule {
private static final Logger logger = Logger.getLogger(HashDbIngestModule.class.getName());
private static final int MAX_COMMENT_SIZE = 500;
private final IngestServices services = IngestServices.getInstance();
private final SleuthkitCase skCase = Case.getCurrentCase().getSleuthkitCase();
private final HashDbManager hashDbManager = HashDbManager.getInstance();
private final HashLookupModuleSettings settings;
private List<HashDb> knownBadHashSets = new ArrayList<>();
private List<HashDb> knownHashSets = new ArrayList<>();
private long jobId;
private static final HashMap<Long, IngestJobTotals> totalsForIngestJobs = new HashMap<>();
private static final IngestModuleReferenceCounter refCounter = new IngestModuleReferenceCounter();
private Blackboard blackboard;
private static class IngestJobTotals {
private AtomicLong totalKnownBadCount = new AtomicLong(0);
private AtomicLong totalCalctime = new AtomicLong(0);
private AtomicLong totalLookuptime = new AtomicLong(0);
}
private static synchronized IngestJobTotals getTotalsForIngestJobs(long ingestJobId) {
IngestJobTotals totals = totalsForIngestJobs.get(ingestJobId);
if (totals == null) {
totals = new HashDbIngestModule.IngestJobTotals();
totalsForIngestJobs.put(ingestJobId, totals);
}
return totals;
}
HashDbIngestModule(HashLookupModuleSettings settings) {
this.settings = settings;
}
@Override
public void startUp(org.sleuthkit.autopsy.ingest.IngestJobContext context) throws IngestModuleException {
jobId = context.getJobId();
if (!hashDbManager.verifyAllDatabasesLoadedCorrectly()) {
throw new IngestModuleException("Could not load all hash databases");
}
updateEnabledHashSets(hashDbManager.getKnownBadFileHashSets(), knownBadHashSets);
updateEnabledHashSets(hashDbManager.getKnownFileHashSets(), knownHashSets);
if (refCounter.incrementAndGet(jobId) == 1) {
// initialize job totals
getTotalsForIngestJobs(jobId);
// if first module for this job then post error msgs if needed
if (knownBadHashSets.isEmpty()) {
services.postMessage(IngestMessage.createWarningMessage(
HashLookupModuleFactory.getModuleName(),
Bundle.HashDbIngestModule_noKnownBadHashDbSetMsg(),
Bundle.HashDbIngestModule_knownBadFileSearchWillNotExecuteWarn()));
}
if (knownHashSets.isEmpty()) {
services.postMessage(IngestMessage.createWarningMessage(
HashLookupModuleFactory.getModuleName(),
Bundle.HashDbIngestModule_noKnownHashDbSetMsg(),
Bundle.HashDbIngestModule_knownFileSearchWillNotExecuteWarn()));
}
}
}
/**
* Cycle through list of hashsets and return the subset that is enabled.
*
* @param allHashSets List of all hashsets from DB manager
* @param enabledHashSets List of enabled ones to return.
*/
private void updateEnabledHashSets(List<HashDb> allHashSets, List<HashDb> enabledHashSets) {
enabledHashSets.clear();
for (HashDb db : allHashSets) {
if (settings.isHashSetEnabled(db)) {
try {
if (db.isValid()) {
enabledHashSets.add(db);
}
} catch (TskCoreException ex) {
logger.log(Level.WARNING, "Error getting index status for " + db.getDisplayName()+ " hash database", ex); //NON-NLS
}
}
}
}
@Override
public ProcessResult process(AbstractFile file) {
blackboard = Case.getCurrentCase().getServices().getBlackboard();
// Skip unallocated space files.
if ((file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) ||
file.getType().equals(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK))) {
return ProcessResult.OK;
}
/*
* Skip directories. One reason for this is because we won't accurately
* calculate hashes of NTFS directories that have content that spans the
* IDX_ROOT and IDX_ALLOC artifacts. So we disable that until a solution
* for it is developed.
*/
if (file.isDir()) {
return ProcessResult.OK;
}
// bail out if we have no hashes set
if ((knownHashSets.isEmpty()) && (knownBadHashSets.isEmpty()) && (!settings.shouldCalculateHashes())) {
return ProcessResult.OK;
}
// Safely get a reference to the totalsForIngestJobs object
IngestJobTotals totals = getTotalsForIngestJobs(jobId);
// calc hash value
String name = file.getName();
String md5Hash = file.getMd5Hash();
if (md5Hash == null || md5Hash.isEmpty()) {
try {
long calcstart = System.currentTimeMillis();
md5Hash = HashUtility.calculateMd5(file, false);
long delta = (System.currentTimeMillis() - calcstart);
totals.totalCalctime.addAndGet(delta);
} catch (IOException ex) {
logger.log(Level.WARNING, "Error calculating hash of file " + name, ex); //NON-NLS
services.postMessage(IngestMessage.createErrorMessage(
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.fileReadErrorMsg",
name),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.calcHashValueErr",
name)));
return ProcessResult.ERROR;
}
}
// look up in notable first
boolean foundBad = false;
ProcessResult ret = ProcessResult.OK;
for (HashDb db : knownBadHashSets) {
try {
long lookupstart = System.currentTimeMillis();
HashHitInfo hashInfo = db.lookupMD5(file);
if (null != hashInfo) {
foundBad = true;
totals.totalKnownBadCount.incrementAndGet();
//try {
file.setKnown(TskData.FileKnown.BAD);
// skCase.setKnown(file, TskData.FileKnown.BAD);
//} catch (TskException ex) {
// logger.log(Level.WARNING, "Couldn't set notable state for file " + name + " - see sleuthkit log for details", ex); //NON-NLS
// services.postMessage(IngestMessage.createErrorMessage(
// HashLookupModuleFactory.getModuleName(),
// NbBundle.getMessage(this.getClass(),
// "HashDbIngestModule.hashLookupErrorMsg",
// name),
// NbBundle.getMessage(this.getClass(),
// "HashDbIngestModule.settingKnownBadStateErr",
// name)));
// ret = ProcessResult.ERROR;
//}
String hashSetName = db.getDisplayName();
String comment = "";
ArrayList<String> comments = hashInfo.getComments();
int i = 0;
for (String c : comments) {
if (++i > 1) {
comment += " ";
}
comment += c;
if (comment.length() > MAX_COMMENT_SIZE) {
comment = comment.substring(0, MAX_COMMENT_SIZE) + "...";
break;
}
}
postHashSetHitToBlackboard(file, md5Hash, hashSetName, comment, db.getSendIngestMessages());
}
long delta = (System.currentTimeMillis() - lookupstart);
totals.totalLookuptime.addAndGet(delta);
} catch (TskException ex) {
logger.log(Level.WARNING, "Couldn't lookup notable hash for file " + name + " - see sleuthkit log for details", ex); //NON-NLS
services.postMessage(IngestMessage.createErrorMessage(
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.hashLookupErrorMsg",
name),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.lookingUpKnownBadHashValueErr",
name)));
ret = ProcessResult.ERROR;
}
}
// If the file is not in the notable sets, search for it in the known sets.
// Any hit is sufficient to classify it as known, and there is no need to create
// a hit artifact or send a message to the application inbox.
if (!foundBad) {
for (HashDb db : knownHashSets) {
try {
long lookupstart = System.currentTimeMillis();
if (db.lookupMD5Quick(file)) {
//try {
file.setKnown(TskData.FileKnown.KNOWN);
//skCase.setKnown(file, TskData.FileKnown.KNOWN);
break;
//} catch (TskException ex) {
// logger.log(Level.WARNING, "Couldn't set known state for file " + name + " - see sleuthkit log for details", ex); //NON-NLS
// ret = ProcessResult.ERROR;
//}
}
long delta = (System.currentTimeMillis() - lookupstart);
totals.totalLookuptime.addAndGet(delta);
} catch (TskException ex) {
logger.log(Level.WARNING, "Couldn't lookup known hash for file " + name + " - see sleuthkit log for details", ex); //NON-NLS
services.postMessage(IngestMessage.createErrorMessage(
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.hashLookupErrorMsg",
name),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.lookingUpKnownHashValueErr",
name)));
ret = ProcessResult.ERROR;
}
}
}
return ret;
}
@Messages({"HashDbIngestModule.indexError.message=Failed to index hashset hit artifact for keyword search."})
private void postHashSetHitToBlackboard(AbstractFile abstractFile, String md5Hash, String hashSetName, String comment, boolean showInboxMessage) {
try {
String MODULE_NAME = NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.moduleName");
BlackboardArtifact badFile = abstractFile.newArtifact(ARTIFACT_TYPE.TSK_HASHSET_HIT);
Collection<BlackboardAttribute> attributes = new ArrayList<>();
//TODO Revisit usage of deprecated constructor as per TSK-583
//BlackboardAttribute att2 = new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID(), MODULE_NAME, "Known Bad", hashSetName);
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, hashSetName));
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_HASH_MD5, MODULE_NAME, md5Hash));
attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_COMMENT, MODULE_NAME, comment));
badFile.addAttributes(attributes);
try {
// index the artifact for keyword search
blackboard.indexArtifact(badFile);
} catch (Blackboard.BlackboardException ex) {
logger.log(Level.SEVERE, "Unable to index blackboard artifact " + badFile.getArtifactID(), ex); //NON-NLS
MessageNotifyUtil.Notify.error(
Bundle.HashDbIngestModule_indexError_message(), badFile.getDisplayName());
}
if (showInboxMessage) {
StringBuilder detailsSb = new StringBuilder();
//details
detailsSb.append("<table border='0' cellpadding='4' width='280'>"); //NON-NLS
//hit
detailsSb.append("<tr>"); //NON-NLS
detailsSb.append("<th>") //NON-NLS
.append(NbBundle.getMessage(this.getClass(), "HashDbIngestModule.postToBB.fileName"))
.append("</th>"); //NON-NLS
detailsSb.append("<td>") //NON-NLS
.append(abstractFile.getName())
.append("</td>"); //NON-NLS
detailsSb.append("</tr>"); //NON-NLS
detailsSb.append("<tr>"); //NON-NLS
detailsSb.append("<th>") //NON-NLS
.append(NbBundle.getMessage(this.getClass(), "HashDbIngestModule.postToBB.md5Hash"))
.append("</th>"); //NON-NLS
detailsSb.append("<td>").append(md5Hash).append("</td>"); //NON-NLS
detailsSb.append("</tr>"); //NON-NLS
detailsSb.append("<tr>"); //NON-NLS
detailsSb.append("<th>") //NON-NLS
.append(NbBundle.getMessage(this.getClass(), "HashDbIngestModule.postToBB.hashsetName"))
.append("</th>"); //NON-NLS
detailsSb.append("<td>").append(hashSetName).append("</td>"); //NON-NLS
detailsSb.append("</tr>"); //NON-NLS
detailsSb.append("</table>"); //NON-NLS
services.postMessage(IngestMessage.createDataMessage(HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(this.getClass(),
"HashDbIngestModule.postToBB.knownBadMsg",
abstractFile.getName()),
detailsSb.toString(),
abstractFile.getName() + md5Hash,
badFile));
}
services.fireModuleDataEvent(new ModuleDataEvent(MODULE_NAME, ARTIFACT_TYPE.TSK_HASHSET_HIT, Collections.singletonList(badFile)));
} catch (TskException ex) {
logger.log(Level.WARNING, "Error creating blackboard artifact", ex); //NON-NLS
}
}
private static synchronized void postSummary(long jobId,
List<HashDb> knownBadHashSets, List<HashDb> knownHashSets) {
IngestJobTotals jobTotals = getTotalsForIngestJobs(jobId);
totalsForIngestJobs.remove(jobId);
if ((!knownBadHashSets.isEmpty()) || (!knownHashSets.isEmpty())) {
StringBuilder detailsSb = new StringBuilder();
//details
detailsSb.append("<table border='0' cellpadding='4' width='280'>"); //NON-NLS
detailsSb.append("<tr><td>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.knownBadsFound"))
.append("</td>"); //NON-NLS
detailsSb.append("<td>").append(jobTotals.totalKnownBadCount.get()).append("</td></tr>"); //NON-NLS
detailsSb.append("<tr><td>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.totalCalcTime"))
.append("</td><td>").append(jobTotals.totalCalctime.get()).append("</td></tr>\n"); //NON-NLS
detailsSb.append("<tr><td>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.totalLookupTime"))
.append("</td><td>").append(jobTotals.totalLookuptime.get()).append("</td></tr>\n"); //NON-NLS
detailsSb.append("</table>"); //NON-NLS
detailsSb.append("<p>") //NON-NLS
.append(NbBundle.getMessage(HashDbIngestModule.class, "HashDbIngestModule.complete.databasesUsed"))
.append("</p>\n<ul>"); //NON-NLS
for (HashDb db : knownBadHashSets) {
detailsSb.append("<li>").append(db.getHashSetName()).append("</li>\n"); //NON-NLS
}
detailsSb.append("</ul>"); //NON-NLS
IngestServices.getInstance().postMessage(IngestMessage.createMessage(
IngestMessage.MessageType.INFO,
HashLookupModuleFactory.getModuleName(),
NbBundle.getMessage(HashDbIngestModule.class,
"HashDbIngestModule.complete.hashLookupResults"),
detailsSb.toString()));
}
}
@Override
public void shutDown() {
if (refCounter.decrementAndGet(jobId) == 0) {
postSummary(jobId, knownBadHashSets, knownHashSets);
}
}
}
| Cleanup
| Core/src/org/sleuthkit/autopsy/modules/hashdatabase/HashDbIngestModule.java | Cleanup |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.