lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | bsd-3-clause | fe0d25e2423043e99f243398e85ad45395693754 | 0 | mkoistinen/JBookTrader,mkoistinen/JBookTrader,GabrielDancause/jbooktrader,mkoistinen/JBookTrader,GabrielDancause/jbooktrader,GabrielDancause/jbooktrader | package com.jbooktrader.strategy;
import com.jbooktrader.indicator.velocity.*;
import com.jbooktrader.platform.indicator.*;
import com.jbooktrader.platform.model.*;
import com.jbooktrader.platform.optimizer.*;
import com.jbooktrader.strategy.base.*;
/**
*
*/
public class SecondNature extends StrategyES {
// Technical indicators
private final Indicator balanceVelocityInd, trendVelocityInd;
// Strategy parameters names
private static final String FAST_PERIOD = "Fast Period";
private static final String SLOW_PERIOD = "Slow Period";
private static final String TREND_PERIOD = "Trend Period";
private static final String BALANCE_ENTRY = "Balance Entry";
// Strategy parameters values
private final int balanceVelocityEntry;
public SecondNature(StrategyParams optimizationParams) throws JBookTraderException {
super(optimizationParams);
balanceVelocityEntry = getParam(BALANCE_ENTRY);
balanceVelocityInd = new BalanceVelocity(getParam(FAST_PERIOD), getParam(SLOW_PERIOD));
trendVelocityInd = new TrendStrengthVelocity(getParam(TREND_PERIOD));
addIndicator(balanceVelocityInd);
addIndicator(trendVelocityInd);
}
/**
* Adds parameters to strategy. Each parameter must have 5 values:
* name: identifier
* min, max, step: range for optimizer
* value: used in backtesting and trading
*/
@Override
public void setParams() {
addParam(FAST_PERIOD, 3, 25, 1, 14);
addParam(SLOW_PERIOD, 600, 1800, 5, 1125);
addParam(TREND_PERIOD, 300, 600, 5, 384);
addParam(BALANCE_ENTRY, 110, 140, 1, 126);
}
/**
* This method is invoked by the framework when an order book changes and the technical
* indicators are recalculated. This is where the strategy itself should be defined.
*/
@Override
public void onBookChange() {
double balanceVelocity = balanceVelocityInd.getValue() * 10;
double trendVelocity = trendVelocityInd.getValue();
if (trendVelocity < 0) {
if (balanceVelocity >= balanceVelocityEntry) {
setPosition(1);
} else if (balanceVelocity <= -balanceVelocityEntry) {
setPosition(-1);
}
}
}
}
| source/com/jbooktrader/strategy/SecondNature.java | package com.jbooktrader.strategy;
import com.jbooktrader.indicator.velocity.*;
import com.jbooktrader.platform.indicator.*;
import com.jbooktrader.platform.model.*;
import com.jbooktrader.platform.optimizer.*;
import com.jbooktrader.strategy.base.*;
/**
*
*/
public class SecondNature extends StrategyES {
// Technical indicators
private final Indicator balanceVelocityInd, trendVelocityInd;
// Strategy parameters names
private static final String FAST_PERIOD = "Fast Period";
private static final String SLOW_PERIOD = "Slow Period";
private static final String TREND_PERIOD = "Trend Period";
private static final String BALANCE_ENTRY = "Balance Entry";
// Strategy parameters values
private final int balanceVelocityEntry;
public SecondNature(StrategyParams optimizationParams) throws JBookTraderException {
super(optimizationParams);
balanceVelocityEntry = getParam(BALANCE_ENTRY);
balanceVelocityInd = new BalanceVelocity(getParam(FAST_PERIOD), getParam(SLOW_PERIOD));
trendVelocityInd = new TrendStrengthVelocity(getParam(TREND_PERIOD));
addIndicator(balanceVelocityInd);
addIndicator(trendVelocityInd);
}
/**
* Adds parameters to strategy. Each parameter must have 5 values:
* name: identifier
* min, max, step: range for optimizer
* value: used in backtesting and trading
*/
@Override
public void setParams() {
addParam(FAST_PERIOD, 3, 25, 1, 14);
addParam(SLOW_PERIOD, 600, 1800, 5, 1125);
addParam(TREND_PERIOD, 300, 600, 5, 385);
addParam(BALANCE_ENTRY, 110, 140, 1, 126);
}
/**
* This method is invoked by the framework when an order book changes and the technical
* indicators are recalculated. This is where the strategy itself should be defined.
*/
@Override
public void onBookChange() {
double balanceVelocity = balanceVelocityInd.getValue() * 10;
double trendVelocity = trendVelocityInd.getValue();
if (trendVelocity < 0) {
if (balanceVelocity >= balanceVelocityEntry) {
setPosition(1);
} else if (balanceVelocity <= -balanceVelocityEntry) {
setPosition(-1);
}
}
}
}
| Minor adjustment.
| source/com/jbooktrader/strategy/SecondNature.java | Minor adjustment. | <ide><path>ource/com/jbooktrader/strategy/SecondNature.java
<ide> public void setParams() {
<ide> addParam(FAST_PERIOD, 3, 25, 1, 14);
<ide> addParam(SLOW_PERIOD, 600, 1800, 5, 1125);
<del> addParam(TREND_PERIOD, 300, 600, 5, 385);
<add> addParam(TREND_PERIOD, 300, 600, 5, 384);
<ide> addParam(BALANCE_ENTRY, 110, 140, 1, 126);
<ide> }
<ide> |
|
Java | apache-2.0 | 197a6245beca80956513f36839d30366e6f7a8f9 | 0 | reportportal/commons-model | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.model;
/**
* Contains constants for defining validation constraints.
*
* @author Aliaksei_Makayed
*/
//TODO review and move to API service
public class ValidationConstraints {
private ValidationConstraints() {
}
/* 1 always exists as predefined type */
public static final int MAX_ISSUE_SUBTYPES = 15;
public static final int MIN_COLLECTION_SIZE = 1;
public static final int MAX_NUMBER_OF_FILTER_ENTITIES = 20;
public static final int MIN_WIDGET_LIMIT = 1;
public static final int MAX_WIDGET_LIMIT = 150;
public static final int MIN_FILTER_LIMIT = 1;
public static final int MAX_FILTER_LIMIT = 150;
public static final int MIN_LAUNCH_NAME_LENGTH = 1;
public static final int MIN_TEST_ITEM_NAME_LENGTH = 1;
public static final int MAX_TEST_ITEM_NAME_LENGTH = 1024;
public static final int MAX_TEST_ITEM_LOCATION_LENGTH = 256;
public static final int MIN_ITEM_ATTRIBUTE_VALUE_LENGTH = 1;
public static final int MIN_NAME_LENGTH = 3;
public static final int MAX_NAME_LENGTH = 256;
public static final int MIN_DESCRIPTION_LENGTH = 0;
public static final int MAX_DESCRIPTION_LENGTH = 65536;
public static final int MAX_PARAMETERS_LENGTH = 256;
public static final int MAX_LAUNCH_DESCRIPTION_LENGTH = 1024;
public static final int MAX_WIDGET_NAME_LENGTH = 128;
public static final int MAX_DASHBOARD_NAME_LENGTH = 128;
public static final int MAX_USER_FILTER_NAME_LENGTH = 128;
public static final int MAX_ATTRIBUTE_LENGTH = 128;
public static final int MIN_PAGE_NUMBER = 1;
public static final int MAX_PAGE_NUMBER = 1024;
public static final int MAX_HISTORY_DEPTH_BOUND = 31;
public static final int MIN_HISTORY_DEPTH_BOUND = 0;
public static final int MAX_HISTORY_SIZE_BOUND = 31;
public static final int MIN_LOGIN_LENGTH = 1;
public static final int MAX_LOGIN_LENGTH = 128;
public static final int MIN_PASSWORD_LENGTH = 4;
public static final int MAX_PASSWORD_LENGTH = 256;
public static final int TICKET_MIN_LOG_SIZE = 0;
public static final int TICKET_MAX_LOG_SIZE = 50;
public static final int MAX_CUSTOMER_LENGTH = 64;
public static final int MIN_USER_NAME_LENGTH = 3;
public static final int MAX_USER_NAME_LENGTH = 256;
public static final int MAX_PHOTO_SIZE = 1024 * 1024;
public static final int MAX_PHOTO_HEIGHT = 500;
public static final int MAX_PHOTO_WIDTH = 300;
public static final int MIN_DOMAIN_SIZE = 1;
public static final int MAX_DOMAIN_SIZE = 255;
public static final int MIN_SUBTYPE_SHORT_NAME = 1;
public static final int MAX_SUBTYPE_SHORT_NAME = 4;
public static final int MIN_SUBTYPE_LONG_NAME = 3;
public static final int MAX_SUBTYPE_LONG_NAME = 55;
public static final int MIN_ANALYSIS_PATTERN_NAME_LENGTH = 3;
public static final int MAX_ANALYSIS_PATTERN_NAME_LENGTH = 128;
public static final int MAX_DESCRIPTION = 256;
public static final int MIN_DESCRIPTION = 1;
public static final int MIN_DOC_FREQ = 1;
public static final int MAX_DOC_FREQ = 10;
public static final int MIN_TERM_FREQ = 1;
public static final int MAX_TERM_FREQ = 10;
public static final int MIN_SHOULD_MATCH = 50;
public static final int MAX_SHOULD_MATCH = 100;
public static final int MIN_NUMBER_OF_LOG_LINES = -1;
public static final int MAX_NUMBER_OF_LOG_LINES = 5;
public static final String HEX_COLOR_REGEXP = "#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
public static final String PROJECT_NAME_REGEXP = "[a-zA-Z0-9-_]+";
} | src/main/java/com/epam/ta/reportportal/ws/model/ValidationConstraints.java | /*
* Copyright 2019 EPAM Systems
*
* 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.epam.ta.reportportal.ws.model;
/**
* Contains constants for defining validation constraints.
*
* @author Aliaksei_Makayed
*/
//TODO review and move to API service
public class ValidationConstraints {
private ValidationConstraints() {
}
/* 1 always exists as predefined type */
public static final int MAX_ISSUE_SUBTYPES = 15;
public static final int MIN_COLLECTION_SIZE = 1;
public static final int MAX_NUMBER_OF_FILTER_ENTITIES = 20;
public static final int MIN_WIDGET_LIMIT = 1;
public static final int MAX_WIDGET_LIMIT = 150;
public static final int MIN_FILTER_LIMIT = 1;
public static final int MAX_FILTER_LIMIT = 150;
public static final int MIN_LAUNCH_NAME_LENGTH = 1;
public static final int MIN_TEST_ITEM_NAME_LENGTH = 1;
public static final int MAX_TEST_ITEM_NAME_LENGTH = 1024;
public static final int MAX_TEST_ITEM_LOCATION_LENGTH = 256;
public static final int MIN_ITEM_ATTRIBUTE_VALUE_LENGTH = 1;
public static final int MIN_NAME_LENGTH = 3;
public static final int MAX_NAME_LENGTH = 256;
public static final int MIN_DESCRIPTION_LENGTH = 0;
public static final int MAX_DESCRIPTION_LENGTH = 65536;
public static final int MAX_PARAMETERS_LENGTH = 256;
public static final int MAX_LAUNCH_DESCRIPTION_LENGTH = 1024;
public static final int MAX_WIDGET_NAME_LENGTH = 128;
public static final int MAX_DASHBOARD_NAME_LENGTH = 128;
public static final int MAX_USER_FILTER_NAME_LENGTH = 128;
public static final int MAX_ATTRIBUTE_LENGTH = 128;
public static final int MIN_PAGE_NUMBER = 1;
public static final int MAX_PAGE_NUMBER = 1024;
public static final int MAX_HISTORY_DEPTH_BOUND = 31;
public static final int MIN_HISTORY_DEPTH_BOUND = 0;
public static final int MAX_HISTORY_SIZE_BOUND = 31;
public static final int MIN_LOGIN_LENGTH = 1;
public static final int MAX_LOGIN_LENGTH = 128;
public static final int MIN_PASSWORD_LENGTH = 4;
public static final int MAX_PASSWORD_LENGTH = 128;
public static final int TICKET_MIN_LOG_SIZE = 0;
public static final int TICKET_MAX_LOG_SIZE = 50;
public static final int MAX_CUSTOMER_LENGTH = 64;
public static final int MIN_USER_NAME_LENGTH = 3;
public static final int MAX_USER_NAME_LENGTH = 256;
public static final int MAX_PHOTO_SIZE = 1024 * 1024;
public static final int MAX_PHOTO_HEIGHT = 500;
public static final int MAX_PHOTO_WIDTH = 300;
public static final int MIN_DOMAIN_SIZE = 1;
public static final int MAX_DOMAIN_SIZE = 255;
public static final int MIN_SUBTYPE_SHORT_NAME = 1;
public static final int MAX_SUBTYPE_SHORT_NAME = 4;
public static final int MIN_SUBTYPE_LONG_NAME = 3;
public static final int MAX_SUBTYPE_LONG_NAME = 55;
public static final int MIN_ANALYSIS_PATTERN_NAME_LENGTH = 3;
public static final int MAX_ANALYSIS_PATTERN_NAME_LENGTH = 128;
public static final int MAX_DESCRIPTION = 256;
public static final int MIN_DESCRIPTION = 1;
public static final int MIN_DOC_FREQ = 1;
public static final int MAX_DOC_FREQ = 10;
public static final int MIN_TERM_FREQ = 1;
public static final int MAX_TERM_FREQ = 10;
public static final int MIN_SHOULD_MATCH = 50;
public static final int MAX_SHOULD_MATCH = 100;
public static final int MIN_NUMBER_OF_LOG_LINES = -1;
public static final int MAX_NUMBER_OF_LOG_LINES = 5;
public static final String HEX_COLOR_REGEXP = "#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
public static final String PROJECT_NAME_REGEXP = "[a-zA-Z0-9-_]+";
} | add id to saml provider resource
| src/main/java/com/epam/ta/reportportal/ws/model/ValidationConstraints.java | add id to saml provider resource | <ide><path>rc/main/java/com/epam/ta/reportportal/ws/model/ValidationConstraints.java
<ide> public static final int MAX_LOGIN_LENGTH = 128;
<ide>
<ide> public static final int MIN_PASSWORD_LENGTH = 4;
<del> public static final int MAX_PASSWORD_LENGTH = 128;
<add> public static final int MAX_PASSWORD_LENGTH = 256;
<ide>
<ide> public static final int TICKET_MIN_LOG_SIZE = 0;
<ide> public static final int TICKET_MAX_LOG_SIZE = 50; |
|
Java | apache-2.0 | 84fc98880f667dd73f0fede99a301bbb57f6055a | 0 | joshelser/accumulo,ivakegg/accumulo,apache/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,lstav/accumulo,phrocker/accumulo-1,mjwall/accumulo,dhutchis/accumulo,lstav/accumulo,joshelser/accumulo,mjwall/accumulo,mikewalch/accumulo,keith-turner/accumulo,mjwall/accumulo,adamjshook/accumulo,ivakegg/accumulo,lstav/accumulo,keith-turner/accumulo,mikewalch/accumulo,dhutchis/accumulo,dhutchis/accumulo,ivakegg/accumulo,joshelser/accumulo,mikewalch/accumulo,mjwall/accumulo,dhutchis/accumulo,dhutchis/accumulo,keith-turner/accumulo,ctubbsii/accumulo,milleruntime/accumulo,mjwall/accumulo,lstav/accumulo,keith-turner/accumulo,adamjshook/accumulo,milleruntime/accumulo,mjwall/accumulo,dhutchis/accumulo,adamjshook/accumulo,ctubbsii/accumulo,milleruntime/accumulo,adamjshook/accumulo,phrocker/accumulo-1,lstav/accumulo,mikewalch/accumulo,phrocker/accumulo,mikewalch/accumulo,ivakegg/accumulo,adamjshook/accumulo,ctubbsii/accumulo,joshelser/accumulo,milleruntime/accumulo,apache/accumulo,lstav/accumulo,joshelser/accumulo,ctubbsii/accumulo,phrocker/accumulo,ivakegg/accumulo,joshelser/accumulo,phrocker/accumulo,phrocker/accumulo,keith-turner/accumulo,mjwall/accumulo,phrocker/accumulo-1,phrocker/accumulo,adamjshook/accumulo,lstav/accumulo,milleruntime/accumulo,phrocker/accumulo-1,adamjshook/accumulo,apache/accumulo,ctubbsii/accumulo,keith-turner/accumulo,dhutchis/accumulo,ctubbsii/accumulo,joshelser/accumulo,apache/accumulo,ivakegg/accumulo,phrocker/accumulo-1,mikewalch/accumulo,milleruntime/accumulo,dhutchis/accumulo,milleruntime/accumulo,joshelser/accumulo,phrocker/accumulo-1,keith-turner/accumulo,ivakegg/accumulo,phrocker/accumulo,dhutchis/accumulo,phrocker/accumulo,apache/accumulo,adamjshook/accumulo,mikewalch/accumulo,mikewalch/accumulo,apache/accumulo,phrocker/accumulo,adamjshook/accumulo,phrocker/accumulo,apache/accumulo | /*
* 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.accumulo.server.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.UUID;
import jline.ConsoleReader;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.file.FileOperations;
import org.apache.accumulo.core.file.FileSKVWriter;
import org.apache.accumulo.core.file.FileUtil;
import org.apache.accumulo.core.iterators.user.VersioningIterator;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.master.thrift.MasterGoalState;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.constraints.MetadataConstraints;
import org.apache.accumulo.server.iterators.MetadataBulkLoadFilter;
import org.apache.accumulo.server.master.state.tables.TableManager;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.security.SecurityUtil;
import org.apache.accumulo.server.security.ZKAuthenticator;
import org.apache.accumulo.server.tabletserver.TabletTime;
import org.apache.accumulo.server.zookeeper.IZooReaderWriter;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
/**
* This class is used to setup the directory structure and the root tablet to get an instance started
*
*/
public class Initialize {
private static final Logger log = Logger.getLogger(Initialize.class);
private static final String ROOT_USER = "root";
private static boolean clearInstanceName = false;
private static ConsoleReader reader = null;
private static ConsoleReader getConsoleReader() throws IOException {
if (reader == null)
reader = new ConsoleReader();
return reader;
}
private static HashMap<String,String> initialMetadataConf = new HashMap<String,String>();
static {
initialMetadataConf.put(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "32K");
initialMetadataConf.put(Property.TABLE_FILE_REPLICATION.getKey(), "5");
initialMetadataConf.put(Property.TABLE_WALOG_ENABLED.getKey(), "true");
initialMetadataConf.put(Property.TABLE_MAJC_RATIO.getKey(), "1");
initialMetadataConf.put(Property.TABLE_SPLIT_THRESHOLD.getKey(), "4M");
initialMetadataConf.put(Property.TABLE_CONSTRAINT_PREFIX.getKey() + "1", MetadataConstraints.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "scan.vers", "10," + VersioningIterator.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "scan.vers.opt.maxVersions", "1");
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "minc.vers", "10," + VersioningIterator.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "minc.vers.opt.maxVersions", "1");
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.vers", "10," + VersioningIterator.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.vers.opt.maxVersions", "1");
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.bulkLoadFilter", "20," + MetadataBulkLoadFilter.class.getName());
initialMetadataConf.put(Property.TABLE_FAILURES_IGNORE.getKey(), "false");
initialMetadataConf.put(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey() + "tablet",
String.format("%s,%s", Constants.METADATA_TABLET_COLUMN_FAMILY.toString(), Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY.toString()));
initialMetadataConf.put(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey() + "server", String.format("%s,%s,%s,%s",
Constants.METADATA_DATAFILE_COLUMN_FAMILY.toString(), Constants.METADATA_LOG_COLUMN_FAMILY.toString(),
Constants.METADATA_SERVER_COLUMN_FAMILY.toString(), Constants.METADATA_FUTURE_LOCATION_COLUMN_FAMILY.toString()));
initialMetadataConf.put(Property.TABLE_LOCALITY_GROUPS.getKey(), "tablet,server");
initialMetadataConf.put(Property.TABLE_DEFAULT_SCANTIME_VISIBILITY.getKey(), "");
initialMetadataConf.put(Property.TABLE_INDEXCACHE_ENABLED.getKey(), "true");
initialMetadataConf.put(Property.TABLE_BLOCKCACHE_ENABLED.getKey(), "true");
}
public static boolean doInit(Configuration conf, FileSystem fs) throws IOException {
if (!ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_DFS_URI).equals(""))
log.info("Hadoop Filesystem is " + ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_DFS_URI));
else
log.info("Hadoop Filesystem is " + FileSystem.getDefaultUri(conf));
log.info("Accumulo data dir is " + ServerConstants.getBaseDir());
log.info("Zookeeper server is " + ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_ZK_HOST));
log.info("Checking if Zookeeper is available. If this hangs, then you need to make sure zookeeper is running");
if (!zookeeperAvailable()) {
log.fatal("Zookeeper needs to be up and running in order to init. Exiting ...");
return false;
}
if (ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_SECRET).equals(Property.INSTANCE_SECRET.getDefaultValue())) {
ConsoleReader c = getConsoleReader();
c.beep();
c.printNewline();
c.printNewline();
c.printString("Warning!!! Your instance secret is still set to the default, this is not secure. We highly recommend you change it.");
c.printNewline();
c.printNewline();
c.printNewline();
c.printString("You can change the instance secret in accumulo by using:");
c.printNewline();
c.printString(" bin/accumulo " + org.apache.accumulo.server.util.ChangeSecret.class.getName() + " oldPassword newPassword.");
c.printNewline();
c.printString("You will also need to edit your secret in your configuration file by adding the property instance.secret to your conf/accumulo-site.xml. Without this accumulo will not operate correctly");
c.printNewline();
}
UUID uuid = UUID.randomUUID();
try {
if (isInitialized(fs)) {
log.fatal("It appears this location was previously initialized, exiting ... ");
return false;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// prompt user for instance name and root password early, in case they
// abort, we don't leave an inconsistent HDFS/ZooKeeper structure
String instanceNamePath;
try {
instanceNamePath = getInstanceNamePath();
} catch (Exception e) {
log.fatal("Failed to talk to zookeeper", e);
return false;
}
byte[] rootpass = getRootPassword();
try {
initZooKeeper(uuid.toString(), instanceNamePath);
} catch (Exception e) {
log.fatal("Failed to initialize zookeeper", e);
return false;
}
try {
initFileSystem(fs, conf, uuid);
} catch (Exception e) {
log.fatal("Failed to initialize filesystem", e);
return false;
}
try {
initSecurity(uuid.toString(), rootpass);
} catch (Exception e) {
log.fatal("Failed to initialize security", e);
return false;
}
return true;
}
/**
* @return
*/
private static boolean zookeeperAvailable() {
IZooReaderWriter zoo = ZooReaderWriter.getInstance();
try {
return zoo.exists("/");
} catch (KeeperException e) {
return false;
} catch (InterruptedException e) {
return false;
}
}
private static void initFileSystem(FileSystem fs, Configuration conf, UUID uuid) throws IOException {
FileStatus fstat;
// the actual disk location of the root tablet
final Path rootTablet = new Path(ServerConstants.getRootTabletDir());
final Path tableMetadataTablet = new Path(ServerConstants.getMetadataTableDir() + Constants.TABLE_TABLET_LOCATION);
final Path defaultMetadataTablet = new Path(ServerConstants.getMetadataTableDir() + Constants.DEFAULT_TABLET_LOCATION);
final Path metadataTableDir = new Path(ServerConstants.getMetadataTableDir());
fs.mkdirs(new Path(ServerConstants.getDataVersionLocation(), "" + Constants.DATA_VERSION));
// create an instance id
fs.mkdirs(ServerConstants.getInstanceIdLocation());
fs.createNewFile(new Path(ServerConstants.getInstanceIdLocation(), uuid.toString()));
// initialize initial metadata config in zookeeper
initMetadataConfig();
// create metadata table
try {
fstat = fs.getFileStatus(metadataTableDir);
if (!fstat.isDir()) {
log.fatal("location " + metadataTableDir.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe) {
// create btl dir
if (!fs.mkdirs(metadataTableDir)) {
log.fatal("unable to create directory " + metadataTableDir.toString());
return;
}
}
// create root tablet
try {
fstat = fs.getFileStatus(rootTablet);
if (!fstat.isDir()) {
log.fatal("location " + rootTablet.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe) {
// create btl dir
if (!fs.mkdirs(rootTablet)) {
log.fatal("unable to create directory " + rootTablet.toString());
return;
}
// populate the root tablet with info about the default tablet
// the root tablet contains the key extent and locations of all the
// metadata tablets
String initRootTabFile = ServerConstants.getMetadataTableDir() + "/root_tablet/00000_00000."
+ FileOperations.getNewFileExtension(AccumuloConfiguration.getDefaultConfiguration());
FileSKVWriter mfw = FileOperations.getInstance().openWriter(initRootTabFile, fs, conf, AccumuloConfiguration.getDefaultConfiguration());
mfw.startDefaultLocalityGroup();
// -----------] root tablet info
Text rootExtent = Constants.ROOT_TABLET_EXTENT.getMetadataEntry();
// root's directory
Key rootDirKey = new Key(rootExtent, Constants.METADATA_DIRECTORY_COLUMN.getColumnFamily(), Constants.METADATA_DIRECTORY_COLUMN.getColumnQualifier(), 0);
mfw.append(rootDirKey, new Value("/root_tablet".getBytes()));
// root's prev row
Key rootPrevRowKey = new Key(rootExtent, Constants.METADATA_PREV_ROW_COLUMN.getColumnFamily(), Constants.METADATA_PREV_ROW_COLUMN.getColumnQualifier(), 0);
mfw.append(rootPrevRowKey, new Value(new byte[] {0}));
// ----------] table tablet info
Text tableExtent = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), Constants.METADATA_RESERVED_KEYSPACE_START_KEY.getRow()));
// table tablet's directory
Key tableDirKey = new Key(tableExtent, Constants.METADATA_DIRECTORY_COLUMN.getColumnFamily(), Constants.METADATA_DIRECTORY_COLUMN.getColumnQualifier(), 0);
mfw.append(tableDirKey, new Value(Constants.TABLE_TABLET_LOCATION.getBytes()));
// table tablet time
Key tableTimeKey = new Key(tableExtent, Constants.METADATA_TIME_COLUMN.getColumnFamily(), Constants.METADATA_TIME_COLUMN.getColumnQualifier(), 0);
mfw.append(tableTimeKey, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes()));
// table tablet's prevrow
Key tablePrevRowKey = new Key(tableExtent, Constants.METADATA_PREV_ROW_COLUMN.getColumnFamily(), Constants.METADATA_PREV_ROW_COLUMN.getColumnQualifier(),
0);
mfw.append(tablePrevRowKey, KeyExtent.encodePrevEndRow(new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null))));
// ----------] default tablet info
Text defaultExtent = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null));
// default's directory
Key defaultDirKey = new Key(defaultExtent, Constants.METADATA_DIRECTORY_COLUMN.getColumnFamily(),
Constants.METADATA_DIRECTORY_COLUMN.getColumnQualifier(), 0);
mfw.append(defaultDirKey, new Value(Constants.DEFAULT_TABLET_LOCATION.getBytes()));
// default's time
Key defaultTimeKey = new Key(defaultExtent, Constants.METADATA_TIME_COLUMN.getColumnFamily(), Constants.METADATA_TIME_COLUMN.getColumnQualifier(), 0);
mfw.append(defaultTimeKey, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes()));
// default's prevrow
Key defaultPrevRowKey = new Key(defaultExtent, Constants.METADATA_PREV_ROW_COLUMN.getColumnFamily(),
Constants.METADATA_PREV_ROW_COLUMN.getColumnQualifier(), 0);
mfw.append(defaultPrevRowKey, KeyExtent.encodePrevEndRow(Constants.METADATA_RESERVED_KEYSPACE_START_KEY.getRow()));
mfw.close();
}
// create table and default tablets directories
try {
fstat = fs.getFileStatus(defaultMetadataTablet);
if (!fstat.isDir()) {
log.fatal("location " + defaultMetadataTablet.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe) {
try {
fstat = fs.getFileStatus(tableMetadataTablet);
if (!fstat.isDir()) {
log.fatal("location " + tableMetadataTablet.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe2) {
// create table info dir
if (!fs.mkdirs(tableMetadataTablet)) {
log.fatal("unable to create directory " + tableMetadataTablet.toString());
return;
}
}
// create default dir
if (!fs.mkdirs(defaultMetadataTablet)) {
log.fatal("unable to create directory " + defaultMetadataTablet.toString());
return;
}
}
}
private static void initZooKeeper(String uuid, String instanceNamePath) throws KeeperException, InterruptedException {
// setup basic data in zookeeper
IZooReaderWriter zoo = ZooReaderWriter.getInstance();
ZooUtil.putPersistentData(zoo.getZooKeeper(), Constants.ZROOT, new byte[0], -1, NodeExistsPolicy.SKIP, Ids.OPEN_ACL_UNSAFE);
ZooUtil.putPersistentData(zoo.getZooKeeper(), Constants.ZROOT + Constants.ZINSTANCES, new byte[0], -1, NodeExistsPolicy.SKIP, Ids.OPEN_ACL_UNSAFE);
// setup instance name
if (clearInstanceName)
zoo.recursiveDelete(instanceNamePath, NodeMissingPolicy.SKIP);
zoo.putPersistentData(instanceNamePath, uuid.getBytes(), NodeExistsPolicy.FAIL);
// setup the instance
String zkInstanceRoot = Constants.ZROOT + "/" + uuid;
zoo.putPersistentData(zkInstanceRoot, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTABLES, Constants.ZTABLES_INITIAL_ID, NodeExistsPolicy.FAIL);
TableManager.prepareNewTableState(uuid, Constants.METADATA_TABLE_ID, Constants.METADATA_TABLE_NAME, TableState.ONLINE, NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTSERVERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZPROBLEMS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZROOT_TABLET, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZROOT_TABLET_WALOGS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZLOGGERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTRACERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTER_LOCK, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTER_GOAL_STATE, MasterGoalState.NORMAL.toString().getBytes(), NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZGC, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZGC_LOCK, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZCONFIG, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTABLE_LOCKS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZHDFS_RESERVATIONS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZNEXT_FILE, new byte[] {'0'}, NodeExistsPolicy.FAIL);
}
private static String getInstanceNamePath() throws IOException, KeeperException, InterruptedException {
// setup the instance name
String instanceName, instanceNamePath = null;
boolean exists = true;
do {
instanceName = getConsoleReader().readLine("Instance name : ");
if (instanceName == null)
System.exit(0);
instanceName = instanceName.trim();
if (instanceName.length() == 0)
continue;
instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + instanceName;
if (clearInstanceName) {
exists = false;
break;
} else if ((boolean) (exists = ZooReaderWriter.getInstance().exists(instanceNamePath))) {
String decision = getConsoleReader().readLine("Instance name \"" + instanceName + "\" exists. Delete existing entry from zookeeper? [Y/N] : ");
if (decision == null)
System.exit(0);
if (decision.length() == 1 && decision.toLowerCase(Locale.ENGLISH).charAt(0) == 'y') {
clearInstanceName = true;
exists = false;
}
}
} while (exists);
return instanceNamePath;
}
private static byte[] getRootPassword() throws IOException {
String rootpass;
String confirmpass;
do {
rootpass = getConsoleReader().readLine("Enter initial password for " + ROOT_USER + ": ", '*');
if (rootpass == null)
System.exit(0);
confirmpass = getConsoleReader().readLine("Confirm initial password for " + ROOT_USER + ": ", '*');
if (confirmpass == null)
System.exit(0);
if (!rootpass.equals(confirmpass))
log.error("Passwords do not match");
} while (!rootpass.equals(confirmpass));
return rootpass.getBytes();
}
private static void initSecurity(String iid, byte[] rootpass) throws AccumuloSecurityException {
new ZKAuthenticator(iid).initializeSecurity(SecurityConstants.getSystemCredentials(), ROOT_USER, rootpass);
}
protected static void initMetadataConfig() throws IOException {
try {
for (Entry<String,String> entry : initialMetadataConf.entrySet())
if (!TablePropUtil.setTableProperty(Constants.METADATA_TABLE_ID, entry.getKey(), entry.getValue()))
throw new IOException("Cannot create per-table property " + entry.getKey());
} catch (Exception e) {
log.fatal("error talking to zookeeper", e);
throw new IOException(e);
}
}
public static boolean isInitialized(FileSystem fs) throws IOException {
return (fs.exists(ServerConstants.getInstanceIdLocation()) || fs.exists(ServerConstants.getDataVersionLocation()));
}
public static void main(String[] args) {
boolean justSecurity = false;
for (String arg : args) {
if (arg.equals("--reset-security")) {
justSecurity = true;
} else if (arg.equals("--clear-instance-name")) {
clearInstanceName = true;
} else {
RuntimeException e = new RuntimeException();
log.fatal("Bad argument " + arg, e);
throw e;
}
}
try {
Configuration conf = CachedConfiguration.getInstance();
SecurityUtil.serverLogin();
FileSystem fs = FileUtil.getFileSystem(conf, ServerConfiguration.getSiteConfiguration());
if (justSecurity) {
if (isInitialized(fs))
initSecurity(HdfsZooInstance.getInstance().getInstanceID(), getRootPassword());
else
log.fatal("Attempted to reset security on accumulo before it was initialized");
} else if (!doInit(conf, fs))
System.exit(-1);
} catch (Exception e) {
log.fatal(e, e);
throw new RuntimeException(e);
}
}
}
| src/server/src/main/java/org/apache/accumulo/server/util/Initialize.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.accumulo.server.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.UUID;
import jline.ConsoleReader;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.file.FileOperations;
import org.apache.accumulo.core.file.FileSKVWriter;
import org.apache.accumulo.core.file.FileUtil;
import org.apache.accumulo.core.iterators.user.VersioningIterator;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.master.thrift.MasterGoalState;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.core.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.constraints.MetadataConstraints;
import org.apache.accumulo.server.iterators.MetadataBulkLoadFilter;
import org.apache.accumulo.server.master.state.tables.TableManager;
import org.apache.accumulo.server.security.SecurityConstants;
import org.apache.accumulo.server.security.SecurityUtil;
import org.apache.accumulo.server.security.ZKAuthenticator;
import org.apache.accumulo.server.tabletserver.TabletTime;
import org.apache.accumulo.server.zookeeper.IZooReaderWriter;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
/**
* This class is used to setup the directory structure and the root tablet to get an instance started
*
*/
public class Initialize {
private static final Logger log = Logger.getLogger(Initialize.class);
private static final String ROOT_USER = "root";
private static boolean clearInstanceName = false;
private static ConsoleReader reader = null;
private static ConsoleReader getConsoleReader() throws IOException {
if (reader == null)
reader = new ConsoleReader();
return reader;
}
private static HashMap<String,String> initialMetadataConf = new HashMap<String,String>();
static {
initialMetadataConf.put(Property.TABLE_FILE_COMPRESSED_BLOCK_SIZE.getKey(), "32K");
initialMetadataConf.put(Property.TABLE_FILE_REPLICATION.getKey(), "5");
initialMetadataConf.put(Property.TABLE_WALOG_ENABLED.getKey(), "true");
initialMetadataConf.put(Property.TABLE_MAJC_RATIO.getKey(), "1");
initialMetadataConf.put(Property.TABLE_SPLIT_THRESHOLD.getKey(), "4M");
initialMetadataConf.put(Property.TABLE_CONSTRAINT_PREFIX.getKey() + "1", MetadataConstraints.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "scan.vers", "10," + VersioningIterator.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "scan.vers.opt.maxVersions", "1");
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "minc.vers", "10," + VersioningIterator.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "minc.vers.opt.maxVersions", "1");
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.vers", "10," + VersioningIterator.class.getName());
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.vers.opt.maxVersions", "1");
initialMetadataConf.put(Property.TABLE_ITERATOR_PREFIX.getKey() + "majc.bulkLoadFilter", "20," + MetadataBulkLoadFilter.class.getName());
initialMetadataConf.put(Property.TABLE_FAILURES_IGNORE.getKey(), "false");
initialMetadataConf.put(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey() + "tablet",
String.format("%s,%s", Constants.METADATA_TABLET_COLUMN_FAMILY.toString(), Constants.METADATA_CURRENT_LOCATION_COLUMN_FAMILY.toString()));
initialMetadataConf.put(Property.TABLE_LOCALITY_GROUP_PREFIX.getKey() + "server", String.format("%s,%s,%s,%s",
Constants.METADATA_DATAFILE_COLUMN_FAMILY.toString(), Constants.METADATA_LOG_COLUMN_FAMILY.toString(),
Constants.METADATA_SERVER_COLUMN_FAMILY.toString(), Constants.METADATA_FUTURE_LOCATION_COLUMN_FAMILY.toString()));
initialMetadataConf.put(Property.TABLE_LOCALITY_GROUPS.getKey(), "tablet,server");
initialMetadataConf.put(Property.TABLE_DEFAULT_SCANTIME_VISIBILITY.getKey(), "");
initialMetadataConf.put(Property.TABLE_INDEXCACHE_ENABLED.getKey(), "true");
initialMetadataConf.put(Property.TABLE_BLOCKCACHE_ENABLED.getKey(), "true");
}
public static boolean doInit(Configuration conf, FileSystem fs) throws IOException {
if (!ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_DFS_URI).equals(""))
log.info("Hadoop Filesystem is " + ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_DFS_URI));
else
log.info("Hadoop Filesystem is " + FileSystem.getDefaultUri(conf));
log.info("Accumulo data dir is " + ServerConstants.getBaseDir());
log.info("Zookeeper server is " + ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_ZK_HOST));
if (ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_SECRET).equals(Property.INSTANCE_SECRET.getDefaultValue())) {
ConsoleReader c = getConsoleReader();
c.beep();
c.printNewline();
c.printNewline();
c.printString("Warning!!! Your instance secret is still set to the default, this is not secure. We highly recommend you change it.");
c.printNewline();
c.printNewline();
c.printNewline();
c.printString("You can change the instance secret in accumulo by using:");
c.printNewline();
c.printString(" bin/accumulo " + org.apache.accumulo.server.util.ChangeSecret.class.getName() + " oldPassword newPassword.");
c.printNewline();
c.printString("You will also need to edit your secret in your configuration file by adding the property instance.secret to your conf/accumulo-site.xml. Without this accumulo will not operate correctly");
c.printNewline();
}
UUID uuid = UUID.randomUUID();
try {
if (isInitialized(fs)) {
log.fatal("It appears this location was previously initialized, exiting ... ");
return false;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// prompt user for instance name and root password early, in case they
// abort, we don't leave an inconsistent HDFS/ZooKeeper structure
String instanceNamePath;
try {
instanceNamePath = getInstanceNamePath();
} catch (Exception e) {
log.fatal("Failed to talk to zookeeper", e);
return false;
}
byte[] rootpass = getRootPassword();
try {
initZooKeeper(uuid.toString(), instanceNamePath);
} catch (Exception e) {
log.fatal("Failed to initialize zookeeper", e);
return false;
}
try {
initFileSystem(fs, conf, uuid);
} catch (Exception e) {
log.fatal("Failed to initialize filesystem", e);
return false;
}
try {
initSecurity(uuid.toString(), rootpass);
} catch (Exception e) {
log.fatal("Failed to initialize security", e);
return false;
}
return true;
}
private static void initFileSystem(FileSystem fs, Configuration conf, UUID uuid) throws IOException {
FileStatus fstat;
// the actual disk location of the root tablet
final Path rootTablet = new Path(ServerConstants.getRootTabletDir());
final Path tableMetadataTablet = new Path(ServerConstants.getMetadataTableDir() + Constants.TABLE_TABLET_LOCATION);
final Path defaultMetadataTablet = new Path(ServerConstants.getMetadataTableDir() + Constants.DEFAULT_TABLET_LOCATION);
final Path metadataTableDir = new Path(ServerConstants.getMetadataTableDir());
fs.mkdirs(new Path(ServerConstants.getDataVersionLocation(), "" + Constants.DATA_VERSION));
// create an instance id
fs.mkdirs(ServerConstants.getInstanceIdLocation());
fs.createNewFile(new Path(ServerConstants.getInstanceIdLocation(), uuid.toString()));
// initialize initial metadata config in zookeeper
initMetadataConfig();
// create metadata table
try {
fstat = fs.getFileStatus(metadataTableDir);
if (!fstat.isDir()) {
log.fatal("location " + metadataTableDir.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe) {
// create btl dir
if (!fs.mkdirs(metadataTableDir)) {
log.fatal("unable to create directory " + metadataTableDir.toString());
return;
}
}
// create root tablet
try {
fstat = fs.getFileStatus(rootTablet);
if (!fstat.isDir()) {
log.fatal("location " + rootTablet.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe) {
// create btl dir
if (!fs.mkdirs(rootTablet)) {
log.fatal("unable to create directory " + rootTablet.toString());
return;
}
// populate the root tablet with info about the default tablet
// the root tablet contains the key extent and locations of all the
// metadata tablets
String initRootTabFile = ServerConstants.getMetadataTableDir() + "/root_tablet/00000_00000."
+ FileOperations.getNewFileExtension(AccumuloConfiguration.getDefaultConfiguration());
FileSKVWriter mfw = FileOperations.getInstance().openWriter(initRootTabFile, fs, conf, AccumuloConfiguration.getDefaultConfiguration());
mfw.startDefaultLocalityGroup();
// -----------] root tablet info
Text rootExtent = Constants.ROOT_TABLET_EXTENT.getMetadataEntry();
// root's directory
Key rootDirKey = new Key(rootExtent, Constants.METADATA_DIRECTORY_COLUMN.getColumnFamily(), Constants.METADATA_DIRECTORY_COLUMN.getColumnQualifier(), 0);
mfw.append(rootDirKey, new Value("/root_tablet".getBytes()));
// root's prev row
Key rootPrevRowKey = new Key(rootExtent, Constants.METADATA_PREV_ROW_COLUMN.getColumnFamily(), Constants.METADATA_PREV_ROW_COLUMN.getColumnQualifier(), 0);
mfw.append(rootPrevRowKey, new Value(new byte[] {0}));
// ----------] table tablet info
Text tableExtent = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), Constants.METADATA_RESERVED_KEYSPACE_START_KEY.getRow()));
// table tablet's directory
Key tableDirKey = new Key(tableExtent, Constants.METADATA_DIRECTORY_COLUMN.getColumnFamily(), Constants.METADATA_DIRECTORY_COLUMN.getColumnQualifier(), 0);
mfw.append(tableDirKey, new Value(Constants.TABLE_TABLET_LOCATION.getBytes()));
// table tablet time
Key tableTimeKey = new Key(tableExtent, Constants.METADATA_TIME_COLUMN.getColumnFamily(), Constants.METADATA_TIME_COLUMN.getColumnQualifier(), 0);
mfw.append(tableTimeKey, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes()));
// table tablet's prevrow
Key tablePrevRowKey = new Key(tableExtent, Constants.METADATA_PREV_ROW_COLUMN.getColumnFamily(), Constants.METADATA_PREV_ROW_COLUMN.getColumnQualifier(),
0);
mfw.append(tablePrevRowKey, KeyExtent.encodePrevEndRow(new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null))));
// ----------] default tablet info
Text defaultExtent = new Text(KeyExtent.getMetadataEntry(new Text(Constants.METADATA_TABLE_ID), null));
// default's directory
Key defaultDirKey = new Key(defaultExtent, Constants.METADATA_DIRECTORY_COLUMN.getColumnFamily(),
Constants.METADATA_DIRECTORY_COLUMN.getColumnQualifier(), 0);
mfw.append(defaultDirKey, new Value(Constants.DEFAULT_TABLET_LOCATION.getBytes()));
// default's time
Key defaultTimeKey = new Key(defaultExtent, Constants.METADATA_TIME_COLUMN.getColumnFamily(), Constants.METADATA_TIME_COLUMN.getColumnQualifier(), 0);
mfw.append(defaultTimeKey, new Value((TabletTime.LOGICAL_TIME_ID + "0").getBytes()));
// default's prevrow
Key defaultPrevRowKey = new Key(defaultExtent, Constants.METADATA_PREV_ROW_COLUMN.getColumnFamily(),
Constants.METADATA_PREV_ROW_COLUMN.getColumnQualifier(), 0);
mfw.append(defaultPrevRowKey, KeyExtent.encodePrevEndRow(Constants.METADATA_RESERVED_KEYSPACE_START_KEY.getRow()));
mfw.close();
}
// create table and default tablets directories
try {
fstat = fs.getFileStatus(defaultMetadataTablet);
if (!fstat.isDir()) {
log.fatal("location " + defaultMetadataTablet.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe) {
try {
fstat = fs.getFileStatus(tableMetadataTablet);
if (!fstat.isDir()) {
log.fatal("location " + tableMetadataTablet.toString() + " exists but is not a directory");
return;
}
} catch (FileNotFoundException fnfe2) {
// create table info dir
if (!fs.mkdirs(tableMetadataTablet)) {
log.fatal("unable to create directory " + tableMetadataTablet.toString());
return;
}
}
// create default dir
if (!fs.mkdirs(defaultMetadataTablet)) {
log.fatal("unable to create directory " + defaultMetadataTablet.toString());
return;
}
}
}
private static void initZooKeeper(String uuid, String instanceNamePath) throws KeeperException, InterruptedException {
// setup basic data in zookeeper
IZooReaderWriter zoo = ZooReaderWriter.getInstance();
ZooUtil.putPersistentData(zoo.getZooKeeper(), Constants.ZROOT, new byte[0], -1, NodeExistsPolicy.SKIP, Ids.OPEN_ACL_UNSAFE);
ZooUtil.putPersistentData(zoo.getZooKeeper(), Constants.ZROOT + Constants.ZINSTANCES, new byte[0], -1, NodeExistsPolicy.SKIP, Ids.OPEN_ACL_UNSAFE);
// setup instance name
if (clearInstanceName)
zoo.recursiveDelete(instanceNamePath, NodeMissingPolicy.SKIP);
zoo.putPersistentData(instanceNamePath, uuid.getBytes(), NodeExistsPolicy.FAIL);
// setup the instance
String zkInstanceRoot = Constants.ZROOT + "/" + uuid;
zoo.putPersistentData(zkInstanceRoot, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTABLES, Constants.ZTABLES_INITIAL_ID, NodeExistsPolicy.FAIL);
TableManager.prepareNewTableState(uuid, Constants.METADATA_TABLE_ID, Constants.METADATA_TABLE_NAME, TableState.ONLINE, NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTSERVERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZPROBLEMS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZROOT_TABLET, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZROOT_TABLET_WALOGS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZLOGGERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTRACERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTERS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTER_LOCK, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZMASTER_GOAL_STATE, MasterGoalState.NORMAL.toString().getBytes(), NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZGC, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZGC_LOCK, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZCONFIG, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZTABLE_LOCKS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZHDFS_RESERVATIONS, new byte[0], NodeExistsPolicy.FAIL);
zoo.putPersistentData(zkInstanceRoot + Constants.ZNEXT_FILE, new byte[] {'0'}, NodeExistsPolicy.FAIL);
}
private static String getInstanceNamePath() throws IOException, KeeperException, InterruptedException {
// setup the instance name
String instanceName, instanceNamePath = null;
boolean exists = true;
do {
instanceName = getConsoleReader().readLine("Instance name : ");
if (instanceName == null)
System.exit(0);
instanceName = instanceName.trim();
if (instanceName.length() == 0)
continue;
instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + instanceName;
if (clearInstanceName) {
exists = false;
break;
} else if ((boolean) (exists = ZooReaderWriter.getInstance().exists(instanceNamePath))) {
String decision = getConsoleReader().readLine("Instance name \"" + instanceName + "\" exists. Delete existing entry from zookeeper? [Y/N] : ");
if (decision == null)
System.exit(0);
if (decision.length() == 1 && decision.toLowerCase(Locale.ENGLISH).charAt(0) == 'y') {
clearInstanceName = true;
exists = false;
}
}
} while (exists);
return instanceNamePath;
}
private static byte[] getRootPassword() throws IOException {
String rootpass;
String confirmpass;
do {
rootpass = getConsoleReader().readLine("Enter initial password for " + ROOT_USER + ": ", '*');
if (rootpass == null)
System.exit(0);
confirmpass = getConsoleReader().readLine("Confirm initial password for " + ROOT_USER + ": ", '*');
if (confirmpass == null)
System.exit(0);
if (!rootpass.equals(confirmpass))
log.error("Passwords do not match");
} while (!rootpass.equals(confirmpass));
return rootpass.getBytes();
}
private static void initSecurity(String iid, byte[] rootpass) throws AccumuloSecurityException {
new ZKAuthenticator(iid).initializeSecurity(SecurityConstants.getSystemCredentials(), ROOT_USER, rootpass);
}
protected static void initMetadataConfig() throws IOException {
try {
for (Entry<String,String> entry : initialMetadataConf.entrySet())
if (!TablePropUtil.setTableProperty(Constants.METADATA_TABLE_ID, entry.getKey(), entry.getValue()))
throw new IOException("Cannot create per-table property " + entry.getKey());
} catch (Exception e) {
log.fatal("error talking to zookeeper", e);
throw new IOException(e);
}
}
public static boolean isInitialized(FileSystem fs) throws IOException {
return (fs.exists(ServerConstants.getInstanceIdLocation()) || fs.exists(ServerConstants.getDataVersionLocation()));
}
public static void main(String[] args) {
boolean justSecurity = false;
for (String arg : args) {
if (arg.equals("--reset-security")) {
justSecurity = true;
} else if (arg.equals("--clear-instance-name")) {
clearInstanceName = true;
} else {
RuntimeException e = new RuntimeException();
log.fatal("Bad argument " + arg, e);
throw e;
}
}
try {
Configuration conf = CachedConfiguration.getInstance();
SecurityUtil.serverLogin();
FileSystem fs = FileUtil.getFileSystem(conf, ServerConfiguration.getSiteConfiguration());
if (justSecurity) {
if (isInitialized(fs))
initSecurity(HdfsZooInstance.getInstance().getInstanceID(), getRootPassword());
else
log.fatal("Attempted to reset security on accumulo before it was initialized");
} else if (!doInit(conf, fs))
System.exit(-1);
} catch (Exception e) {
log.fatal(e, e);
throw new RuntimeException(e);
}
}
}
| Accumulo-459 - Zookeeper is made to recheck on failure, so detecting failure is a bit more difficult. However, that doesn't mean we can't be informative for the user if it's not availabile.
git-svn-id: cc0c05f7b56177c0e6043873654ef5698b7b466b@1336398 13f79535-47bb-0310-9956-ffa450edef68
| src/server/src/main/java/org/apache/accumulo/server/util/Initialize.java | Accumulo-459 - Zookeeper is made to recheck on failure, so detecting failure is a bit more difficult. However, that doesn't mean we can't be informative for the user if it's not availabile. | <ide><path>rc/server/src/main/java/org/apache/accumulo/server/util/Initialize.java
<ide>
<ide> log.info("Accumulo data dir is " + ServerConstants.getBaseDir());
<ide> log.info("Zookeeper server is " + ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_ZK_HOST));
<add> log.info("Checking if Zookeeper is available. If this hangs, then you need to make sure zookeeper is running");
<add> if (!zookeeperAvailable()) {
<add> log.fatal("Zookeeper needs to be up and running in order to init. Exiting ...");
<add> return false;
<add> }
<ide> if (ServerConfiguration.getSiteConfiguration().get(Property.INSTANCE_SECRET).equals(Property.INSTANCE_SECRET.getDefaultValue())) {
<ide> ConsoleReader c = getConsoleReader();
<ide> c.beep();
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @return
<add> */
<add> private static boolean zookeeperAvailable() {
<add> IZooReaderWriter zoo = ZooReaderWriter.getInstance();
<add> try {
<add> return zoo.exists("/");
<add> } catch (KeeperException e) {
<add> return false;
<add> } catch (InterruptedException e) {
<add> return false;
<add> }
<add> }
<add>
<ide> private static void initFileSystem(FileSystem fs, Configuration conf, UUID uuid) throws IOException {
<ide> FileStatus fstat;
<ide> |
|
Java | lgpl-2.1 | 438370acbd164bfdc7bf6c6601539e55e34c6be1 | 0 | RockManJoe64/swingx,RockManJoe64/swingx | /*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import org.jdesktop.swingx.JXLoginPane.JXLoginFrame;
import org.jdesktop.swingx.JXLoginPane.SaveMode;
import org.jdesktop.swingx.auth.LoginService;
import org.jdesktop.swingx.auth.SimpleLoginService;
import org.jdesktop.swingx.graphics.GraphicsUtilities;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.plaf.basic.BasicLoginPaneUI;
/**
* Simple tests to ensure that the {@code JXLoginPane} can be instantiated and
* displayed.
*
* @author Karl Schaefer
*/
public class JXLoginPaneVisualCheck extends InteractiveTestCase {
public JXLoginPaneVisualCheck() {
super("JXLoginPane Test");
}
public static void main(String[] args) throws Exception {
// setSystemLF(true);
JXLoginPaneVisualCheck test = new JXLoginPaneVisualCheck();
try {
// test.runInteractiveTests();
test.runInteractiveTests("interactiveComparativeDialogs");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* Issue #538-swingx Failure to set locale at runtime
*
*/
public void interactiveDisplay() {
JComponent.setDefaultLocale(Locale.FRANCE);
JXLoginPane panel = new JXLoginPane();
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #538-swingx Failure to set locale at runtime
*
*/
public void interactiveDisplayFixedUser() {
JComponent.setDefaultLocale(Locale.FRANCE);
JXLoginPane panel = new JXLoginPane();
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
panel.setUserName("aGuy");
panel.setUserNameEnabled(false);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #538-swingx Failure to set locale at runtime
*
*/
public void interactiveSetBackground() {
JXLoginPane panel = new JXLoginPane();
panel.setBackgroundPainter(new MattePainter(Color.RED, true));
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #777-swingx Custom banner not picked up due to double updateUI() call
*
*/
public void interactiveCustomBannerDisplay() {
JXLoginPane panel = new JXLoginPane();
panel.setUI(new DummyLoginPaneUI(panel));
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #636-swingx Unexpected resize on long exception message.
*
*/
public void interactiveError() {
JComponent.setDefaultLocale(Locale.FRANCE);
final JXLoginPane panel = new JXLoginPane(new LoginService() {
@Override
public boolean authenticate(String name, char[] password,
String server) throws Exception {
throw new Exception("Ex.");
}});
final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel);
// if uncommented dialog will disappear immediately due to invocation of login action
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message.");
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
evaluateChildren(frame.getContentPane().getComponents());
}});
}
/**
* Issue #636-swingx Unexpected resize on long exception message.
*
*/
public void interactiveBackground() {
JComponent.setDefaultLocale(Locale.FRANCE);
final JXLoginPane panel = new JXLoginPane(new LoginService() {
@Override
public boolean authenticate(String name, char[] password,
String server) throws Exception {
throw new Exception("Ex.");
}});
final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel);
// if uncomented dialog will disappear immediatelly dou to invocation of login action
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message.");
panel.setSaveMode(SaveMode.BOTH);
frame.getContentPane().setBackgroundPainter(new MattePainter(
new GradientPaint(0, 0, Color.BLUE, 1, 0, Color.YELLOW), true));
frame.pack();
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
evaluateChildren(frame.getContentPane().getComponents());
}});
}
/**
* Progress message test.
*/
public void interactiveProgress() {
final JXLoginPane panel = new JXLoginPane();
final JFrame frame = JXLoginPane.showLoginFrame(panel);
panel.setLoginService(new LoginService() {
@Override
public boolean authenticate(String name, char[] password,
String server) throws Exception {
panel.startLogin();
Thread.sleep(5000);
return true;
}});
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
evaluateChildren(frame.getContentPane().getComponents());
}});
}
private boolean evaluateChildren(Component[] components) {
for (Component c: components) {
if (c instanceof JButton && "login".equals(((JButton) c).getActionCommand())) {
((JButton) c).doClick();
return true;
} else if (c instanceof Container) {
if (evaluateChildren(((Container) c).getComponents()) ){
return true;
}
}
}
return false;
}
public class DummyLoginPaneUI extends BasicLoginPaneUI {
public DummyLoginPaneUI(JXLoginPane dlg) {
super(dlg);
}
@Override
public Image getBanner() {
Image banner = super.getBanner();
BufferedImage im = GraphicsUtilities.createCompatibleTranslucentImage(banner.getWidth(null), banner.getHeight(null));
Graphics2D g = im.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(banner, 0, 0, 100, 100, null);
} finally {
g.dispose();
}
return im;
}
}
@Override
protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) {
super.createAndAddMenus(menuBar, component);
JMenu menu = new JMenu("Locales");
menu.add(new AbstractAction("Change Locale") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
if (component.getLocale() == Locale.FRANCE) {
component.setLocale(Locale.ENGLISH);
} else {
component.setLocale(Locale.FRANCE);
}
}});
menuBar.add(menu);
}
/**
* swingx-917
* @throws Exception
*/
public void interactiveBrokenLayoutAfterFailedLogin() throws Exception {
// PENDING JW: removed while fixing #1186-swingx (no dependency on sun packages)
// revisit: why do we do this at all? If really needed replace
// sun.awt.AppContext.getAppContext().put("JComponent.defaultLocale", Locale.FRANCE);
Map<String, char[]> aMap = new HashMap<String, char[]>();
aMap.put("asdf", "asdf".toCharArray());
JXLoginPane panel = new JXLoginPane(new SimpleLoginService(aMap));
panel.setSaveMode(JXLoginPane.SaveMode.BOTH);
panel.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(
PropertyChangeEvent thePropertyChangeEvent) {
System.err.println(thePropertyChangeEvent.getPropertyName()
+ " " + thePropertyChangeEvent.getOldValue()
+ " -> " + thePropertyChangeEvent.getNewValue());
}
});
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.pack();
frame.setVisible(true);
}
public void interactiveComparativeDialogs() {
JXDialog dialog = new JXDialog(new JXLoginPane());
dialog.pack();
dialog.setVisible(true);
JXLoginPane.showLoginDialog(null, new JXLoginPane());
}
/**
* Do nothing, make the test runner happy
* (would output a warning without a test fixture).
*
*/
public void testDummy() {
}
}
| src/test/org/jdesktop/swingx/JXLoginPaneVisualCheck.java | /*
* Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* California 95054, U.S.A. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jdesktop.swingx;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
import org.jdesktop.swingx.JXLoginPane.JXLoginFrame;
import org.jdesktop.swingx.JXLoginPane.SaveMode;
import org.jdesktop.swingx.auth.LoginService;
import org.jdesktop.swingx.auth.SimpleLoginService;
import org.jdesktop.swingx.graphics.GraphicsUtilities;
import org.jdesktop.swingx.painter.MattePainter;
import org.jdesktop.swingx.plaf.basic.BasicLoginPaneUI;
/**
* Simple tests to ensure that the {@code JXLoginPane} can be instantiated and
* displayed.
*
* @author Karl Schaefer
*/
public class JXLoginPaneVisualCheck extends InteractiveTestCase {
public JXLoginPaneVisualCheck() {
super("JXLoginPane Test");
}
public static void main(String[] args) throws Exception {
// setSystemLF(true);
JXLoginPaneVisualCheck test = new JXLoginPaneVisualCheck();
try {
test.runInteractiveTests();
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* Issue #538-swingx Failure to set locale at runtime
*
*/
public void interactiveDisplay() {
JComponent.setDefaultLocale(Locale.FRANCE);
JXLoginPane panel = new JXLoginPane();
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #538-swingx Failure to set locale at runtime
*
*/
public void interactiveDisplayFixedUser() {
JComponent.setDefaultLocale(Locale.FRANCE);
JXLoginPane panel = new JXLoginPane();
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
panel.setUserName("aGuy");
panel.setUserNameEnabled(false);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #538-swingx Failure to set locale at runtime
*
*/
public void interactiveSetBackground() {
JXLoginPane panel = new JXLoginPane();
panel.setBackgroundPainter(new MattePainter(Color.RED, true));
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #777-swingx Custom banner not picked up due to double updateUI() call
*
*/
public void interactiveCustomBannerDisplay() {
JXLoginPane panel = new JXLoginPane();
panel.setUI(new DummyLoginPaneUI(panel));
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
}
/**
* Issue #636-swingx Unexpected resize on long exception message.
*
*/
public void interactiveError() {
JComponent.setDefaultLocale(Locale.FRANCE);
final JXLoginPane panel = new JXLoginPane(new LoginService() {
@Override
public boolean authenticate(String name, char[] password,
String server) throws Exception {
throw new Exception("Ex.");
}});
final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel);
// if uncommented dialog will disappear immediately due to invocation of login action
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message.");
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
evaluateChildren(frame.getContentPane().getComponents());
}});
}
/**
* Issue #636-swingx Unexpected resize on long exception message.
*
*/
public void interactiveBackground() {
JComponent.setDefaultLocale(Locale.FRANCE);
final JXLoginPane panel = new JXLoginPane(new LoginService() {
@Override
public boolean authenticate(String name, char[] password,
String server) throws Exception {
throw new Exception("Ex.");
}});
final JXLoginFrame frame = JXLoginPane.showLoginFrame(panel);
// if uncomented dialog will disappear immediatelly dou to invocation of login action
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setErrorMessage("TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO TO Unexpected resize on long exception message. Unexpected resize on long exception message.");
panel.setSaveMode(SaveMode.BOTH);
frame.getContentPane().setBackgroundPainter(new MattePainter(
new GradientPaint(0, 0, Color.BLUE, 1, 0, Color.YELLOW), true));
frame.pack();
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
evaluateChildren(frame.getContentPane().getComponents());
}});
}
/**
* Progress message test.
*/
public void interactiveProgress() {
final JXLoginPane panel = new JXLoginPane();
final JFrame frame = JXLoginPane.showLoginFrame(panel);
panel.setLoginService(new LoginService() {
@Override
public boolean authenticate(String name, char[] password,
String server) throws Exception {
panel.startLogin();
Thread.sleep(5000);
return true;
}});
frame.setJMenuBar(createAndFillMenuBar(panel));
panel.setSaveMode(SaveMode.BOTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
evaluateChildren(frame.getContentPane().getComponents());
}});
}
private boolean evaluateChildren(Component[] components) {
for (Component c: components) {
if (c instanceof JButton && "login".equals(((JButton) c).getActionCommand())) {
((JButton) c).doClick();
return true;
} else if (c instanceof Container) {
if (evaluateChildren(((Container) c).getComponents()) ){
return true;
}
}
}
return false;
}
public class DummyLoginPaneUI extends BasicLoginPaneUI {
public DummyLoginPaneUI(JXLoginPane dlg) {
super(dlg);
}
@Override
public Image getBanner() {
Image banner = super.getBanner();
BufferedImage im = GraphicsUtilities.createCompatibleTranslucentImage(banner.getWidth(null), banner.getHeight(null));
Graphics2D g = im.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(banner, 0, 0, 100, 100, null);
} finally {
g.dispose();
}
return im;
}
}
@Override
protected void createAndAddMenus(JMenuBar menuBar, final JComponent component) {
super.createAndAddMenus(menuBar, component);
JMenu menu = new JMenu("Locales");
menu.add(new AbstractAction("Change Locale") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
if (component.getLocale() == Locale.FRANCE) {
component.setLocale(Locale.ENGLISH);
} else {
component.setLocale(Locale.FRANCE);
}
}});
menuBar.add(menu);
}
/**
* swingx-917
* @throws Exception
*/
public void interactiveBrokenLayoutAfterFailedLogin() throws Exception {
// PENDING JW: removed while fixing #1186-swingx (no dependency on sun packages)
// revisit: why do we do this at all? If really needed replace
// sun.awt.AppContext.getAppContext().put("JComponent.defaultLocale", Locale.FRANCE);
Map<String, char[]> aMap = new HashMap<String, char[]>();
aMap.put("asdf", "asdf".toCharArray());
JXLoginPane panel = new JXLoginPane(new SimpleLoginService(aMap));
panel.setSaveMode(JXLoginPane.SaveMode.BOTH);
panel.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(
PropertyChangeEvent thePropertyChangeEvent) {
System.err.println(thePropertyChangeEvent.getPropertyName()
+ " " + thePropertyChangeEvent.getOldValue()
+ " -> " + thePropertyChangeEvent.getNewValue());
}
});
JFrame frame = JXLoginPane.showLoginFrame(panel);
frame.pack();
frame.setVisible(true);
}
/**
* Do nothing, make the test runner happy
* (would output a warning without a test fixture).
*
*/
public void testDummy() {
}
}
| Additional visual check | src/test/org/jdesktop/swingx/JXLoginPaneVisualCheck.java | Additional visual check | <ide><path>rc/test/org/jdesktop/swingx/JXLoginPaneVisualCheck.java
<ide> JXLoginPaneVisualCheck test = new JXLoginPaneVisualCheck();
<ide>
<ide> try {
<del> test.runInteractiveTests();
<add>// test.runInteractiveTests();
<add> test.runInteractiveTests("interactiveComparativeDialogs");
<ide> } catch (Exception e) {
<ide> System.err.println("exception when executing interactive tests:");
<ide> e.printStackTrace();
<ide> frame.setVisible(true);
<ide> }
<ide>
<add> public void interactiveComparativeDialogs() {
<add> JXDialog dialog = new JXDialog(new JXLoginPane());
<add> dialog.pack();
<add> dialog.setVisible(true);
<add> JXLoginPane.showLoginDialog(null, new JXLoginPane());
<add> }
<add>
<ide> /**
<ide> * Do nothing, make the test runner happy
<ide> * (would output a warning without a test fixture). |
|
JavaScript | mit | 5703c05f27109d6ac16e0501f5bd685286c298d9 | 0 | mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS | import React from "react"
import _ from "underscore"
import fileIsDynamicCode from "../fileIsDynamicCode"
import isMobile from "../isMobile"
import config from "../config"
import ReactTooltip from "react-tooltip"
import "react-fastclick" // import for side effects, no export
import adjustColumnForEscapeSequences from "../adjustColumnForEscapeSequences"
import getDefaultInspectedCharacterIndex from "./getDefaultInspectedCharacterIndex"
import RoundTripMessageWrapper from "../RoundTripMessageWrapper"
import Perf from "react-addons-perf"
window.Perf = Perf
var currentInspectedPage;
var resolvedFrameCache = {}
function resolveFrame(frameString, callback) {
if (resolvedFrameCache[frameString]) {
callback(null, resolvedFrameCache[frameString])
return function cancel(){}
} else {
return currentInspectedPage.send("resolveFrame", frameString, function(err, frame){
if (!err){
resolvedFrameCache[frameString] = frame;
}
callback(err, frame)
});
}
}
var codeFilePathCache = {}
function getCodeFilePath(path, callback) {
if (codeFilePathCache[path]) {
callback(codeFilePathCache[path])
return;
} else {
currentInspectedPage.send("getCodeFilePath", path, function(newPath){
codeFilePathCache[path] = newPath
callback(newPath)
})
}
}
function getFilenameFromPath(path){
var pathParts = path.split("/");
var filename = _.last(pathParts);
filename = filename.replace(".dontprocess", "");
return filename
}
function catchExceptions(fnToRun, onError){
if (config.catchUIErrors) {
try {
fnToRun()
} catch (err) {
onError(err)
}
} else {
fnToRun();
}
}
function truncate(str, maxLength){
if (str.length <= maxLength) {
return str
}
return str.substr(0, 40) + "..."
}
export class OriginPath extends React.Component {
constructor(props){
super(props)
this.state = {
showFullPath: false
}
}
render(){
var originPath = this.props.originPath;
if (!originPath) {
return <div>Fetching origin path</div>
}
originPath = originPath.filter(function(pathItem){
// This is really an implementation detail and doesn't add any value to the user
// Ideally I'd clean up the code to not generate that action at all,
// but for now just filtering it out
if (pathItem.origin.action === "Initial Body HTML") {
return false;
}
return true;
})
window.originPath = originPath
var lastOriginPathStep = _.last(originPath)
var firstOriginPathStep = _.first(originPath)
var inbetweenSteps = originPath.slice(1, originPath.length - 1).reverse();
var inbetweenStepsComponents = []
if (this.state.showFullPath){
for (var originPathStep of inbetweenSteps) {
inbetweenStepsComponents.push(this.getOriginPathItem(originPathStep))
}
}
var lastStep = this.getOriginPathItem(lastOriginPathStep);
var firstStep = null;
if (originPath.length > 1) {
firstStep = this.getOriginPathItem(firstOriginPathStep)
}
var showFullPathButton = null;
if (!this.state.showFullPath && originPath.length > 2){
showFullPathButton = <div style={{marginBottom: 20}}>
<button
className="fromjs-btn-link"
ref="showFullPathButton"
onClick={() => {
this.refs.showFullPathButton.textContent = "Rendering additional steps may take a few seconds."
setTimeout(() => {
this.setState({showFullPath: true})
}, 10)
}}>
=> Show {inbetweenSteps.length} steps in-between
</button>
</div>
}
return <div>
{lastStep}
{showFullPathButton}
{inbetweenStepsComponents}
{firstStep}
</div>
}
getOriginPathItem(originPathStep){
return <OriginPathItem
key={JSON.stringify({
originId: originPathStep.origin.id,
characterIndex: originPathStep.characterIndex
})}
originPathItem={originPathStep}
handleValueSpanClick={this.props.handleValueSpanClick}
/>
}
}
class OriginPathItem extends React.Component {
constructor(props){
super(props)
this.state = {
selectedFrameString: null,
resolvedFrame: null,
codeFilePath: null,
showDetailsDropdown: false,
previewFrameString: null
}
}
componentDidMount(){
var origin = this.props.originPathItem.origin
if (origin.isHTMLFileContent) {
this.selectFrameString(getFrameFromHTMLFileContentOriginPathItem(this.props.originPathItem))
} else {
if (!origin.stack) {
return
}
this.selectFrameString(_.first(origin.stack))
}
this.makeSureIsResolvingFrame();
}
componentDidUpdate(){
this.makeSureIsResolvingFrame();
}
makeSureIsResolvingFrame(){
var frame = this.state.selectedFrameString
if (frame && !this.state.resolvedFrame){
if (this.cancelFrameResolution) {
this.cancelFrameResolution()
}
this.cancelFrameResolution = resolveFrame(frame, (err, resolvedFrame) => {
this.setState({resolvedFrame})
this.cancelGetCodeFilePath = getCodeFilePath(resolvedFrame.fileName, (codeFilePath) => {
this.setState({codeFilePath})
})
})
}
}
componentWillUnmount(){
if (this.cancelFrameResolution){
this.cancelFrameResolution()
}
if (this.cancelGetCodeFilePath){
this.cancelGetCodeFilePath()
}
}
render(){
var originObject = this.props.originPathItem.origin
var filenameLink = null
var viewSourceOriginButton = null;
if (this.state.resolvedFrame) {
var filename = this.state.resolvedFrame.fileName;
var originalFilename = filename.replace(".dontprocess", "");
var filenameParts = originalFilename.split("/")
var uiFilename = _.last(filenameParts)
filenameLink = <a
className="origin-path-step__filename"
href={this.state.codeFilePath}
target="_blank"
>
{uiFilename}
</a>
}
// This isn't a crucial feature... you can just click on the origin inside the path
// I disabled this feature because the fromJSDynamicFileOrigins is not available in the
// inspector iframe,
// if (this.state.resolvedFrame && fileIsDynamicCode(this.state.resolvedFrame.fileName)){
// viewSourceOriginButton = <button
// className="fromjs-btn-link fromjs-origin-path-step__only-show-on-step-hover"
// onClick={
// () => this.props.handleValueSpanClick(fromJSDynamicFileOrigins[this.state.resolvedFrame.fileName], 0)
// }>
// Show Source Origin
// </button>
// }
var stack = null;
var originPathItem = this.props.originPathItem;
var previewStack = null;
if (this.state.previewFrameString){
previewStack = <StackFrame
frame={this.state.previewFrameString}
key={this.state.previewFrameString}
originPathItem={originPathItem} />
}
else if (this.state.selectedFrameString) {
stack = <StackFrame
frame={this.state.selectedFrameString}
key={this.state.selectedFrameString}
originPathItem={originPathItem}
/>
} else {
stack = <div style={{padding: 10}}>
(Empty stack.)
</div>
}
var stackFrameSelector = null;
if (this.state.showDetailsDropdown){
stackFrameSelector = <StackFrameSelector
stack={originObject.stack}
selectedFrameString={this.state.selectedFrameString}
onFrameSelected={(frameString) => {
this.selectFrameString(frameString)
this.setState({showDetailsDropdown: false})
}}
onFrameHovered={(frameString) => {
this.setState({previewFrameString: frameString})
}}
/>
}
var inputValueLinks = null;
if (this.state.showDetailsDropdown){
var noParametersMessage = null;
if (originObject.inputValues.length === 0){
noParametersMessage = <div style={{color: "#777"}}>(No parameters.)</div>
}
inputValueLinks = <div style={{background: "aliceblue", paddingLeft: 10, paddingBottom: 10}}>
<div>
<span data-multiline data-tip={
"These are the input values of the string transformation.<br>"
+ "The parameters of a string concatenation would be the two strings being joined together.<br>"
+ "A replace call would show the original string, the string being replaced, and the replacement string."
}>
Parameters
<span className="fromjs-info-icon">i</span>:
</span>
</div>
{noParametersMessage}
{originObject.inputValues.map((iv) => {
return <div className="fromjs-input-value-link"
onClick={() => this.props.handleValueSpanClick(iv, 0)}>
"{truncate(iv.value, 40)}"
</div>
})}
</div>
}
var toggleFrameSelectorButton = null;
if (originObject.stack && originObject.stack.length > 1) {
toggleFrameSelectorButton = <button
className="fromjs-origin-path-step__stack-frame-selector-toggle"
onClick={() => this.setState({showDetailsDropdown: !this.state.showDetailsDropdown})}>
{this.state.showDetailsDropdown ? "\u25B2" : "\u25BC"}
</button>
}
var valueView = null;
if (!config.alwaysShowValue && originObject.action === "Initial Page HTML") {
valueView = <div></div>
} else {
valueView = <div style={{borderTop: "1px dotted #ddd"}} data-test-marker-step-value>
<ValueEl
originPathItem={this.props.originPathItem}
handleValueSpanClick={this.props.handleValueSpanClick} />
</div>
}
return <div className="fromjs-origin-path-step" style={{border: "1px solid #ddd", marginBottom: 20}}>
<div >
<div style={{background: "aliceblue"}}>
<span style={{
display: "inline-block",
padding: 5
}}>
<span style={{fontWeight: "bold", marginRight: 5}}
data-test-marker-step-action>
{originObject.action}
</span>
<span>
{filenameLink}
</span>
{viewSourceOriginButton}
</span>
{toggleFrameSelectorButton}
</div>
{inputValueLinks}
{stackFrameSelector}
{stack}
{previewStack}
</div>
{valueView}
</div>
}
selectFrameString(frameString){
this.setState({
selectedFrameString: frameString,
resolvedFrame: null,
codeFilePath: null
})
}
}
class StackFrameSelector extends React.Component {
render(){
var self = this;
return <div>
{this.props.stack.map(function(frameString){
return <StackFrameSelectorItem
isSelected={self.props.selectedFrameString === frameString}
onMouseEnter={() => self.props.onFrameHovered(frameString)}
onMouseLeave={() => self.props.onFrameHovered(null)}
frameString={frameString}
onClick={() => self.props.onFrameSelected(frameString)}
/>
})}
</div>
}
}
class StackFrameSelectorItem extends React.Component {
constructor(props){
super(props);
this.state = {
resolvedFrame: null
}
}
componentDidMount(){
this.cancelFrameResolution = resolveFrame(this.props.frameString, (err, resolvedFrame) => {
this.setState({resolvedFrame})
})
}
componentWillUnmount(){
if (this.cancelFrameResolution){
this.cancelFrameResolution()
}
}
render(){
var className = "fromjs-stack-frame-selector__item " ;
if (this.props.isSelected) {
className += "fromjs-stack-frame-selector__item--selected"
}
var loadingMessage = null;
var frameInfo = null;
var resolvedFrame = this.state.resolvedFrame;
if (resolvedFrame) {
var filename = getFilenameFromPath(resolvedFrame.fileName)
var functionName = resolvedFrame.functionName;
if (functionName === undefined) {
functionName = "(anonymous function)"
}
frameInfo = <div>
{functionName}
<div style={{float: "right"}}>{filename}</div>
</div>
} else {
loadingMessage = "Loading..."
}
return <div
className={className}
onClick={this.props.onClick}
onMouseEnter={() => this.props.onMouseEnter()}
onMouseLeave={() => this.props.onMouseLeave()}>
{loadingMessage}
{frameInfo}
</div>
}
}
function getFrameFromHTMLFileContentOriginPathItem(originPathItem){
var origin = originPathItem.origin
var valueBeforeChar = origin.value.substr(0, originPathItem.characterIndex)
var splitIntoLines = valueBeforeChar.split("\n")
var line = splitIntoLines.length;
var charIndex = _.last(splitIntoLines).length
return "at initialHtml (" + origin.isHTMLFileContent.filename + ":" + line + ":" + charIndex
}
class ValueEl extends React.Component {
render(){
var step = this.props.originPathItem;
var val = step.origin.value
return <TextEl
text={val}
highlightedCharacterIndex={step.characterIndex}
onCharacterClick={(charIndex) => this.props.handleValueSpanClick(step.origin, charIndex)}
/>
}
}
class TextEl extends React.Component {
constructor(props){
super(props)
this.state = {
truncateText: true
}
}
shouldComponentUpdate(nextProps, nextState){
// console.time("TextEl shouldUpdate")
var shouldUpdate = JSON.stringify(nextProps) !== JSON.stringify(this.props) ||
JSON.stringify(nextState) !== JSON.stringify(this.state)
// console.timeEnd("TextEl shouldUpdate")
return shouldUpdate
}
render(){
var self = this;
function splitLines(str){
var lineStrings = str.split("\n")
var lines = [];
var charOffset = 0
lineStrings.forEach(function(lineString, i){
var isLastLine = i + 1 === lineStrings.length
var text = lineString + (isLastLine ? "" : "\n");
var charOffsetStart = charOffset
var charOffsetEnd = charOffset + text.length;
lines.push({
text: text,
lineNumber: i,
charOffsetStart: charOffsetStart,
charOffsetEnd: charOffsetEnd,
containsCharIndex: function(index){
return index >= charOffsetStart && index < charOffsetEnd
},
splitAtCharIndex: function(index){
var lineBeforeIndex = text.substr(0, highlightedCharIndex - charOffsetStart);
var lineAtIndex = text.substr(highlightedCharIndex - charOffsetStart, 1);
var lineAfterIndex = text.substr(highlightedCharIndex + 1 - charOffsetStart)
return [{
text: lineBeforeIndex,
charOffsetStart: charOffsetStart
}, {
text: lineAtIndex,
charOffsetStart: charOffsetStart + lineBeforeIndex.length
}, {
text: lineAfterIndex,
charOffsetStart: charOffsetStart + lineBeforeIndex.length + lineAtIndex.length
}]
}
})
charOffset = charOffsetEnd
})
if (charOffset !== str.length){
throw "looks like sth went wrong?"
}
return lines;
}
function processChar(char){
if (char==="\n"){
char = "\u21B5" // downwards arrow with corner leftwards
}
if (char===" ") {
char = '\xa0'
}
if (char==="\t"){
char = "\xa0\xa0"
}
return char
}
function charIsWhitespace(char){
return char === "\t" || char === " "
}
function getValueSpan(char, extraClasses, key, onClick, onMouseEnter, onMouseLeave){
var className = extraClasses;
if (charIsWhitespace(char)){
className += " fromjs-value__whitespace-character"
}
var processedChar = processChar(char)
return <span
className={className}
onClick={onClick}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
key={key}
>
{processedChar}
</span>
}
function getValueSpans(val, indexOffset){
var els = [];
for (let index=0; index<val.length; index++){
var char = val[index]
els.push(getValueSpan(char, "", index + indexOffset, () => {
self.props.onCharacterClick(index + indexOffset)
}, () => {
if (!self.props.onCharacterHover) {return}
self.props.onCharacterHover(index + indexOffset)
},() => {
if (!self.props.onCharacterHover) {return}
self.props.onCharacterHover(null)
}))
}
return els
}
var val = this.props.text
var self = this;
var highlightedCharIndex = this.props.highlightedCharacterIndex
if (highlightedCharIndex === undefined || highlightedCharIndex === null) {
return <div className="fromjs-value">
{getValueSpans(val, 0)}
</div>
} else {
var lines = splitLines(val)
var valBeforeColumn = val.substr(0, highlightedCharIndex);
var valAtColumn = val.substr(highlightedCharIndex, 1);
var valAfterColumn = val.substr(highlightedCharIndex+ 1)
var highlightedCharLineIndex = valBeforeColumn.split("\n").length
var showFromLineIndex = highlightedCharLineIndex - 2;
if (showFromLineIndex < 0) {
showFromLineIndex = 0;
}
var showToLineIndex = showFromLineIndex + 3
if (!this.state.truncateText) {
showFromLineIndex = 0;
showToLineIndex = lines.length;
}
var linesToShow = lines.slice(showFromLineIndex, showToLineIndex)
function getLineComponent(line, beforeSpan, afterSpan){
var valueSpans = []
if (line.containsCharIndex(highlightedCharIndex)){
var chunks = line.splitAtCharIndex(highlightedCharIndex)
var textBeforeHighlight = chunks[0].text
if (textBeforeHighlight.length > 50 && self.state.truncateText) {
var textA = textBeforeHighlight.slice(0, 40)
var textB = textBeforeHighlight.slice(textBeforeHighlight.length - 10)
valueSpans = [
getValueSpans(textA, chunks[0].charOffsetStart),
getEllipsisSpan("ellipsis-line-before-highlight"),
getValueSpans(textB, chunks[0].charOffsetStart + textBeforeHighlight.length - textB.length)
]
} else {
valueSpans = valueSpans.concat(getValueSpans(chunks[0].text, chunks[0].charOffsetStart))
}
valueSpans = valueSpans.concat(getValueSpan(chunks[1].text, "fromjs-highlighted-character", "highlighted-char-key", function(){}, function(){}, function(){}))
var restofLineValueSpans;
var textAfterHighlight = chunks[2].text;
if (textAfterHighlight.length > 60 && self.state.truncateText){
restofLineValueSpans = [
getValueSpans(chunks[2].text.slice(0, 60), chunks[2].charOffsetStart),
getEllipsisSpan("ellipsis-line-after-highlight")
]
} else {
restofLineValueSpans = getValueSpans(chunks[2].text, chunks[2].charOffsetStart)
}
valueSpans = valueSpans.concat(restofLineValueSpans)
} else {
valueSpans = getValueSpans(line.text, line.charOffsetStart);
}
return <div key={"Line" + line.lineNumber}>
{beforeSpan}
{valueSpans}
{afterSpan}
</div>
}
function getEllipsisSpan(key){
return <span onClick={() => self.disableTruncateText()} key={key}>...</span>
}
var ret = <HorizontalScrollContainer>
<div className="fromjs-value">
<div className="fromjs-value__content" ref={(el) => {
this.scrollToHighlightedChar(el, highlightedCharLineIndex);
}}>
{linesToShow.map((line, i) =>{
var beforeSpan = null;
if (i === 0 && line.charOffsetStart > 0){
beforeSpan = getEllipsisSpan("beforeEllipsis")
}
var afterSpan = null;
if (i === linesToShow.length - 1 && line.charOffsetEnd < val.length) {
afterSpan = getEllipsisSpan("afterEllipsis")
}
return getLineComponent(line, beforeSpan, afterSpan)
})}
</div>
</div>
</HorizontalScrollContainer>
return ret;
}
}
scrollToHighlightedChar(el, highlightedCharLineIndex){
if (!el){return}
if (this.state.truncateText) {return}
var lineHeight = 18;
var lineAtTop = highlightedCharLineIndex - 4;
if (lineAtTop < 0) {
lineAtTop = 0;
}
el.scrollTop = lineAtTop * lineHeight;
}
disableTruncateText(){
if (this.props.text.length > 20000) {
alert("Refusing to expand text longer than 20,000 characters. It will just crash your browser.");
return
}
this.setState({truncateText: false})
}
}
const MAX_LINES_TO_SHOW_BEFORE_AND_AFTER = 200;
class StackFrame extends React.Component{
constructor(props){
super(props)
this.state = {
resolvedFrame: null,
truncate: true
}
}
componentDidMount(){
this.cancelFrameResolution = resolveFrame(this.props.frame, (err, resolvedFrame) => {
this.setState({resolvedFrame})
})
}
componentWillUnmount(){
if (this.cancelFrameResolution){
this.cancelFrameResolution()
}
}
render(){
function processFrameString(str){
return str
.replace(/ /g, '\xa0') //nbsp
.replace(/\t/g, '\xa0\xa0')
}
if (this.state.resolvedFrame === null) {
return <div style={{padding: 5, paddingLeft: 10}}>Loading...</div>
}
var frame = this.state.resolvedFrame;
var self = this;
var barSpan = <span className="fromjs-stack__code-column"></span>
var originPathItem = this.props.originPathItem;
var highlighNthCharAfterColumn = null;
if (originPathItem.origin.action === "String Literal" ){
highlighNthCharAfterColumn = "'".length + originPathItem.characterIndex
}
if (originPathItem.origin.action === "Initial Page HTML"){
highlighNthCharAfterColumn = 0;
barSpan = null;
}
var highlightClass = "fromjs-highlighted-character"
var hasHighlight = highlighNthCharAfterColumn !== null
if (!hasHighlight) {
highlighNthCharAfterColumn = 0
highlightClass = ""
}
highlighNthCharAfterColumn = adjustColumnForEscapeSequences(frame.line.substr(frame.columnNumber), highlighNthCharAfterColumn)
var strBetweenBarAndHighlight = frame.line.substring(frame.columnNumber, frame.columnNumber + highlighNthCharAfterColumn)
// If strings are too long and would hide highlighted content truncate them
var strBeforeBar = frame.line.substr(0, frame.columnNumber)
if (strBeforeBar.length > 50 && this.state.truncate) {
strBeforeBar = strBeforeBar.substr(0, 10) + "..." + strBeforeBar.substr(strBeforeBar.length - 20)
}
if (strBetweenBarAndHighlight.length > 50 && this.state.truncate) {
strBetweenBarAndHighlight = strBetweenBarAndHighlight.substr(0, 10) + "..." + strBetweenBarAndHighlight.substr(strBetweenBarAndHighlight.length - 20)
}
class LineNumber extends React.Component {
render(){
var arrow = null;
if (this.props.arrow){
arrow = <div className={"fromjs-stack__line-number-arrow"}>
{this.props.arrow}
</div>
}
return <span
className={"fromjs-stack__line-number " + (this.props.arrow ? "fromjs-stack__line-number--has-arrow": "")}>
<span className="fromjs-stack__line-number-text">{this.props.lineNumber}</span>
{arrow}
</span>
}
}
function getLine(lineStr, lineNumber, arrow){
return <div>
<LineNumber lineNumber={lineNumber} arrow={arrow} />
<span style={{opacity: .75}}>{processFrameString(lineStr)}</span>
</div>
}
function getPrevLines(){
if (frame.prevLines.length === 0) {
return [];
}
if (self.state.truncate) {
return getLine(_.last(frame.prevLines), frame.lineNumber - 1, "\u25B2")
} else {
var prevLinesToShow = frame.prevLines;
if (prevLinesToShow.length > MAX_LINES_TO_SHOW_BEFORE_AND_AFTER) {
prevLinesToShow = frame.prevLines.slice(frame.prevLines.length - MAX_LINES_TO_SHOW_BEFORE_AND_AFTER)
}
var linesNotShown = frame.prevLines.length - prevLinesToShow.length;
return prevLinesToShow.map(function(line, i){
return getLine(line, i + 1 + linesNotShown)
})
}
}
function getNextLines(){
if (frame.nextLines.length === 0) {
return []
}
if (self.state.truncate) {
return getLine(_.first(frame.nextLines), frame.lineNumber + 1, "\u25BC")
} else {
var nextLinesToShow = frame.nextLines;
if (frame.nextLines.length > MAX_LINES_TO_SHOW_BEFORE_AND_AFTER) {
nextLinesToShow = frame.nextLines.slice(0, MAX_LINES_TO_SHOW_BEFORE_AND_AFTER)
}
return nextLinesToShow.map(function(line, i){
return getLine(line, i + frame.lineNumber + 1)
})
}
}
var highlightIndexInLine = frame.columnNumber + highlighNthCharAfterColumn
var highlightedString = processFrameString(frame.line.substr(highlightIndexInLine, 1));
if (frame.line.length == highlightIndexInLine) {
// after last proper char in line, display new line
highlightedString = "\u21B5"
}
if (frame.line.length < highlightIndexInLine) {
debugger // shoudn't happen
}
return <div style={{
display: "block",
maxHeight: 18 * 7,
overflow: "auto"
}} ref={(el) => this.scrollToLine(el, frame.lineNumber)}>
<HorizontalScrollContainer>
<div>
<code
className={"fromjs-stack__code" + (self.state.truncate ? " fromjs-stack__code--truncated" :"")}
onClick={() => {
if (self.state.truncate){
self.setState({truncate: false})
}
}}
>
{getPrevLines()}
<div>
<LineNumber lineNumber={frame.lineNumber} />
<span>
{processFrameString(strBeforeBar)}
</span>
{barSpan}
<span>
{processFrameString(strBetweenBarAndHighlight)}
</span>
<span className={highlightClass}>
{highlightedString}
</span>
<span>
{processFrameString(frame.line.substr(frame.columnNumber + highlighNthCharAfterColumn + 1))}
</span>
</div>
{getNextLines()}
</code>
</div>
</HorizontalScrollContainer>
</div>
}
scrollToLine(el, lineNumber){
if (el === null){
return;
}
if (this.state.truncate) {
return;
}
var linesNotShownBefore = this.state.resolvedFrame.prevLines.length - MAX_LINES_TO_SHOW_BEFORE_AND_AFTER;
if (linesNotShownBefore < 0){
linesNotShownBefore = 0;
}
var lineHeight = 18;
var scrollToLine = lineNumber - 4 - linesNotShownBefore;
if (scrollToLine < 0){
scrollToLine = 0;
}
el.scrollTop = scrollToLine * lineHeight;
}
}
class HorizontalScrollContainer extends React.Component {
render(){
return <div className="fromjs-horizontal-scroll-container">
<div>
{this.props.children}
</div>
</div>
}
}
class ElementOriginPath extends React.Component {
constructor(props){
super(props)
this.state = {
characterIndex: getDefaultInspectedCharacterIndex(props.el.outerHTML),
previewCharacterIndex: null,
rootOrigin: null,
originPathKey: null,
previewOriginPathKey: null,
originPath: null,
previewOriginPath: null
}
this.componentWillUpdate(props, this.state, true);
}
componentWillReceiveProps(nextProps) {
if (nextProps.el.__fromJSElementId !== this.props.el.__fromJSElementId){
console.log("resetting root origin", nextProps.el.outerHTML.substring(0, 100))
this.setState({
rootOrigin: null,
characterIndex: getDefaultInspectedCharacterIndex(nextProps.el.outerHTML),
})
}
}
componentWillUpdate(nextProps, nextState, forceUpdate) {
if (nextState.previewCharacterIndex === this.state.previewCharacterIndex &&
nextState.characterIndex === this.state.characterIndex &&
nextState.rootOrigin === this.state.rootOrigin &&
nextProps.el.__fromJSElementId === this.props.el.__fromJSElementId &&
forceUpdate !== true) {
return
}
if (this.cancelSelectionGetOriginKeyAndPath) {
this.cancelSelectionGetOriginKeyAndPath();
}
if (this.cancelPreviewGetOriginKeyAndPath) {
this.cancelPreviewGetOriginKeyAndPath();
}
if (nextState.previewCharacterIndex !== null) {
// We don't reset the state because we want to keep the current UI visible until the new data comes in
this.cancelPreviewGetOriginKeyAndPath = this.getOriginKeyAndPath(nextProps, nextState, nextState.previewCharacterIndex, (key, originPath) => {
var setState = () => this.setState({
previewOriginPath: originPath,
previewOriginPathKey: key
})
if (originPath) {
var lastStep = _.last(originPath)
var origin = lastStep.origin
// resolve frame so it's cached when we display it, so you don't get the "loading..." message
var frameString;
if (origin.isHTMLFileContent) {
frameString = getFrameFromHTMLFileContentOriginPathItem(lastStep)
} else {
frameString = _.first(origin.stack)
}
if (frameString !== undefined) {
resolveFrame(frameString, setState)
} else {
setState();
}
} else {
setState()
}
})
} else {
// Don't reset yet so it doesn't flash the previous value, instead we want to continue showing the
// preview value
this.cancelSelectionGetOriginKeyAndPath = this.getOriginKeyAndPath(nextProps, nextState, nextState.characterIndex, (key, originPath) => this.setState({
originPathKey: key,
originPath: originPath,
previewOriginPathKey: null,
previewOriginPath: null
}))
}
}
getOriginKeyAndPath(props, state, characterIndex, callback){
var canceled = false;
this.getOriginPathKey(props, state, characterIndex, key => {
this.getOriginPath(props, state, characterIndex, originPath => {
if (canceled) {return}
callback(key, originPath)
})
})
return function cancel(){
canceled = true;
}
}
componentWillUnmount(){
if (this.cancelGetRootOriginAtChar) {
this.cancelGetRootOriginAtChar();
}
}
render(){
var showPreview = this.state.previewOriginPath;
var originPath = <div style={{display: showPreview ? "none" : "block"}}>
<OriginPath
originPath={this.state.originPath}
key={this.state.originPathKey}
handleValueSpanClick={(origin, characterIndex) => {
this.props.onNonElementOriginSelected()
currentInspectedPage.send("UISelectNonElementOrigin")
this.setState({
rootOrigin: origin,
characterIndex
})
}}
/>
</div>
var previewOriginPath = null;
if (showPreview) {
previewOriginPath = <OriginPath
originPath={this.state.previewOriginPath}
key={this.state.previewOriginPathKey}
/>
}
var showUpButton = typeof this.props.goUpInDOM === "function"
var upButton = null;
if (showUpButton && !window.disableSelectParentElement){
upButton = <div style={{position: "absolute", top: 0, right: 0, border: "1px solid #eee"}}>
<button
data-tip={"Inspect parent element"}
onClick={() => this.props.goUpInDOM() }
className={"fromjs-go-up-button"}
>
{"\u21e7"}
</button>
</div>
}
var onCharacterClick = (characterIndex) => this.setState({
characterIndex,
previewCharacterIndex: null,
originPathKey: null,
originPath: null
})
if (!this.props.isPreviewElement) {
window.e2eTestSimulateInpsectCharacter = onCharacterClick
}
return <div>
<div style={{padding: 10}}>
<div style={{fontWeight: "bold", fontSize: 20, marginBottom: 20}}>
Where does this character come from?
</div>
<div style={{position: "relative"}}>
<div style={{border: "1px solid #ddd",
width: showUpButton ? "calc(100% - 30px)" : "100%"}}
data-test-marker-inspected-value>
<TextEl
text={this.getInspectedValue()}
highlightedCharacterIndex={this.state.characterIndex}
onCharacterClick={onCharacterClick}
onCharacterHover={(characterIndex) => {
if (isMobile()) { return }
this.setState({previewCharacterIndex: characterIndex})
}}
/>
</div>
{upButton}
</div>
</div>
<hr/>
<div style={{padding: 10}}>
{originPath}
{previewOriginPath}
</div>
</div>
}
originComesFromElement(props, state){
return state.rootOrigin === null
}
getInspectedValue(){
if (this.state.rootOrigin){
return this.state.rootOrigin.value
} else if (this.props.el) {
var outerHtml = this.props.el.outerHTML
if (this.props.el.tagName === "BODY") {
// contains the FromJS UI, which we don't want to show
var fromJSHtml = document.querySelector(".fromjs-outer-container").outerHTML
var fromJSStartInBody = outerHtml.indexOf(fromJSHtml)
var fromJSEndInBody = fromJSStartInBody + fromJSHtml.length
outerHtml = outerHtml.slice(0, fromJSStartInBody) + outerHtml.slice(fromJSEndInBody)
}
return outerHtml
}
return null;
}
getOriginPath(props, state, characterIndex, callback){
if (characterIndex === null){
// characterIndex should never be null, but right now it is sometimes
callback(null)
return;
}
var isCanceled = false
this.getOriginAndCharacterIndex(props, state, characterIndex, function(info){
if (isCanceled) {
return;
}
currentInspectedPage.send("whereDoesCharComeFrom", info.origin.id, info.characterIndex, function(){
if (!isCanceled) {
callback.apply(this, arguments)
}
})
})
return function cancel(){
isCanceled = true;
}
}
getOriginPathKey(props, state, characterIndex, callback){
this.getOriginAndCharacterIndex(props, state, characterIndex, function(info){
callback(JSON.stringify({
originId: info.origin.id,
characterIndex: info.characterIndex
}))
})
}
getOriginAndCharacterIndex(props, state, characterIndex, callback){
characterIndex = parseFloat(characterIndex);
if (this.originComesFromElement(props, state)) {
this.cancelGetRootOriginAtChar = currentInspectedPage.send("getRootOriginAtChar", props.el.__fromJSElementId, characterIndex, function(rootOrigin){
callback(rootOrigin)
});
} else {
callback({
characterIndex: characterIndex,
origin: state.rootOrigin
})
}
}
}
class ElementMarker extends React.Component {
shouldComponentUpdate(newProps){
return this.props.el !== newProps.el;
}
render(){
if (this.props.el === null) {
return null;
}
var rect = this.props.el.getBoundingClientRect()
var style = {
...this.props.style,
left: rect.left + document.body.scrollLeft,
top: rect.top + document.body.scrollTop,
height: rect.height,
width: rect.width
}
return <div style={style} className="fromjs-element-marker"></div>
}
}
export class SelectedElementMarker extends React.Component {
render(){
return <ElementMarker el={this.props.el} style={{outline: "2px solid #0088ff"}} />
}
}
export class PreviewElementMarker extends React.Component {
render(){
return <ElementMarker el={this.props.el} style={{outline: "2px solid green"}} />
}
}
class Intro extends React.Component {
render(){
var browserIsChrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
var notChromeMessage = null
if (!browserIsChrome) {
notChromeMessage = <div style={{border: "2px solid red", padding: 10}}>
FromJS is currently built to only work in Chrome. It sort of works
in other browsers too, but some things are broken.
</div>
}
return <div className="fromjs-intro">
{notChromeMessage}
<h2>What is this?</h2>
<p>
FromJS helps you understand how an app works by showing how its UI relates to the source code.
</p>
<p>
Select a DOM element on the left to see where its
content came from. This could be a string in the JavaScript code,
localStorage data, or directly from the HTML file.
</p>
<h2>
Does this work for all apps?
</h2>
<p>
Sometimes it works, but most of the time it doesn{"'"}t. I{"'"}m slowly trying to support more
JS functionality.
</p>
<p>
<a href="https://github.com/mattzeunert/fromjs">Github</a>
–
<a href="http://www.fromjs.com/">FromJS.com</a>
–
<a href="https://twitter.com/mattzeunert">Twitter</a>
</p>
</div>
}
}
export class FromJSView extends React.Component {
constructor(props){
super(props)
this.state = {
el: null,
previewEl: null,
// this shoudldn't be needed, should just reset state.el, but right now that wouldn't work
nonElementOriginSelected: null
}
currentInspectedPage = new RoundTripMessageWrapper(window.parent, "IFrame")
setTimeout(function(){
currentInspectedPage.send("InspectorReady", function(){})
})
currentInspectedPage.on("selectElement", (el) => {
this.setState({
el: el,
nonElementOriginSelected: false
})
})
var onPreviewElement = (el) => {
// Delay to prevent setting null inbetween when exiting one element and then entering another
this.setState({previewEl: el})
}
onPreviewElement = _.debounce(onPreviewElement, 10)
currentInspectedPage.on("previewElement", onPreviewElement, 10)
// ReactTooltip doesn't respond to UI changes automatically
setInterval(function(){
ReactTooltip.rebuild()
}, 100)
}
render(){
var preview = null;
var info = null;
var selectionMarker = null;
var previewMarker = null;
var intro = null;
var showPreview = this.state.previewEl !== null && (!this.state.el || this.state.previewEl.__fromJSElementId !== this.state.el.__fromJSElementId)
if (showPreview){
preview = <ElementOriginPath
el={this.state.previewEl}
goUpInDOM={() => "can't call this function, but needs to be there so button is shown"}
isPreviewElement={true}
/>
}
if (this.state.el) {
var goUpInDOM = null
if (!this.state.nonElementOriginSelected && this.state.el.tagName !== "BODY") {
goUpInDOM = () => currentInspectedPage.send("UISelectParentElement")
}
info = <div style={{display: showPreview ? "none" : "block"}}>
<ElementOriginPath
el={this.state.el}
onNonElementOriginSelected={() => this.setState({nonElementOriginSelected: true})}
goUpInDOM={goUpInDOM} />
</div>
}
if (this.state.el && !this.state.nonElementOriginSelected) {
// selectionMarker = <SelectedElementMarker el={this.state.el} />
}
if (!this.state.previewEl && !this.state.el){
intro = <Intro />
}
return <div>
<div id="fromjs" className="fromjs">
<button
onClick={() => currentInspectedPage.send("UICloseInspector")}
className="toggle-inspector-button close-inspector-button">
</button>
{intro}
{preview}
{info}
{/* Add some spacing since it seems you can't scroll down all the way*/}
{isMobile() ? <div><br/><br/><br/></div> : null}
<ReactTooltip effect="solid" />
</div>
{previewMarker}
{selectionMarker}
</div>
}
}
| src/ui/ui.js | import React from "react"
import _ from "underscore"
import fileIsDynamicCode from "../fileIsDynamicCode"
import isMobile from "../isMobile"
import config from "../config"
import ReactTooltip from "react-tooltip"
import "react-fastclick" // import for side effects, no export
import adjustColumnForEscapeSequences from "../adjustColumnForEscapeSequences"
import getDefaultInspectedCharacterIndex from "./getDefaultInspectedCharacterIndex"
import RoundTripMessageWrapper from "../RoundTripMessageWrapper"
import Perf from "react-addons-perf"
window.Perf = Perf
var currentInspectedPage;
var resolvedFrameCache = {}
function resolveFrame(frameString, callback) {
if (resolvedFrameCache[frameString]) {
callback(null, resolvedFrameCache[frameString])
return function cancel(){}
} else {
return currentInspectedPage.send("resolveFrame", frameString, function(err, frame){
if (!err){
resolvedFrameCache[frameString] = frame;
}
callback(err, frame)
});
}
}
var codeFilePathCache = {}
function getCodeFilePath(path, callback) {
if (codeFilePathCache[path]) {
callback(codeFilePathCache[path])
return;
} else {
currentInspectedPage.send("getCodeFilePath", path, function(newPath){
codeFilePathCache[path] = newPath
callback(newPath)
})
}
}
function getFilenameFromPath(path){
var pathParts = path.split("/");
var filename = _.last(pathParts);
filename = filename.replace(".dontprocess", "");
return filename
}
function catchExceptions(fnToRun, onError){
if (config.catchUIErrors) {
try {
fnToRun()
} catch (err) {
onError(err)
}
} else {
fnToRun();
}
}
function truncate(str, maxLength){
if (str.length <= maxLength) {
return str
}
return str.substr(0, 40) + "..."
}
export class OriginPath extends React.Component {
constructor(props){
super(props)
this.state = {
showFullPath: false
}
}
render(){
var originPath = this.props.originPath;
if (!originPath) {
return <div>Fetching origin path</div>
}
originPath = originPath.filter(function(pathItem){
// This is really an implementation detail and doesn't add any value to the user
// Ideally I'd clean up the code to not generate that action at all,
// but for now just filtering it out
if (pathItem.origin.action === "Initial Body HTML") {
return false;
}
return true;
})
window.originPath = originPath
var lastOriginPathStep = _.last(originPath)
var firstOriginPathStep = _.first(originPath)
var inbetweenSteps = originPath.slice(1, originPath.length - 1).reverse();
var inbetweenStepsComponents = []
if (this.state.showFullPath){
for (var originPathStep of inbetweenSteps) {
inbetweenStepsComponents.push(this.getOriginPathItem(originPathStep))
}
}
var lastStep = this.getOriginPathItem(lastOriginPathStep);
var firstStep = null;
if (originPath.length > 1) {
firstStep = this.getOriginPathItem(firstOriginPathStep)
}
var showFullPathButton = null;
if (!this.state.showFullPath && originPath.length > 2){
showFullPathButton = <div style={{marginBottom: 20}}>
<button
className="fromjs-btn-link"
ref="showFullPathButton"
onClick={() => {
this.refs.showFullPathButton.textContent = "Rendering additional steps may take a few seconds."
setTimeout(() => {
this.setState({showFullPath: true})
}, 10)
}}>
=> Show {inbetweenSteps.length} steps in-between
</button>
</div>
}
return <div>
{lastStep}
{showFullPathButton}
{inbetweenStepsComponents}
{firstStep}
</div>
}
getOriginPathItem(originPathStep){
return <OriginPathItem
key={JSON.stringify({
originId: originPathStep.origin.id,
characterIndex: originPathStep.characterIndex
})}
originPathItem={originPathStep}
handleValueSpanClick={this.props.handleValueSpanClick}
/>
}
}
class OriginPathItem extends React.Component {
constructor(props){
super(props)
this.state = {
selectedFrameString: null,
resolvedFrame: null,
codeFilePath: null,
showDetailsDropdown: false,
previewFrameString: null
}
}
componentDidMount(){
var origin = this.props.originPathItem.origin
if (origin.isHTMLFileContent) {
this.selectFrameString(getFrameFromHTMLFileContentOriginPathItem(this.props.originPathItem))
} else {
if (!origin.stack) {
return
}
this.selectFrameString(_.first(origin.stack))
}
this.makeSureIsResolvingFrame();
}
componentDidUpdate(){
this.makeSureIsResolvingFrame();
}
makeSureIsResolvingFrame(){
var frame = this.state.selectedFrameString
if (frame && !this.state.resolvedFrame){
if (this.cancelFrameResolution) {
this.cancelFrameResolution()
}
this.cancelFrameResolution = resolveFrame(frame, (err, resolvedFrame) => {
this.setState({resolvedFrame})
this.cancelGetCodeFilePath = getCodeFilePath(resolvedFrame.fileName, (codeFilePath) => {
this.setState({codeFilePath})
})
})
}
}
componentWillUnmount(){
if (this.cancelFrameResolution){
this.cancelFrameResolution()
}
if (this.cancelGetCodeFilePath){
this.cancelGetCodeFilePath()
}
}
render(){
var originObject = this.props.originPathItem.origin
var filenameLink = null
var viewSourceOriginButton = null;
if (this.state.resolvedFrame) {
var filename = this.state.resolvedFrame.fileName;
var originalFilename = filename.replace(".dontprocess", "");
var filenameParts = originalFilename.split("/")
var uiFilename = _.last(filenameParts)
filenameLink = <a
className="origin-path-step__filename"
href={this.state.codeFilePath}
target="_blank"
>
{uiFilename}
</a>
}
// This isn't a crucial feature... you can just click on the origin inside the path
// I disabled this feature because the fromJSDynamicFileOrigins is not available in the
// inspector iframe,
// if (this.state.resolvedFrame && fileIsDynamicCode(this.state.resolvedFrame.fileName)){
// viewSourceOriginButton = <button
// className="fromjs-btn-link fromjs-origin-path-step__only-show-on-step-hover"
// onClick={
// () => this.props.handleValueSpanClick(fromJSDynamicFileOrigins[this.state.resolvedFrame.fileName], 0)
// }>
// Show Source Origin
// </button>
// }
var stack = null;
var originPathItem = this.props.originPathItem;
var previewStack = null;
if (this.state.previewFrameString){
previewStack = <StackFrame
frame={this.state.previewFrameString}
key={this.state.previewFrameString}
originPathItem={originPathItem} />
}
else if (this.state.selectedFrameString) {
stack = <StackFrame
frame={this.state.selectedFrameString}
key={this.state.selectedFrameString}
originPathItem={originPathItem}
/>
} else {
stack = <div style={{padding: 10}}>
(Empty stack.)
</div>
}
var stackFrameSelector = null;
if (this.state.showDetailsDropdown){
stackFrameSelector = <StackFrameSelector
stack={originObject.stack}
selectedFrameString={this.state.selectedFrameString}
onFrameSelected={(frameString) => {
this.selectFrameString(frameString)
this.setState({showDetailsDropdown: false})
}}
onFrameHovered={(frameString) => {
this.setState({previewFrameString: frameString})
}}
/>
}
var inputValueLinks = null;
if (this.state.showDetailsDropdown){
var noParametersMessage = null;
if (originObject.inputValues.length === 0){
noParametersMessage = <div style={{color: "#777"}}>(No parameters.)</div>
}
inputValueLinks = <div style={{background: "aliceblue", paddingLeft: 10, paddingBottom: 10}}>
<div>
<span data-multiline data-tip={
"These are the input values of the string transformation.<br>"
+ "The parameters of a string concatenation would be the two strings being joined together.<br>"
+ "A replace call would show the original string, the string being replaced, and the replacement string."
}>
Parameters
<span className="fromjs-info-icon">i</span>:
</span>
</div>
{noParametersMessage}
{originObject.inputValues.map((iv) => {
return <div className="fromjs-input-value-link"
onClick={() => this.props.handleValueSpanClick(iv, 0)}>
"{truncate(iv.value, 40)}"
</div>
})}
</div>
}
var toggleFrameSelectorButton = null;
if (originObject.stack && originObject.stack.length > 1) {
toggleFrameSelectorButton = <button
className="fromjs-origin-path-step__stack-frame-selector-toggle"
onClick={() => this.setState({showDetailsDropdown: !this.state.showDetailsDropdown})}>
{this.state.showDetailsDropdown ? "\u25B2" : "\u25BC"}
</button>
}
var valueView = null;
if (!config.alwaysShowValue && originObject.action === "Initial Page HTML") {
valueView = <div></div>
} else {
valueView = <div style={{borderTop: "1px dotted #ddd"}} data-test-marker-step-value>
<ValueEl
originPathItem={this.props.originPathItem}
handleValueSpanClick={this.props.handleValueSpanClick} />
</div>
}
return <div className="fromjs-origin-path-step" style={{border: "1px solid #ddd", marginBottom: 20}}>
<div >
<div style={{background: "aliceblue"}}>
<span style={{
display: "inline-block",
padding: 5
}}>
<span style={{fontWeight: "bold", marginRight: 5}}
data-test-marker-step-action>
{originObject.action}
</span>
<span>
{filenameLink}
</span>
{viewSourceOriginButton}
</span>
{toggleFrameSelectorButton}
</div>
{inputValueLinks}
{stackFrameSelector}
{stack}
{previewStack}
</div>
{valueView}
</div>
}
selectFrameString(frameString){
this.setState({
selectedFrameString: frameString,
resolvedFrame: null,
codeFilePath: null
})
}
}
class StackFrameSelector extends React.Component {
render(){
var self = this;
return <div>
{this.props.stack.map(function(frameString){
return <StackFrameSelectorItem
isSelected={self.props.selectedFrameString === frameString}
onMouseEnter={() => self.props.onFrameHovered(frameString)}
onMouseLeave={() => self.props.onFrameHovered(null)}
frameString={frameString}
onClick={() => self.props.onFrameSelected(frameString)}
/>
})}
</div>
}
}
class StackFrameSelectorItem extends React.Component {
constructor(props){
super(props);
this.state = {
resolvedFrame: null
}
}
componentDidMount(){
this.cancelFrameResolution = resolveFrame(this.props.frameString, (err, resolvedFrame) => {
this.setState({resolvedFrame})
})
}
componentWillUnmount(){
if (this.cancelFrameResolution){
this.cancelFrameResolution()
}
}
render(){
var className = "fromjs-stack-frame-selector__item " ;
if (this.props.isSelected) {
className += "fromjs-stack-frame-selector__item--selected"
}
var loadingMessage = null;
var frameInfo = null;
var resolvedFrame = this.state.resolvedFrame;
if (resolvedFrame) {
var filename = getFilenameFromPath(resolvedFrame.fileName)
var functionName = resolvedFrame.functionName;
if (functionName === undefined) {
functionName = "(anonymous function)"
}
frameInfo = <div>
{functionName}
<div style={{float: "right"}}>{filename}</div>
</div>
} else {
loadingMessage = "Loading..."
}
return <div
className={className}
onClick={this.props.onClick}
onMouseEnter={() => this.props.onMouseEnter()}
onMouseLeave={() => this.props.onMouseLeave()}>
{loadingMessage}
{frameInfo}
</div>
}
}
function getFrameFromHTMLFileContentOriginPathItem(originPathItem){
var origin = originPathItem.origin
var valueBeforeChar = origin.value.substr(0, originPathItem.characterIndex)
var splitIntoLines = valueBeforeChar.split("\n")
var line = splitIntoLines.length;
var charIndex = _.last(splitIntoLines).length
return "at initialHtml (" + origin.isHTMLFileContent.filename + ":" + line + ":" + charIndex
}
class ValueEl extends React.Component {
render(){
var step = this.props.originPathItem;
var val = step.origin.value
return <TextEl
text={val}
highlightedCharacterIndex={step.characterIndex}
onCharacterClick={(charIndex) => this.props.handleValueSpanClick(step.origin, charIndex)}
/>
}
}
class TextEl extends React.Component {
constructor(props){
super(props)
this.state = {
truncateText: true
}
}
shouldComponentUpdate(nextProps, nextState){
// console.time("TextEl shouldUpdate")
var shouldUpdate = JSON.stringify(nextProps) !== JSON.stringify(this.props) ||
JSON.stringify(nextState) !== JSON.stringify(this.state)
// console.timeEnd("TextEl shouldUpdate")
return shouldUpdate
}
render(){
var self = this;
function splitLines(str){
var lineStrings = str.split("\n")
var lines = [];
var charOffset = 0
lineStrings.forEach(function(lineString, i){
var isLastLine = i + 1 === lineStrings.length
var text = lineString + (isLastLine ? "" : "\n");
var charOffsetStart = charOffset
var charOffsetEnd = charOffset + text.length;
lines.push({
text: text,
lineNumber: i,
charOffsetStart: charOffsetStart,
charOffsetEnd: charOffsetEnd,
containsCharIndex: function(index){
return index >= charOffsetStart && index < charOffsetEnd
},
splitAtCharIndex: function(index){
var lineBeforeIndex = text.substr(0, highlightedCharIndex - charOffsetStart);
var lineAtIndex = text.substr(highlightedCharIndex - charOffsetStart, 1);
var lineAfterIndex = text.substr(highlightedCharIndex + 1 - charOffsetStart)
return [{
text: lineBeforeIndex,
charOffsetStart: charOffsetStart
}, {
text: lineAtIndex,
charOffsetStart: charOffsetStart + lineBeforeIndex.length
}, {
text: lineAfterIndex,
charOffsetStart: charOffsetStart + lineBeforeIndex.length + lineAtIndex.length
}]
}
})
charOffset = charOffsetEnd
})
if (charOffset !== str.length){
throw "looks like sth went wrong?"
}
return lines;
}
function processChar(char){
if (char==="\n"){
char = "\u21B5" // downwards arrow with corner leftwards
}
if (char===" ") {
char = '\xa0'
}
if (char==="\t"){
char = "\xa0\xa0"
}
return char
}
function charIsWhitespace(char){
return char === "\t" || char === " "
}
function getValueSpan(char, extraClasses, key, onClick, onMouseEnter, onMouseLeave){
var className = extraClasses;
if (charIsWhitespace(char)){
className += " fromjs-value__whitespace-character"
}
var processedChar = processChar(char)
return <span
className={className}
onClick={onClick}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
key={key}
>
{processedChar}
</span>
}
function getValueSpans(val, indexOffset){
var els = [];
for (let index=0; index<val.length; index++){
var char = val[index]
els.push(getValueSpan(char, "", index + indexOffset, () => {
self.props.onCharacterClick(index + indexOffset)
}, () => {
if (!self.props.onCharacterHover) {return}
self.props.onCharacterHover(index + indexOffset)
},() => {
if (!self.props.onCharacterHover) {return}
self.props.onCharacterHover(null)
}))
}
return els
}
var val = this.props.text
var self = this;
var highlightedCharIndex = this.props.highlightedCharacterIndex
if (highlightedCharIndex === undefined || highlightedCharIndex === null) {
return <div className="fromjs-value">
{getValueSpans(val, 0)}
</div>
} else {
var lines = splitLines(val)
var valBeforeColumn = val.substr(0, highlightedCharIndex);
var valAtColumn = val.substr(highlightedCharIndex, 1);
var valAfterColumn = val.substr(highlightedCharIndex+ 1)
var highlightedCharLineIndex = valBeforeColumn.split("\n").length
var showFromLineIndex = highlightedCharLineIndex - 2;
if (showFromLineIndex < 0) {
showFromLineIndex = 0;
}
var showToLineIndex = showFromLineIndex + 3
if (!this.state.truncateText) {
showFromLineIndex = 0;
showToLineIndex = lines.length;
}
var linesToShow = lines.slice(showFromLineIndex, showToLineIndex)
function getLineComponent(line, beforeSpan, afterSpan){
var valueSpans = []
if (line.containsCharIndex(highlightedCharIndex)){
var chunks = line.splitAtCharIndex(highlightedCharIndex)
var textBeforeHighlight = chunks[0].text
if (textBeforeHighlight.length > 50 && self.state.truncateText) {
var textA = textBeforeHighlight.slice(0, 40)
var textB = textBeforeHighlight.slice(textBeforeHighlight.length - 10)
valueSpans = [
getValueSpans(textA, chunks[0].charOffsetStart),
getEllipsisSpan("ellipsis-line-before-highlight"),
getValueSpans(textB, chunks[0].charOffsetStart + textBeforeHighlight.length - textB.length)
]
} else {
valueSpans = valueSpans.concat(getValueSpans(chunks[0].text, chunks[0].charOffsetStart))
}
valueSpans = valueSpans.concat(getValueSpan(chunks[1].text, "fromjs-highlighted-character", "highlighted-char-key", function(){}, function(){}, function(){}))
var restofLineValueSpans;
var textAfterHighlight = chunks[2].text;
if (textAfterHighlight.length > 60 && self.state.truncateText){
restofLineValueSpans = [
getValueSpans(chunks[2].text.slice(0, 60), chunks[2].charOffsetStart),
getEllipsisSpan("ellipsis-line-after-highlight")
]
} else {
restofLineValueSpans = getValueSpans(chunks[2].text, chunks[2].charOffsetStart)
}
valueSpans = valueSpans.concat(restofLineValueSpans)
} else {
valueSpans = getValueSpans(line.text, line.charOffsetStart);
}
return <div key={"Line" + line.lineNumber}>
{beforeSpan}
{valueSpans}
{afterSpan}
</div>
}
function getEllipsisSpan(key){
return <span onClick={() => self.disableTruncateText()} key={key}>...</span>
}
var ret = <HorizontalScrollContainer>
<div className="fromjs-value">
<div className="fromjs-value__content" ref={(el) => {
this.scrollToHighlightedChar(el, highlightedCharLineIndex);
}}>
{linesToShow.map((line, i) =>{
var beforeSpan = null;
if (i === 0 && line.charOffsetStart > 0){
beforeSpan = getEllipsisSpan("beforeEllipsis")
}
var afterSpan = null;
if (i === linesToShow.length - 1 && line.charOffsetEnd < val.length) {
afterSpan = getEllipsisSpan("afterEllipsis")
}
return getLineComponent(line, beforeSpan, afterSpan)
})}
</div>
</div>
</HorizontalScrollContainer>
return ret;
}
}
scrollToHighlightedChar(el, highlightedCharLineIndex){
if (!el){return}
if (this.state.truncateText) {return}
var lineHeight = 18;
var lineAtTop = highlightedCharLineIndex - 4;
if (lineAtTop < 0) {
lineAtTop = 0;
}
el.scrollTop = lineAtTop * lineHeight;
}
disableTruncateText(){
if (this.props.text.length > 20000) {
alert("Refusing to expand text longer than 20,000 characters. It will just crash your browser.");
return
}
this.setState({truncateText: false})
}
}
const MAX_LINES_TO_SHOW_BEFORE_AND_AFTER = 200;
class StackFrame extends React.Component{
constructor(props){
super(props)
this.state = {
resolvedFrame: null,
truncate: true
}
}
componentDidMount(){
this.cancelFrameResolution = resolveFrame(this.props.frame, (err, resolvedFrame) => {
this.setState({resolvedFrame})
})
}
componentWillUnmount(){
if (this.cancelFrameResolution){
this.cancelFrameResolution()
}
}
render(){
function processFrameString(str){
return str
.replace(/ /g, '\xa0') //nbsp
.replace(/\t/g, '\xa0\xa0')
}
if (this.state.resolvedFrame === null) {
return <div style={{padding: 5, paddingLeft: 10}}>Loading...</div>
}
var frame = this.state.resolvedFrame;
var self = this;
var barSpan = <span className="fromjs-stack__code-column"></span>
var originPathItem = this.props.originPathItem;
var highlighNthCharAfterColumn = null;
if (originPathItem.origin.action === "String Literal" ){
highlighNthCharAfterColumn = "'".length + originPathItem.characterIndex
}
if (originPathItem.origin.action === "Initial Page HTML"){
highlighNthCharAfterColumn = 0;
barSpan = null;
}
var highlightClass = "fromjs-highlighted-character"
var hasHighlight = highlighNthCharAfterColumn !== null
if (!hasHighlight) {
highlighNthCharAfterColumn = 0
highlightClass = ""
}
highlighNthCharAfterColumn = adjustColumnForEscapeSequences(frame.line.substr(frame.columnNumber), highlighNthCharAfterColumn)
var strBetweenBarAndHighlight = frame.line.substring(frame.columnNumber, frame.columnNumber + highlighNthCharAfterColumn)
// If strings are too long and would hide highlighted content truncate them
var strBeforeBar = frame.line.substr(0, frame.columnNumber)
if (strBeforeBar.length > 50 && this.state.truncate) {
strBeforeBar = strBeforeBar.substr(0, 10) + "..." + strBeforeBar.substr(strBeforeBar.length - 20)
}
if (strBetweenBarAndHighlight.length > 50 && this.state.truncate) {
strBetweenBarAndHighlight = strBetweenBarAndHighlight.substr(0, 10) + "..." + strBetweenBarAndHighlight.substr(strBetweenBarAndHighlight.length - 20)
}
class LineNumber extends React.Component {
render(){
var arrow = null;
if (this.props.arrow){
arrow = <div className={"fromjs-stack__line-number-arrow"}>
{this.props.arrow}
</div>
}
return <span
className={"fromjs-stack__line-number " + (this.props.arrow ? "fromjs-stack__line-number--has-arrow": "")}>
<span className="fromjs-stack__line-number-text">{this.props.lineNumber}</span>
{arrow}
</span>
}
}
function getLine(lineStr, lineNumber, arrow){
return <div>
<LineNumber lineNumber={lineNumber} arrow={arrow} />
<span style={{opacity: .75}}>{processFrameString(lineStr)}</span>
</div>
}
function getPrevLines(){
if (frame.prevLines.length === 0) {
return [];
}
if (self.state.truncate) {
return getLine(_.last(frame.prevLines), frame.lineNumber - 1, "\u25B2")
} else {
var prevLinesToShow = frame.prevLines;
if (prevLinesToShow.length > MAX_LINES_TO_SHOW_BEFORE_AND_AFTER) {
prevLinesToShow = frame.prevLines.slice(frame.prevLines.length - MAX_LINES_TO_SHOW_BEFORE_AND_AFTER)
}
var linesNotShown = frame.prevLines.length - prevLinesToShow.length;
return prevLinesToShow.map(function(line, i){
return getLine(line, i + 1 + linesNotShown)
})
}
}
function getNextLines(){
if (frame.nextLines.length === 0) {
return []
}
if (self.state.truncate) {
return getLine(_.first(frame.nextLines), frame.lineNumber + 1, "\u25BC")
} else {
var nextLinesToShow = frame.nextLines;
if (frame.nextLines.length > MAX_LINES_TO_SHOW_BEFORE_AND_AFTER) {
nextLinesToShow = frame.nextLines.slice(0, MAX_LINES_TO_SHOW_BEFORE_AND_AFTER)
}
return nextLinesToShow.map(function(line, i){
return getLine(line, i + frame.lineNumber + 1)
})
}
}
var highlightIndexInLine = frame.columnNumber + highlighNthCharAfterColumn
var highlightedString = processFrameString(frame.line.substr(highlightIndexInLine, 1));
if (frame.line.length == highlightIndexInLine) {
// after last proper char in line, display new line
highlightedString = "\u21B5"
}
if (frame.line.length < highlightIndexInLine) {
debugger // shoudn't happen
}
return <div style={{
display: "block",
maxHeight: 18 * 7,
overflow: "auto"
}} ref={(el) => this.scrollToLine(el, frame.lineNumber)}>
<HorizontalScrollContainer>
<div>
<code
className={"fromjs-stack__code" + (self.state.truncate ? " fromjs-stack__code--truncated" :"")}
onClick={() => {
if (self.state.truncate){
self.setState({truncate: false})
}
}}
>
{getPrevLines()}
<div>
<LineNumber lineNumber={frame.lineNumber} />
<span>
{processFrameString(strBeforeBar)}
</span>
{barSpan}
<span>
{processFrameString(strBetweenBarAndHighlight)}
</span>
<span className={highlightClass}>
{highlightedString}
</span>
<span>
{processFrameString(frame.line.substr(frame.columnNumber + highlighNthCharAfterColumn + 1))}
</span>
</div>
{getNextLines()}
</code>
</div>
</HorizontalScrollContainer>
</div>
}
scrollToLine(el, lineNumber){
if (el === null){
return;
}
if (this.state.truncate) {
return;
}
var linesNotShownBefore = this.state.resolvedFrame.prevLines.length - MAX_LINES_TO_SHOW_BEFORE_AND_AFTER;
if (linesNotShownBefore < 0){
linesNotShownBefore = 0;
}
var lineHeight = 18;
var scrollToLine = lineNumber - 4 - linesNotShownBefore;
if (scrollToLine < 0){
scrollToLine = 0;
}
el.scrollTop = scrollToLine * lineHeight;
}
}
class HorizontalScrollContainer extends React.Component {
render(){
return <div className="fromjs-horizontal-scroll-container">
<div>
{this.props.children}
</div>
</div>
}
}
class ElementOriginPath extends React.Component {
constructor(props){
super(props)
this.state = {
characterIndex: getDefaultInspectedCharacterIndex(props.el.outerHTML),
previewCharacterIndex: null,
rootOrigin: null,
originPathKey: null,
previewOriginPathKey: null,
originPath: null,
previewOriginPath: null
}
this.componentWillUpdate(props, this.state, true);
}
componentWillReceiveProps(nextProps) {
if (nextProps.el.__fromJSElementId !== this.props.el.__fromJSElementId){
console.log("resetting root origin", nextProps.el.outerHTML.substring(0, 100))
this.setState({
rootOrigin: null,
characterIndex: getDefaultInspectedCharacterIndex(nextProps.el.outerHTML),
})
}
}
componentWillUpdate(nextProps, nextState, forceUpdate) {
if (nextState.previewCharacterIndex === this.state.previewCharacterIndex &&
nextState.characterIndex === this.state.characterIndex &&
nextState.rootOrigin === this.state.rootOrigin &&
nextProps.el.__fromJSElementId === this.props.el.__fromJSElementId &&
forceUpdate !== true) {
return
}
if (this.cancelSelectionGetOriginKeyAndPath) {
this.cancelSelectionGetOriginKeyAndPath();
}
if (this.cancelPreviewGetOriginKeyAndPath) {
this.cancelPreviewGetOriginKeyAndPath();
}
if (nextState.previewCharacterIndex !== null) {
// We don't reset the state because we want to keep the current UI visible until the new data comes in
this.cancelPreviewGetOriginKeyAndPath = this.getOriginKeyAndPath(nextProps, nextState, nextState.previewCharacterIndex, (key, originPath) => {
var setState = () => this.setState({
previewOriginPath: originPath,
previewOriginPathKey: key
})
if (originPath) {
var lastStep = _.last(originPath)
var origin = lastStep.origin
// resolve frame so it's cached when we display it, so you don't get the "loading..." message
var frameString;
if (origin.isHTMLFileContent) {
frameString = getFrameFromHTMLFileContentOriginPathItem(lastStep)
} else {
frameString = _.first(origin.stack)
}
if (frameString !== undefined) {
resolveFrame(frameString, setState)
} else {
setState();
}
} else {
setState()
}
})
} else {
// Don't reset yet so it doesn't flash the previous value, instead we want to continue showing the
// preview value
this.cancelSelectionGetOriginKeyAndPath = this.getOriginKeyAndPath(nextProps, nextState, nextState.characterIndex, (key, originPath) => this.setState({
originPathKey: key,
originPath: originPath,
previewOriginPathKey: null,
previewOriginPath: null
}))
}
}
getOriginKeyAndPath(props, state, characterIndex, callback){
var canceled = false;
this.getOriginPathKey(props, state, characterIndex, key => {
this.getOriginPath(props, state, characterIndex, originPath => {
if (canceled) {return}
callback(key, originPath)
})
})
return function cancel(){
canceled = true;
}
}
componentWillUnmount(){
if (this.cancelGetRootOriginAtChar) {
this.cancelGetRootOriginAtChar();
}
}
render(){
var showPreview = this.state.previewOriginPath;
var originPath = <div style={{display: showPreview ? "none" : "block"}}>
<OriginPath
originPath={this.state.originPath}
key={this.state.originPathKey}
handleValueSpanClick={(origin, characterIndex) => {
this.props.onNonElementOriginSelected()
currentInspectedPage.send("UISelectNonElementOrigin")
this.setState({
rootOrigin: origin,
characterIndex
})
}}
/>
</div>
var previewOriginPath = null;
if (showPreview) {
previewOriginPath = <OriginPath
originPath={this.state.previewOriginPath}
key={this.state.previewOriginPathKey}
/>
}
var showUpButton = typeof this.props.goUpInDOM === "function"
var upButton = null;
if (showUpButton && !window.disableSelectParentElement){
upButton = <div style={{position: "absolute", top: 0, right: 0, border: "1px solid #eee"}}>
<button
data-tip={"Inspect parent element"}
onClick={() => this.props.goUpInDOM() }
className={"fromjs-go-up-button"}
>
{"\u21e7"}
</button>
</div>
}
var onCharacterClick = (characterIndex) => this.setState({
characterIndex,
previewCharacterIndex: null,
originPathKey: null,
originPath: null
})
if (!this.props.isPreviewElement) {
window.e2eTestSimulateInpsectCharacter = onCharacterClick
}
return <div>
<div style={{padding: 10}}>
<div style={{fontWeight: "bold", fontSize: 20, marginBottom: 20}}>
Where does this character come from?
</div>
<div style={{position: "relative"}}>
<div style={{border: "1px solid #ddd",
width: showUpButton ? "calc(100% - 30px)" : "100%"}}
data-test-marker-inspected-value>
<TextEl
text={this.getInspectedValue()}
highlightedCharacterIndex={this.state.characterIndex}
onCharacterClick={onCharacterClick}
onCharacterHover={(characterIndex) => {
if (isMobile()) { return }
this.setState({previewCharacterIndex: characterIndex})
}}
/>
</div>
{upButton}
</div>
</div>
<hr/>
<div style={{padding: 10}}>
{originPath}
{previewOriginPath}
</div>
</div>
}
originComesFromElement(props, state){
return state.rootOrigin === null
}
getInspectedValue(){
if (this.state.rootOrigin){
return this.state.rootOrigin.value
} else if (this.props.el) {
var outerHtml = this.props.el.outerHTML
if (this.props.el.tagName === "BODY") {
// contains the FromJS UI, which we don't want to show
var fromJSHtml = document.querySelector(".fromjs-outer-container").outerHTML
var fromJSStartInBody = outerHtml.indexOf(fromJSHtml)
var fromJSEndInBody = fromJSStartInBody + fromJSHtml.length
outerHtml = outerHtml.slice(0, fromJSStartInBody) + outerHtml.slice(fromJSEndInBody)
}
return outerHtml
}
return null;
}
getOriginPath(props, state, characterIndex, callback){
if (characterIndex === null){
// characterIndex should never be null, but right now it is sometimes
callback(null)
return;
}
var isCanceled = false
this.getOriginAndCharacterIndex(props, state, characterIndex, function(info){
if (isCanceled) {
return;
}
currentInspectedPage.send("whereDoesCharComeFrom", info.origin.id, info.characterIndex, function(){
if (!isCanceled) {
callback.apply(this, arguments)
}
})
})
return function cancel(){
isCanceled = true;
}
}
getOriginPathKey(props, state, characterIndex, callback){
this.getOriginAndCharacterIndex(props, state, characterIndex, function(info){
callback(JSON.stringify({
originId: info.origin.id,
characterIndex: info.characterIndex
}))
})
}
getOriginAndCharacterIndex(props, state, characterIndex, callback){
characterIndex = parseFloat(characterIndex);
if (this.originComesFromElement(props, state)) {
this.cancelGetRootOriginAtChar = currentInspectedPage.send("getRootOriginAtChar", props.el.__fromJSElementId, characterIndex, function(rootOrigin){
callback(rootOrigin)
});
} else {
callback({
characterIndex: characterIndex,
origin: state.rootOrigin
})
}
}
}
class ElementMarker extends React.Component {
shouldComponentUpdate(newProps){
return this.props.el !== newProps.el;
}
render(){
if (this.props.el === null) {
return null;
}
var rect = this.props.el.getBoundingClientRect()
var style = {
...this.props.style,
left: rect.left + document.body.scrollLeft,
top: rect.top + document.body.scrollTop,
height: rect.height,
width: rect.width
}
return <div style={style} className="fromjs-element-marker"></div>
}
}
export class SelectedElementMarker extends React.Component {
render(){
return <ElementMarker el={this.props.el} style={{outline: "2px solid #0088ff"}} />
}
}
export class PreviewElementMarker extends React.Component {
render(){
return <ElementMarker el={this.props.el} style={{outline: "2px solid green"}} />
}
}
class Intro extends React.Component {
render(){
var browserIsChrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
var notChromeMessage = null
if (!browserIsChrome) {
notChromeMessage = <div style={{border: "2px solid red", padding: 10}}>
FromJS is currently built to only work in Chrome. It sort of works
in other browsers too, but some things are broken.
</div>
}
return <div className="fromjs-intro">
{notChromeMessage}
<h2>What is this?</h2>
<p>
FromJS helps you understand how an app works and how its UI relates to the source code.
</p>
<p>
Select a DOM element on the left to see where its
content came from. This could be a string in the JavaScript code,
localStorage data, or directly from the HTML file.
</p>
<h2>
Does this work for all apps?
</h2>
<p>
Sometimes it works, but most of the time it doesn{"'"}t. I{"'"}m slowly trying to support more
JS functionality. I{"'"}m also working on a
Chrome extension to make it easier to run FromJS on any page.
</p>
<p>
<a href="https://github.com/mattzeunert/fromjs">Github</a>
–
<a href="http://www.fromjs.com/">FromJS.com</a>
–
<a href="https://twitter.com/mattzeunert">Twitter</a>
</p>
</div>
}
}
export class FromJSView extends React.Component {
constructor(props){
super(props)
this.state = {
el: null,
previewEl: null,
// this shoudldn't be needed, should just reset state.el, but right now that wouldn't work
nonElementOriginSelected: null
}
currentInspectedPage = new RoundTripMessageWrapper(window.parent, "IFrame")
setTimeout(function(){
currentInspectedPage.send("InspectorReady", function(){})
})
currentInspectedPage.on("selectElement", (el) => {
this.setState({
el: el,
nonElementOriginSelected: false
})
})
var onPreviewElement = (el) => {
// Delay to prevent setting null inbetween when exiting one element and then entering another
this.setState({previewEl: el})
}
onPreviewElement = _.debounce(onPreviewElement, 10)
currentInspectedPage.on("previewElement", onPreviewElement, 10)
// ReactTooltip doesn't respond to UI changes automatically
setInterval(function(){
ReactTooltip.rebuild()
}, 100)
}
render(){
var preview = null;
var info = null;
var selectionMarker = null;
var previewMarker = null;
var intro = null;
var showPreview = this.state.previewEl !== null && (!this.state.el || this.state.previewEl.__fromJSElementId !== this.state.el.__fromJSElementId)
if (showPreview){
preview = <ElementOriginPath
el={this.state.previewEl}
goUpInDOM={() => "can't call this function, but needs to be there so button is shown"}
isPreviewElement={true}
/>
}
if (this.state.el) {
var goUpInDOM = null
if (!this.state.nonElementOriginSelected && this.state.el.tagName !== "BODY") {
goUpInDOM = () => currentInspectedPage.send("UISelectParentElement")
}
info = <div style={{display: showPreview ? "none" : "block"}}>
<ElementOriginPath
el={this.state.el}
onNonElementOriginSelected={() => this.setState({nonElementOriginSelected: true})}
goUpInDOM={goUpInDOM} />
</div>
}
if (this.state.el && !this.state.nonElementOriginSelected) {
// selectionMarker = <SelectedElementMarker el={this.state.el} />
}
if (!this.state.previewEl && !this.state.el){
intro = <Intro />
}
return <div>
<div id="fromjs" className="fromjs">
<button
onClick={() => currentInspectedPage.send("UICloseInspector")}
className="toggle-inspector-button close-inspector-button">
</button>
{intro}
{preview}
{info}
{/* Add some spacing since it seems you can't scroll down all the way*/}
{isMobile() ? <div><br/><br/><br/></div> : null}
<ReactTooltip effect="solid" />
</div>
{previewMarker}
{selectionMarker}
</div>
}
}
| Tweak intro.
| src/ui/ui.js | Tweak intro. | <ide><path>rc/ui/ui.js
<ide> {notChromeMessage}
<ide> <h2>What is this?</h2>
<ide> <p>
<del> FromJS helps you understand how an app works and how its UI relates to the source code.
<add> FromJS helps you understand how an app works by showing how its UI relates to the source code.
<ide> </p>
<ide> <p>
<ide> Select a DOM element on the left to see where its
<ide> </h2>
<ide> <p>
<ide> Sometimes it works, but most of the time it doesn{"'"}t. I{"'"}m slowly trying to support more
<del> JS functionality. I{"'"}m also working on a
<del> Chrome extension to make it easier to run FromJS on any page.
<add> JS functionality.
<ide> </p>
<ide>
<ide> <p> |
|
Java | mit | ec172bb4714d36235a7d3d502edc0deaa39542b8 | 0 | CjHare/systematic-trading | /**
* Copyright (c) 2015, CJ Hare 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 [project] 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 HOLDER 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.systematic.trading.maths.indicator.rsi;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;
import com.systematic.trading.collection.NonNullableArrayList;
import com.systematic.trading.data.TradingDayPrices;
import com.systematic.trading.data.price.ClosingPrice;
import com.systematic.trading.maths.indicator.Validator;
/**
* Relative Strength Index - RSI
*
* A technical momentum indicator that compares the magnitude of recent gains to recent losses in an
* attempt to determine over bought and over sold conditions of an asset.
*
* RSI = 100 - 100/(1 + RS*)
*
* Where RS = Average of x days' up closes / Average of x days' down closes.
*
* Uses the EMA in calculation of the relative strength (J. Welles Wilder approach), not the SMA.
*
* Taking the prior value plus the current value is a smoothing technique similar to that used in
* exponential moving average calculation. This also means that RSI values become more accurate as
* the calculation period extends.
*
* @author CJ Hare
*/
public class RelativeStrengthIndexCalculator implements RelativeStrengthIndex {
/** Constant for the value of 100. */
private static final BigDecimal ONE_HUNDRED = BigDecimal.valueOf(50);
/** Scale, precision and rounding to apply to mathematical operations. */
private final MathContext mathContext;
/** The number of trading days to look back for calculation. */
private final int lookback;
/** Provides the array to store the result in. */
private final List<BigDecimal> relativeStrengthValues;
/** Provides the array to store the result in. */
private final List<BigDecimal> relativeStrengthIndexValues;
/** Required number of data points required for ATR calculation. */
private final int minimumNumberOfPrices;
/** Constant used for smoothing the moving average. */
private final BigDecimal smoothingConstant;
/** Responsible for parsing and validating the input. */
private final Validator validator;
/**
* @param lookback the number of days to use when calculating the RSI.
* @param daysOfRsiValues the number of trading days to calculate the RSI value.
* @param validator validates and parses input.
* @param mathContext the scale, precision and rounding to apply to mathematical operations.
*/
public RelativeStrengthIndexCalculator(final int lookback, final int daysOfRsiValues, final Validator validator,
final MathContext mathContext) {
this.relativeStrengthIndexValues = new NonNullableArrayList<>();
this.relativeStrengthValues = new NonNullableArrayList<>();
this.minimumNumberOfPrices = lookback + daysOfRsiValues;
this.smoothingConstant = calculateSmoothingConstant(lookback);
this.mathContext = mathContext;
this.validator = validator;
this.lookback = lookback;
}
@Override
public List<BigDecimal> rsi( final TradingDayPrices[] data ) {
validator.verifyZeroNullEntries(data);
validator.verifyEnoughValues(data, minimumNumberOfPrices);
relativeStrengthIndexValues.clear();
relativeStrengthValues.clear();
/* For the first zero - time period entries calculate the SMA based on up to down movement
* Upwards movement upward = closeToday - closeYesterday downward = 0 Downwards movement
* upward = closeYesterday - closeToday */
final int startRsiIndex = 0;
ClosingPrice closeToday;
ClosingPrice closeYesterday = data[startRsiIndex].getClosingPrice();
BigDecimal upward = BigDecimal.ZERO;
BigDecimal downward = BigDecimal.ZERO;
final int endInitialLookback = startRsiIndex + lookback;
for (int i = startRsiIndex; i < endInitialLookback; i++) {
closeToday = data[i].getClosingPrice();
switch (closeToday.compareTo(closeYesterday)) {
// Today's price is higher then yesterdays
case 1:
upward = upward.add(closeToday.subtract(closeYesterday, mathContext));
break;
// Today's price is lower then yesterdays
case -1:
downward = downward.add(closeYesterday.subtract(closeToday, mathContext));
break;
// When equal there's no movement, both are zero
case 0:
default:
break;
}
closeYesterday = closeToday;
}
// Dividing by the number of time periods for a SMA
// Reduce lookup by one, as the initial value is neither up or down
upward = upward.divide(BigDecimal.valueOf(lookback - 1L), mathContext);
downward = downward.divide(BigDecimal.valueOf(lookback - 1L), mathContext);
/* RS = EMA(U,n) / EMA(D,n) (smoothing constant) multiplier: (2 / (Time periods + 1) ) EMA:
* {Close - EMA(previous day)} x multiplier + EMA(previous day). */
for (int i = endInitialLookback; i < data.length; i++) {
closeToday = data[i].getClosingPrice();
closeYesterday = data[i - 1].getClosingPrice();
switch (closeToday.compareTo(closeYesterday)) {
case 1: // Today's price is higher then yesterdays
upward = (closeToday.subtract(closeYesterday, mathContext).subtract(upward, mathContext))
.multiply(smoothingConstant, mathContext).add(upward, mathContext);
downward = downward.negate().multiply(smoothingConstant, mathContext).add(downward, mathContext);
break;
case -1: // Today's price is lower then yesterdays
upward = upward.negate().multiply(smoothingConstant, mathContext).add(upward, mathContext);
downward = (closeYesterday.subtract(closeToday, mathContext).subtract(downward, mathContext))
.multiply(smoothingConstant, mathContext).add(downward, mathContext);
break;
case 0: // When equal there's no movement, both are zero
default:
break;
}
// When downward approaches zero, RSI approaches 100
if (downward.compareTo(BigDecimal.ZERO) <= 0) {
relativeStrengthValues.add(ONE_HUNDRED);
} else {
relativeStrengthValues.add(upward.divide(downward, mathContext));
}
}
/* RSI = 100 / 1 + RS */
for (final BigDecimal rs : relativeStrengthValues) {
relativeStrengthIndexValues
.add(ONE_HUNDRED.subtract(ONE_HUNDRED.divide(BigDecimal.ONE.add(rs), mathContext)));
}
return relativeStrengthIndexValues;
}
private BigDecimal calculateSmoothingConstant( final int lookback ) {
return BigDecimal.valueOf(2d / (lookback + 1));
}
}
| systematic-trading-maths/src/main/java/com/systematic/trading/maths/indicator/rsi/RelativeStrengthIndexCalculator.java | /**
* Copyright (c) 2015, CJ Hare 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 [project] 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 HOLDER 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.systematic.trading.maths.indicator.rsi;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;
import com.systematic.trading.collection.NonNullableArrayList;
import com.systematic.trading.data.TradingDayPrices;
import com.systematic.trading.data.price.ClosingPrice;
import com.systematic.trading.maths.indicator.Validator;
/**
* Relative Strength Index - RSI
*
* A technical momentum indicator that compares the magnitude of recent gains to recent losses in an
* attempt to determine over bought and over sold conditions of an asset.
*
* RSI = 100 - 100/(1 + RS*)
*
* Where RS = Average of x days' up closes / Average of x days' down closes.
*
* Uses the EMA in calculation of the relative strength (J. Welles Wilder approach), not the SMA.
*
* Taking the prior value plus the current value is a smoothing technique similar to that used in
* exponential moving average calculation. This also means that RSI values become more accurate as
* the calculation period extends.
*
* @author CJ Hare
*/
public class RelativeStrengthIndexCalculator implements RelativeStrengthIndex {
/** Constant for the value of 100. */
private static final BigDecimal ONE_HUNDRED = BigDecimal.valueOf(50);
/** Scale, precision and rounding to apply to mathematical operations. */
private final MathContext mathContext;
/** The number of trading days to look back for calculation. */
private final int lookback;
/** Provides the array to store the result in. */
private final List<BigDecimal> relativeStrengthValues;
/** Provides the array to store the result in. */
private final List<BigDecimal> relativeStrengthIndexValues;
/** Required number of data points required for ATR calculation. */
private final int minimumNumberOfPrices;
/** Constant used for smoothing the moving average. */
private final BigDecimal smoothingConstant;
/** Responsible for parsing and validating the input. */
private final Validator validator;
/**
* @param lookback the number of days to use when calculating the RSI.
* @param daysOfRsiValues the number of trading days to calculate the RSI value.
* @param validator validates and parses input.
* @param mathContext the scale, precision and rounding to apply to mathematical operations.
*/
public RelativeStrengthIndexCalculator(final int lookback, final int daysOfRsiValues, final Validator validator,
final MathContext mathContext) {
this.relativeStrengthIndexValues = new NonNullableArrayList<>();
this.relativeStrengthValues = new NonNullableArrayList<>();
this.minimumNumberOfPrices = lookback + daysOfRsiValues;
this.smoothingConstant = calculateSmoothingConstant(lookback);
this.mathContext = mathContext;
this.validator = validator;
this.lookback = lookback;
}
@Override
public List<BigDecimal> rsi( final TradingDayPrices[] data ) {
validator.verifyZeroNullEntries(data);
validator.verifyEnoughValues(data, minimumNumberOfPrices);
relativeStrengthIndexValues.clear();
relativeStrengthValues.clear();
/* For the first zero - time period entries calculate the SMA based on up to down movement
* Upwards movement upward = closeToday - closeYesterday downward = 0 Downwards movement
* upward = closeYesterday - closeToday */
final int startRsiIndex = 0;
ClosingPrice closeToday;
ClosingPrice closeYesterday = data[startRsiIndex].getClosingPrice();
BigDecimal upward = BigDecimal.ZERO;
BigDecimal downward = BigDecimal.ZERO;
final int endInitialLookback = startRsiIndex + lookback;
for (int i = startRsiIndex; i < endInitialLookback; i++) {
closeToday = data[i].getClosingPrice();
switch (closeToday.compareTo(closeYesterday)) {
// Today's price is higher then yesterdays
case 1:
upward = upward.add(closeToday.subtract(closeYesterday, mathContext));
break;
// Today's price is lower then yesterdays
case -1:
downward = downward.add(closeYesterday.subtract(closeToday, mathContext));
break;
// When equal there's no movement, both are zero
case 0:
default:
break;
}
closeYesterday = closeToday;
}
// Dividing by the number of time periods for a SMA
// Reduce lookup by one, as the initial value is neither up or down
upward = upward.divide(BigDecimal.valueOf(lookback - 1L), mathContext);
downward = downward.divide(BigDecimal.valueOf(lookback - 1L), mathContext);
/* RS = EMA(U,n) / EMA(D,n) (smoothing constant) multiplier: (2 / (Time periods + 1) ) EMA:
* {Close - EMA(previous day)} x multiplier + EMA(previous day). */
for (int i = endInitialLookback; i < data.length; i++) {
closeToday = data[i].getClosingPrice();
closeYesterday = data[i - 1].getClosingPrice();
switch (closeToday.compareTo(closeYesterday)) {
// Today's price is higher then yesterdays
case 1:
upward = (closeToday.subtract(closeYesterday, mathContext).subtract(upward, mathContext))
.multiply(smoothingConstant, mathContext).add(upward, mathContext);
downward = downward.negate().multiply(smoothingConstant, mathContext).add(downward, mathContext);
break;
// Today's price is lower then yesterdays
case -1:
upward = upward.negate().multiply(smoothingConstant, mathContext).add(upward, mathContext);
downward = (closeYesterday.subtract(closeToday, mathContext).subtract(downward, mathContext))
.multiply(smoothingConstant, mathContext).add(downward, mathContext);
break;
// When equal there's no movement, both are zero
case 0:
default:
break;
}
// When downward approaches zero, RSI approaches 100
if (downward.compareTo(BigDecimal.ZERO) <= 0) {
relativeStrengthValues.add(ONE_HUNDRED);
} else {
relativeStrengthValues.add(upward.divide(downward, mathContext));
}
}
/* RSI = 100 / 1 + RS */
for (final BigDecimal rs : relativeStrengthValues) {
relativeStrengthIndexValues
.add(ONE_HUNDRED.subtract(ONE_HUNDRED.divide(BigDecimal.ONE.add(rs), mathContext)));
}
return relativeStrengthIndexValues;
}
private BigDecimal calculateSmoothingConstant( final int lookback ) {
return BigDecimal.valueOf(2d / (lookback + 1));
}
}
| Reducing lines in case statements
| systematic-trading-maths/src/main/java/com/systematic/trading/maths/indicator/rsi/RelativeStrengthIndexCalculator.java | Reducing lines in case statements | <ide><path>ystematic-trading-maths/src/main/java/com/systematic/trading/maths/indicator/rsi/RelativeStrengthIndexCalculator.java
<ide>
<ide> switch (closeToday.compareTo(closeYesterday)) {
<ide>
<del> // Today's price is higher then yesterdays
<del> case 1:
<add> case 1: // Today's price is higher then yesterdays
<ide> upward = (closeToday.subtract(closeYesterday, mathContext).subtract(upward, mathContext))
<ide> .multiply(smoothingConstant, mathContext).add(upward, mathContext);
<del>
<ide> downward = downward.negate().multiply(smoothingConstant, mathContext).add(downward, mathContext);
<ide> break;
<ide>
<del> // Today's price is lower then yesterdays
<del> case -1:
<add> case -1: // Today's price is lower then yesterdays
<ide> upward = upward.negate().multiply(smoothingConstant, mathContext).add(upward, mathContext);
<del>
<ide> downward = (closeYesterday.subtract(closeToday, mathContext).subtract(downward, mathContext))
<ide> .multiply(smoothingConstant, mathContext).add(downward, mathContext);
<ide> break;
<ide>
<del> // When equal there's no movement, both are zero
<del> case 0:
<add> case 0: // When equal there's no movement, both are zero
<ide> default:
<ide> break;
<ide> }
<ide>
<ide> return relativeStrengthIndexValues;
<ide> }
<del>
<add>
<ide> private BigDecimal calculateSmoothingConstant( final int lookback ) {
<ide> return BigDecimal.valueOf(2d / (lookback + 1));
<ide> } |
|
Java | mit | 00c7c751e821e716fb6f9b5f39922136a54e083a | 0 | bugminer/bugminer,bugminer/bugminer,bugminer/bugminer,bugminer/bugminer | package de.unistuttgart.iste.rss.bugminer.scm.git;
import de.unistuttgart.iste.rss.bugminer.TestConfig;
import de.unistuttgart.iste.rss.bugminer.annotations.DataDirectory;
import de.unistuttgart.iste.rss.bugminer.config.EntityFactory;
import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRepo;
import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRevision;
import de.unistuttgart.iste.rss.bugminer.model.entities.LineChange;
import de.unistuttgart.iste.rss.bugminer.model.entities.LineChangeKind;
import de.unistuttgart.iste.rss.bugminer.model.entities.Project;
import de.unistuttgart.iste.rss.bugminer.scm.Commit;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* Tests the git strategy without needing to install vagrant
*/
@ContextConfiguration(classes = TestConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class GitStrategyWithoutVagrantIT {
@Autowired
private GitStrategy strategy;
@Autowired
@DataDirectory
private Path dataDirectory;
@Autowired
private EntityFactory entityFactory;
@Before
public void setUpGitRepo() throws IOException, GitAPIException {
Path repoPath = dataDirectory.resolve("scm").resolve("project").resolve("main");
SimpleRepo.bareCloneTo(repoPath);
}
@Test
public void testGetCommits() throws IOException {
Project project = entityFactory.make(Project.class);
project.setName("project");
CodeRepo repo = entityFactory.make(CodeRepo.class);
repo.setProject(project);
repo.setName("main");
Commit commit = strategy.getCommits(repo).findFirst().get();
assertEquals("Jan Melcher", commit.getAuthor());
assertEquals(repo, commit.getCodeRevision().getCodeRepo());
assertEquals("554068c08d994fee03ecde677725a9e1cc4e6457", commit.getCodeRevision().getCommitId());
assertEquals("Change fileA\n", commit.getCommitMessage());
}
@Test
public void testGetDiff() throws IOException {
Project project = entityFactory.make(Project.class);
project.setName("project");
CodeRepo repo = entityFactory.make(CodeRepo.class);
repo.setProject(project);
repo.setName("main");
CodeRevision oldest = new CodeRevision(repo, SimpleRepo.FIRST_COMMIT);
CodeRevision newest = new CodeRevision(repo, SimpleRepo.THIRD_COMMIT);
List<LineChange> changes = strategy.getDiff(oldest, newest);
assertThat(changes, hasSize(3));
assertThat(changes.get(0).getCodeRepo(), is(repo));
assertThat(changes.get(0).getFileName(), is("fileA"));
assertThat(changes.get(0).getKind(), is(LineChangeKind.DELETION));
assertThat(changes.get(0).getOldLineNumber(), is(1));
assertThat(changes.get(0).getNewLineNumberIndex(), nullValue());
assertThat(changes.get(1).getCodeRepo(), is(repo));
assertThat(changes.get(1).getFileName(), is("fileA"));
assertThat(changes.get(1).getKind(), is(LineChangeKind.ADDITION));
assertThat(changes.get(1).getOldLineNumber(), is(1));
assertThat(changes.get(1).getNewLineNumberIndex(), is(0));
assertThat(changes.get(2).getCodeRepo(), is(repo));
assertThat(changes.get(2).getFileName(), is("fileB"));
assertThat(changes.get(2).getKind(), is(LineChangeKind.ADDITION));
assertThat(changes.get(2).getOldLineNumber(), is(0));
assertThat(changes.get(2).getNewLineNumberIndex(), is(0));
}
}
| bugminer-server/src/test/java/de/unistuttgart/iste/rss/bugminer/scm/git/GitStrategyWithoutVagrantIT.java | package de.unistuttgart.iste.rss.bugminer.scm.git;
import de.unistuttgart.iste.rss.bugminer.TestConfig;
import de.unistuttgart.iste.rss.bugminer.annotations.DataDirectory;
import de.unistuttgart.iste.rss.bugminer.config.EntityFactory;
import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRepo;
import de.unistuttgart.iste.rss.bugminer.model.entities.CodeRevision;
import de.unistuttgart.iste.rss.bugminer.model.entities.LineChange;
import de.unistuttgart.iste.rss.bugminer.model.entities.LineChangeKind;
import de.unistuttgart.iste.rss.bugminer.model.entities.Project;
import de.unistuttgart.iste.rss.bugminer.scm.Commit;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* Tests the git strategy without needing to install vagrant
*/
@ContextConfiguration(classes = TestConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class GitStrategyWithoutVagrantIT {
@Autowired
private GitStrategy strategy;
@Autowired
@DataDirectory
private Path dataDirectory;
@Autowired
private EntityFactory entityFactory;
@Before
public void setUpGitRepo() throws IOException, GitAPIException {
Path repoPath = dataDirectory.resolve("scm").resolve("project").resolve("main");
SimpleRepo.bareCloneTo(repoPath);
}
@Test
public void testGetCommits() throws IOException {
Project project = entityFactory.make(Project.class);
project.setName("project");
CodeRepo repo = entityFactory.make(CodeRepo.class);
repo.setProject(project);
repo.setName("main");
Commit commit = strategy.getCommits(repo).findFirst().get();
assertEquals("Jan Melcher", commit.getAuthor());
assertEquals(repo, commit.getCodeRevision().getCodeRepo());
assertEquals("554068c08d994fee03ecde677725a9e1cc4e6457", commit.getCodeRevision().getCommitId());
assertEquals("Change fileA\n", commit.getCommitMessage());
}
@Test
public void testGetDiff() throws IOException {
Project project = entityFactory.make(Project.class);
project.setName("project");
CodeRepo repo = entityFactory.make(CodeRepo.class);
repo.setProject(project);
repo.setName("main");
CodeRevision oldest = new CodeRevision(repo, SimpleRepo.FIRST_COMMIT);
CodeRevision newest = new CodeRevision(repo, SimpleRepo.THIRD_COMMIT);
List<LineChange> changes = strategy.getDiff(oldest, newest);
assertThat(changes, hasSize(3));
assertThat(changes.get(0).getCodeRepo(), is(repo));
assertThat(changes.get(0).getFileName(), is("fileA"));
assertThat(changes.get(0).getKind(), is(LineChangeKind.DELETION));
assertThat(changes.get(0).getOldLineNumber(), is(1));
assertThat(changes.get(0).getNewLineNumberIndex(), nullValue());
assertThat(changes.get(1).getCodeRepo(), is(repo));
assertThat(changes.get(1).getFileName(), is("fileA"));
assertThat(changes.get(1).getKind(), is(LineChangeKind.ADDITION));
assertThat(changes.get(1).getOldLineNumber(), is(1));
assertThat(changes.get(1).getNewLineNumberIndex(), is(0));
assertThat(changes.get(2).getCodeRepo(), is(repo));
assertThat(changes.get(2).getFileName(), is("fileB"));
assertThat(changes.get(2).getKind(), is(LineChangeKind.ADDITION));
assertThat(changes.get(2).getOldLineNumber(), is(0));
assertThat(changes.get(2).getNewLineNumberIndex(), is(0));
}
}
| fix indentation
| bugminer-server/src/test/java/de/unistuttgart/iste/rss/bugminer/scm/git/GitStrategyWithoutVagrantIT.java | fix indentation | <ide><path>ugminer-server/src/test/java/de/unistuttgart/iste/rss/bugminer/scm/git/GitStrategyWithoutVagrantIT.java
<ide> @ContextConfiguration(classes = TestConfig.class)
<ide> @RunWith(SpringJUnit4ClassRunner.class)
<ide> public class GitStrategyWithoutVagrantIT {
<del> @Autowired
<del> private GitStrategy strategy;
<add> @Autowired
<add> private GitStrategy strategy;
<ide>
<del> @Autowired
<del> @DataDirectory
<del> private Path dataDirectory;
<add> @Autowired
<add> @DataDirectory
<add> private Path dataDirectory;
<ide>
<del> @Autowired
<del> private EntityFactory entityFactory;
<add> @Autowired
<add> private EntityFactory entityFactory;
<ide>
<del> @Before
<del> public void setUpGitRepo() throws IOException, GitAPIException {
<del> Path repoPath = dataDirectory.resolve("scm").resolve("project").resolve("main");
<del> SimpleRepo.bareCloneTo(repoPath);
<del> }
<add> @Before
<add> public void setUpGitRepo() throws IOException, GitAPIException {
<add> Path repoPath = dataDirectory.resolve("scm").resolve("project").resolve("main");
<add> SimpleRepo.bareCloneTo(repoPath);
<add> }
<ide>
<del> @Test
<del> public void testGetCommits() throws IOException {
<del> Project project = entityFactory.make(Project.class);
<del> project.setName("project");
<del> CodeRepo repo = entityFactory.make(CodeRepo.class);
<del> repo.setProject(project);
<del> repo.setName("main");
<add> @Test
<add> public void testGetCommits() throws IOException {
<add> Project project = entityFactory.make(Project.class);
<add> project.setName("project");
<add> CodeRepo repo = entityFactory.make(CodeRepo.class);
<add> repo.setProject(project);
<add> repo.setName("main");
<ide>
<del> Commit commit = strategy.getCommits(repo).findFirst().get();
<add> Commit commit = strategy.getCommits(repo).findFirst().get();
<ide>
<del> assertEquals("Jan Melcher", commit.getAuthor());
<del> assertEquals(repo, commit.getCodeRevision().getCodeRepo());
<del> assertEquals("554068c08d994fee03ecde677725a9e1cc4e6457", commit.getCodeRevision().getCommitId());
<del> assertEquals("Change fileA\n", commit.getCommitMessage());
<del> }
<add> assertEquals("Jan Melcher", commit.getAuthor());
<add> assertEquals(repo, commit.getCodeRevision().getCodeRepo());
<add> assertEquals("554068c08d994fee03ecde677725a9e1cc4e6457", commit.getCodeRevision().getCommitId());
<add> assertEquals("Change fileA\n", commit.getCommitMessage());
<add> }
<ide>
<del> @Test
<del> public void testGetDiff() throws IOException {
<del> Project project = entityFactory.make(Project.class);
<del> project.setName("project");
<del> CodeRepo repo = entityFactory.make(CodeRepo.class);
<del> repo.setProject(project);
<del> repo.setName("main");
<add> @Test
<add> public void testGetDiff() throws IOException {
<add> Project project = entityFactory.make(Project.class);
<add> project.setName("project");
<add> CodeRepo repo = entityFactory.make(CodeRepo.class);
<add> repo.setProject(project);
<add> repo.setName("main");
<ide>
<del> CodeRevision oldest = new CodeRevision(repo, SimpleRepo.FIRST_COMMIT);
<del> CodeRevision newest = new CodeRevision(repo, SimpleRepo.THIRD_COMMIT);
<del> List<LineChange> changes = strategy.getDiff(oldest, newest);
<del> assertThat(changes, hasSize(3));
<del> assertThat(changes.get(0).getCodeRepo(), is(repo));
<del> assertThat(changes.get(0).getFileName(), is("fileA"));
<del> assertThat(changes.get(0).getKind(), is(LineChangeKind.DELETION));
<del> assertThat(changes.get(0).getOldLineNumber(), is(1));
<del> assertThat(changes.get(0).getNewLineNumberIndex(), nullValue());
<add> CodeRevision oldest = new CodeRevision(repo, SimpleRepo.FIRST_COMMIT);
<add> CodeRevision newest = new CodeRevision(repo, SimpleRepo.THIRD_COMMIT);
<add> List<LineChange> changes = strategy.getDiff(oldest, newest);
<add> assertThat(changes, hasSize(3));
<add> assertThat(changes.get(0).getCodeRepo(), is(repo));
<add> assertThat(changes.get(0).getFileName(), is("fileA"));
<add> assertThat(changes.get(0).getKind(), is(LineChangeKind.DELETION));
<add> assertThat(changes.get(0).getOldLineNumber(), is(1));
<add> assertThat(changes.get(0).getNewLineNumberIndex(), nullValue());
<ide>
<del> assertThat(changes.get(1).getCodeRepo(), is(repo));
<del> assertThat(changes.get(1).getFileName(), is("fileA"));
<del> assertThat(changes.get(1).getKind(), is(LineChangeKind.ADDITION));
<del> assertThat(changes.get(1).getOldLineNumber(), is(1));
<del> assertThat(changes.get(1).getNewLineNumberIndex(), is(0));
<add> assertThat(changes.get(1).getCodeRepo(), is(repo));
<add> assertThat(changes.get(1).getFileName(), is("fileA"));
<add> assertThat(changes.get(1).getKind(), is(LineChangeKind.ADDITION));
<add> assertThat(changes.get(1).getOldLineNumber(), is(1));
<add> assertThat(changes.get(1).getNewLineNumberIndex(), is(0));
<ide>
<del> assertThat(changes.get(2).getCodeRepo(), is(repo));
<del> assertThat(changes.get(2).getFileName(), is("fileB"));
<del> assertThat(changes.get(2).getKind(), is(LineChangeKind.ADDITION));
<del> assertThat(changes.get(2).getOldLineNumber(), is(0));
<del> assertThat(changes.get(2).getNewLineNumberIndex(), is(0));
<del> }
<add> assertThat(changes.get(2).getCodeRepo(), is(repo));
<add> assertThat(changes.get(2).getFileName(), is("fileB"));
<add> assertThat(changes.get(2).getKind(), is(LineChangeKind.ADDITION));
<add> assertThat(changes.get(2).getOldLineNumber(), is(0));
<add> assertThat(changes.get(2).getNewLineNumberIndex(), is(0));
<add> }
<ide> } |
|
JavaScript | agpl-3.0 | 25162e49b1fa0826ab6df9e827090d1065949e35 | 0 | meh/miniLOL,meh/miniLOL | /****************************************************************************
* Copyleft meh. [http://meh.doesntexist.org | [email protected]] *
* *
* This file is part of miniLOL. *
* *
* miniLOL 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. *
* *
* miniLOL 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 miniLOL. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
/*
* miniLOL is a Javascript/XML based CMS, thus, being in the XXI century,
* I pretend those two standards to be respected.
*
* Get a real browser, get Firefox.
*/
miniLOL = {
version: "1.2",
initialize: function () {
if (miniLOL.initialized) {
throw new Error("miniLOL has already been initialized.");
}
miniLOL.initialized = false;
miniLOL.path = location.href.match(/^(.*?)\/[^\/]*?(#|$)/)[1];
miniLOL.resources = {};
miniLOL.tmp = {};
Event.observe(document, ":go", (miniLOL.tmp.fixScroll = function () {
miniLOL.theme.content().scrollTo();
}));
[function () {
Event.observe(document, ":resource.loaded", function (event) {
if (event.memo.resource.name != "miniLOL.config" || event.memo.arguments[0] != "resources/config.xml") {
return;
}
if (!miniLOL.config["core"]) {
miniLOL.config["core"] = {};
}
if (!miniLOL.config["core"].siteTitle) {
miniLOL.config["core"].siteTitle = "miniLOL #{version}".interpolate(miniLOL);
}
if (!miniLOL.config["core"].loadingMessage) {
miniLOL.config["core"].loadingMessage = "Loading...";
}
if (!miniLOL.config["core"].homePage) {
miniLOL.config["core"].homePage = "#home";
}
else {
if (miniLOL.config["core"].homePage.charAt(0) != '#' && !miniLOL.config["core"].homePage.isURL()) {
miniLOL.config["core"].homePage = '#' + miniLOL.config["core"].homePage;
}
}
if (!document.title) {
document.title = miniLOL.config["core"].siteTitle;
}
});
miniLOL.resource.set(new miniLOL.Resource("miniLOL.config", {
initialize: function () {
miniLOL.config = this.data;
},
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
var dom = miniLOL.utils.fixDOM(http.responseXML).documentElement;
var domain = dom.getAttribute("domain") || "core";
var config = miniLOL.config[domain] || {};
miniLOL.config[domain] = Object.extend(config, Element.toObject(dom));
}.bind(this),
onFailure: function (http) {
miniLOL.error("miniLOL.config: Error while loading #{path} (#{status} - #{statusText})".interpolate({
path: path,
status: http.status,
statusText: http.statusText
}), true);
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
this.data = miniLOL.config = {};
}
}));
miniLOL.resource.get("miniLOL.config").load("resources/config.xml");
$(document.body).update(miniLOL.config["core"].loadingMessage);
Event.fire(document, ":initializing");
},
function () {
miniLOL.resource.set(new miniLOL.Resource("miniLOL.menus", {
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
var response = miniLOL.utils.fixDOM(http.responseXML);
miniLOL.menus["default"] = response.getElementById("default");
$A(response.documentElement.childNodes).each(function (menu) {
if (menu.nodeType != Node.ELEMENT_NODE) {
return;
}
var id = menu.getAttribute("id");
if (!id && !miniLOL.menus["default"]) {
miniLOL.menus["default"] = menu;
}
else {
miniLOL.menus[id] = menu;
}
});
if (!miniLOL.menus["default"]) {
miniLOL.error("Error while analyzing menus.xml\n\nNo default menu was found.", true);
return;
}
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
this.data = miniLOL.menus = {};
}
}));
miniLOL.resource.get("miniLOL.menus").load("resources/menus.xml");
},
function () {
miniLOL.resource.set(new miniLOL.Resource("miniLOL.pages", {
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
miniLOL.utils.fixDOM(http.responseXML).xpath('//page').each(function (page) {
var id = page.getAttribute("id");
delete miniLOL.pages.cache[id];
miniLOL.pages.data[id] = page;
});
},
onFailure: function (http) {
miniLOL.error("miniLOL.pages: Error while loading #{path} (#{status} - #{statusText})".interpolate({
path: path,
status: http.status,
statusText: http.statusText
}, true));
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
miniLOL.pages = this.data = {
data: {},
cache: {}
};
}
}));
if (miniLOL.utils.exists("resources/pages.xml")) {
miniLOL.resource.get("miniLOL.pages").load("resources/pages.xml");
}
},
function () {
miniLOL.resource.set(new miniLOL.Resource("miniLOL.functions", {
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
miniLOL.utils.fixDOM(http.responseXML).xpath('//function').each(function (func) {
try {
miniLOL.functions[func.getAttribute("name")] = new Function(
"var text = arguments[0]; var args = arguments[1]; arguments = args; #{code}; return text;".interpolate({
code: func.firstChild.nodeValue
})
);
}
catch (e) {
miniLOL.error("Error while creating `#{name}` wrapper from #{path}:\n\n#{error}".interpolate({
name: func.getAttribute("name"),
path: path,
error: e.toString()
}), true);
return;
}
});
},
onFailure: function (http) {
miniLOL.error("miniLOL.functions: Error while loading #{path} (#{status} - #{statusText})".interpolate({
path: path,
status: http.status,
statusText: http.statusText
}), true);
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
miniLOL.functions = this.data = {};
},
render: function (types, content, args) {
types.split(/\s*,\s*/).each(function (type) {
if (Object.isFunction(this.data[type])) {
content = this.data[type](content, args);
}
}, this);
return content;
}
}));
miniLOL.resource.get("miniLOL.functions").load("resources/functions.xml");
},
function () {
$$("link").each(function (css) {
miniLOL.theme.style.list[css.getAttribute("href")] = css;
});
if (miniLOL.config["core"].theme) {
miniLOL.error(!miniLOL.theme.load(miniLOL.config["core"].theme));
miniLOL.theme.template.menu();
}
else {
miniLOL.error(!miniLOL.theme.deprecated());
}
},
function () {
if (miniLOL.menu.enabled()) {
miniLOL.menu.set(miniLOL.config["core"].loadingMessage);
}
},
function () {
miniLOL.content.set("Loading modules...");
miniLOL.resource.set(new miniLOL.Resource("miniLOL.modules", {
load: function (path, output) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
miniLOL.module.path = http.responseXML.documentElement.getAttribute("path") || 'modules';
var modules = miniLOL.utils.fixDOM(http.responseXML).xpath("//module").filter(function (module) {
return module.getAttribute("name");
});
modules.each(function (module, index) {
if (output) {
miniLOL.content.set("Loading `#{name}`... [#{number}/#{total}]".interpolate({
name: module.getAttribute("name"),
number: index + 1,
total: modules.length
}));
}
if (!miniLOL.module.load(module.getAttribute("name"))) {
miniLOL.error(true);
}
if (miniLOL.error()) {
throw $break;
}
}, this);
},
onFailure: function (http) {
miniLOL.error("Error while loading modules.xml (#{status} - #{statusText})".interpolate(http), true);
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
miniLOL.modules = this.data = {};
}
}));
miniLOL.resource.get("miniLOL.modules").load("resources/modules.xml", true);
},
function () {
if (miniLOL.menu.enabled()) {
miniLOL.menu.change("default");
}
},
function () {
miniLOL.content.set("Checking dependencies...");
try {
miniLOL.module.dependencies.check();
}
catch (e) {
miniLOL.error("`#{module}` requires `#{require}`".interpolate(e), true);
}
}].each(function (callback) {
try {
callback();
}
catch (e) {
miniLOL.error(e.toString(), true);
}
if (miniLOL.error()) {
throw $break;
}
});
if (miniLOL.error()) {
if (!document.body.innerHTML) {
miniLOL.error("Something went wrong, but nobody told me what :(", true);
}
return false;
}
if (miniLOL.config["core"].initialization) {
eval(miniLOL.config["core"].initialization);
}
miniLOL.go(/[#?]./.test(location.href) ? location.href.replace(/^.*[#?]/, '#') : miniLOL.config["core"].homePage);
Event.observe(document, ":refresh", function () {
miniLOL.resource.reload();
});
new PeriodicalExecuter(function () {
Event.fire(document, ":refresh");
}, miniLOL.config["core"].refreshEvery || 360)
Event.fire(document, ":initialized");
Event.stopObserving(document, ":initialized");
miniLOL.initialized = true;
},
error: function (text, major, element) {
if (miniLOL.error.major) {
return true;
}
if (Object.isUndefined(text)) {
return Boolean(miniLOL.error.major);
}
if (Object.isBoolean(text)) {
return miniLOL.error.major = text;
}
element = element || miniLOL.theme.content() || document.body;
$(element).update("<pre>" + text.replace(/<br\/>/g, '\n').escapeHTML() + "</pre>");
if (major) {
miniLOL.error.major = true;
}
Event.fire(document, ":error", { text: text, element: element, major: major });
},
content: {
set: function (data) {
var wrap = { content: data };
Event.fire(document, ":content.set", wrap);
miniLOL.theme.content().update(wrap.content);
},
get: function () {
return miniLOL.theme.content().innerHTML;
}
},
resource: {
set: function (name, resource) {
if (Object.isString(name)) {
miniLOL.resources[name] = resource;
}
else {
miniLOL.resources[name.name] = name;
}
},
get: function (name) {
return miniLOL.resources[name];
},
reload: function (what) {
if (Object.isArray(what)) {
what.each(function (name) {
miniLOL.resource.get(name).reload();
})
}
else if (Object.isString(what)) {
miniLOL.resource.get(name).reload();
}
else {
for (var resource in miniLOL.resources) {
resource.reload()
}
}
}
},
theme: {
style: {
list: {},
load: function (name, path, overload) {
path = path || "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: miniLOL.theme.name });
Event.fire(document, ":theme.style.load", { name: name, path: path, overload: Boolean(overload) });
if (miniLOL.theme.style.exists(name, path)) {
if (overload) {
miniLOL.theme.style.unload(miniLOL.theme.style.list[name], path);
}
else {
return true;
}
}
var file = "#{path}/#{style}.css".interpolate({ path: path, style: name });
var style = miniLOL.utils.includeCSS(file);
if (!style) {
return false;
}
miniLOL.theme.style.list[file] = style;
return true;
},
unload: function (name, path) {
path = path || "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: miniLOL.theme.name });
Event.fire(document, ":theme.style.unload", { name: name, path: path });
var file = "#{path}/#{style}.css".interpolate({ path: path, style: name });
if (miniLOL.theme.style.list[file]) {
miniLOL.theme.style.list[file].remove();
delete miniLOL.theme.style.list[file];
}
},
exists: function (name, path) {
path = path || "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: miniLOL.theme.name });
return Boolean(miniLOL.theme.style.list["#{path}/#{style}.css".interpolate({ path: path, style: name })]);
}
},
template: {
load: function (name, path, check) {
if (!path && !miniLOL.theme.name) {
return 0;
}
path = path || "#{path}/#{theme}".interpolate({
path: miniLOL.theme.path,
theme: miniLOL.theme.name
});
Event.fire(document, ":theme.template.load", { name: name, path: path });
var file = "#{path}/#{name}.xml".interpolate({ path: path, name: name });
if (!check && !Object.isUndefined(miniLOL.theme.template.cache[file])) {
return miniLOL.theme.template.cache[file];
}
new Ajax.Request(file, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, file)) {
return;
}
miniLOL.theme.template.cache[file] = miniLOL.utils.fixDOM(http.responseXML);
},
onFailure: function () {
miniLOL.theme.template.cache[file] = false;
}
});
if (miniLOL.error()) {
return false;
}
return miniLOL.theme.template.cache[file];
},
menu: function () {
return miniLOL.theme.templates.menu;
},
exists: function (name, path) {
return Boolean(miniLOL.theme.template.load(name, path));
},
clearCache: function () {
miniLOL.theme.template.cache = {};
miniLOL.theme.templates = {};
miniLOL.theme.templates.list = {}
miniLOL.theme.templates.list["default"] = {
global: '<div #{attributes}>#{data}</div>',
before: '#{data}',
after: '#{data}',
link: '<div class="#{class}" id="#{id}">#{before}<a href="#{href}" target="#{target}" #{attributes}>#{text}</a>#{after}</div>',
item: '<div class="#{class}" id="#{id}">#{before}<span #{attributes}>#{text}</span>#{after}</div>',
nest: '<div class="#{class}" style="#{style}">#{data}</div>',
data: '<div class="data">#{before}#{data}#{after}</div>'
};
miniLOL.theme.templates.list["table"] = {
global: '<table #{attributes}>#{data}</table>',
before: '#{data}',
after: '#{data}',
link: '<tr><td>#{before}</td><td><a href="#{href}" target="#{target}" #{attributes}>#{text}</a></td><td>#{after}</td></tr>',
item: '<tr><td>#{before}</td><td>#{text}</td><td>#{after}</td></tr>',
nest: '<div class="#{class}" style="#{style}">#{data}</div>',
data: '<div class="data">#{before}#{data}#{after}</div>'
}
}
},
load: function (name, runtime, noInitialization) {
miniLOL.theme.unload();
var oldPath = miniLOL.theme.path;
var oldName = miniLOL.theme.name;
// The syntax to change the theme path is path:theme
var path = name.match(/^(.+?):(.+)$/);
if (path) {
miniLOL.theme.path = path[1];
miniLOL.theme.name = path[2];
}
else {
miniLOL.theme.path = "themes";
miniLOL.theme.name = name;
}
if (miniLOL.theme.name == oldName && miniLOL.theme.path == oldPath) {
return true;
}
var path = "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: name });
Event.fire(document, ":theme.load", { name: name, runtime: Boolean(runtime) });
var error;
// Get the information about the theme and parse the needed data
new Ajax.Request("#{path}/theme.xml".interpolate({ path: path, theme: name }), {
method: "get",
asynchronous: false,
onSuccess: function (http) {
var info = miniLOL.theme.information = {};
var doc = miniLOL.utils.fixDOM(http.responseXML);
info.name = doc.documentElement.getAttribute("name") || "Unknown";
info.author = doc.documentElement.getAttribute("author") || "Anonymous";
info.homepage = doc.documentElement.getAttribute("homepage") || '';
miniLOL.theme.menu.node = doc.documentElement.getAttribute("menu") || "menu";
miniLOL.theme.content.node = doc.documentElement.getAttribute("content") || "body";
try {
var initialize = doc.getElementsByTagName("initialize");
if (initialize.length) {
miniLOL.theme.initialize = new Function(initialize[0].firstChild.nodeValue);
}
else {
miniLOL.theme.initialize = new Function;
}
}
catch (e) {
error = "An error occurred on the theme's initialize function:\n\n"+e.toString();
return false;
}
try {
var finalize = doc.getElementsByTagName("finalize");
if (finalize.length) {
miniLOL.theme.finalize = new Function(finalize[0].firstChild.nodeValue);
}
else {
miniLOL.theme.finalize = new Function;
}
}
catch (e) {
error = "An error occurred on the theme's finalize function:\n\n"+e.toString();
return false;
}
info.styles = [];
doc.xpath("/theme/styles/style").each(function (style) {
info.styles.push(style.getAttribute("name"));
});
doc.xpath("/theme/templates/*").each(function (node) {
miniLOL.theme.templates[node.nodeName] = Element.toObject(node);
}, this);
},
onFailure: function () {
error = "Could not load theme's information.";
}
});
if (error) {
miniLOL.error(error, true);
return false;
}
// Get the html layout and set it
new Ajax.Request("#{path}/template.html".interpolate({ path: path, theme: name }), {
method: "get",
asynchronous: false,
onSuccess: function (http) {
$(document.body).update(http.responseText);
},
onFailure: function () {
error = "Could not load template.html.";
}
});
if (error) {
miniLOL.error(error, true);
return false;
}
miniLOL.theme.information.styles.each(function (style) {
if (!miniLOL.theme.style.load(style, false, true)) {
miniLOL.error("Couldn't load `#{style}` style/".interpolate({
style: style
}), true);
throw $break;
}
});
if (miniLOL.error()) {
return false;
}
if (runtime && miniLOL.initialized) {
miniLOL.menu.change(miniLOL.menu.current, true);
miniLOL.go(location.href);
}
miniLOL.theme.tmp = {};
// Sadly this has some problems.
// I didn't find a way to know if the CSSs have already been applied and the initialize
// may get wrong information from stuff that uses sizes set by the CSS.
//
// So it's the designer's work to hack that shit and get it working, you can see an example
// in the original theme initialize.
//
// If someone knows a way to fix this, please contact me.
// (Already tried XHR and create <style>, but url() would get borked and it only worked in Firefox and Opera)
if (!noInitialization && miniLOL.theme.initialize) {
miniLOL.theme.initialize.call(miniLOL.theme.tmp);
}
Event.fire(document, ":theme.loaded", { name: name, runtime: Boolean(runtime) });
return true;
},
unload: function (noFinalization) {
miniLOL.theme.template.clearCache();
if (!miniLOL.theme.name) {
return;
}
Event.fire(document, ":theme.unload", { name: miniLOL.theme.name });
if (!noFinalization && miniLOL.theme.finalize) {
miniLOL.theme.finalize.call(miniLOL.theme.tmp || {});
}
delete miniLOL.theme.tmp;
$A(miniLOL.theme.information.styles).each(function (style) {
miniLOL.theme.style.unload(style);
});
delete miniLOL.theme.name;
delete miniLOL.theme.initialize;
delete miniLOL.theme.finalize;
delete miniLOL.theme.information;
},
content: function () {
return $(miniLOL.theme.content.node);
},
menu: function () {
return $(miniLOL.theme.menu.node);
},
deprecated: function () {
miniLOL.theme.path = "themes";
miniLOL.theme.content.node = miniLOL.config["core"].contentNode || "body";
miniLOL.theme.menu.node = miniLOL.config["core"].menuNode || "menu";
miniLOL.theme.template.clearCache();
new Ajax.Request("resources/template.html", {
method: "get",
asynchronous: false,
onSuccess: function (http) {
$(document.body).update(http.responseText);
},
onFailure: function () {
$(document.body).update('<div id="menu"></div><div id="body"></div>');
}
});
miniLOL.utils.includeCSS("resources/style.css");
miniLOL.theme.template.clearCache();
return true;
}
},
menu: {
set: function (data) {
if (!miniLOL.menu.enabled()) {
return;
}
miniLOL.theme.menu().update(data);
},
get: function (name, layer) {
layer = layer || 0;
if (!miniLOL.menu.enabled()) {
return "";
}
name = name || "default";
if (!miniLOL.menu.exists(name)) {
return null;
}
return miniLOL.menu.parse(miniLOL.menus[name], layer);
},
change: function (name, force) {
if (name == miniLOL.menu.current && !force) {
return;
}
var content = miniLOL.menu.get(name);
if (content) {
miniLOL.menu.set(content);
miniLOL.menu.current = name;
}
else {
var error = "The menu `#{name}` doesn't exist.".interpolate({
name: name
});
miniLOL.error(error, true);
return error;
}
Event.fire(document, ":menu.change", miniLOL.menus[name]);
},
enabled: function () {
return Boolean(miniLOL.menus["default"]);
},
exists: function (name) {
return Boolean(miniLOL.menus[name]);
},
parse: function (menu, layer) {
layer = layer || 0;
var template = miniLOL.theme.template.menu();
if (!template || !menu) {
if (miniLOL.error()) {
return false;
}
}
var first = true;
var output = "";
$A(menu.childNodes).each(function (e) {
switch (e.nodeType) {
case Node.ELEMENT_NODE:
if (e.nodeName == "menu") {
output += miniLOL.menu.parsers.layer(template, layer).menu.interpolate({
data: miniLOL.menu.parse(e, layer)
});
}
else if (e.nodeName == "item") {
output += miniLOL.menu.parsers.item(e, template, layer)
}
else {
output += miniLOL.menu.parsers.other(e, template);
}
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
if (!first) {
output += e.nodeValue;
}
first = false;
break;
}
});
if (!output.isEmpty()) {
if (layer == 0) {
return miniLOL.menu.parsers.layer(template, layer).menu.interpolate({
data: output
});
}
else {
return output;
}
}
else {
return "";
}
},
parsers: {
layer: function (template, layer) {
var result = {
menu: "",
item: ""
};
if (template) {
result = Object.extend(result, template.layers["_" + layer] || template.layers["default"] || {});
if (!result.menu) {
result.menu = "#{data}";
}
if (!result.item) {
result.item = '<a href="#{href}" #{attributes}>#{text}</a> ';
}
}
return result;
},
item: function (element, template, layer) {
var item = element.cloneNode(true);
var itemClass = item.getAttribute("class") || ""; item.removeAttribute("class");
var itemId = item.getAttribute("id") || ""; item.removeAttribute("id");
var itemHref = item.getAttribute("href") || ""; item.removeAttribute("href");
return miniLOL.menu.parsers.layer(template, layer).item.interpolate(Object.extend(Object.fromAttributes(item.attributes), {
"class": itemClass,
id: itemId,
href: itemHref,
attributes: String.fromAttributes(item.attributes),
text: miniLOL.utils.getFirstText(element.childNodes),
data: miniLOL.menu.parse(element, layer + 1)
}));
},
other: function (data, template) {
if (!data || !template) {
return "";
}
var text = template[data.nodeName];
if (!text) {
return "";
}
var output = "";
var outputs = {};
$A(data.childNodes).each(function (e) {
if (e.nodeType == Node.ELEMENT_NODE) {
outputs[e.nodeName] = miniLOL.menu.parsers.other(e, template);
}
});
outputs["text"] = miniLOL.utils.getFirstText(data.childNodes);
return text.interpolate(Object.extend(outputs, Object.fromAttributes(data.attributes)));
}
}
},
page: {
get: function (name, queries, url) {
miniLOL.content.set(miniLOL.config["core"].loadingMessage);
Event.fire(document, ":page.get", { name: name, queries: queries });
var page = miniLOL.pages.data[name];
var type = queries.type;
if (!page) {
miniLOL.content.set("404 - Not Found");
return false;
}
if (page.getAttribute("alias")) {
if (typeof queries[name] != "string") {
delete queries[name];
}
delete queries.page;
if (!queries.title && page.getAttribute("title")) {
queries.title = encodeURIComponent(page.getAttribute("title"));
}
var queries = Object.toQueryString(queries);
if (queries) {
queries = "&"+queries;
}
page = page.getAttribute("alias");
if (!page.isURL() && page.charAt(0) != "#") {
page = "#"+page;
}
return miniLOL.go(page+queries);
}
if (Object.isUndefined(type)) {
type = page.getAttribute("type");
}
if (url) {
var data = {};
Object.extend(data, miniLOL.config["core"]);
Object.extend(data, queries);
document.title = (
queries.title
|| page.getAttribute("title")
|| miniLOL.config["core"].siteTitle
).interpolate(data);
}
if (miniLOL.pages.cache[name]) {
if (type) {
miniLOL.content.set(miniLOL.resource.get("miniLOL.functions").render(type, miniLOL.pages.cache[name], queries));
}
else {
miniLOL.content.set(miniLOL.pages.cache[name]);
}
return true;
}
var pageArguments = page.getAttribute("arguments");
if (pageArguments) {
pageArguments = pageArguments.replace(/[ ,]+/g, "&").toQueryParams();
for (var key in pageArguments) {
if (queries[key] == null) {
queries[key] = pageArguments[key];
}
}
}
var output = miniLOL.page.parse(page);
miniLOL.pages.cache[name] = output;
if (type) {
output = miniLOL.resource.get("miniLOL.functions").render(type, output, queries);
}
miniLOL.content.set(output);
return true;
},
parse: function (page, data) {
var output = "";
$A(page.childNodes).each(function (e) {
switch (e.nodeType) {
case Node.ELEMENT_NODE:
if (Object.isFunction(miniLOL.page.parsers[e.nodeName])) {
output += miniLOL.page.parsers[e.nodeName](e, data);
}
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
output += e.nodeValue;
break;
}
});
return output;
},
parsers: {
list: function (element, data) {
var list = element.cloneNode(false);
data = data || [element];
var listBefore = list.getAttribute("before") || data[0].getAttribute("before") || ""; list.removeAttribute("before");
var listAfter = list.getAttribute("after") || data[0].getAttribute("after") || ""; list.removeAttribute("after");
var listArgs = list.getAttribute("arguments") || data[0].getAttribute("arguments") || ""; list.removeAttribute("arguments");
var listType = list.getAttribute("type") || data[0].getAttribute("type") || ""; list.removeAttribute("type");
var listMenu = list.getAttribute("menu") || data[0].getAttribute("menu"); list.removeAttribute("menu");
var listTemplate = list.getAttribute("template"); list.removeAttribute("template");
if (!miniLOL.theme.templates.list[listTemplate]) {
listTemplate = "default";
}
var output = "";
$A(element.childNodes).each(function (e) {
if (e.nodeType == Node.ELEMENT_NODE) {
if (e.nodeName == "link") {
var link = e.cloneNode(true);
var href = link.getAttribute("href"); link.removeAttribute("href");
var target = link.getAttribute("target"); link.removeAttribute("target");
var text = link.getAttribute("text") || (link.firstChild ? link.firstChild.nodeValue : href);
var before = link.getAttribute("before") || listBefore || ""; link.removeAttribute("before");
var after = link.getAttribute("after") || listAfter || ""; link.removeAttribute("after");
var domain = link.getAttribute("domain") || ""; link.removeAttribute("domain");
var args = link.getAttribute("arguments") || listArgs; link.removeAttribute("arguments");
var menu = link.getAttribute("menu") || listMenu; link.removeAttribute("menu");
var title = link.getAttribute("title") || ""; link.removeAttribute("title");
var out = href.isURL();
var linkClass = link.getAttribute("class") || ""; link.removeAttribute("class");
var linkId = link.getAttribute("id") || ""; link.removeAttribute("id");
if (target || out) {
href = (!out) ? "data/" + href : href;
target = target || "_blank";
}
else {
var ltype = link.getAttribute("type") || listType || ""; link.removeAttribute("type");
if (domain == "in" || href.charAt(0) == "#") {
if (href.charAt(0) != "#") {
href = "#" + href;
}
}
else {
href = "#page=" + href;
}
args = args ? "&"+args.replace(/[ ,]+/g, "&") : "";
ltype = ltype ? "&type="+ltype : "";
menu = miniLOL.menu.enabled() && menu ? "&menu="+menu : "";
target = "";
if (title) {
title = title.interpolate({
text: text,
href: href
});
title = "&title="+encodeURIComponent(title);
}
href = href + args + ltype + menu + title;
}
output += miniLOL.theme.templates.list[listTemplate].link.interpolate(Object.extend(Object.fromAttributes(link.attributes), {
"class": linkClass,
id: linkId,
attributes: String.fromAttributes(link.attributes),
before: miniLOL.theme.templates.list[listTemplate].before.interpolate({ data: before }),
after: miniLOL.theme.templates.list[listTemplate].after.interpolate({ data: after }),
href: href,
target: target,
text: text,
title: title
}));
}
else if (e.nodeName == "item") {
var item = e.cloneNode(true);
var text = item.getAttribute("text") || (item.firstChild ? item.firstChild.nodeValue : "")
var before = item.getAttribute("before") || listBefore || ""; item.removeAttribute("before");
var after = item.getAttribute("after") || listAfter || ""; item.removeAttribute("after");
var itemClass = item.getAttribute("class") || ""; item.removeAttribute("class");
var itemId = item.getAttribute("id") || ""; item.removeAttribute("id");
output += miniLOL.theme.templates.list[listTemplate].item.interpolate(Object.extend(Object.fromAttributes(item.attributes), {
"class": itemClass,
id: itemId,
attributes: String.fromAttributes(item.attributes),
before: miniLOL.theme.templates.list[listTemplate].before.interpolate({ data: before }),
after: miniLOL.theme.templates.list[listTemplate].after.interpolate({ data: after }),
text: text
}));
}
else if (e.nodeName == "list") {
output += miniLOL.page.parsers.list(e, [element]);
}
else if (e.nodeName == "nest") {
toParse = e.cloneNode(true);
var before = e.getAttribute("before") || listBefore || "";
var after = e.getAttribute("after") || listAfter || "";
output += miniLOL.theme.templates.list[listTemplate].nest.interpolate({
"class": e.getAttribute("class") || "",
style: e.getAttribute("style") || "",
before: miniLOL.theme.templates.list[listTemplate].before.interpolate({ data: before }),
after: miniLOL.theme.templates.list[listTemplate].after.interpolate({ data: after }),
data: miniLOL.page.parse(toParse, [element])
});
}
}
else if (e.nodeType == Node.CDATA_SECTION_NODE || e.nodeType == Node.TEXT_NODE) {
if (e.nodeValue.isEmpty()) {
return;
}
output += miniLOL.theme.templates.list[listTemplate].data.interpolate({
data: e.nodeValue
});
}
});
return miniLOL.theme.templates.list[listTemplate].global.interpolate(Object.extend(Object.fromAttributes(list.attributes), {
attributes: String.fromAttributes(list.attributes),
data: output
}));
},
include: function (element, data) {
var include = element.cloneNode(false);
var href = element.getAttribute("href"); element.removeAttribute("href");
var update = element.getAttribute("update"); element.removeAttribute("update");
var domain = location.href.match(/^http(s)?:\/\/(.*?)([^\.]\.\w+)/)[3];
var matches = href.match(/^http(s)?:\/\/(.*?)([^\.]\.\w+)/);
var output = "";
if (matches && matches[3] != domain) {
output = '<iframe src="#{href}" #{attributes}></iframe>'.interpolate({
href: href,
attributes: Object.fromAttributes(element.attributes)
});
}
else {
output = "<div ";
}
return "";
}
},
load: function (path, queries, url) {
miniLOL.content.set(miniLOL.config["core"].loadingMessage);
Event.fire(document, ":page.load", { path: path, queries: queries });
if (url) {
document.title = (
queries.title
|| miniLOL.config["core"].siteTitle
).interpolate(Object.extend(Object.extend({}, miniLOL.config["core"]), queries));
}
new Ajax.Request("data/#{path}?#{queries}".interpolate({ path: path, queries: Object.toQueryString(queries) }), {
method: "get",
onSuccess: function (http) {
if (queries.type) {
miniLOL.content.set(miniLOL.resource.get("miniLOL.functions").render(queries.type, http.responseText, queries));
}
else {
miniLOL.content.set(http.responseText);
}
Event.fire(document, ":page.loaded", http);
Event.fire(document, ":go", url.getHashFragment());
},
onFailure: function (http) {
miniLOL.content.set("#{status} - #{statusText}".interpolate(http));
Event.fire(document, ":page.loaded", http);
}
});
}
},
module: {
create: function (name, obj) {
if (!obj) {
miniLOL.error("Like, do I know how this module is done?", true);
return false;
}
obj.name = name;
obj.root = "#{path}/#{module}".interpolate({
path: miniLOL.module.path,
module: name
});
if (!obj.type) {
obj.type = "active";
}
if (!obj.execute) {
obj.execute = new Function;
}
for (var func in obj) {
if (Object.isFunction(obj[func])) {
obj[func] = obj[func].bind(obj)
}
}
if (obj.initialize) {
try {
if (obj.initialize() === false) {
if (miniLOL.error()) {
return false;
}
throw new Error("An error occurred while initializing the module.");
}
}
catch (e) {
e.fileName = "#{root}/#{path}/#{module}/main.js".interpolate({
root: miniLOL.path,
path: miniLOL.module.path,
module: name
});
throw e;
}
}
miniLOL.modules[name] = obj;
$A(obj.aliases).each(function (alias) {
miniLOL.modules[alias] = obj;
});
Event.fire(document, ":module.create", obj);
},
execute: function (name, vars, output) {
if (!name) {
miniLOL.error("What module should be executed?");
return false;
}
if (!miniLOL.module.exists(name)) {
if (output) {
miniLOL.error("The module `#{name}` isn't loaded.".interpolate({ name: name }), true);
}
return false;
}
if (output) {
miniLOL.content.set(miniLOL.config["core"].loadingMessage);
var data = {};
Object.extend(data, miniLOL.config["core"]);
Object.extend(data, vars);
document.title = (
vars.title
|| miniLOL.module.get(name).title
|| miniLOL.config["core"].siteTitle
).interpolate(data);
}
vars = (Object.isArray(vars)) ? vars : [vars];
Event.fire(document, ":module.execute", { name: name, arguments: vars });
var result;
try {
result = miniLOL.module.get(name).execute.apply(miniLOL.module.get(name), vars);
}
catch (e) {
e.fileName = "#{root}/#{path}/#{module}/main.js".interpolate({
root: miniLOL.path,
path: miniLOL.module.path,
module: name
});
miniLOL.error("An error occurred while executing the module `#{name}`\n\n#{file} @ #{line}:\n#{error}".interpolate({
name: name,
file: e.fileName,
line: e.lineNumber,
error: e.toString()
}), true);
return false;
}
Event.fire(document, ":module.executed", { name: name, arguments: vars, result: result });
if (Object.isUndefined(result)) {
result = true;
}
return result;
},
load: function (name) {
Event.fire(document, ":module.load", name);
try {
try {
miniLOL.utils.require("#{path}/#{module}/main.min.js".interpolate({
path: miniLOL.module.path,
module: name
}));
}
catch (e) {
if (e.http) {
miniLOL.utils.require("#{path}/#{module}/main.js".interpolate({
path: miniLOL.module.path,
module: name
}));
}
else {
throw e;
}
}
if (miniLOL.error()) {
return false;
}
if (!miniLOL.module.exists(name)) {
throw new Error("Something went wrong while loading the module `#{name}`.".interpolate({
name: name
}));
}
Event.fire(document, ":module.loaded", name);
return true;
}
catch (e) {
miniLOL.error("An error occurred while loading the module `#{name}`\n\n#{root}/#{file} @ #{line}:\n\n#{error}".interpolate({
name: name,
root: miniLOL.path,
file: e.fileName,
line: e.lineNumber,
error: e.toString()
}), true);
return false;
}
},
get: function (name) {
return miniLOL.modules[name];
},
exists: function (name) {
return Boolean(miniLOL.module.get(name));
},
dependencies: {
check: function () {
for (var module in miniLOL.modules) {
var dependencies = miniLOL.module.get(module).dependencies;
if (dependencies) {
for (var i = 0; i < dependencies.length; i++) {
if (!miniLOL.module.get(dependencies[i])) {
throw { module: module, require: dependencies[i] };
}
}
}
}
return true;
},
needs: function (name, callback, context, wait) {
if (miniLOL.module.get(name)) {
callback.call(context || window);
}
else {
setTimeout(function () {
miniLOL.module.dependencies.needs(name, callback, context);
}, wait || 10);
}
}
}
},
go: function (url, again) {
if (url.isURL()) {
if (!url.startsWith(miniLOL.path)) {
location.href = url;
}
}
else {
if (url.charAt(0) != '#') {
url = '#' + url;
}
}
var queries = url.toQueryParams();
var matches = url.match(/#(([^=&]*)&|([^=&]*)$)/); // hate WebKit so much.
var result = false;
if (queries.menu) {
miniLOL.menu.change(queries.menu);
}
if (matches) {
queries.page = matches[2] || matches[3];
if (queries.page) {
result = miniLOL.page.get(queries.page, queries, url);
}
else if (!again) {
result = miniLOL.go("#{page}&#{queries}".interpolate({
page: miniLOL.config["core"].homePage,
queries: Object.toQueryString(queries)
}), true);
}
}
else if (queries.module) {
result = miniLOL.module.execute(queries.module, queries, true);
}
else if (queries.page) {
var page = queries.page; delete queries.page;
miniLOL.page.load(page, queries, url);
}
else {
result = miniLOL.go(miniLOL.config["core"].homePage);
}
if (result) {
Event.fire(document, ":go", url.getHashFragment());
}
return result;
},
utils: {
getElementById: function (id) {
var result;
$A(this.getElementsByTagName("*")).each(function (element) {
if (element.getAttribute("id") == id) {
result = element;
throw $break;
}
});
return result;
},
xpath: function (query) {
var result = [];
var tmp;
if (Prototype.Browser.IE) {
tmp = this.real.selectNodes(query);
for (var i = 0; i < tmp.length; i++) {
result.push(tmp.item(i));
}
}
else {
tmp = this.evaluate(query, this, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < tmp.snapshotLength; i++) {
result.push(tmp.snapshotItem(i));
}
}
return result;
},
fixDOM: function (obj) {
if (!obj) {
return;
}
if (Prototype.Browser.IE) {
obj = { real: obj };
obj.documentElement = obj.real.documentElement;
obj.getElementsByTagName = function (name) {
return this.real.getElementsByTagName(name);
};
obj.getElementById = function (id) {
return miniLOL.utils.getElementById.call(this.real, id);
}
obj.real.setProperty("SelectionLanguage", "XPath");
}
else if (!Prototype.Browser.Good) {
obj.getElementById = miniLOL.utils.getElementById;
}
obj.xpath = miniLOL.utils.xpath;
return obj;
},
checkXML: function (xml, path) {
var error = false;
if (!xml) {
error = "There's a syntax error.";
}
if (xml.documentElement.nodeName == "parsererror") {
error = xml.documentElement.textContent;
}
if (path && error) {
miniLOL.error("Error while parsing #{path}\n\n#{error}".interpolate({
path: path,
error: error
}), true);
return error;
}
return error;
},
getFirstText: function (elements) {
var result = "";
(Object.isArray(elements) ? elements : $A(elements)).each(function (element) {
switch (element.nodeType) {
case Node.ELEMENT_NODE:
throw $break;
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
if (!element.nodeValue.isEmpty()) {
result = element.nodeValue.strip();
throw $break;
}
break;
}
});
return result;
},
exists: function (path) {
var result = false;
new Ajax.Request(path, {
method: "head",
asynchronous: false,
onSuccess: function () {
result = true;
}
});
return result;
},
includeCSS: function (path) {
var style;
if (style = miniLOL.theme.style.list[path]) {
return style;
}
else if (style = $$("link").find(function (css) { return css.getAttribute("href") == path })) {
miniLOL.theme.style.list[path] = style;
return style;
}
else if (style = miniLOL.utils.exists(path)) {
style = new Element("link", {
rel: "stylesheet",
href: path,
type: "text/css"
});
$$("head")[0].insert(style);
Event.fire(document, ":css.include", path);
return style;
}
else {
return false;
}
},
css: function (style, id) {
var css = new Element("style", { type: "text/css" }).update(style);
if (id) {
css.setAtribute("id", id);
}
$$("head").first().appendChild(css);
Event.fire(document, ":css.create", css);
return css;
},
execute: function (path) {
var result;
var error;
new Ajax.Request(path, {
method: "get",
asynchronous: false,
evalJS: false,
onSuccess: function (http) {
try {
result = window.eval(http.responseText);
}
catch (e) {
error = e;
error.fileName = path;
error.lineNumber -= 5;
}
},
onFailure: function (http) {
error = new Error("Failed to retrieve `#{file}` (#{status} - #{statusText}).".interpolate({
file: path,
status: http.status,
statusText: http.statusText
}));
error.fileName = path;
error.lineNumber = 0;
}
});
if (error) {
throw error;
}
return result;
},
include: function (path) {
var result = false;
new Ajax.Request(path, {
method: "get",
asynchronous: false,
evalJS: false,
onSuccess: function (http) {
try {
window.eval(http.responseText);
result = true;
} catch (e) {
result = false;
}
}
});
return result;
},
require: function (path) {
var error = false;
new Ajax.Request(path, {
method: "get",
asynchronous: false,
evalJS: false,
onSuccess: function (http) {
try {
window.eval(http.responseText);
} catch (e) {
error = e;
error.fileName = path;
error.lineNumber -= 5;
}
},
onFailure: function (http) {
error = new Error("Failed to retrieve `#{file}` (#{status} - #{statusText}).".interpolate({
file: path,
status: http.status,
statusText: http.statusText
}));
error.fileName = path;
error.lineNumber = 0;
error.http = {
status: http.status,
text: http.statusText
}
}
});
if (error) {
throw error;
}
return true;
}
}
}
miniLOL.utils.require("system/Resource.js");
miniLOL.utils.require("system/preparation.js");
| system/miniLOL.js | /****************************************************************************
* Copyleft meh. [http://meh.doesntexist.org | [email protected]] *
* *
* This file is part of miniLOL. *
* *
* miniLOL 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. *
* *
* miniLOL 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 miniLOL. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************/
/*
* miniLOL is a Javascript/XML based CMS, thus, being in the XXI century,
* I pretend those two standards to be respected.
*
* Get a real browser, get Firefox.
*/
miniLOL = {
version: "1.2",
initialize: function () {
if (miniLOL.initialized) {
throw new Error("miniLOL has already been initialized.");
}
miniLOL.initialized = false;
miniLOL.path = location.href.match(/^(.*?)\/[^\/]*?(#|$)/)[1];
miniLOL.resources = {};
miniLOL.tmp = {};
Event.observe(document, ":go", (miniLOL.tmp.fixScroll = function () {
miniLOL.theme.content().scrollTo();
}));
[function () {
Event.observe(document, ":resource.loaded", function (event) {
if (event.memo.resource.name != "miniLOL.config" || event.memo.arguments[0] != "resources/config.xml") {
return;
}
if (!miniLOL.config["core"]) {
miniLOL.config["core"] = {};
}
if (!miniLOL.config["core"].siteTitle) {
miniLOL.config["core"].siteTitle = "miniLOL #{version}".interpolate(miniLOL);
}
if (!miniLOL.config["core"].loadingMessage) {
miniLOL.config["core"].loadingMessage = "Loading...";
}
if (!miniLOL.config["core"].homePage) {
miniLOL.config["core"].homePage = "#home";
}
else {
if (miniLOL.config["core"].homePage.charAt(0) != '#' && !miniLOL.config["core"].homePage.isURL()) {
miniLOL.config["core"].homePage = '#' + miniLOL.config["core"].homePage;
}
}
if (!document.title) {
document.title = miniLOL.config["core"].siteTitle;
}
});
miniLOL.resource.set(new miniLOL.Resource("miniLOL.config", {
initialize: function () {
miniLOL.config = this.data;
},
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
var dom = miniLOL.utils.fixDOM(http.responseXML).documentElement;
var domain = dom.getAttribute("domain") || "core";
var config = miniLOL.config[domain] || {};
miniLOL.config[domain] = Object.extend(config, Element.toObject(dom));
}.bind(this),
onFailure: function (http) {
miniLOL.error("miniLOL.config: Error while loading #{path} (#{status} - #{statusText})".interpolate({
path: path,
status: http.status,
statusText: http.statusText
}), true);
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
this.data = miniLOL.config = {};
}
}));
miniLOL.resource.get("miniLOL.config").load("resources/config.xml");
$(document.body).update(miniLOL.config["core"].loadingMessage);
},
function () {
miniLOL.resource.set(new miniLOL.Resource("miniLOL.menus", {
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
var response = miniLOL.utils.fixDOM(http.responseXML);
miniLOL.menus["default"] = response.getElementById("default");
$A(response.documentElement.childNodes).each(function (menu) {
if (menu.nodeType != Node.ELEMENT_NODE) {
return;
}
var id = menu.getAttribute("id");
if (!id && !miniLOL.menus["default"]) {
miniLOL.menus["default"] = menu;
}
else {
miniLOL.menus[id] = menu;
}
});
if (!miniLOL.menus["default"]) {
miniLOL.error("Error while analyzing menus.xml\n\nNo default menu was found.", true);
return;
}
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
this.data = miniLOL.menus = {};
}
}));
miniLOL.resource.get("miniLOL.menus").load("resources/menus.xml");
},
function () {
miniLOL.resource.set(new miniLOL.Resource("miniLOL.pages", {
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
miniLOL.utils.fixDOM(http.responseXML).xpath('//page').each(function (page) {
var id = page.getAttribute("id");
delete miniLOL.pages.cache[id];
miniLOL.pages.data[id] = page;
});
},
onFailure: function (http) {
miniLOL.error("miniLOL.pages: Error while loading #{path} (#{status} - #{statusText})".interpolate({
path: path,
status: http.status,
statusText: http.statusText
}, true));
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
miniLOL.pages = this.data = {
data: {},
cache: {}
};
}
}));
if (miniLOL.utils.exists("resources/pages.xml")) {
miniLOL.resource.get("miniLOL.pages").load("resources/pages.xml");
}
},
function () {
miniLOL.resource.set(new miniLOL.Resource("miniLOL.functions", {
load: function (path) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
miniLOL.utils.fixDOM(http.responseXML).xpath('//function').each(function (func) {
try {
miniLOL.functions[func.getAttribute("name")] = new Function(
"var text = arguments[0]; var args = arguments[1]; arguments = args; #{code}; return text;".interpolate({
code: func.firstChild.nodeValue
})
);
}
catch (e) {
miniLOL.error("Error while creating `#{name}` wrapper from #{path}:\n\n#{error}".interpolate({
name: func.getAttribute("name"),
path: path,
error: e.toString()
}), true);
return;
}
});
},
onFailure: function (http) {
miniLOL.error("miniLOL.functions: Error while loading #{path} (#{status} - #{statusText})".interpolate({
path: path,
status: http.status,
statusText: http.statusText
}), true);
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
miniLOL.functions = this.data = {};
},
render: function (types, content, args) {
types.split(/\s*,\s*/).each(function (type) {
if (Object.isFunction(this.data[type])) {
content = this.data[type](content, args);
}
}, this);
return content;
}
}));
miniLOL.resource.get("miniLOL.functions").load("resources/functions.xml");
},
function () {
$$("link").each(function (css) {
miniLOL.theme.style.list[css.getAttribute("href")] = css;
});
if (miniLOL.config["core"].theme) {
miniLOL.error(!miniLOL.theme.load(miniLOL.config["core"].theme));
miniLOL.theme.template.menu();
}
else {
miniLOL.error(!miniLOL.theme.deprecated());
}
},
function () {
if (miniLOL.menu.enabled()) {
miniLOL.menu.set(miniLOL.config["core"].loadingMessage);
}
},
function () {
miniLOL.content.set("Loading modules...");
miniLOL.resource.set(new miniLOL.Resource("miniLOL.modules", {
load: function (path, output) {
new Ajax.Request(path, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, path)) {
return;
}
miniLOL.module.path = http.responseXML.documentElement.getAttribute("path") || 'modules';
var modules = miniLOL.utils.fixDOM(http.responseXML).xpath("//module").filter(function (module) {
return module.getAttribute("name");
});
modules.each(function (module, index) {
if (output) {
miniLOL.content.set("Loading `#{name}`... [#{number}/#{total}]".interpolate({
name: module.getAttribute("name"),
number: index + 1,
total: modules.length
}));
}
if (!miniLOL.module.load(module.getAttribute("name"))) {
miniLOL.error(true);
}
if (miniLOL.error()) {
throw $break;
}
}, this);
},
onFailure: function (http) {
miniLOL.error("Error while loading modules.xml (#{status} - #{statusText})".interpolate(http), true);
}
});
if (miniLOL.error()) {
return false;
}
return true;
},
clear: function () {
miniLOL.modules = this.data = {};
}
}));
miniLOL.resource.get("miniLOL.modules").load("resources/modules.xml", true);
},
function () {
if (miniLOL.menu.enabled()) {
miniLOL.menu.change("default");
}
},
function () {
miniLOL.content.set("Checking dependencies...");
try {
miniLOL.module.dependencies.check();
}
catch (e) {
miniLOL.error("`#{module}` requires `#{require}`".interpolate(e), true);
}
}].each(function (callback) {
try {
callback();
}
catch (e) {
miniLOL.error(e.toString(), true);
}
if (miniLOL.error()) {
throw $break;
}
});
if (miniLOL.error()) {
if (!document.body.innerHTML) {
miniLOL.error("Something went wrong, but nobody told me what :(", true);
}
return false;
}
if (miniLOL.config["core"].initialization) {
eval(miniLOL.config["core"].initialization);
}
miniLOL.go(/[#?]./.test(location.href) ? location.href.replace(/^.*[#?]/, '#') : miniLOL.config["core"].homePage);
Event.observe(document, ":refresh", function () {
miniLOL.resource.reload();
});
new PeriodicalExecuter(function () {
Event.fire(document, ":refresh");
}, miniLOL.config["core"].refreshEvery || 360)
Event.fire(document, ":initialized");
Event.stopObserving(document, ":initialized");
miniLOL.initialized = true;
},
error: function (text, major, element) {
if (miniLOL.error.major) {
return true;
}
if (Object.isUndefined(text)) {
return Boolean(miniLOL.error.major);
}
if (Object.isBoolean(text)) {
return miniLOL.error.major = text;
}
element = element || miniLOL.theme.content() || document.body;
$(element).update("<pre>" + text.replace(/<br\/>/g, '\n').escapeHTML() + "</pre>");
if (major) {
miniLOL.error.major = true;
}
Event.fire(document, ":error", { text: text, element: element, major: major });
},
content: {
set: function (data) {
var wrap = { content: data };
Event.fire(document, ":content.set", wrap);
miniLOL.theme.content().update(wrap.content);
},
get: function () {
return miniLOL.theme.content().innerHTML;
}
},
resource: {
set: function (name, resource) {
if (Object.isString(name)) {
miniLOL.resources[name] = resource;
}
else {
miniLOL.resources[name.name] = name;
}
},
get: function (name) {
return miniLOL.resources[name];
},
reload: function (what) {
if (Object.isArray(what)) {
what.each(function (name) {
miniLOL.resource.get(name).reload();
})
}
else if (Object.isString(what)) {
miniLOL.resource.get(name).reload();
}
else {
for (var resource in miniLOL.resources) {
resource.reload()
}
}
}
},
theme: {
style: {
list: {},
load: function (name, path, overload) {
path = path || "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: miniLOL.theme.name });
Event.fire(document, ":theme.style.load", { name: name, path: path, overload: Boolean(overload) });
if (miniLOL.theme.style.exists(name, path)) {
if (overload) {
miniLOL.theme.style.unload(miniLOL.theme.style.list[name], path);
}
else {
return true;
}
}
var file = "#{path}/#{style}.css".interpolate({ path: path, style: name });
var style = miniLOL.utils.includeCSS(file);
if (!style) {
return false;
}
miniLOL.theme.style.list[file] = style;
return true;
},
unload: function (name, path) {
path = path || "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: miniLOL.theme.name });
Event.fire(document, ":theme.style.unload", { name: name, path: path });
var file = "#{path}/#{style}.css".interpolate({ path: path, style: name });
if (miniLOL.theme.style.list[file]) {
miniLOL.theme.style.list[file].remove();
delete miniLOL.theme.style.list[file];
}
},
exists: function (name, path) {
path = path || "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: miniLOL.theme.name });
return Boolean(miniLOL.theme.style.list["#{path}/#{style}.css".interpolate({ path: path, style: name })]);
}
},
template: {
load: function (name, path, check) {
if (!path && !miniLOL.theme.name) {
return 0;
}
path = path || "#{path}/#{theme}".interpolate({
path: miniLOL.theme.path,
theme: miniLOL.theme.name
});
Event.fire(document, ":theme.template.load", { name: name, path: path });
var file = "#{path}/#{name}.xml".interpolate({ path: path, name: name });
if (!check && !Object.isUndefined(miniLOL.theme.template.cache[file])) {
return miniLOL.theme.template.cache[file];
}
new Ajax.Request(file, {
method: "get",
asynchronous: false,
onSuccess: function (http) {
if (miniLOL.utils.checkXML(http.responseXML, file)) {
return;
}
miniLOL.theme.template.cache[file] = miniLOL.utils.fixDOM(http.responseXML);
},
onFailure: function () {
miniLOL.theme.template.cache[file] = false;
}
});
if (miniLOL.error()) {
return false;
}
return miniLOL.theme.template.cache[file];
},
menu: function () {
return miniLOL.theme.templates.menu;
},
exists: function (name, path) {
return Boolean(miniLOL.theme.template.load(name, path));
},
clearCache: function () {
miniLOL.theme.template.cache = {};
miniLOL.theme.templates = {};
miniLOL.theme.templates.list = {}
miniLOL.theme.templates.list["default"] = {
global: '<div #{attributes}>#{data}</div>',
before: '#{data}',
after: '#{data}',
link: '<div class="#{class}" id="#{id}">#{before}<a href="#{href}" target="#{target}" #{attributes}>#{text}</a>#{after}</div>',
item: '<div class="#{class}" id="#{id}">#{before}<span #{attributes}>#{text}</span>#{after}</div>',
nest: '<div class="#{class}" style="#{style}">#{data}</div>',
data: '<div class="data">#{before}#{data}#{after}</div>'
};
miniLOL.theme.templates.list["table"] = {
global: '<table #{attributes}>#{data}</table>',
before: '#{data}',
after: '#{data}',
link: '<tr><td>#{before}</td><td><a href="#{href}" target="#{target}" #{attributes}>#{text}</a></td><td>#{after}</td></tr>',
item: '<tr><td>#{before}</td><td>#{text}</td><td>#{after}</td></tr>',
nest: '<div class="#{class}" style="#{style}">#{data}</div>',
data: '<div class="data">#{before}#{data}#{after}</div>'
}
}
},
load: function (name, runtime, noInitialization) {
miniLOL.theme.unload();
var oldPath = miniLOL.theme.path;
var oldName = miniLOL.theme.name;
// The syntax to change the theme path is path:theme
var path = name.match(/^(.+?):(.+)$/);
if (path) {
miniLOL.theme.path = path[1];
miniLOL.theme.name = path[2];
}
else {
miniLOL.theme.path = "themes";
miniLOL.theme.name = name;
}
if (miniLOL.theme.name == oldName && miniLOL.theme.path == oldPath) {
return true;
}
var path = "#{path}/#{theme}".interpolate({ path: miniLOL.theme.path, theme: name });
Event.fire(document, ":theme.load", { name: name, runtime: Boolean(runtime) });
var error;
// Get the information about the theme and parse the needed data
new Ajax.Request("#{path}/theme.xml".interpolate({ path: path, theme: name }), {
method: "get",
asynchronous: false,
onSuccess: function (http) {
var info = miniLOL.theme.information = {};
var doc = miniLOL.utils.fixDOM(http.responseXML);
info.name = doc.documentElement.getAttribute("name") || "Unknown";
info.author = doc.documentElement.getAttribute("author") || "Anonymous";
info.homepage = doc.documentElement.getAttribute("homepage") || '';
miniLOL.theme.menu.node = doc.documentElement.getAttribute("menu") || "menu";
miniLOL.theme.content.node = doc.documentElement.getAttribute("content") || "body";
try {
var initialize = doc.getElementsByTagName("initialize");
if (initialize.length) {
miniLOL.theme.initialize = new Function(initialize[0].firstChild.nodeValue);
}
else {
miniLOL.theme.initialize = new Function;
}
}
catch (e) {
error = "An error occurred on the theme's initialize function:\n\n"+e.toString();
return false;
}
try {
var finalize = doc.getElementsByTagName("finalize");
if (finalize.length) {
miniLOL.theme.finalize = new Function(finalize[0].firstChild.nodeValue);
}
else {
miniLOL.theme.finalize = new Function;
}
}
catch (e) {
error = "An error occurred on the theme's finalize function:\n\n"+e.toString();
return false;
}
info.styles = [];
doc.xpath("/theme/styles/style").each(function (style) {
info.styles.push(style.getAttribute("name"));
});
doc.xpath("/theme/templates/*").each(function (node) {
miniLOL.theme.templates[node.nodeName] = Element.toObject(node);
}, this);
},
onFailure: function () {
error = "Could not load theme's information.";
}
});
if (error) {
miniLOL.error(error, true);
return false;
}
// Get the html layout and set it
new Ajax.Request("#{path}/template.html".interpolate({ path: path, theme: name }), {
method: "get",
asynchronous: false,
onSuccess: function (http) {
$(document.body).update(http.responseText);
},
onFailure: function () {
error = "Could not load template.html.";
}
});
if (error) {
miniLOL.error(error, true);
return false;
}
miniLOL.theme.information.styles.each(function (style) {
if (!miniLOL.theme.style.load(style, false, true)) {
miniLOL.error("Couldn't load `#{style}` style/".interpolate({
style: style
}), true);
throw $break;
}
});
if (miniLOL.error()) {
return false;
}
if (runtime && miniLOL.initialized) {
miniLOL.menu.change(miniLOL.menu.current, true);
miniLOL.go(location.href);
}
miniLOL.theme.tmp = {};
// Sadly this has some problems.
// I didn't find a way to know if the CSSs have already been applied and the initialize
// may get wrong information from stuff that uses sizes set by the CSS.
//
// So it's the designer's work to hack that shit and get it working, you can see an example
// in the original theme initialize.
//
// If someone knows a way to fix this, please contact me.
// (Already tried XHR and create <style>, but url() would get borked and it only worked in Firefox and Opera)
if (!noInitialization && miniLOL.theme.initialize) {
miniLOL.theme.initialize.call(miniLOL.theme.tmp);
}
Event.fire(document, ":theme.loaded", { name: name, runtime: Boolean(runtime) });
return true;
},
unload: function (noFinalization) {
miniLOL.theme.template.clearCache();
if (!miniLOL.theme.name) {
return;
}
Event.fire(document, ":theme.unload", { name: miniLOL.theme.name });
if (!noFinalization && miniLOL.theme.finalize) {
miniLOL.theme.finalize.call(miniLOL.theme.tmp || {});
}
delete miniLOL.theme.tmp;
$A(miniLOL.theme.information.styles).each(function (style) {
miniLOL.theme.style.unload(style);
});
delete miniLOL.theme.name;
delete miniLOL.theme.initialize;
delete miniLOL.theme.finalize;
delete miniLOL.theme.information;
},
content: function () {
return $(miniLOL.theme.content.node);
},
menu: function () {
return $(miniLOL.theme.menu.node);
},
deprecated: function () {
miniLOL.theme.path = "themes";
miniLOL.theme.content.node = miniLOL.config["core"].contentNode || "body";
miniLOL.theme.menu.node = miniLOL.config["core"].menuNode || "menu";
miniLOL.theme.template.clearCache();
new Ajax.Request("resources/template.html", {
method: "get",
asynchronous: false,
onSuccess: function (http) {
$(document.body).update(http.responseText);
},
onFailure: function () {
$(document.body).update('<div id="menu"></div><div id="body"></div>');
}
});
miniLOL.utils.includeCSS("resources/style.css");
miniLOL.theme.template.clearCache();
return true;
}
},
menu: {
set: function (data) {
if (!miniLOL.menu.enabled()) {
return;
}
miniLOL.theme.menu().update(data);
},
get: function (name, layer) {
layer = layer || 0;
if (!miniLOL.menu.enabled()) {
return "";
}
name = name || "default";
if (!miniLOL.menu.exists(name)) {
return null;
}
return miniLOL.menu.parse(miniLOL.menus[name], layer);
},
change: function (name, force) {
if (name == miniLOL.menu.current && !force) {
return;
}
var content = miniLOL.menu.get(name);
if (content) {
miniLOL.menu.set(content);
miniLOL.menu.current = name;
}
else {
var error = "The menu `#{name}` doesn't exist.".interpolate({
name: name
});
miniLOL.error(error, true);
return error;
}
Event.fire(document, ":menu.change", miniLOL.menus[name]);
},
enabled: function () {
return Boolean(miniLOL.menus["default"]);
},
exists: function (name) {
return Boolean(miniLOL.menus[name]);
},
parse: function (menu, layer) {
layer = layer || 0;
var template = miniLOL.theme.template.menu();
if (!template || !menu) {
if (miniLOL.error()) {
return false;
}
}
var first = true;
var output = "";
$A(menu.childNodes).each(function (e) {
switch (e.nodeType) {
case Node.ELEMENT_NODE:
if (e.nodeName == "menu") {
output += miniLOL.menu.parsers.layer(template, layer).menu.interpolate({
data: miniLOL.menu.parse(e, layer)
});
}
else if (e.nodeName == "item") {
output += miniLOL.menu.parsers.item(e, template, layer)
}
else {
output += miniLOL.menu.parsers.other(e, template);
}
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
if (!first) {
output += e.nodeValue;
}
first = false;
break;
}
});
if (!output.isEmpty()) {
if (layer == 0) {
return miniLOL.menu.parsers.layer(template, layer).menu.interpolate({
data: output
});
}
else {
return output;
}
}
else {
return "";
}
},
parsers: {
layer: function (template, layer) {
var result = {
menu: "",
item: ""
};
if (template) {
result = Object.extend(result, template.layers["_" + layer] || template.layers["default"] || {});
if (!result.menu) {
result.menu = "#{data}";
}
if (!result.item) {
result.item = '<a href="#{href}" #{attributes}>#{text}</a> ';
}
}
return result;
},
item: function (element, template, layer) {
var item = element.cloneNode(true);
var itemClass = item.getAttribute("class") || ""; item.removeAttribute("class");
var itemId = item.getAttribute("id") || ""; item.removeAttribute("id");
var itemHref = item.getAttribute("href") || ""; item.removeAttribute("href");
return miniLOL.menu.parsers.layer(template, layer).item.interpolate(Object.extend(Object.fromAttributes(item.attributes), {
"class": itemClass,
id: itemId,
href: itemHref,
attributes: String.fromAttributes(item.attributes),
text: miniLOL.utils.getFirstText(element.childNodes),
data: miniLOL.menu.parse(element, layer + 1)
}));
},
other: function (data, template) {
if (!data || !template) {
return "";
}
var text = template[data.nodeName];
if (!text) {
return "";
}
var output = "";
var outputs = {};
$A(data.childNodes).each(function (e) {
if (e.nodeType == Node.ELEMENT_NODE) {
outputs[e.nodeName] = miniLOL.menu.parsers.other(e, template);
}
});
outputs["text"] = miniLOL.utils.getFirstText(data.childNodes);
return text.interpolate(Object.extend(outputs, Object.fromAttributes(data.attributes)));
}
}
},
page: {
get: function (name, queries, url) {
miniLOL.content.set(miniLOL.config["core"].loadingMessage);
Event.fire(document, ":page.get", { name: name, queries: queries });
var page = miniLOL.pages.data[name];
var type = queries.type;
if (!page) {
miniLOL.content.set("404 - Not Found");
return false;
}
if (page.getAttribute("alias")) {
if (typeof queries[name] != "string") {
delete queries[name];
}
delete queries.page;
if (!queries.title && page.getAttribute("title")) {
queries.title = encodeURIComponent(page.getAttribute("title"));
}
var queries = Object.toQueryString(queries);
if (queries) {
queries = "&"+queries;
}
page = page.getAttribute("alias");
if (!page.isURL() && page.charAt(0) != "#") {
page = "#"+page;
}
return miniLOL.go(page+queries);
}
if (Object.isUndefined(type)) {
type = page.getAttribute("type");
}
if (url) {
var data = {};
Object.extend(data, miniLOL.config["core"]);
Object.extend(data, queries);
document.title = (
queries.title
|| page.getAttribute("title")
|| miniLOL.config["core"].siteTitle
).interpolate(data);
}
if (miniLOL.pages.cache[name]) {
if (type) {
miniLOL.content.set(miniLOL.resource.get("miniLOL.functions").render(type, miniLOL.pages.cache[name], queries));
}
else {
miniLOL.content.set(miniLOL.pages.cache[name]);
}
return true;
}
var pageArguments = page.getAttribute("arguments");
if (pageArguments) {
pageArguments = pageArguments.replace(/[ ,]+/g, "&").toQueryParams();
for (var key in pageArguments) {
if (queries[key] == null) {
queries[key] = pageArguments[key];
}
}
}
var output = miniLOL.page.parse(page);
miniLOL.pages.cache[name] = output;
if (type) {
output = miniLOL.resource.get("miniLOL.functions").render(type, output, queries);
}
miniLOL.content.set(output);
return true;
},
parse: function (page, data) {
var output = "";
$A(page.childNodes).each(function (e) {
switch (e.nodeType) {
case Node.ELEMENT_NODE:
if (Object.isFunction(miniLOL.page.parsers[e.nodeName])) {
output += miniLOL.page.parsers[e.nodeName](e, data);
}
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
output += e.nodeValue;
break;
}
});
return output;
},
parsers: {
list: function (element, data) {
var list = element.cloneNode(false);
data = data || [element];
var listBefore = list.getAttribute("before") || data[0].getAttribute("before") || ""; list.removeAttribute("before");
var listAfter = list.getAttribute("after") || data[0].getAttribute("after") || ""; list.removeAttribute("after");
var listArgs = list.getAttribute("arguments") || data[0].getAttribute("arguments") || ""; list.removeAttribute("arguments");
var listType = list.getAttribute("type") || data[0].getAttribute("type") || ""; list.removeAttribute("type");
var listMenu = list.getAttribute("menu") || data[0].getAttribute("menu"); list.removeAttribute("menu");
var listTemplate = list.getAttribute("template"); list.removeAttribute("template");
if (!miniLOL.theme.templates.list[listTemplate]) {
listTemplate = "default";
}
var output = "";
$A(element.childNodes).each(function (e) {
if (e.nodeType == Node.ELEMENT_NODE) {
if (e.nodeName == "link") {
var link = e.cloneNode(true);
var href = link.getAttribute("href"); link.removeAttribute("href");
var target = link.getAttribute("target"); link.removeAttribute("target");
var text = link.getAttribute("text") || (link.firstChild ? link.firstChild.nodeValue : href);
var before = link.getAttribute("before") || listBefore || ""; link.removeAttribute("before");
var after = link.getAttribute("after") || listAfter || ""; link.removeAttribute("after");
var domain = link.getAttribute("domain") || ""; link.removeAttribute("domain");
var args = link.getAttribute("arguments") || listArgs; link.removeAttribute("arguments");
var menu = link.getAttribute("menu") || listMenu; link.removeAttribute("menu");
var title = link.getAttribute("title") || ""; link.removeAttribute("title");
var out = href.isURL();
var linkClass = link.getAttribute("class") || ""; link.removeAttribute("class");
var linkId = link.getAttribute("id") || ""; link.removeAttribute("id");
if (target || out) {
href = (!out) ? "data/" + href : href;
target = target || "_blank";
}
else {
var ltype = link.getAttribute("type") || listType || ""; link.removeAttribute("type");
if (domain == "in" || href.charAt(0) == "#") {
if (href.charAt(0) != "#") {
href = "#" + href;
}
}
else {
href = "#page=" + href;
}
args = args ? "&"+args.replace(/[ ,]+/g, "&") : "";
ltype = ltype ? "&type="+ltype : "";
menu = miniLOL.menu.enabled() && menu ? "&menu="+menu : "";
target = "";
if (title) {
title = title.interpolate({
text: text,
href: href
});
title = "&title="+encodeURIComponent(title);
}
href = href + args + ltype + menu + title;
}
output += miniLOL.theme.templates.list[listTemplate].link.interpolate(Object.extend(Object.fromAttributes(link.attributes), {
"class": linkClass,
id: linkId,
attributes: String.fromAttributes(link.attributes),
before: miniLOL.theme.templates.list[listTemplate].before.interpolate({ data: before }),
after: miniLOL.theme.templates.list[listTemplate].after.interpolate({ data: after }),
href: href,
target: target,
text: text,
title: title
}));
}
else if (e.nodeName == "item") {
var item = e.cloneNode(true);
var text = item.getAttribute("text") || (item.firstChild ? item.firstChild.nodeValue : "")
var before = item.getAttribute("before") || listBefore || ""; item.removeAttribute("before");
var after = item.getAttribute("after") || listAfter || ""; item.removeAttribute("after");
var itemClass = item.getAttribute("class") || ""; item.removeAttribute("class");
var itemId = item.getAttribute("id") || ""; item.removeAttribute("id");
output += miniLOL.theme.templates.list[listTemplate].item.interpolate(Object.extend(Object.fromAttributes(item.attributes), {
"class": itemClass,
id: itemId,
attributes: String.fromAttributes(item.attributes),
before: miniLOL.theme.templates.list[listTemplate].before.interpolate({ data: before }),
after: miniLOL.theme.templates.list[listTemplate].after.interpolate({ data: after }),
text: text
}));
}
else if (e.nodeName == "list") {
output += miniLOL.page.parsers.list(e, [element]);
}
else if (e.nodeName == "nest") {
toParse = e.cloneNode(true);
var before = e.getAttribute("before") || listBefore || "";
var after = e.getAttribute("after") || listAfter || "";
output += miniLOL.theme.templates.list[listTemplate].nest.interpolate({
"class": e.getAttribute("class") || "",
style: e.getAttribute("style") || "",
before: miniLOL.theme.templates.list[listTemplate].before.interpolate({ data: before }),
after: miniLOL.theme.templates.list[listTemplate].after.interpolate({ data: after }),
data: miniLOL.page.parse(toParse, [element])
});
}
}
else if (e.nodeType == Node.CDATA_SECTION_NODE || e.nodeType == Node.TEXT_NODE) {
if (e.nodeValue.isEmpty()) {
return;
}
output += miniLOL.theme.templates.list[listTemplate].data.interpolate({
data: e.nodeValue
});
}
});
return miniLOL.theme.templates.list[listTemplate].global.interpolate(Object.extend(Object.fromAttributes(list.attributes), {
attributes: String.fromAttributes(list.attributes),
data: output
}));
},
include: function (element, data) {
var include = element.cloneNode(false);
var href = element.getAttribute("href"); element.removeAttribute("href");
var update = element.getAttribute("update"); element.removeAttribute("update");
var domain = location.href.match(/^http(s)?:\/\/(.*?)([^\.]\.\w+)/)[3];
var matches = href.match(/^http(s)?:\/\/(.*?)([^\.]\.\w+)/);
var output = "";
if (matches && matches[3] != domain) {
output = '<iframe src="#{href}" #{attributes}></iframe>'.interpolate({
href: href,
attributes: Object.fromAttributes(element.attributes)
});
}
else {
output = "<div ";
}
return "";
}
},
load: function (path, queries, url) {
miniLOL.content.set(miniLOL.config["core"].loadingMessage);
Event.fire(document, ":page.load", { path: path, queries: queries });
if (url) {
document.title = (
queries.title
|| miniLOL.config["core"].siteTitle
).interpolate(Object.extend(Object.extend({}, miniLOL.config["core"]), queries));
}
new Ajax.Request("data/#{path}?#{queries}".interpolate({ path: path, queries: Object.toQueryString(queries) }), {
method: "get",
onSuccess: function (http) {
if (queries.type) {
miniLOL.content.set(miniLOL.resource.get("miniLOL.functions").render(queries.type, http.responseText, queries));
}
else {
miniLOL.content.set(http.responseText);
}
Event.fire(document, ":page.loaded", http);
Event.fire(document, ":go", url.getHashFragment());
},
onFailure: function (http) {
miniLOL.content.set("#{status} - #{statusText}".interpolate(http));
Event.fire(document, ":page.loaded", http);
}
});
}
},
module: {
create: function (name, obj) {
if (!obj) {
miniLOL.error("Like, do I know how this module is done?", true);
return false;
}
obj.name = name;
obj.root = "#{path}/#{module}".interpolate({
path: miniLOL.module.path,
module: name
});
if (!obj.type) {
obj.type = "active";
}
if (!obj.execute) {
obj.execute = new Function;
}
for (var func in obj) {
if (Object.isFunction(obj[func])) {
obj[func] = obj[func].bind(obj)
}
}
if (obj.initialize) {
try {
if (obj.initialize() === false) {
if (miniLOL.error()) {
return false;
}
throw new Error("An error occurred while initializing the module.");
}
}
catch (e) {
e.fileName = "#{root}/#{path}/#{module}/main.js".interpolate({
root: miniLOL.path,
path: miniLOL.module.path,
module: name
});
throw e;
}
}
miniLOL.modules[name] = obj;
$A(obj.aliases).each(function (alias) {
miniLOL.modules[alias] = obj;
});
Event.fire(document, ":module.create", obj);
},
execute: function (name, vars, output) {
if (!name) {
miniLOL.error("What module should be executed?");
return false;
}
if (!miniLOL.module.exists(name)) {
if (output) {
miniLOL.error("The module `#{name}` isn't loaded.".interpolate({ name: name }), true);
}
return false;
}
if (output) {
miniLOL.content.set(miniLOL.config["core"].loadingMessage);
var data = {};
Object.extend(data, miniLOL.config["core"]);
Object.extend(data, vars);
document.title = (
vars.title
|| miniLOL.module.get(name).title
|| miniLOL.config["core"].siteTitle
).interpolate(data);
}
vars = (Object.isArray(vars)) ? vars : [vars];
Event.fire(document, ":module.execute", { name: name, arguments: vars });
var result;
try {
result = miniLOL.module.get(name).execute.apply(miniLOL.module.get(name), vars);
}
catch (e) {
e.fileName = "#{root}/#{path}/#{module}/main.js".interpolate({
root: miniLOL.path,
path: miniLOL.module.path,
module: name
});
miniLOL.error("An error occurred while executing the module `#{name}`\n\n#{file} @ #{line}:\n#{error}".interpolate({
name: name,
file: e.fileName,
line: e.lineNumber,
error: e.toString()
}), true);
return false;
}
Event.fire(document, ":module.executed", { name: name, arguments: vars, result: result });
if (Object.isUndefined(result)) {
result = true;
}
return result;
},
load: function (name) {
Event.fire(document, ":module.load", name);
try {
try {
miniLOL.utils.require("#{path}/#{module}/main.min.js".interpolate({
path: miniLOL.module.path,
module: name
}));
}
catch (e) {
if (e.http) {
miniLOL.utils.require("#{path}/#{module}/main.js".interpolate({
path: miniLOL.module.path,
module: name
}));
}
else {
throw e;
}
}
if (miniLOL.error()) {
return false;
}
if (!miniLOL.module.exists(name)) {
throw new Error("Something went wrong while loading the module `#{name}`.".interpolate({
name: name
}));
}
Event.fire(document, ":module.loaded", name);
return true;
}
catch (e) {
miniLOL.error("An error occurred while loading the module `#{name}`\n\n#{root}/#{file} @ #{line}:\n\n#{error}".interpolate({
name: name,
root: miniLOL.path,
file: e.fileName,
line: e.lineNumber,
error: e.toString()
}), true);
return false;
}
},
get: function (name) {
return miniLOL.modules[name];
},
exists: function (name) {
return Boolean(miniLOL.module.get(name));
},
dependencies: {
check: function () {
for (var module in miniLOL.modules) {
var dependencies = miniLOL.module.get(module).dependencies;
if (dependencies) {
for (var i = 0; i < dependencies.length; i++) {
if (!miniLOL.module.get(dependencies[i])) {
throw { module: module, require: dependencies[i] };
}
}
}
}
return true;
},
needs: function (name, callback, context, wait) {
if (miniLOL.module.get(name)) {
callback.call(context || window);
}
else {
setTimeout(function () {
miniLOL.module.dependencies.needs(name, callback, context);
}, wait || 10);
}
}
}
},
go: function (url, again) {
if (url.isURL()) {
if (!url.startsWith(miniLOL.path)) {
location.href = url;
}
}
else {
if (url.charAt(0) != '#') {
url = '#' + url;
}
}
var queries = url.toQueryParams();
var matches = url.match(/#(([^=&]*)&|([^=&]*)$)/); // hate WebKit so much.
var result = false;
if (queries.menu) {
miniLOL.menu.change(queries.menu);
}
if (matches) {
queries.page = matches[2] || matches[3];
if (queries.page) {
result = miniLOL.page.get(queries.page, queries, url);
}
else if (!again) {
result = miniLOL.go("#{page}&#{queries}".interpolate({
page: miniLOL.config["core"].homePage,
queries: Object.toQueryString(queries)
}), true);
}
}
else if (queries.module) {
result = miniLOL.module.execute(queries.module, queries, true);
}
else if (queries.page) {
var page = queries.page; delete queries.page;
miniLOL.page.load(page, queries, url);
}
else {
result = miniLOL.go(miniLOL.config["core"].homePage);
}
if (result) {
Event.fire(document, ":go", url.getHashFragment());
}
return result;
},
utils: {
getElementById: function (id) {
var result;
$A(this.getElementsByTagName("*")).each(function (element) {
if (element.getAttribute("id") == id) {
result = element;
throw $break;
}
});
return result;
},
xpath: function (query) {
var result = [];
var tmp;
if (Prototype.Browser.IE) {
tmp = this.real.selectNodes(query);
for (var i = 0; i < tmp.length; i++) {
result.push(tmp.item(i));
}
}
else {
tmp = this.evaluate(query, this, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < tmp.snapshotLength; i++) {
result.push(tmp.snapshotItem(i));
}
}
return result;
},
fixDOM: function (obj) {
if (!obj) {
return;
}
if (Prototype.Browser.IE) {
obj = { real: obj };
obj.documentElement = obj.real.documentElement;
obj.getElementsByTagName = function (name) {
return this.real.getElementsByTagName(name);
};
obj.getElementById = function (id) {
return miniLOL.utils.getElementById.call(this.real, id);
}
obj.real.setProperty("SelectionLanguage", "XPath");
}
else if (!Prototype.Browser.Good) {
obj.getElementById = miniLOL.utils.getElementById;
}
obj.xpath = miniLOL.utils.xpath;
return obj;
},
checkXML: function (xml, path) {
var error = false;
if (!xml) {
error = "There's a syntax error.";
}
if (xml.documentElement.nodeName == "parsererror") {
error = xml.documentElement.textContent;
}
if (path && error) {
miniLOL.error("Error while parsing #{path}\n\n#{error}".interpolate({
path: path,
error: error
}), true);
return error;
}
return error;
},
getFirstText: function (elements) {
var result = "";
(Object.isArray(elements) ? elements : $A(elements)).each(function (element) {
switch (element.nodeType) {
case Node.ELEMENT_NODE:
throw $break;
break;
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
if (!element.nodeValue.isEmpty()) {
result = element.nodeValue.strip();
throw $break;
}
break;
}
});
return result;
},
exists: function (path) {
var result = false;
new Ajax.Request(path, {
method: "head",
asynchronous: false,
onSuccess: function () {
result = true;
}
});
return result;
},
includeCSS: function (path) {
var style;
if (style = miniLOL.theme.style.list[path]) {
return style;
}
else if (style = $$("link").find(function (css) { return css.getAttribute("href") == path })) {
miniLOL.theme.style.list[path] = style;
return style;
}
else if (style = miniLOL.utils.exists(path)) {
style = new Element("link", {
rel: "stylesheet",
href: path,
type: "text/css"
});
$$("head")[0].insert(style);
Event.fire(document, ":css.include", path);
return style;
}
else {
return false;
}
},
css: function (style) {
var css = new Element("style", { type: "text/css" }).update(style);
$$("head").first().appendChild(css);
Event.fire(document, ":css.create", css);
return css;
},
execute: function (path) {
var result;
var error;
new Ajax.Request(path, {
method: "get",
asynchronous: false,
evalJS: false,
onSuccess: function (http) {
try {
result = window.eval(http.responseText);
}
catch (e) {
error = e;
error.fileName = path;
error.lineNumber -= 5;
}
},
onFailure: function (http) {
error = new Error("Failed to retrieve `#{file}` (#{status} - #{statusText}).".interpolate({
file: path,
status: http.status,
statusText: http.statusText
}));
error.fileName = path;
error.lineNumber = 0;
}
});
if (error) {
throw error;
}
return result;
},
include: function (path) {
var result = false;
new Ajax.Request(path, {
method: "get",
asynchronous: false,
evalJS: false,
onSuccess: function (http) {
try {
window.eval(http.responseText);
result = true;
} catch (e) {
result = false;
}
}
});
return result;
},
require: function (path) {
var error = false;
new Ajax.Request(path, {
method: "get",
asynchronous: false,
evalJS: false,
onSuccess: function (http) {
try {
window.eval(http.responseText);
} catch (e) {
error = e;
error.fileName = path;
error.lineNumber -= 5;
}
},
onFailure: function (http) {
error = new Error("Failed to retrieve `#{file}` (#{status} - #{statusText}).".interpolate({
file: path,
status: http.status,
statusText: http.statusText
}));
error.fileName = path;
error.lineNumber = 0;
error.http = {
status: http.status,
text: http.statusText
}
}
});
if (error) {
throw error;
}
return true;
}
}
}
miniLOL.utils.require("system/Resource.js");
miniLOL.utils.require("system/preparation.js");
| Added some useless stuff.
| system/miniLOL.js | Added some useless stuff. | <ide><path>ystem/miniLOL.js
<ide> miniLOL.resource.get("miniLOL.config").load("resources/config.xml");
<ide>
<ide> $(document.body).update(miniLOL.config["core"].loadingMessage);
<add>
<add> Event.fire(document, ":initializing");
<ide> },
<ide>
<ide> function () {
<ide> }
<ide> },
<ide>
<del> css: function (style) {
<add> css: function (style, id) {
<ide> var css = new Element("style", { type: "text/css" }).update(style);
<add>
<add> if (id) {
<add> css.setAtribute("id", id);
<add> }
<ide>
<ide> $$("head").first().appendChild(css);
<ide> |
|
Java | agpl-3.0 | f1cb399cf24d13ce026067899219c7e5fe816d99 | 0 | torakiki/pdfsam,torakiki/pdfsam,torakiki/pdfsam,torakiki/pdfsam | /*
* This file is part of the PDF Split And Merge source code
* Created on 27/nov/2013
* Copyright 2013 by Andrea Vacondio ([email protected]).
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pdfsam.ui.selection.multiple;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.pdfsam.ui.commons.SetDestinationRequest.requestDestination;
import static org.pdfsam.ui.commons.SetDestinationRequest.requestFallbackDestination;
import static org.pdfsam.ui.selection.multiple.SelectionChangedEvent.clearSelectionEvent;
import static org.pdfsam.ui.selection.multiple.SelectionChangedEvent.select;
import static org.sejda.eventstudio.StaticStudio.eventStudio;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import javafx.application.Platform;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TableView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.TransferMode;
import javafx.stage.Window;
import org.apache.commons.lang3.StringUtils;
import org.pdfsam.i18n.DefaultI18nContext;
import org.pdfsam.module.ModuleOwned;
import org.pdfsam.pdf.PdfLoadRequestEvent;
import org.pdfsam.support.io.FileType;
import org.pdfsam.ui.commons.OpenFileRequest;
import org.pdfsam.ui.commons.ShowPdfDescriptorRequest;
import org.pdfsam.ui.selection.PasswordFieldPopup;
import org.pdfsam.ui.selection.ShowPasswordFieldPopupRequest;
import org.pdfsam.ui.selection.multiple.move.MoveSelectedEvent;
import org.pdfsam.ui.selection.multiple.move.MoveType;
import org.pdfsam.ui.selection.multiple.move.SelectionAndFocus;
import org.sejda.eventstudio.annotation.EventListener;
import org.sejda.eventstudio.annotation.EventStation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
/**
* Table displaying selected pdf documents
*
* @author Andrea Vacondio
*
*/
public class SelectionTable extends TableView<SelectionTableRowData> implements ModuleOwned {
private static final Logger LOG = LoggerFactory.getLogger(SelectionTable.class);
private String ownerModule = StringUtils.EMPTY;
private Label placeHolder = new Label(DefaultI18nContext.getInstance().i18n("Drag and drop PDF files here"));
private PasswordFieldPopup passwordPopup;
public SelectionTable(String ownerModule, SelectionTableColumn<?>... columns) {
this.ownerModule = defaultString(ownerModule);
setEditable(true);
getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Arrays.stream(columns).forEach(c -> getColumns().add(c.getTableColumn()));
setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY);
getSelectionModel().getSelectedIndices().addListener((Change<? extends Integer> c) -> {
ObservableList<? extends Integer> selected = c.getList();
if (selected.isEmpty()) {
eventStudio().broadcast(clearSelectionEvent(), ownerModule);
LOG.trace("Selection cleared for {}", ownerModule);
} else {
SelectionChangedEvent newSelectionEvent = select(selected).ofTotalRows(getItems().size());
eventStudio().broadcast(newSelectionEvent, ownerModule);
LOG.trace("{} for {}", newSelectionEvent, ownerModule);
}
});
placeHolder.getStyleClass().add("drag-drop-placeholder");
placeHolder.setDisable(true);
setPlaceholder(placeHolder);
setOnDragOver(e -> dragConsume(e, this.onDragOverConsumer()));
setOnDragEntered(e -> dragConsume(e, this.onDragEnteredConsumer()));
setOnDragExited(this::onDragExited);
setOnDragDropped(e -> dragConsume(e, this.onDragDropped()));
passwordPopup = new PasswordFieldPopup(this.ownerModule);
initContextMenu();
eventStudio().addAnnotatedListeners(this);
}
private void initContextMenu() {
MenuItem infoItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Document properties"),
AwesomeIcon.INFO);
infoItem.setOnAction(e -> Platform.runLater(() -> eventStudio().broadcast(
new ShowPdfDescriptorRequest(getSelectionModel().getSelectedItem()))));
MenuItem setDestinationItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Set destination"),
AwesomeIcon.FILE_PDF_ALT);
setDestinationItem.setOnAction(e -> eventStudio()
.broadcast(requestDestination(getSelectionModel().getSelectedItem().getFile(), getOwnerModule()),
getOwnerModule()));
MenuItem removeSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Remove"),
AwesomeIcon.MINUS_SQUARE_ALT);
removeSelected.setOnAction(e -> eventStudio().broadcast(new RemoveSelectedEvent(), getOwnerModule()));
MenuItem moveTopSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move to Top"),
AwesomeIcon.ANGLE_DOUBLE_UP);
moveTopSelected
.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.TOP), getOwnerModule()));
MenuItem moveUpSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move Up"), AwesomeIcon.ANGLE_UP);
moveUpSelected.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.UP), getOwnerModule()));
MenuItem moveDownSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move Down"),
AwesomeIcon.ANGLE_DOWN);
moveDownSelected.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.DOWN),
getOwnerModule()));
MenuItem moveBottomSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move to Bottom"),
AwesomeIcon.ANGLE_DOUBLE_DOWN);
moveBottomSelected.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.BOTTOM),
getOwnerModule()));
MenuItem openFileItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Open"), AwesomeIcon.FILE_ALT);
openFileItem.setOnAction(e -> eventStudio().broadcast(
new OpenFileRequest(getSelectionModel().getSelectedItem().getFile())));
MenuItem openFolderItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Open Folder"),
AwesomeIcon.FOLDER_ALTPEN);
openFolderItem.setOnAction(e -> eventStudio().broadcast(
new OpenFileRequest(getSelectionModel().getSelectedItem().getFile().getParentFile())));
setDestinationItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.ALT_DOWN));
removeSelected.setAccelerator(new KeyCodeCombination(KeyCode.DELETE));
moveBottomSelected.setAccelerator(new KeyCodeCombination(KeyCode.END, KeyCombination.ALT_DOWN));
moveDownSelected.setAccelerator(new KeyCodeCombination(KeyCode.DOWN, KeyCombination.ALT_DOWN));
moveUpSelected.setAccelerator(new KeyCodeCombination(KeyCode.UP, KeyCombination.ALT_DOWN));
moveTopSelected.setAccelerator(new KeyCodeCombination(KeyCode.HOME, KeyCombination.ALT_DOWN));
infoItem.setAccelerator(new KeyCodeCombination(KeyCode.P, KeyCombination.ALT_DOWN));
openFileItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN));
openFolderItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN,
KeyCombination.ALT_DOWN));
eventStudio().add(SelectionChangedEvent.class, (SelectionChangedEvent e) -> {
setDestinationItem.setDisable(!e.isSingleSelection());
infoItem.setDisable(!e.isSingleSelection());
openFileItem.setDisable(!e.isSingleSelection());
openFolderItem.setDisable(!e.isSingleSelection());
removeSelected.setDisable(e.isClearSelection());
moveTopSelected.setDisable(!e.canMove(MoveType.TOP));
moveUpSelected.setDisable(!e.canMove(MoveType.UP));
moveDownSelected.setDisable(!e.canMove(MoveType.DOWN));
moveBottomSelected.setDisable(!e.canMove(MoveType.BOTTOM));
}, getOwnerModule());
setContextMenu(new ContextMenu(setDestinationItem, new SeparatorMenuItem(), removeSelected, moveTopSelected,
moveUpSelected, moveDownSelected, moveBottomSelected, new SeparatorMenuItem(), infoItem, openFileItem,
openFolderItem));
}
private MenuItem createMenuItem(String text, AwesomeIcon icon) {
MenuItem item = new MenuItem(text);
AwesomeDude.setIcon(item, icon);
item.setDisable(true);
return item;
}
private void dragConsume(DragEvent e, Consumer<DragEvent> c) {
List<File> files = e.getDragboard().getFiles();
if (files != null && !files.isEmpty()) {
c.accept(e);
}
e.consume();
}
private Consumer<DragEvent> onDragOverConsumer() {
return (DragEvent e) -> e.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
private Consumer<DragEvent> onDragEnteredConsumer() {
return (DragEvent e) -> placeHolder.setDisable(false);
}
private void onDragExited(DragEvent e) {
placeHolder.setDisable(true);
e.consume();
}
private Consumer<DragEvent> onDragDropped() {
return (DragEvent e) -> {
final PdfLoadRequestEvent<SelectionTableRowData> loadEvent = new PdfLoadRequestEvent<>(getOwnerModule());
e.getDragboard().getFiles().stream().filter(f -> FileType.PDF.matches(f.getName()))
.map(SelectionTableRowData::new).forEach(loadEvent::add);
if (!loadEvent.getDocuments().isEmpty()) {
eventStudio().broadcast(loadEvent, getOwnerModule());
}
e.setDropCompleted(true);
};
}
@EventStation
public String getOwnerModule() {
return ownerModule;
}
@EventListener(priority = Integer.MIN_VALUE)
public void onLoadDocumentsRequest(PdfLoadRequestEvent<SelectionTableRowData> loadEvent) {
getItems().addAll(loadEvent.getDocuments());
loadEvent
.getDocuments()
.stream()
.findFirst()
.ifPresent(
f -> eventStudio().broadcast(requestFallbackDestination(f.getFile(), getOwnerModule()),
getOwnerModule()));
eventStudio().broadcast(loadEvent);
}
@EventListener
public void onClear(final ClearSelectionTableEvent event) {
getItems().forEach(d -> d.invalidate());
getSelectionModel().clearSelection();
getItems().clear();
}
@EventListener
public void onRemoveSelected(RemoveSelectedEvent event) {
List<SelectionTableRowData> selectedItems = getSelectionModel().getSelectedItems();
LOG.trace("Removing {} items", selectedItems.size());
selectedItems.forEach(SelectionTableRowData::invalidate);
getItems().removeAll(selectedItems);
requestFocus();
}
@EventListener
public void onMoveSelected(final MoveSelectedEvent event) {
getSortOrder().clear();
ObservableList<Integer> selectedIndices = getSelectionModel().getSelectedIndices();
Integer[] selected = selectedIndices.toArray(new Integer[selectedIndices.size()]);
int focus = getFocusModel().getFocusedIndex();
getSelectionModel().clearSelection();
SelectionAndFocus newSelection = event.getType().move(selected, getItems(), focus);
if (!SelectionAndFocus.NULL.equals(newSelection)) {
LOG.trace("Changing selection to {}", newSelection);
getSelectionModel().selectIndices(newSelection.getRow(), newSelection.getRows());
getFocusModel().focus(newSelection.getFocus());
scrollTo(newSelection.getFocus());
}
}
@EventListener
public void showPasswordFieldPopup(ShowPasswordFieldPopupRequest request) {
Scene scene = this.getScene();
if (scene != null) {
Window owner = scene.getWindow();
if (owner != null && owner.isShowing()) {
Point2D nodeCoord = request.getRequestingNode().localToScene(
request.getRequestingNode().getWidth() / 2, request.getRequestingNode().getHeight() / 1.5);
double anchorX = Math.round(owner.getX() + scene.getX() + nodeCoord.getX() + 2);
double anchorY = Math.round(owner.getY() + scene.getY() + nodeCoord.getY() + 2);
passwordPopup.showFor(this, request.getPdfDescriptor(), anchorX, anchorY);
}
}
}
}
| pdfsam-fx/src/main/java/org/pdfsam/ui/selection/multiple/SelectionTable.java | /*
* This file is part of the PDF Split And Merge source code
* Created on 27/nov/2013
* Copyright 2013 by Andrea Vacondio ([email protected]).
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pdfsam.ui.selection.multiple;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.pdfsam.ui.commons.SetDestinationRequest.requestDestination;
import static org.pdfsam.ui.commons.SetDestinationRequest.requestFallbackDestination;
import static org.pdfsam.ui.selection.multiple.SelectionChangedEvent.clearSelectionEvent;
import static org.pdfsam.ui.selection.multiple.SelectionChangedEvent.select;
import static org.sejda.eventstudio.StaticStudio.eventStudio;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import javafx.application.Platform;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TableView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.TransferMode;
import javafx.stage.Window;
import org.apache.commons.lang3.StringUtils;
import org.pdfsam.i18n.DefaultI18nContext;
import org.pdfsam.module.ModuleOwned;
import org.pdfsam.pdf.PdfLoadRequestEvent;
import org.pdfsam.support.io.FileType;
import org.pdfsam.ui.commons.OpenFileRequest;
import org.pdfsam.ui.commons.ShowPdfDescriptorRequest;
import org.pdfsam.ui.selection.PasswordFieldPopup;
import org.pdfsam.ui.selection.ShowPasswordFieldPopupRequest;
import org.pdfsam.ui.selection.multiple.move.MoveSelectedEvent;
import org.pdfsam.ui.selection.multiple.move.MoveType;
import org.pdfsam.ui.selection.multiple.move.SelectionAndFocus;
import org.sejda.eventstudio.annotation.EventListener;
import org.sejda.eventstudio.annotation.EventStation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.jensd.fx.fontawesome.AwesomeDude;
import de.jensd.fx.fontawesome.AwesomeIcon;
/**
* Table displaying selected pdf documents
*
* @author Andrea Vacondio
*
*/
public class SelectionTable extends TableView<SelectionTableRowData> implements ModuleOwned {
private static final Logger LOG = LoggerFactory.getLogger(SelectionTable.class);
private String ownerModule = StringUtils.EMPTY;
private Label placeHolder = new Label(DefaultI18nContext.getInstance().i18n("Drag and drop PDF files here"));
private PasswordFieldPopup passwordPopup;
public SelectionTable(String ownerModule, SelectionTableColumn<?>... columns) {
this.ownerModule = defaultString(ownerModule);
setEditable(true);
getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Arrays.stream(columns).forEach(c -> getColumns().add(c.getTableColumn()));
setColumnResizePolicy(CONSTRAINED_RESIZE_POLICY);
getSelectionModel().getSelectedIndices().addListener((Change<? extends Integer> c) -> {
ObservableList<? extends Integer> selected = c.getList();
if (selected.isEmpty()) {
eventStudio().broadcast(clearSelectionEvent(), ownerModule);
LOG.trace("Selection cleared for {}", ownerModule);
} else {
SelectionChangedEvent newSelectionEvent = select(selected).ofTotalRows(getItems().size());
eventStudio().broadcast(newSelectionEvent, ownerModule);
LOG.trace("{} for {}", newSelectionEvent, ownerModule);
}
});
placeHolder.getStyleClass().add("drag-drop-placeholder");
placeHolder.setDisable(true);
setPlaceholder(placeHolder);
setOnDragOver(e -> dragConsume(e, this.onDragOverConsumer()));
setOnDragEntered(e -> dragConsume(e, this.onDragEnteredConsumer()));
setOnDragExited(this::onDragExited);
setOnDragDropped(e -> dragConsume(e, this.onDragDropped()));
passwordPopup = new PasswordFieldPopup(this.ownerModule);
initContextMenu();
eventStudio().addAnnotatedListeners(this);
}
private void initContextMenu() {
MenuItem infoItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Document properties"),
AwesomeIcon.INFO);
infoItem.setOnAction(e -> Platform.runLater(() -> eventStudio().broadcast(
new ShowPdfDescriptorRequest(getSelectionModel().getSelectedItem()))));
MenuItem setDestinationItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Set destination"),
AwesomeIcon.FILE_PDF_ALT);
setDestinationItem.setOnAction(e -> eventStudio()
.broadcast(requestDestination(getSelectionModel().getSelectedItem().getFile(), getOwnerModule()),
getOwnerModule()));
MenuItem removeSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Remove"),
AwesomeIcon.MINUS_SQUARE_ALT);
removeSelected.setOnAction(e -> eventStudio().broadcast(new RemoveSelectedEvent(), getOwnerModule()));
MenuItem moveTopSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move to Top"),
AwesomeIcon.ANGLE_DOUBLE_UP);
moveTopSelected
.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.TOP), getOwnerModule()));
MenuItem moveUpSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move Up"), AwesomeIcon.ANGLE_UP);
moveUpSelected.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.UP), getOwnerModule()));
MenuItem moveDownSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move Down"),
AwesomeIcon.ANGLE_DOWN);
moveDownSelected.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.DOWN),
getOwnerModule()));
MenuItem moveBottomSelected = createMenuItem(DefaultI18nContext.getInstance().i18n("Move to Bottom"),
AwesomeIcon.ANGLE_DOUBLE_DOWN);
moveBottomSelected.setOnAction(e -> eventStudio().broadcast(new MoveSelectedEvent(MoveType.BOTTOM),
getOwnerModule()));
MenuItem openFileItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Open"), AwesomeIcon.FILE_ALT);
openFileItem.setOnAction(e -> eventStudio().broadcast(
new OpenFileRequest(getSelectionModel().getSelectedItem().getFile())));
MenuItem openFolderItem = createMenuItem(DefaultI18nContext.getInstance().i18n("Open Folder"),
AwesomeIcon.FOLDER_ALTPEN);
openFolderItem.setOnAction(e -> eventStudio().broadcast(
new OpenFileRequest(getSelectionModel().getSelectedItem().getFile().getParentFile())));
setDestinationItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.ALT_DOWN));
removeSelected.setAccelerator(new KeyCodeCombination(KeyCode.DELETE));
moveBottomSelected.setAccelerator(new KeyCodeCombination(KeyCode.END, KeyCombination.ALT_DOWN));
moveDownSelected.setAccelerator(new KeyCodeCombination(KeyCode.DOWN, KeyCombination.ALT_DOWN));
moveUpSelected.setAccelerator(new KeyCodeCombination(KeyCode.UP, KeyCombination.ALT_DOWN));
moveTopSelected.setAccelerator(new KeyCodeCombination(KeyCode.HOME, KeyCombination.ALT_DOWN));
infoItem.setAccelerator(new KeyCodeCombination(KeyCode.P, KeyCombination.ALT_DOWN));
openFileItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN));
openFolderItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN,
KeyCombination.ALT_DOWN));
eventStudio().add(SelectionChangedEvent.class, (SelectionChangedEvent e) -> {
setDestinationItem.setDisable(!e.isSingleSelection());
infoItem.setDisable(!e.isSingleSelection());
openFileItem.setDisable(!e.isSingleSelection());
openFolderItem.setDisable(!e.isSingleSelection());
removeSelected.setDisable(e.isClearSelection());
moveTopSelected.setDisable(!e.canMove(MoveType.TOP));
moveUpSelected.setDisable(!e.canMove(MoveType.UP));
moveDownSelected.setDisable(!e.canMove(MoveType.DOWN));
moveBottomSelected.setDisable(!e.canMove(MoveType.BOTTOM));
}, getOwnerModule());
setContextMenu(new ContextMenu(setDestinationItem, new SeparatorMenuItem(), removeSelected, moveTopSelected,
moveUpSelected, moveDownSelected, moveBottomSelected, new SeparatorMenuItem(), infoItem, openFileItem,
openFolderItem));
}
private MenuItem createMenuItem(String text, AwesomeIcon icon) {
MenuItem item = new MenuItem(text);
AwesomeDude.setIcon(item, icon);
item.setDisable(true);
return item;
}
private void dragConsume(DragEvent e, Consumer<DragEvent> c) {
List<File> files = e.getDragboard().getFiles();
if (files != null && !files.isEmpty()) {
c.accept(e);
}
e.consume();
}
private Consumer<DragEvent> onDragOverConsumer() {
return (DragEvent e) -> e.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
private Consumer<DragEvent> onDragEnteredConsumer() {
return (DragEvent e) -> placeHolder.setDisable(false);
}
private void onDragExited(DragEvent e) {
placeHolder.setDisable(true);
e.consume();
}
private Consumer<DragEvent> onDragDropped() {
return (DragEvent e) -> {
final PdfLoadRequestEvent<SelectionTableRowData> loadEvent = new PdfLoadRequestEvent<>(getOwnerModule());
e.getDragboard().getFiles().stream().filter(f -> FileType.PDF.matches(f.getName()))
.map(SelectionTableRowData::new).forEach(loadEvent::add);
eventStudio().broadcast(loadEvent, getOwnerModule());
e.setDropCompleted(true);
};
}
@EventStation
public String getOwnerModule() {
return ownerModule;
}
@EventListener(priority = Integer.MIN_VALUE)
public void onLoadDocumentsRequest(PdfLoadRequestEvent<SelectionTableRowData> loadEvent) {
getItems().addAll(loadEvent.getDocuments());
loadEvent
.getDocuments()
.stream()
.findFirst()
.ifPresent(
f -> eventStudio().broadcast(requestFallbackDestination(f.getFile(), getOwnerModule()),
getOwnerModule()));
eventStudio().broadcast(loadEvent);
}
@EventListener
public void onClear(final ClearSelectionTableEvent event) {
getItems().forEach(d -> d.invalidate());
getSelectionModel().clearSelection();
getItems().clear();
}
@EventListener
public void onRemoveSelected(RemoveSelectedEvent event) {
List<SelectionTableRowData> selectedItems = getSelectionModel().getSelectedItems();
LOG.trace("Removing {} items", selectedItems.size());
selectedItems.forEach(SelectionTableRowData::invalidate);
getItems().removeAll(selectedItems);
requestFocus();
}
@EventListener
public void onMoveSelected(final MoveSelectedEvent event) {
getSortOrder().clear();
ObservableList<Integer> selectedIndices = getSelectionModel().getSelectedIndices();
Integer[] selected = selectedIndices.toArray(new Integer[selectedIndices.size()]);
int focus = getFocusModel().getFocusedIndex();
getSelectionModel().clearSelection();
SelectionAndFocus newSelection = event.getType().move(selected, getItems(), focus);
if (!SelectionAndFocus.NULL.equals(newSelection)) {
LOG.trace("Changing selection to {}", newSelection);
getSelectionModel().selectIndices(newSelection.getRow(), newSelection.getRows());
getFocusModel().focus(newSelection.getFocus());
scrollTo(newSelection.getFocus());
}
}
@EventListener
public void showPasswordFieldPopup(ShowPasswordFieldPopupRequest request) {
Scene scene = this.getScene();
if (scene != null) {
Window owner = scene.getWindow();
if (owner != null && owner.isShowing()) {
Point2D nodeCoord = request.getRequestingNode().localToScene(
request.getRequestingNode().getWidth() / 2, request.getRequestingNode().getHeight() / 1.5);
double anchorX = Math.round(owner.getX() + scene.getX() + nodeCoord.getX() + 2);
double anchorY = Math.round(owner.getY() + scene.getY() + nodeCoord.getY() + 2);
passwordPopup.showFor(this, request.getPdfDescriptor(), anchorX, anchorY);
}
}
}
}
| Send load event only if there actually are documents to be loaded | pdfsam-fx/src/main/java/org/pdfsam/ui/selection/multiple/SelectionTable.java | Send load event only if there actually are documents to be loaded | <ide><path>dfsam-fx/src/main/java/org/pdfsam/ui/selection/multiple/SelectionTable.java
<ide> final PdfLoadRequestEvent<SelectionTableRowData> loadEvent = new PdfLoadRequestEvent<>(getOwnerModule());
<ide> e.getDragboard().getFiles().stream().filter(f -> FileType.PDF.matches(f.getName()))
<ide> .map(SelectionTableRowData::new).forEach(loadEvent::add);
<del> eventStudio().broadcast(loadEvent, getOwnerModule());
<add> if (!loadEvent.getDocuments().isEmpty()) {
<add> eventStudio().broadcast(loadEvent, getOwnerModule());
<add> }
<ide> e.setDropCompleted(true);
<ide> };
<ide> } |
|
Java | apache-2.0 | 6d67ab84ec3902abbe3b6cd5fdca5d84605393a0 | 0 | gbif/gbif-common-ws | /*
* 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.gbif.ws.paths;
/**
* Commons constants of occurrence service.
*/
public final class OccurrencePaths {
public static final String OCCURRENCE_PATH = "occurrence";
public static final String OCC_SEARCH_PATH = OCCURRENCE_PATH + "/search";
public static final String RECORDED_BY_PATH = "recordedBy";
public static final String IDENTIFIED_BY_PATH = "identifiedBy";
public static final String RECORD_NUMBER_PATH = "recordNumber";
public static final String CATALOG_NUMBER_PATH = "catalogNumber";
public static final String INSTITUTION_CODE_PATH = "institutionCode";
public static final String COLLECTION_CODE_PATH = "collectionCode";
public static final String OCCURRENCE_ID_PATH = "occurrenceId";
public static final String ORGANISM_ID_PATH = "organismId";
public static final String LOCALITY_PATH = "locality";
public static final String WATER_BODY_PATH = "waterBody";
public static final String STATE_PROVINCE_PATH = "stateProvince";
public static final String SAMPLING_PROTOCOL_PATH = "samplingProtocol";
public static final String EVENT_ID_PATH = "eventId";
public static final String PARENT_EVENT_ID_PATH = "parentEventId";
public static final String VERBATIM_PATH = "verbatim";
public static final String FRAGMENT_PATH = "fragment";
public static final String DATASET_NAME_PATH = "datasetName";
public static final String OTHER_CATALOG_NUMBERS_PATH = "otherCatalogNumbers";
/**
* Private default constructor.
*/
private OccurrencePaths() {
// empty constructor
}
}
| src/main/java/org/gbif/ws/paths/OccurrencePaths.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 org.gbif.ws.paths;
/**
* Commons constants of occurrence service.
*/
public final class OccurrencePaths {
public static final String OCCURRENCE_PATH = "occurrence";
public static final String OCC_SEARCH_PATH = OCCURRENCE_PATH + "/search";
public static final String RECORDED_BY_PATH = "recordedBy";
public static final String IDENTIFIED_BY_PATH = "identifiedBy";
public static final String RECORD_NUMBER_PATH = "recordNumber";
public static final String CATALOG_NUMBER_PATH = "catalogNumber";
public static final String INSTITUTION_CODE_PATH = "institutionCode";
public static final String COLLECTION_CODE_PATH = "collectionCode";
public static final String OCCURRENCE_ID_PATH = "occurrenceId";
public static final String ORGANISM_ID_PATH = "organismId";
public static final String LOCALITY_PATH = "locality";
public static final String WATER_BODY_PATH = "waterBody";
public static final String STATE_PROVINCE_PATH = "stateProvince";
public static final String SAMPLING_PROTOCOL_PATH = "samplingProtocol";
public static final String EVENT_ID_PATH = "eventId";
public static final String PARENT_EVENT_ID_PATH = "parentEventId";
public static final String VERBATIM_PATH = "verbatim";
public static final String FRAGMENT_PATH = "fragment";
/**
* Private default constructor.
*/
private OccurrencePaths() {
// empty constructor
}
}
| added occ paths for dataset name and other catalog numbers
| src/main/java/org/gbif/ws/paths/OccurrencePaths.java | added occ paths for dataset name and other catalog numbers | <ide><path>rc/main/java/org/gbif/ws/paths/OccurrencePaths.java
<ide>
<ide> public static final String FRAGMENT_PATH = "fragment";
<ide>
<add> public static final String DATASET_NAME_PATH = "datasetName";
<add>
<add> public static final String OTHER_CATALOG_NUMBERS_PATH = "otherCatalogNumbers";
<add>
<ide> /**
<ide> * Private default constructor.
<ide> */ |
|
Java | bsd-3-clause | 6d1d36b9502fd57b1fd829266876f8a0607f8ccb | 0 | skill-lang/skillJavaTestSuite | package creator;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import age.api.SkillFile;
import de.ust.skill.common.java.api.Access;
import de.ust.skill.common.java.api.SkillException;
import de.ust.skill.common.java.internal.FieldDeclaration;
import de.ust.skill.common.java.internal.SkillObject;
public class JSONReaderTest extends common.CommonTest{
@Rule // http://stackoverflow.com/a/2935935
public final ExpectedException exception = ExpectedException.none();
private static Path path;
private static Path skillFilePath;
private JSONObject currentJSON;
/**
* Tests the object generation capabilities.
*/
@BeforeClass
public static void init() throws JSONException, MalformedURLException, IOException {
path = Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "test4.json");
skillFilePath = Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "age-example.sf");
}
@Before
public void loadNextJSONObject() throws JSONException, MalformedURLException, IOException {
this.currentJSON = JSONReader.readJSON(path.toFile());
}
public void jsonTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
JSONObject currentTest = currentJSON;
if(JSONReader.shouldExpectException(currentTest)){
System.out.println("There should be an exception coming up!");
exception.expect(Exception.class);
}
SkillObject obj = JSONReader.createSkillObjectFromJSON(currentTest);
System.out.println(obj.prettyString());
assertTrue(true);
}
@Test
public void test() throws SkillException, IOException{
Map<String, Access<?>> types = new HashMap<>();
Map<String, HashMap<String, FieldDeclaration<?, ?>>> typeFieldMapping = new HashMap<>();
SkillFile sf = SkillFile.open(skillFilePath);
reflectiveInit(sf);
creator.SkillObjectCreator.generateSkillFileMappings(sf, types, typeFieldMapping);
//Create necessary objects
SkillObject jsonObjName1 = types.get("Typename").make();
SkillObject jsonObjName2 = types.get("Typename").make();
jsonObjName1.set(cast(typeFieldMapping.get("Typename").get("Fieldname")), "Value");
sf.close();
}
protected static <T, U> de.ust.skill.common.java.api.FieldDeclaration<T> cast(de.ust.skill.common.java.api.FieldDeclaration<U> arg){
return (de.ust.skill.common.java.api.FieldDeclaration<T>)arg;
}
}
| src/test/java/creator/JSONReaderTest.java | package creator;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import age.api.SkillFile;
import de.ust.skill.common.java.api.Access;
import de.ust.skill.common.java.api.SkillException;
import de.ust.skill.common.java.internal.FieldDeclaration;
import de.ust.skill.common.java.internal.SkillObject;
public class JSONReaderTest extends common.CommonTest{
@Rule // http://stackoverflow.com/a/2935935
public final ExpectedException exception = ExpectedException.none();
private static Path path;
private JSONObject currentJSON;
/**
* Tests the object generation capabilities.
*/
@BeforeClass
public static void init() throws JSONException, MalformedURLException, IOException {
path = Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "test4.json");
}
@Before
public void loadNextJSONObject() throws JSONException, MalformedURLException, IOException {
this.currentJSON = JSONReader.readJSON(path.toFile());
}
@Test
public void jsonTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
JSONObject currentTest = currentJSON;
if(JSONReader.shouldExpectException(currentTest)){
System.out.println("There should be an exception coming up!");
exception.expect(Exception.class);
}
SkillObject obj = JSONReader.createSkillObjectFromJSON(currentTest);
System.out.println(obj.prettyString());
assertTrue(true);
}
@Test
public void test() throws SkillException, IOException{
Map<String, Access<?>> types = new HashMap<>();
Map<String, HashMap<String, FieldDeclaration<?, ?>>> typeFieldMapping = new HashMap<>();
SkillFile sf = SkillFile.open(path);
reflectiveInit(sf);
creator.SkillObjectCreator.generateSkillFileMappings(sf, types, typeFieldMapping);
//Create necessary objects
SkillObject jsonObjName1 = types.get("Typename").make();
SkillObject jsonObjName2 = types.get("Typename").make();
jsonObjName1.set((de.ust.skill.common.java.api.FieldDeclaration<String>) typeFieldMapping.get("Typename").get("Fieldname"), "Value");
sf.close();
}
}
| Add Timm's dirty cast function
| src/test/java/creator/JSONReaderTest.java | Add Timm's dirty cast function | <ide><path>rc/test/java/creator/JSONReaderTest.java
<ide> public final ExpectedException exception = ExpectedException.none();
<ide>
<ide> private static Path path;
<add> private static Path skillFilePath;
<ide> private JSONObject currentJSON;
<ide>
<ide> /**
<ide> @BeforeClass
<ide> public static void init() throws JSONException, MalformedURLException, IOException {
<ide> path = Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "test4.json");
<add> skillFilePath = Paths.get(System.getProperty("user.dir"), "src", "test", "resources", "age-example.sf");
<ide> }
<ide>
<ide> @Before
<ide> this.currentJSON = JSONReader.readJSON(path.toFile());
<ide> }
<ide>
<del> @Test
<ide> public void jsonTest() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
<ide> JSONObject currentTest = currentJSON;
<ide> if(JSONReader.shouldExpectException(currentTest)){
<ide> Map<String, Access<?>> types = new HashMap<>();
<ide> Map<String, HashMap<String, FieldDeclaration<?, ?>>> typeFieldMapping = new HashMap<>();
<ide>
<del> SkillFile sf = SkillFile.open(path);
<add> SkillFile sf = SkillFile.open(skillFilePath);
<ide> reflectiveInit(sf);
<ide>
<ide> creator.SkillObjectCreator.generateSkillFileMappings(sf, types, typeFieldMapping);
<ide> SkillObject jsonObjName1 = types.get("Typename").make();
<ide> SkillObject jsonObjName2 = types.get("Typename").make();
<ide>
<del> jsonObjName1.set((de.ust.skill.common.java.api.FieldDeclaration<String>) typeFieldMapping.get("Typename").get("Fieldname"), "Value");
<add> jsonObjName1.set(cast(typeFieldMapping.get("Typename").get("Fieldname")), "Value");
<ide>
<ide> sf.close();
<ide> }
<ide>
<add> protected static <T, U> de.ust.skill.common.java.api.FieldDeclaration<T> cast(de.ust.skill.common.java.api.FieldDeclaration<U> arg){
<add> return (de.ust.skill.common.java.api.FieldDeclaration<T>)arg;
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | 60aded229b3c506f41419bcca28e0fee86c9c006 | 0 | kuujo/onos,oplinkoms/onos,opennetworkinglab/onos,gkatsikas/onos,gkatsikas/onos,LorenzReinhart/ONOSnew,LorenzReinhart/ONOSnew,opennetworkinglab/onos,osinstom/onos,gkatsikas/onos,opennetworkinglab/onos,kuujo/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,oplinkoms/onos,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,osinstom/onos,osinstom/onos,kuujo/onos,LorenzReinhart/ONOSnew,kuujo/onos,osinstom/onos,kuujo/onos,kuujo/onos,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,opennetworkinglab/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,osinstom/onos,opennetworkinglab/onos,kuujo/onos,opennetworkinglab/onos | /*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.openflow.controller.impl;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.core.CoreService;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.DriverService;
import org.onosproject.openflow.controller.DefaultOpenFlowPacketContext;
import org.onosproject.openflow.controller.Dpid;
import org.onosproject.openflow.controller.OpenFlowController;
import org.onosproject.openflow.controller.OpenFlowEventListener;
import org.onosproject.openflow.controller.OpenFlowMessageListener;
import org.onosproject.openflow.controller.OpenFlowPacketContext;
import org.onosproject.openflow.controller.OpenFlowSwitch;
import org.onosproject.openflow.controller.OpenFlowSwitchListener;
import org.onosproject.openflow.controller.PacketListener;
import org.onosproject.openflow.controller.RoleState;
import org.onosproject.openflow.controller.driver.OpenFlowAgent;
import org.osgi.service.component.ComponentContext;
import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsEntry;
import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsReply;
import org.projectfloodlight.openflow.protocol.OFCircuitPortStatus;
import org.projectfloodlight.openflow.protocol.OFExperimenter;
import org.projectfloodlight.openflow.protocol.OFFactories;
import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFPacketIn;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
import org.projectfloodlight.openflow.protocol.OFPortStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatus;
import org.projectfloodlight.openflow.protocol.OFStatsReply;
import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
import org.projectfloodlight.openflow.protocol.action.OFActionOutput;
import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Device.Type.CONTROLLER;
import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
import static org.onosproject.openflow.controller.Dpid.dpid;
import org.projectfloodlight.openflow.protocol.OFQueueStatsEntry;
import org.projectfloodlight.openflow.protocol.OFQueueStatsReply;
@Component(immediate = true)
@Service
public class OpenFlowControllerImpl implements OpenFlowController {
private static final String APP_ID = "org.onosproject.openflow-base";
private static final String DEFAULT_OFPORT = "6633,6653";
private static final int DEFAULT_WORKER_THREADS = 0;
private static final Logger log =
LoggerFactory.getLogger(OpenFlowControllerImpl.class);
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DriverService driverService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ComponentConfigService cfgService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceService deviceService;
@Property(name = "openflowPorts", value = DEFAULT_OFPORT,
label = "Port numbers (comma separated) used by OpenFlow protocol; default is 6633,6653")
private String openflowPorts = DEFAULT_OFPORT;
@Property(name = "workerThreads", intValue = DEFAULT_WORKER_THREADS,
label = "Number of controller worker threads")
private int workerThreads = DEFAULT_WORKER_THREADS;
protected ExecutorService executorMsgs =
Executors.newFixedThreadPool(32, groupedThreads("onos/of", "event-stats-%d", log));
private final ExecutorService executorBarrier =
Executors.newFixedThreadPool(4, groupedThreads("onos/of", "event-barrier-%d", log));
//Separate executor thread for handling error messages and barrier replies for same failed
// transactions to avoid context switching of thread
protected ExecutorService executorErrorMsgs =
Executors.newSingleThreadExecutor(groupedThreads("onos/of", "event-error-msg-%d", log));
//concurrent hashmap to track failed transactions
protected ConcurrentMap<Long, Boolean> errorMsgs =
new ConcurrentHashMap<>();
protected ConcurrentMap<Dpid, OpenFlowSwitch> connectedSwitches =
new ConcurrentHashMap<>();
protected ConcurrentMap<Dpid, OpenFlowSwitch> activeMasterSwitches =
new ConcurrentHashMap<>();
protected ConcurrentMap<Dpid, OpenFlowSwitch> activeEqualSwitches =
new ConcurrentHashMap<>();
// Key: dpid, value: map with key: long (XID), value: completable future
protected ConcurrentMap<Dpid, ConcurrentMap<Long, CompletableFuture<OFMessage>>> responses =
new ConcurrentHashMap<>();
protected OpenFlowSwitchAgent agent = new OpenFlowSwitchAgent();
protected Set<OpenFlowSwitchListener> ofSwitchListener = new CopyOnWriteArraySet<>();
protected Multimap<Integer, PacketListener> ofPacketListener =
ArrayListMultimap.create();
protected Set<OpenFlowEventListener> ofEventListener = new CopyOnWriteArraySet<>();
protected Set<OpenFlowMessageListener> ofMessageListener = new CopyOnWriteArraySet<>();
protected Multimap<Dpid, OFFlowStatsEntry> fullFlowStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFTableStatsEntry> fullTableStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFGroupStatsEntry> fullGroupStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFGroupDescStatsEntry> fullGroupDescStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFPortStatsEntry> fullPortStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFQueueStatsEntry> fullQueueStats =
ArrayListMultimap.create();
private final Controller ctrl = new Controller();
private InternalDeviceListener listener = new InternalDeviceListener();
@Activate
public void activate(ComponentContext context) {
coreService.registerApplication(APP_ID, this::cleanup);
cfgService.registerProperties(getClass());
deviceService.addListener(listener);
ctrl.setConfigParams(context.getProperties());
ctrl.start(agent, driverService);
}
private void cleanup() {
// Close listening channel and all OF channels. Clean information about switches
// before deactivating
ctrl.stop();
connectedSwitches.values().forEach(OpenFlowSwitch::disconnectSwitch);
connectedSwitches.clear();
activeMasterSwitches.clear();
activeEqualSwitches.clear();
}
@Deactivate
public void deactivate() {
deviceService.removeListener(listener);
cleanup();
cfgService.unregisterProperties(getClass(), false);
}
@Modified
public void modified(ComponentContext context) {
ctrl.stop();
ctrl.setConfigParams(context.getProperties());
ctrl.start(agent, driverService);
}
@Override
public Iterable<OpenFlowSwitch> getSwitches() {
return connectedSwitches.values();
}
@Override
public Iterable<OpenFlowSwitch> getMasterSwitches() {
return activeMasterSwitches.values();
}
@Override
public Iterable<OpenFlowSwitch> getEqualSwitches() {
return activeEqualSwitches.values();
}
@Override
public OpenFlowSwitch getSwitch(Dpid dpid) {
return connectedSwitches.get(dpid);
}
@Override
public OpenFlowSwitch getMasterSwitch(Dpid dpid) {
return activeMasterSwitches.get(dpid);
}
@Override
public OpenFlowSwitch getEqualSwitch(Dpid dpid) {
return activeEqualSwitches.get(dpid);
}
@Override
public void addListener(OpenFlowSwitchListener listener) {
if (!ofSwitchListener.contains(listener)) {
this.ofSwitchListener.add(listener);
}
}
@Override
public void removeListener(OpenFlowSwitchListener listener) {
this.ofSwitchListener.remove(listener);
}
@Override
public void addMessageListener(OpenFlowMessageListener listener) {
ofMessageListener.add(listener);
}
@Override
public void removeMessageListener(OpenFlowMessageListener listener) {
ofMessageListener.remove(listener);
}
@Override
public void addPacketListener(int priority, PacketListener listener) {
ofPacketListener.put(priority, listener);
}
@Override
public void removePacketListener(PacketListener listener) {
ofPacketListener.values().remove(listener);
}
@Override
public void addEventListener(OpenFlowEventListener listener) {
ofEventListener.add(listener);
}
@Override
public void removeEventListener(OpenFlowEventListener listener) {
ofEventListener.remove(listener);
}
@Override
public void write(Dpid dpid, OFMessage msg) {
this.getSwitch(dpid).sendMsg(msg);
}
@Override
public CompletableFuture<OFMessage> writeResponse(Dpid dpid, OFMessage msg) {
write(dpid, msg);
ConcurrentMap<Long, CompletableFuture<OFMessage>> xids =
responses.computeIfAbsent(dpid, k -> new ConcurrentHashMap<>());
CompletableFuture<OFMessage> future = new CompletableFuture<>();
xids.put(msg.getXid(), future);
return future;
}
// CHECKSTYLE IGNORE MethodLength FOR NEXT 300 LINES
@Override
public void processPacket(Dpid dpid, OFMessage msg) {
Collection<OFFlowStatsEntry> flowStats;
Collection<OFTableStatsEntry> tableStats;
Collection<OFGroupStatsEntry> groupStats;
Collection<OFGroupDescStatsEntry> groupDescStats;
Collection<OFQueueStatsEntry> queueStatsEntries;
OpenFlowSwitch sw = this.getSwitch(dpid);
// Check if someone is waiting for this message
ConcurrentMap<Long, CompletableFuture<OFMessage>> xids = responses.get(dpid);
if (xids != null) {
CompletableFuture<OFMessage> future = xids.remove(msg.getXid());
if (future != null) {
future.complete(msg);
}
}
switch (msg.getType()) {
case PORT_STATUS:
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.portChanged(dpid, (OFPortStatus) msg);
}
break;
case FEATURES_REPLY:
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchChanged(dpid);
}
break;
case PACKET_IN:
if (sw == null) {
log.error("Ignoring PACKET_IN, switch {} is not found", dpid);
break;
}
OpenFlowPacketContext pktCtx = DefaultOpenFlowPacketContext
.packetContextFromPacketIn(sw, (OFPacketIn) msg);
for (PacketListener p : ofPacketListener.values()) {
p.handlePacket(pktCtx);
}
break;
// TODO: Consider using separate threadpool for sensitive messages.
// ie. Back to back error could cause us to starve.
case FLOW_REMOVED:
executorMsgs.execute(new OFMessageHandler(dpid, msg));
break;
case ERROR:
log.debug("Received error message from {}: {}", dpid, msg);
errorMsgs.putIfAbsent(msg.getXid(), true);
executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
break;
case STATS_REPLY:
OFStatsReply reply = (OFStatsReply) msg;
switch (reply.getStatsType()) {
case QUEUE:
queueStatsEntries = publishQueueStats(dpid, (OFQueueStatsReply) reply);
if (queueStatsEntries != null) {
OFQueueStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildQueueStatsReply();
rep.setEntries(Lists.newLinkedList(queueStatsEntries));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case PORT_DESC:
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchChanged(dpid);
}
break;
case FLOW:
flowStats = publishFlowStats(dpid, (OFFlowStatsReply) reply);
if (flowStats != null) {
OFFlowStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildFlowStatsReply();
rep.setEntries(Lists.newLinkedList(flowStats));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case TABLE:
tableStats = publishTableStats(dpid, (OFTableStatsReply) reply);
if (tableStats != null) {
OFTableStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildTableStatsReply();
rep.setEntries(Lists.newLinkedList(tableStats));
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case GROUP:
groupStats = publishGroupStats(dpid, (OFGroupStatsReply) reply);
if (groupStats != null) {
OFGroupStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildGroupStatsReply();
rep.setEntries(Lists.newLinkedList(groupStats));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case GROUP_DESC:
groupDescStats = publishGroupDescStats(dpid,
(OFGroupDescStatsReply) reply);
if (groupDescStats != null) {
OFGroupDescStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildGroupDescStatsReply();
rep.setEntries(Lists.newLinkedList(groupDescStats));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case PORT:
executorMsgs.execute(new OFMessageHandler(dpid, reply));
break;
case METER:
executorMsgs.execute(new OFMessageHandler(dpid, reply));
break;
case EXPERIMENTER:
if (reply instanceof OFCalientFlowStatsReply) {
// Convert Calient flow statistics to regular flow stats
// TODO: parse remaining fields such as power levels etc. when we have proper monitoring API
if (sw == null) {
log.error("Switch {} is not found", dpid);
break;
}
OFFlowStatsReply.Builder fsr = sw.factory().buildFlowStatsReply();
List<OFFlowStatsEntry> entries = new LinkedList<>();
for (OFCalientFlowStatsEntry entry : ((OFCalientFlowStatsReply) msg).getEntries()) {
// Single instruction, i.e., output to port
OFActionOutput action = OFFactories
.getFactory(msg.getVersion())
.actions()
.buildOutput()
.setPort(entry.getOutPort())
.build();
OFInstruction instruction = OFFactories
.getFactory(msg.getVersion())
.instructions()
.applyActions(Collections.singletonList(action));
OFFlowStatsEntry fs = sw.factory().buildFlowStatsEntry()
.setMatch(entry.getMatch())
.setTableId(entry.getTableId())
.setDurationSec(entry.getDurationSec())
.setDurationNsec(entry.getDurationNsec())
.setPriority(entry.getPriority())
.setIdleTimeout(entry.getIdleTimeout())
.setHardTimeout(entry.getHardTimeout())
.setFlags(entry.getFlags())
.setCookie(entry.getCookie())
.setInstructions(Collections.singletonList(instruction))
.build();
entries.add(fs);
}
fsr.setEntries(entries);
flowStats = publishFlowStats(dpid, fsr.build());
if (flowStats != null) {
OFFlowStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildFlowStatsReply();
rep.setEntries(Lists.newLinkedList(flowStats));
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
} else {
executorMsgs.execute(new OFMessageHandler(dpid, reply));
}
break;
default:
log.warn("Discarding unknown stats reply type {}", reply.getStatsType());
break;
}
break;
case BARRIER_REPLY:
if (errorMsgs.containsKey(msg.getXid())) {
//To make oferror msg handling and corresponding barrier reply serialized,
// executorErrorMsgs is used for both transaction
errorMsgs.remove(msg.getXid());
executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
} else {
executorBarrier.execute(new OFMessageHandler(dpid, msg));
}
break;
case EXPERIMENTER:
if (sw == null) {
log.error("Switch {} is not found", dpid);
break;
}
long experimenter = ((OFExperimenter) msg).getExperimenter();
if (experimenter == 0x748771) {
// LINC-OE port stats
OFCircuitPortStatus circuitPortStatus = (OFCircuitPortStatus) msg;
OFPortStatus.Builder portStatus = sw.factory().buildPortStatus();
OFPortDesc.Builder portDesc = sw.factory().buildPortDesc();
portDesc.setPortNo(circuitPortStatus.getPortNo())
.setHwAddr(circuitPortStatus.getHwAddr())
.setName(circuitPortStatus.getName())
.setConfig(circuitPortStatus.getConfig())
.setState(circuitPortStatus.getState());
portStatus.setReason(circuitPortStatus.getReason()).setDesc(portDesc.build());
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.portChanged(dpid, portStatus.build());
}
} else {
log.warn("Handling experimenter type {} not yet implemented",
((OFExperimenter) msg).getExperimenter(), msg);
}
break;
default:
log.warn("Handling message type {} not yet implemented {}",
msg.getType(), msg);
}
}
private synchronized Collection<OFFlowStatsEntry> publishFlowStats(Dpid dpid,
OFFlowStatsReply reply) {
//TODO: Get rid of synchronized
fullFlowStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullFlowStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFTableStatsEntry> publishTableStats(Dpid dpid,
OFTableStatsReply reply) {
//TODO: Get rid of synchronized
fullTableStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullTableStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFGroupStatsEntry> publishGroupStats(Dpid dpid,
OFGroupStatsReply reply) {
//TODO: Get rid of synchronized
fullGroupStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullGroupStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFGroupDescStatsEntry> publishGroupDescStats(Dpid dpid,
OFGroupDescStatsReply reply) {
//TODO: Get rid of synchronized
fullGroupDescStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullGroupDescStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFPortStatsEntry> publishPortStats(Dpid dpid,
OFPortStatsReply reply) {
fullPortStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullPortStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFQueueStatsEntry> publishQueueStats(Dpid dpid, OFQueueStatsReply reply) {
fullQueueStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullQueueStats.removeAll(dpid);
}
return null;
}
@Override
public void setRole(Dpid dpid, RoleState role) {
final OpenFlowSwitch sw = getSwitch(dpid);
if (sw == null) {
log.debug("Switch not connected. Ignoring setRole({}, {})", dpid, role);
return;
}
sw.setRole(role);
}
class InternalDeviceListener implements DeviceListener {
@Override
public boolean isRelevant(DeviceEvent event) {
return event.subject().type() != CONTROLLER && event.type() == DEVICE_REMOVED;
}
@Override
public void event(DeviceEvent event) {
switch (event.type()) {
case DEVICE_ADDED:
break;
case DEVICE_AVAILABILITY_CHANGED:
break;
case DEVICE_REMOVED:
// Device administratively removed, disconnect
Optional.ofNullable(getSwitch(dpid(event.subject().id().uri())))
.ifPresent(OpenFlowSwitch::disconnectSwitch);
break;
case DEVICE_SUSPENDED:
break;
case DEVICE_UPDATED:
break;
case PORT_ADDED:
break;
case PORT_REMOVED:
break;
case PORT_STATS_UPDATED:
break;
case PORT_UPDATED:
break;
default:
break;
}
}
}
/**
* Implementation of an OpenFlow Agent which is responsible for
* keeping track of connected switches and the state in which
* they are.
*/
public class OpenFlowSwitchAgent implements OpenFlowAgent {
private final Logger log = LoggerFactory.getLogger(OpenFlowSwitchAgent.class);
private final Lock switchLock = new ReentrantLock();
@Override
public boolean addConnectedSwitch(Dpid dpid, OpenFlowSwitch sw) {
if (connectedSwitches.get(dpid) != null) {
log.error("Trying to add connectedSwitch but found a previous "
+ "value for dpid: {}", dpid);
return false;
} else {
log.info("Added switch {}", dpid);
connectedSwitches.put(dpid, sw);
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchAdded(dpid);
}
return true;
}
}
@Override
public boolean validActivation(Dpid dpid) {
if (connectedSwitches.get(dpid) == null) {
log.error("Trying to activate switch but is not in "
+ "connected switches: dpid {}. Aborting ..",
dpid);
return false;
}
if (activeMasterSwitches.get(dpid) != null ||
activeEqualSwitches.get(dpid) != null) {
log.error("Trying to activate switch but it is already "
+ "activated: dpid {}. Found in activeMaster: {} "
+ "Found in activeEqual: {}. Aborting ..",
dpid,
(activeMasterSwitches.get(dpid) == null) ? 'N' : 'Y',
(activeEqualSwitches.get(dpid) == null) ? 'N' : 'Y');
return false;
}
return true;
}
@Override
public boolean addActivatedMasterSwitch(Dpid dpid, OpenFlowSwitch sw) {
switchLock.lock();
try {
if (!validActivation(dpid)) {
return false;
}
activeMasterSwitches.put(dpid, sw);
return true;
} finally {
switchLock.unlock();
}
}
@Override
public boolean addActivatedEqualSwitch(Dpid dpid, OpenFlowSwitch sw) {
switchLock.lock();
try {
if (!validActivation(dpid)) {
return false;
}
activeEqualSwitches.put(dpid, sw);
log.info("Added Activated EQUAL Switch {}", dpid);
return true;
} finally {
switchLock.unlock();
}
}
@Override
public void transitionToMasterSwitch(Dpid dpid) {
switchLock.lock();
try {
if (activeMasterSwitches.containsKey(dpid)) {
return;
}
OpenFlowSwitch sw = activeEqualSwitches.remove(dpid);
if (sw == null) {
sw = getSwitch(dpid);
if (sw == null) {
log.error("Transition to master called on sw {}, but switch "
+ "was not found in controller-cache", dpid);
return;
}
}
log.info("Transitioned switch {} to MASTER", dpid);
activeMasterSwitches.put(dpid, sw);
} finally {
switchLock.unlock();
}
}
@Override
public void transitionToEqualSwitch(Dpid dpid) {
switchLock.lock();
try {
if (activeEqualSwitches.containsKey(dpid)) {
return;
}
OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
if (sw == null) {
sw = getSwitch(dpid);
if (sw == null) {
log.error("Transition to equal called on sw {}, but switch "
+ "was not found in controller-cache", dpid);
return;
}
}
log.info("Transitioned switch {} to EQUAL", dpid);
activeEqualSwitches.put(dpid, sw);
} finally {
switchLock.unlock();
}
}
@Override
public void removeConnectedSwitch(Dpid dpid) {
connectedSwitches.remove(dpid);
OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
if (sw == null) {
log.debug("sw was null for {}", dpid);
sw = activeEqualSwitches.remove(dpid);
}
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchRemoved(dpid);
}
}
@Override
public void processDownstreamMessage(Dpid dpid, List<OFMessage> m) {
for (OpenFlowMessageListener listener : ofMessageListener) {
listener.handleOutgoingMessage(dpid, m);
}
}
@Override
public void processMessage(Dpid dpid, OFMessage m) {
processPacket(dpid, m);
for (OpenFlowMessageListener listener : ofMessageListener) {
listener.handleIncomingMessage(dpid, m);
}
}
@Override
public void returnRoleReply(Dpid dpid, RoleState requested, RoleState response) {
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.receivedRoleReply(dpid, requested, response);
}
}
}
/**
* OpenFlow message handler.
*/
protected final class OFMessageHandler implements Runnable {
protected final OFMessage msg;
protected final Dpid dpid;
public OFMessageHandler(Dpid dpid, OFMessage msg) {
this.msg = msg;
this.dpid = dpid;
}
@Override
public void run() {
for (OpenFlowEventListener listener : ofEventListener) {
listener.handleMessage(dpid, msg);
}
}
}
}
| protocols/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenFlowControllerImpl.java | /*
* Copyright 2015-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.openflow.controller.impl;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.core.CoreService;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.DriverService;
import org.onosproject.openflow.controller.DefaultOpenFlowPacketContext;
import org.onosproject.openflow.controller.Dpid;
import org.onosproject.openflow.controller.OpenFlowController;
import org.onosproject.openflow.controller.OpenFlowEventListener;
import org.onosproject.openflow.controller.OpenFlowMessageListener;
import org.onosproject.openflow.controller.OpenFlowPacketContext;
import org.onosproject.openflow.controller.OpenFlowSwitch;
import org.onosproject.openflow.controller.OpenFlowSwitchListener;
import org.onosproject.openflow.controller.PacketListener;
import org.onosproject.openflow.controller.RoleState;
import org.onosproject.openflow.controller.driver.OpenFlowAgent;
import org.osgi.service.component.ComponentContext;
import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsEntry;
import org.projectfloodlight.openflow.protocol.OFCalientFlowStatsReply;
import org.projectfloodlight.openflow.protocol.OFCircuitPortStatus;
import org.projectfloodlight.openflow.protocol.OFExperimenter;
import org.projectfloodlight.openflow.protocol.OFFactories;
import org.projectfloodlight.openflow.protocol.OFFlowStatsEntry;
import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFPacketIn;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
import org.projectfloodlight.openflow.protocol.OFPortStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatus;
import org.projectfloodlight.openflow.protocol.OFStatsReply;
import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
import org.projectfloodlight.openflow.protocol.OFTableStatsEntry;
import org.projectfloodlight.openflow.protocol.OFTableStatsReply;
import org.projectfloodlight.openflow.protocol.action.OFActionOutput;
import org.projectfloodlight.openflow.protocol.instruction.OFInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Device.Type.CONTROLLER;
import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
import static org.onosproject.openflow.controller.Dpid.dpid;
@Component(immediate = true)
@Service
public class OpenFlowControllerImpl implements OpenFlowController {
private static final String APP_ID = "org.onosproject.openflow-base";
private static final String DEFAULT_OFPORT = "6633,6653";
private static final int DEFAULT_WORKER_THREADS = 0;
private static final Logger log =
LoggerFactory.getLogger(OpenFlowControllerImpl.class);
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DriverService driverService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected ComponentConfigService cfgService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceService deviceService;
@Property(name = "openflowPorts", value = DEFAULT_OFPORT,
label = "Port numbers (comma separated) used by OpenFlow protocol; default is 6633,6653")
private String openflowPorts = DEFAULT_OFPORT;
@Property(name = "workerThreads", intValue = DEFAULT_WORKER_THREADS,
label = "Number of controller worker threads")
private int workerThreads = DEFAULT_WORKER_THREADS;
protected ExecutorService executorMsgs =
Executors.newFixedThreadPool(32, groupedThreads("onos/of", "event-stats-%d", log));
private final ExecutorService executorBarrier =
Executors.newFixedThreadPool(4, groupedThreads("onos/of", "event-barrier-%d", log));
//Separate executor thread for handling error messages and barrier replies for same failed
// transactions to avoid context switching of thread
protected ExecutorService executorErrorMsgs =
Executors.newSingleThreadExecutor(groupedThreads("onos/of", "event-error-msg-%d", log));
//concurrent hashmap to track failed transactions
protected ConcurrentMap<Long, Boolean> errorMsgs =
new ConcurrentHashMap<>();
protected ConcurrentMap<Dpid, OpenFlowSwitch> connectedSwitches =
new ConcurrentHashMap<>();
protected ConcurrentMap<Dpid, OpenFlowSwitch> activeMasterSwitches =
new ConcurrentHashMap<>();
protected ConcurrentMap<Dpid, OpenFlowSwitch> activeEqualSwitches =
new ConcurrentHashMap<>();
// Key: dpid, value: map with key: long (XID), value: completable future
protected ConcurrentMap<Dpid, ConcurrentMap<Long, CompletableFuture<OFMessage>>> responses =
new ConcurrentHashMap<>();
protected OpenFlowSwitchAgent agent = new OpenFlowSwitchAgent();
protected Set<OpenFlowSwitchListener> ofSwitchListener = new CopyOnWriteArraySet<>();
protected Multimap<Integer, PacketListener> ofPacketListener =
ArrayListMultimap.create();
protected Set<OpenFlowEventListener> ofEventListener = new CopyOnWriteArraySet<>();
protected Set<OpenFlowMessageListener> ofMessageListener = new CopyOnWriteArraySet<>();
protected Multimap<Dpid, OFFlowStatsEntry> fullFlowStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFTableStatsEntry> fullTableStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFGroupStatsEntry> fullGroupStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFGroupDescStatsEntry> fullGroupDescStats =
ArrayListMultimap.create();
protected Multimap<Dpid, OFPortStatsEntry> fullPortStats =
ArrayListMultimap.create();
private final Controller ctrl = new Controller();
private InternalDeviceListener listener = new InternalDeviceListener();
@Activate
public void activate(ComponentContext context) {
coreService.registerApplication(APP_ID, this::cleanup);
cfgService.registerProperties(getClass());
deviceService.addListener(listener);
ctrl.setConfigParams(context.getProperties());
ctrl.start(agent, driverService);
}
private void cleanup() {
// Close listening channel and all OF channels. Clean information about switches
// before deactivating
ctrl.stop();
connectedSwitches.values().forEach(OpenFlowSwitch::disconnectSwitch);
connectedSwitches.clear();
activeMasterSwitches.clear();
activeEqualSwitches.clear();
}
@Deactivate
public void deactivate() {
deviceService.removeListener(listener);
cleanup();
cfgService.unregisterProperties(getClass(), false);
}
@Modified
public void modified(ComponentContext context) {
ctrl.stop();
ctrl.setConfigParams(context.getProperties());
ctrl.start(agent, driverService);
}
@Override
public Iterable<OpenFlowSwitch> getSwitches() {
return connectedSwitches.values();
}
@Override
public Iterable<OpenFlowSwitch> getMasterSwitches() {
return activeMasterSwitches.values();
}
@Override
public Iterable<OpenFlowSwitch> getEqualSwitches() {
return activeEqualSwitches.values();
}
@Override
public OpenFlowSwitch getSwitch(Dpid dpid) {
return connectedSwitches.get(dpid);
}
@Override
public OpenFlowSwitch getMasterSwitch(Dpid dpid) {
return activeMasterSwitches.get(dpid);
}
@Override
public OpenFlowSwitch getEqualSwitch(Dpid dpid) {
return activeEqualSwitches.get(dpid);
}
@Override
public void addListener(OpenFlowSwitchListener listener) {
if (!ofSwitchListener.contains(listener)) {
this.ofSwitchListener.add(listener);
}
}
@Override
public void removeListener(OpenFlowSwitchListener listener) {
this.ofSwitchListener.remove(listener);
}
@Override
public void addMessageListener(OpenFlowMessageListener listener) {
ofMessageListener.add(listener);
}
@Override
public void removeMessageListener(OpenFlowMessageListener listener) {
ofMessageListener.remove(listener);
}
@Override
public void addPacketListener(int priority, PacketListener listener) {
ofPacketListener.put(priority, listener);
}
@Override
public void removePacketListener(PacketListener listener) {
ofPacketListener.values().remove(listener);
}
@Override
public void addEventListener(OpenFlowEventListener listener) {
ofEventListener.add(listener);
}
@Override
public void removeEventListener(OpenFlowEventListener listener) {
ofEventListener.remove(listener);
}
@Override
public void write(Dpid dpid, OFMessage msg) {
this.getSwitch(dpid).sendMsg(msg);
}
@Override
public CompletableFuture<OFMessage> writeResponse(Dpid dpid, OFMessage msg) {
write(dpid, msg);
ConcurrentMap<Long, CompletableFuture<OFMessage>> xids =
responses.computeIfAbsent(dpid, k -> new ConcurrentHashMap<>());
CompletableFuture<OFMessage> future = new CompletableFuture<>();
xids.put(msg.getXid(), future);
return future;
}
@Override
public void processPacket(Dpid dpid, OFMessage msg) {
Collection<OFFlowStatsEntry> flowStats;
Collection<OFTableStatsEntry> tableStats;
Collection<OFGroupStatsEntry> groupStats;
Collection<OFGroupDescStatsEntry> groupDescStats;
OpenFlowSwitch sw = this.getSwitch(dpid);
// Check if someone is waiting for this message
ConcurrentMap<Long, CompletableFuture<OFMessage>> xids = responses.get(dpid);
if (xids != null) {
CompletableFuture<OFMessage> future = xids.remove(msg.getXid());
if (future != null) {
future.complete(msg);
}
}
switch (msg.getType()) {
case PORT_STATUS:
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.portChanged(dpid, (OFPortStatus) msg);
}
break;
case FEATURES_REPLY:
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchChanged(dpid);
}
break;
case PACKET_IN:
if (sw == null) {
log.error("Ignoring PACKET_IN, switch {} is not found", dpid);
break;
}
OpenFlowPacketContext pktCtx = DefaultOpenFlowPacketContext
.packetContextFromPacketIn(sw, (OFPacketIn) msg);
for (PacketListener p : ofPacketListener.values()) {
p.handlePacket(pktCtx);
}
break;
// TODO: Consider using separate threadpool for sensitive messages.
// ie. Back to back error could cause us to starve.
case FLOW_REMOVED:
executorMsgs.execute(new OFMessageHandler(dpid, msg));
break;
case ERROR:
log.debug("Received error message from {}: {}", dpid, msg);
errorMsgs.putIfAbsent(msg.getXid(), true);
executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
break;
case STATS_REPLY:
OFStatsReply reply = (OFStatsReply) msg;
switch (reply.getStatsType()) {
case PORT_DESC:
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchChanged(dpid);
}
break;
case FLOW:
flowStats = publishFlowStats(dpid, (OFFlowStatsReply) reply);
if (flowStats != null) {
OFFlowStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildFlowStatsReply();
rep.setEntries(Lists.newLinkedList(flowStats));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case TABLE:
tableStats = publishTableStats(dpid, (OFTableStatsReply) reply);
if (tableStats != null) {
OFTableStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildTableStatsReply();
rep.setEntries(Lists.newLinkedList(tableStats));
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case GROUP:
groupStats = publishGroupStats(dpid, (OFGroupStatsReply) reply);
if (groupStats != null) {
OFGroupStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildGroupStatsReply();
rep.setEntries(Lists.newLinkedList(groupStats));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case GROUP_DESC:
groupDescStats = publishGroupDescStats(dpid,
(OFGroupDescStatsReply) reply);
if (groupDescStats != null) {
OFGroupDescStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildGroupDescStatsReply();
rep.setEntries(Lists.newLinkedList(groupDescStats));
rep.setXid(reply.getXid());
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
break;
case PORT:
executorMsgs.execute(new OFMessageHandler(dpid, reply));
break;
case METER:
executorMsgs.execute(new OFMessageHandler(dpid, reply));
break;
case EXPERIMENTER:
if (reply instanceof OFCalientFlowStatsReply) {
// Convert Calient flow statistics to regular flow stats
// TODO: parse remaining fields such as power levels etc. when we have proper monitoring API
if (sw == null) {
log.error("Switch {} is not found", dpid);
break;
}
OFFlowStatsReply.Builder fsr = sw.factory().buildFlowStatsReply();
List<OFFlowStatsEntry> entries = new LinkedList<>();
for (OFCalientFlowStatsEntry entry : ((OFCalientFlowStatsReply) msg).getEntries()) {
// Single instruction, i.e., output to port
OFActionOutput action = OFFactories
.getFactory(msg.getVersion())
.actions()
.buildOutput()
.setPort(entry.getOutPort())
.build();
OFInstruction instruction = OFFactories
.getFactory(msg.getVersion())
.instructions()
.applyActions(Collections.singletonList(action));
OFFlowStatsEntry fs = sw.factory().buildFlowStatsEntry()
.setMatch(entry.getMatch())
.setTableId(entry.getTableId())
.setDurationSec(entry.getDurationSec())
.setDurationNsec(entry.getDurationNsec())
.setPriority(entry.getPriority())
.setIdleTimeout(entry.getIdleTimeout())
.setHardTimeout(entry.getHardTimeout())
.setFlags(entry.getFlags())
.setCookie(entry.getCookie())
.setInstructions(Collections.singletonList(instruction))
.build();
entries.add(fs);
}
fsr.setEntries(entries);
flowStats = publishFlowStats(dpid, fsr.build());
if (flowStats != null) {
OFFlowStatsReply.Builder rep =
OFFactories.getFactory(msg.getVersion()).buildFlowStatsReply();
rep.setEntries(Lists.newLinkedList(flowStats));
executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
}
} else {
executorMsgs.execute(new OFMessageHandler(dpid, reply));
}
break;
default:
log.warn("Discarding unknown stats reply type {}", reply.getStatsType());
break;
}
break;
case BARRIER_REPLY:
if (errorMsgs.containsKey(msg.getXid())) {
//To make oferror msg handling and corresponding barrier reply serialized,
// executorErrorMsgs is used for both transaction
errorMsgs.remove(msg.getXid());
executorErrorMsgs.execute(new OFMessageHandler(dpid, msg));
} else {
executorBarrier.execute(new OFMessageHandler(dpid, msg));
}
break;
case EXPERIMENTER:
if (sw == null) {
log.error("Switch {} is not found", dpid);
break;
}
long experimenter = ((OFExperimenter) msg).getExperimenter();
if (experimenter == 0x748771) {
// LINC-OE port stats
OFCircuitPortStatus circuitPortStatus = (OFCircuitPortStatus) msg;
OFPortStatus.Builder portStatus = sw.factory().buildPortStatus();
OFPortDesc.Builder portDesc = sw.factory().buildPortDesc();
portDesc.setPortNo(circuitPortStatus.getPortNo())
.setHwAddr(circuitPortStatus.getHwAddr())
.setName(circuitPortStatus.getName())
.setConfig(circuitPortStatus.getConfig())
.setState(circuitPortStatus.getState());
portStatus.setReason(circuitPortStatus.getReason()).setDesc(portDesc.build());
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.portChanged(dpid, portStatus.build());
}
} else {
log.warn("Handling experimenter type {} not yet implemented",
((OFExperimenter) msg).getExperimenter(), msg);
}
break;
default:
log.warn("Handling message type {} not yet implemented {}",
msg.getType(), msg);
}
}
private synchronized Collection<OFFlowStatsEntry> publishFlowStats(Dpid dpid,
OFFlowStatsReply reply) {
//TODO: Get rid of synchronized
fullFlowStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullFlowStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFTableStatsEntry> publishTableStats(Dpid dpid,
OFTableStatsReply reply) {
//TODO: Get rid of synchronized
fullTableStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullTableStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFGroupStatsEntry> publishGroupStats(Dpid dpid,
OFGroupStatsReply reply) {
//TODO: Get rid of synchronized
fullGroupStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullGroupStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFGroupDescStatsEntry> publishGroupDescStats(Dpid dpid,
OFGroupDescStatsReply reply) {
//TODO: Get rid of synchronized
fullGroupDescStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullGroupDescStats.removeAll(dpid);
}
return null;
}
private synchronized Collection<OFPortStatsEntry> publishPortStats(Dpid dpid,
OFPortStatsReply reply) {
fullPortStats.putAll(dpid, reply.getEntries());
if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
return fullPortStats.removeAll(dpid);
}
return null;
}
@Override
public void setRole(Dpid dpid, RoleState role) {
final OpenFlowSwitch sw = getSwitch(dpid);
if (sw == null) {
log.debug("Switch not connected. Ignoring setRole({}, {})", dpid, role);
return;
}
sw.setRole(role);
}
class InternalDeviceListener implements DeviceListener {
@Override
public boolean isRelevant(DeviceEvent event) {
return event.subject().type() != CONTROLLER && event.type() == DEVICE_REMOVED;
}
@Override
public void event(DeviceEvent event) {
switch (event.type()) {
case DEVICE_ADDED:
break;
case DEVICE_AVAILABILITY_CHANGED:
break;
case DEVICE_REMOVED:
// Device administratively removed, disconnect
Optional.ofNullable(getSwitch(dpid(event.subject().id().uri())))
.ifPresent(OpenFlowSwitch::disconnectSwitch);
break;
case DEVICE_SUSPENDED:
break;
case DEVICE_UPDATED:
break;
case PORT_ADDED:
break;
case PORT_REMOVED:
break;
case PORT_STATS_UPDATED:
break;
case PORT_UPDATED:
break;
default:
break;
}
}
}
/**
* Implementation of an OpenFlow Agent which is responsible for
* keeping track of connected switches and the state in which
* they are.
*/
public class OpenFlowSwitchAgent implements OpenFlowAgent {
private final Logger log = LoggerFactory.getLogger(OpenFlowSwitchAgent.class);
private final Lock switchLock = new ReentrantLock();
@Override
public boolean addConnectedSwitch(Dpid dpid, OpenFlowSwitch sw) {
if (connectedSwitches.get(dpid) != null) {
log.error("Trying to add connectedSwitch but found a previous "
+ "value for dpid: {}", dpid);
return false;
} else {
log.info("Added switch {}", dpid);
connectedSwitches.put(dpid, sw);
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchAdded(dpid);
}
return true;
}
}
@Override
public boolean validActivation(Dpid dpid) {
if (connectedSwitches.get(dpid) == null) {
log.error("Trying to activate switch but is not in "
+ "connected switches: dpid {}. Aborting ..",
dpid);
return false;
}
if (activeMasterSwitches.get(dpid) != null ||
activeEqualSwitches.get(dpid) != null) {
log.error("Trying to activate switch but it is already "
+ "activated: dpid {}. Found in activeMaster: {} "
+ "Found in activeEqual: {}. Aborting ..",
dpid,
(activeMasterSwitches.get(dpid) == null) ? 'N' : 'Y',
(activeEqualSwitches.get(dpid) == null) ? 'N' : 'Y');
return false;
}
return true;
}
@Override
public boolean addActivatedMasterSwitch(Dpid dpid, OpenFlowSwitch sw) {
switchLock.lock();
try {
if (!validActivation(dpid)) {
return false;
}
activeMasterSwitches.put(dpid, sw);
return true;
} finally {
switchLock.unlock();
}
}
@Override
public boolean addActivatedEqualSwitch(Dpid dpid, OpenFlowSwitch sw) {
switchLock.lock();
try {
if (!validActivation(dpid)) {
return false;
}
activeEqualSwitches.put(dpid, sw);
log.info("Added Activated EQUAL Switch {}", dpid);
return true;
} finally {
switchLock.unlock();
}
}
@Override
public void transitionToMasterSwitch(Dpid dpid) {
switchLock.lock();
try {
if (activeMasterSwitches.containsKey(dpid)) {
return;
}
OpenFlowSwitch sw = activeEqualSwitches.remove(dpid);
if (sw == null) {
sw = getSwitch(dpid);
if (sw == null) {
log.error("Transition to master called on sw {}, but switch "
+ "was not found in controller-cache", dpid);
return;
}
}
log.info("Transitioned switch {} to MASTER", dpid);
activeMasterSwitches.put(dpid, sw);
} finally {
switchLock.unlock();
}
}
@Override
public void transitionToEqualSwitch(Dpid dpid) {
switchLock.lock();
try {
if (activeEqualSwitches.containsKey(dpid)) {
return;
}
OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
if (sw == null) {
sw = getSwitch(dpid);
if (sw == null) {
log.error("Transition to equal called on sw {}, but switch "
+ "was not found in controller-cache", dpid);
return;
}
}
log.info("Transitioned switch {} to EQUAL", dpid);
activeEqualSwitches.put(dpid, sw);
} finally {
switchLock.unlock();
}
}
@Override
public void removeConnectedSwitch(Dpid dpid) {
connectedSwitches.remove(dpid);
OpenFlowSwitch sw = activeMasterSwitches.remove(dpid);
if (sw == null) {
log.debug("sw was null for {}", dpid);
sw = activeEqualSwitches.remove(dpid);
}
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.switchRemoved(dpid);
}
}
@Override
public void processDownstreamMessage(Dpid dpid, List<OFMessage> m) {
for (OpenFlowMessageListener listener : ofMessageListener) {
listener.handleOutgoingMessage(dpid, m);
}
}
@Override
public void processMessage(Dpid dpid, OFMessage m) {
processPacket(dpid, m);
for (OpenFlowMessageListener listener : ofMessageListener) {
listener.handleIncomingMessage(dpid, m);
}
}
@Override
public void returnRoleReply(Dpid dpid, RoleState requested, RoleState response) {
for (OpenFlowSwitchListener l : ofSwitchListener) {
l.receivedRoleReply(dpid, requested, response);
}
}
}
/**
* OpenFlow message handler.
*/
protected final class OFMessageHandler implements Runnable {
protected final OFMessage msg;
protected final Dpid dpid;
public OFMessageHandler(Dpid dpid, OFMessage msg) {
this.msg = msg;
this.dpid = dpid;
}
@Override
public void run() {
for (OpenFlowEventListener listener : ofEventListener) {
listener.handleMessage(dpid, msg);
}
}
}
}
| ONOS dont give QUEUE stats like other stats message (portstats etc.). I modified OpenFlowControllerImpl for this development.
Change-Id: I36b2cd494ea78c1a4ca2ca4426810bfdb4b0d697
| protocols/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenFlowControllerImpl.java | ONOS dont give QUEUE stats like other stats message (portstats etc.). I modified OpenFlowControllerImpl for this development. | <ide><path>rotocols/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenFlowControllerImpl.java
<ide> import static org.onosproject.net.Device.Type.CONTROLLER;
<ide> import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
<ide> import static org.onosproject.openflow.controller.Dpid.dpid;
<add>import org.projectfloodlight.openflow.protocol.OFQueueStatsEntry;
<add>import org.projectfloodlight.openflow.protocol.OFQueueStatsReply;
<add>
<ide>
<ide> @Component(immediate = true)
<ide> @Service
<ide> protected Multimap<Dpid, OFPortStatsEntry> fullPortStats =
<ide> ArrayListMultimap.create();
<ide>
<add> protected Multimap<Dpid, OFQueueStatsEntry> fullQueueStats =
<add> ArrayListMultimap.create();
<add>
<ide> private final Controller ctrl = new Controller();
<ide> private InternalDeviceListener listener = new InternalDeviceListener();
<ide>
<ide> return future;
<ide> }
<ide>
<add> // CHECKSTYLE IGNORE MethodLength FOR NEXT 300 LINES
<ide> @Override
<ide> public void processPacket(Dpid dpid, OFMessage msg) {
<ide> Collection<OFFlowStatsEntry> flowStats;
<ide> Collection<OFTableStatsEntry> tableStats;
<ide> Collection<OFGroupStatsEntry> groupStats;
<ide> Collection<OFGroupDescStatsEntry> groupDescStats;
<add> Collection<OFQueueStatsEntry> queueStatsEntries;
<ide>
<ide> OpenFlowSwitch sw = this.getSwitch(dpid);
<ide>
<ide> break;
<ide> }
<ide> OpenFlowPacketContext pktCtx = DefaultOpenFlowPacketContext
<del> .packetContextFromPacketIn(sw, (OFPacketIn) msg);
<add> .packetContextFromPacketIn(sw, (OFPacketIn) msg);
<ide> for (PacketListener p : ofPacketListener.values()) {
<ide> p.handlePacket(pktCtx);
<ide> }
<ide> case STATS_REPLY:
<ide> OFStatsReply reply = (OFStatsReply) msg;
<ide> switch (reply.getStatsType()) {
<add> case QUEUE:
<add> queueStatsEntries = publishQueueStats(dpid, (OFQueueStatsReply) reply);
<add> if (queueStatsEntries != null) {
<add> OFQueueStatsReply.Builder rep =
<add> OFFactories.getFactory(msg.getVersion()).buildQueueStatsReply();
<add> rep.setEntries(Lists.newLinkedList(queueStatsEntries));
<add> rep.setXid(reply.getXid());
<add> executorMsgs.execute(new OFMessageHandler(dpid, rep.build()));
<add> }
<add> break;
<ide> case PORT_DESC:
<ide> for (OpenFlowSwitchListener l : ofSwitchListener) {
<ide> l.switchChanged(dpid);
<ide> return null;
<ide> }
<ide>
<add> private synchronized Collection<OFQueueStatsEntry> publishQueueStats(Dpid dpid, OFQueueStatsReply reply) {
<add> fullQueueStats.putAll(dpid, reply.getEntries());
<add> if (!reply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
<add> return fullQueueStats.removeAll(dpid);
<add> }
<add> return null;
<add> }
<add>
<ide> @Override
<ide> public void setRole(Dpid dpid, RoleState role) {
<ide> final OpenFlowSwitch sw = getSwitch(dpid); |
|
Java | apache-2.0 | 95b1e00cf11622a89916d422dce74c9db11ae916 | 0 | ysb33r/asciidoctorj,solent/asciidoctorj,asciidoctor/asciidoctorj,robertpanzer/asciidoctorj,ysb33r/asciidoctorj,solent/asciidoctorj,danielgrycman/asciidoctorj,danielgrycman/asciidoctorj,mojavelinux/asciidoctorj,danielgrycman/asciidoctorj,ysb33r/asciidoctorj,ancho/asciidoctorj,mojavelinux/asciidoctorj,asciidoctor/asciidoctorj,lefou/asciidoctorj,asciidoctor/asciidoctorj,ancho/asciidoctorj,robertpanzer/asciidoctorj,lefou/asciidoctorj,ancho/asciidoctorj,danielgrycman/asciidoctorj,mojavelinux/asciidoctorj,lefou/asciidoctorj,ysb33r/asciidoctorj,abelsromero/asciidoctorj,abelsromero/asciidoctorj,lefou/asciidoctorj,abelsromero/asciidoctorj,solent/asciidoctorj,solent/asciidoctorj,robertpanzer/asciidoctorj | package org.asciidoctor;
import static org.junit.Assert.assertThat;
import static org.asciidoctor.OptionsBuilder.options;
import static org.hamcrest.CoreMatchers.is;
import java.io.File;
import org.asciidoctor.internal.JRubyAsciidoctor;
import org.junit.Test;
public class WhenANoneStandardBackendIsSet {
private Asciidoctor asciidoctor = JRubyAsciidoctor.create();
@Test
public void epub3_should_be_rendered_for_epub3_backend() {
asciidoctor.renderFile(new File("target/test-classes/epub-index.adoc"),
options().safe(SafeMode.SAFE).backend("epub3").get());
assertThat(new File("target/test-classes/epub-index.epub").exists(), is(true));
}
}
| src/test/java/org/asciidoctor/WhenANoneStandardBackendIsSet.java | package org.asciidoctor;
import static org.asciidoctor.OptionsBuilder.options;
import java.io.File;
import org.asciidoctor.internal.JRubyAsciidoctor;
import org.junit.Test;
public class WhenANoneStandardBackendIsSet {
private Asciidoctor asciidoctor = JRubyAsciidoctor.create();
@Test
public void epub3_should_be_rendered_for_epub3_backend() {
//System.setProperty("file.encoding", "UTF-8");
asciidoctor.renderFile(new File("target/test-classes/epub-index.adoc"),
options().safe(SafeMode.SAFE).backend("epub3").get());
}
}
| resolves issue #168 by adding a test for epub3 backend.
| src/test/java/org/asciidoctor/WhenANoneStandardBackendIsSet.java | resolves issue #168 by adding a test for epub3 backend. | <ide><path>rc/test/java/org/asciidoctor/WhenANoneStandardBackendIsSet.java
<ide> package org.asciidoctor;
<ide>
<add>import static org.junit.Assert.assertThat;
<ide> import static org.asciidoctor.OptionsBuilder.options;
<add>import static org.hamcrest.CoreMatchers.is;
<ide>
<ide> import java.io.File;
<ide>
<ide>
<ide> @Test
<ide> public void epub3_should_be_rendered_for_epub3_backend() {
<del> //System.setProperty("file.encoding", "UTF-8");
<ide>
<ide> asciidoctor.renderFile(new File("target/test-classes/epub-index.adoc"),
<ide> options().safe(SafeMode.SAFE).backend("epub3").get());
<add>
<add> assertThat(new File("target/test-classes/epub-index.epub").exists(), is(true));
<add>
<ide> }
<ide>
<ide> } |
|
Java | mit | error: pathspec 'Party.java' did not match any file(s) known to git
| 588b3d96daecd80d179929c5a245422892ccf857 | 1 | rpaskin/lp2java | import java.awt.*;
import java.awt.event.*;
class Party {
public void buildInvite(){
Frame f = new Frame();
Label l = new Label("Festa na casa do Tim!");
Button b = new Button("Com certeza!");
Button c = new Button("Nem pensar");
Panel p = new Panel();
p.add(l);
}
} | Party.java | Primeiro demo
| Party.java | Primeiro demo | <ide><path>arty.java
<add>import java.awt.*;
<add>import java.awt.event.*;
<add>class Party {
<add> public void buildInvite(){
<add> Frame f = new Frame();
<add> Label l = new Label("Festa na casa do Tim!");
<add> Button b = new Button("Com certeza!");
<add> Button c = new Button("Nem pensar");
<add> Panel p = new Panel();
<add> p.add(l);
<add> }
<add>} |
|
JavaScript | mit | 3352048f9e70699475ad80728aa07501841bf8e4 | 0 | Availity/metalsmith-prism | /* global describe, it */
var chai = require('chai');
var metalsmith = require('metalsmith');
var metalsmithPrism = require('../lib');
var fs = require('fs');
var path = require('path');
var expect = chai.expect;
var fixture = path.resolve.bind(path, __dirname, 'fixtures/markup');
function file(_path) {
return fs.readFileSync(fixture(_path), 'utf8');
}
describe('metalsmith-prism', function() {
it('should highlight code blocks for json, markup, ruby and bash', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism())
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/json.html')).to.be.eql(file('expected/json.html'));
expect(file('build/markup.html')).to.be.eql(file('expected/markup.html'));
expect(file('build/ruby.html')).to.be.eql(file('expected/ruby.html'));
expect(file('build/bash.html')).to.be.eql(file('expected/bash.html'));
done();
});
});
it('should NOT highlight unknown language code blocks', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism())
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/unknown.html')).to.be.eql(file('expected/unknown.html'));
done();
});
});
it('should decode markup blocks when options#decode is true', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism({
decode: true
}))
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/markup-encoded.html')).to.be.eql(file('expected/markup-encoded.html'));
done();
});
});
it('should add line numbers class to <pre> tag when options#lineNumbers is true', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism({
lineNumbers: true
}))
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/line-numbers.html')).to.be.eql(file('expected/line-numbers.html'));
done();
});
});
});
| tests/index.js | /* global describe, it */
var chai = require('chai');
var metalsmith = require('metalsmith');
var metalsmithPrism = require('../lib');
var fs = require('fs');
var path = require('path');
var expect = chai.expect;
var fixture = path.resolve.bind(path, __dirname, 'fixtures/markup');
function file(_path) {
return fs.readFileSync(fixture(_path), 'utf8');
}
describe('metalsmith-prism', function() {
it('should highlight code blocks for json, markup, ruby and bash', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism())
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/json.html')).to.be.eql(file('expected/json.html'));
expect(file('build/markup.html')).to.be.eql(file('expected/markup.html'));
expect(file('build/ruby.html')).to.be.eql(file('expected/ruby.html'));
expect(file('build/bash.html')).to.be.eql(file('expected/bash.html'));
done();
});
});
it('should NOT highlight unknown language code blocks', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism())
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/unknown.html')).to.be.eql(file('expected/unknown.html'));
done();
});
});
it('should decode markup blocks when options#decode is true', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism({
decode: true
}))
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/markup-encoded.html')).to.be.eql(file('expected/markup-encoded.html'));
done();
});
});
it('should add line numbers class when options#lineNumbers is true', function(done) {
var metal = metalsmith(fixture());
metal
.use(metalsmithPrism({
lineNumbers: true
}))
.build(function(err) {
if (err) {
return done(err);
}
expect(file('build/line-numbers.html')).to.be.eql(file('expected/line-numbers.html'));
done();
});
});
});
| refactor spec description
| tests/index.js | refactor spec description | <ide><path>ests/index.js
<ide>
<ide> });
<ide>
<del> it('should add line numbers class when options#lineNumbers is true', function(done) {
<add> it('should add line numbers class to <pre> tag when options#lineNumbers is true', function(done) {
<ide>
<ide> var metal = metalsmith(fixture());
<ide> |
|
Java | mit | 99cb226e7c3362dbd4b15862f161af6c3f32e1a9 | 0 | kcsl/immutability-benchmark,kcsl/immutability-benchmark,kcsl/immutability-benchmark,kcsl/immutability-benchmark | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class ReImInferGrader {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
// debug
// args = new String[]{"/Users/benjholla/Desktop/test","/Users/benjholla/Desktop/test/summary.txt"};
File inputDirectory = new File(args[0]);
File summaryFile = new File(args[1]);
File executionProofFile = new File(inputDirectory.getAbsolutePath() + File.separator + "execution-proof.txt");
File analysisResultFile = new File(inputDirectory.getAbsolutePath() + File.separator + "reim-result.csv");
FileWriter summary = new FileWriter(summaryFile, true);
String executionResult;
try {
Scanner scanner = new Scanner(executionProofFile);
String line1 = scanner.nextLine();
String line2 = scanner.nextLine();
if(line1.equals(line2)){
executionResult = "READONLY";
} else {
executionResult = "MUTABLE";
}
scanner.close();
} catch (Exception e){
executionResult = "Grader Error: " + e.getMessage();
}
System.out.println("Execution Result: " + executionResult);
String analysisResult = "UNTYPED";
try {
Scanner scanner = new Scanner(analysisResultFile);
while(scanner.hasNextLine()){
String line = scanner.nextLine().trim();
if(line.contains("\t" + "test" + "\t")){
if(line.contains("@Readonly")){
analysisResult = "READONLY";
} else if(line.contains("@Mutable")){
analysisResult = "MUTABLE";
} else if(line.contains("@Polyread")){
analysisResult = "POLYREAD";
} else {
throw new RuntimeException("Unexpected type " + line);
}
break;
}
}
scanner.close();
} catch (Exception e){
analysisResult = "Grader Error: " + e.getMessage();
}
System.out.println("Analysis Result: " + analysisResult);
String status;
String rationale;
if(analysisResult.equals("READONLY") && executionResult.equals("MUTABLE")){
status = "FAIL";
rationale = "test was mutated but reported as readonly";
System.out.println("FAIL");
summary.write(inputDirectory.getName() + ",FAIL\n");
} else if(analysisResult.equals("MUTABLE") && executionResult.equals("READONLY")){
status = "FAIL";
rationale = "test was readonly but reported as mutable";
} else {
if(analysisResult.equals("POLYREAD") && executionResult.equals("MUTABLE")){
status = "PASS";
rationale = "polyread indicates a mutation could occur in a given context";
} else if(analysisResult.equals(executionResult)){
status = "PASS";
rationale = "correct analysis";
} else {
status = "FAIL";
rationale = "UNKNOWN";
}
}
System.out.println("Score: " + status + "," + rationale);
summary.write(inputDirectory.getName() + "," + status + "," + rationale + "\n");
summary.close();
}
}
| harnesses/ReImInfer-0.1.3/ReImInferGrader/src/ReImInferGrader.java | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class ReImInferGrader {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
// debug
// args = new String[]{"C:\\Users\\Ben\\Desktop\\test4","C:\\Users\\Ben\\Desktop\\test3\\summary.txt"};
File inputDirectory = new File(args[0]);
File summaryFile = new File(args[1]);
File executionProof = new File(inputDirectory.getAbsolutePath() + File.separator + "execution-proof.txt");
File analysisResult = new File(inputDirectory.getAbsolutePath() + File.separator + "reim-result.csv");
FileWriter summary = new FileWriter(summaryFile, true);
try {
Scanner scanner = new Scanner(executionProof);
HashMap<String,Set<String>> comparisons = new HashMap<String,Set<String>>();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
// strip testcase name
line = line.replace(line.split(" ")[0], "").replace(" ","");
// parse object fields
line = line.substring(line.indexOf("[") + 1, line.lastIndexOf("]"));
Scanner tokens = new Scanner(line).useDelimiter(",|=");
while(tokens.hasNext()){
String field = tokens.next();
String value;
// consider nested objects
if(line.contains("=[")){
line = line.substring(line.indexOf("[") + 1);
tokens = new Scanner(line).useDelimiter("]");
value = tokens.next();
line = line.substring(value.length()+1);
if(line.startsWith(",")){
line = line.substring(1);
}
// check if there are any fields left
if(!line.contains(",") && !line.contains("=")){
line = "";
}
tokens = new Scanner(line).useDelimiter(",|=");
} else {
value = tokens.next();
}
if(!comparisons.containsKey(field)){
comparisons.put(field, new HashSet<String>());
}
comparisons.get(field).add(value);
}
}
HashMap<String,Boolean> mutations = new HashMap<String,Boolean>();
for(Entry<String,Set<String>> entry : comparisons.entrySet()){
mutations.put(entry.getKey(), entry.getValue().size() != 1);
}
HashMap<String,Set<String>> analysis = new HashMap<String,Set<String>>();
scanner = new Scanner(analysisResult);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
for(String field : mutations.keySet()){
if(line.contains("\t" + field + "\t")){
if(!analysis.containsKey(field)){
analysis.put(field, new HashSet<String>());
}
if(line.contains("@Readonly")){
analysis.get(field).add("READONLY");
}
if(line.contains("@Mutable")){
analysis.get(field).add("MUTABLE");
}
if(line.contains("@Polyread")){
analysis.get(field).add("POLYREAD");
}
if(analysis.get(field).isEmpty()) {
throw new RuntimeException("Unexpected input: " + line);
}
break;
}
}
}
FileWriter writer = new FileWriter(new File(inputDirectory.getAbsolutePath() + File.separator + "grader-logic.txt"));
writer.write("Comparisons: " + comparisons.toString() + "\n");
writer.write("Mutations: " + mutations.toString() + "\n");
writer.write("Analysis: " + analysis.toString() + "\n");
writer.close();
for(Entry<String,Set<String>> result : analysis.entrySet()){
String key = result.getKey();
if(result.getValue().contains("READONLY") && result.getValue().size()==1 && mutations.containsKey(key) && mutations.get(key) == true){
// analysis reported readonly but there was a mutation
System.out.println("FAIL");
summary.write(inputDirectory.getName() + ",FAIL\n");
summary.close();
return;
} else if(result.getValue().contains("MUTABLE") && result.getValue().size()==1 && mutations.containsKey(key) && mutations.get(key) == false){
// analysis reported mutable, but there was no mutation
System.out.println("FAIL");
summary.write(inputDirectory.getName() + ",FAIL\n");
summary.close();
return;
}
// else if(result.getValue().equals("POLYREAD") && mutations.containsKey(key) && mutations.get(key) == false){
// // analysis reported polyread but there was no mutation
// System.out.println("FAIL");
// return;
// }
}
System.out.println("PASS");
summary.write(inputDirectory.getName() + ",PASS\n");
summary.close();
} catch (Exception e){
e.printStackTrace();
System.out.println("GRADER ERROR");
summary.write(inputDirectory.getName() + ",GRADER ERROR\n");
summary.close();
}
}
}
| reworked reiminfer 0.1.3 grader | harnesses/ReImInfer-0.1.3/ReImInferGrader/src/ReImInferGrader.java | reworked reiminfer 0.1.3 grader | <ide><path>arnesses/ReImInfer-0.1.3/ReImInferGrader/src/ReImInferGrader.java
<ide> public static void main(String[] args) throws IOException {
<ide>
<ide> // debug
<del>// args = new String[]{"C:\\Users\\Ben\\Desktop\\test4","C:\\Users\\Ben\\Desktop\\test3\\summary.txt"};
<add>// args = new String[]{"/Users/benjholla/Desktop/test","/Users/benjholla/Desktop/test/summary.txt"};
<ide>
<ide> File inputDirectory = new File(args[0]);
<ide> File summaryFile = new File(args[1]);
<del> File executionProof = new File(inputDirectory.getAbsolutePath() + File.separator + "execution-proof.txt");
<del> File analysisResult = new File(inputDirectory.getAbsolutePath() + File.separator + "reim-result.csv");
<add> File executionProofFile = new File(inputDirectory.getAbsolutePath() + File.separator + "execution-proof.txt");
<add> File analysisResultFile = new File(inputDirectory.getAbsolutePath() + File.separator + "reim-result.csv");
<ide>
<ide> FileWriter summary = new FileWriter(summaryFile, true);
<ide>
<add> String executionResult;
<ide> try {
<del> Scanner scanner = new Scanner(executionProof);
<del> HashMap<String,Set<String>> comparisons = new HashMap<String,Set<String>>();
<add> Scanner scanner = new Scanner(executionProofFile);
<add> String line1 = scanner.nextLine();
<add> String line2 = scanner.nextLine();
<add> if(line1.equals(line2)){
<add> executionResult = "READONLY";
<add> } else {
<add> executionResult = "MUTABLE";
<add> }
<add> scanner.close();
<add> } catch (Exception e){
<add> executionResult = "Grader Error: " + e.getMessage();
<add> }
<add> System.out.println("Execution Result: " + executionResult);
<add>
<add> String analysisResult = "UNTYPED";
<add> try {
<add> Scanner scanner = new Scanner(analysisResultFile);
<ide> while(scanner.hasNextLine()){
<del> String line = scanner.nextLine();
<del> // strip testcase name
<del> line = line.replace(line.split(" ")[0], "").replace(" ","");
<del> // parse object fields
<del> line = line.substring(line.indexOf("[") + 1, line.lastIndexOf("]"));
<del> Scanner tokens = new Scanner(line).useDelimiter(",|=");
<del> while(tokens.hasNext()){
<del> String field = tokens.next();
<del> String value;
<del> // consider nested objects
<del> if(line.contains("=[")){
<del> line = line.substring(line.indexOf("[") + 1);
<del> tokens = new Scanner(line).useDelimiter("]");
<del> value = tokens.next();
<del> line = line.substring(value.length()+1);
<del> if(line.startsWith(",")){
<del> line = line.substring(1);
<del> }
<del> // check if there are any fields left
<del> if(!line.contains(",") && !line.contains("=")){
<del> line = "";
<del> }
<del> tokens = new Scanner(line).useDelimiter(",|=");
<add> String line = scanner.nextLine().trim();
<add> if(line.contains("\t" + "test" + "\t")){
<add> if(line.contains("@Readonly")){
<add> analysisResult = "READONLY";
<add> } else if(line.contains("@Mutable")){
<add> analysisResult = "MUTABLE";
<add> } else if(line.contains("@Polyread")){
<add> analysisResult = "POLYREAD";
<ide> } else {
<del> value = tokens.next();
<add> throw new RuntimeException("Unexpected type " + line);
<ide> }
<del> if(!comparisons.containsKey(field)){
<del> comparisons.put(field, new HashSet<String>());
<del> }
<del> comparisons.get(field).add(value);
<add> break;
<ide> }
<ide> }
<del>
<del> HashMap<String,Boolean> mutations = new HashMap<String,Boolean>();
<del> for(Entry<String,Set<String>> entry : comparisons.entrySet()){
<del> mutations.put(entry.getKey(), entry.getValue().size() != 1);
<add> scanner.close();
<add> } catch (Exception e){
<add> analysisResult = "Grader Error: " + e.getMessage();
<add> }
<add> System.out.println("Analysis Result: " + analysisResult);
<add>
<add> String status;
<add> String rationale;
<add> if(analysisResult.equals("READONLY") && executionResult.equals("MUTABLE")){
<add> status = "FAIL";
<add> rationale = "test was mutated but reported as readonly";
<add> System.out.println("FAIL");
<add> summary.write(inputDirectory.getName() + ",FAIL\n");
<add> } else if(analysisResult.equals("MUTABLE") && executionResult.equals("READONLY")){
<add> status = "FAIL";
<add> rationale = "test was readonly but reported as mutable";
<add> } else {
<add> if(analysisResult.equals("POLYREAD") && executionResult.equals("MUTABLE")){
<add> status = "PASS";
<add> rationale = "polyread indicates a mutation could occur in a given context";
<add> } else if(analysisResult.equals(executionResult)){
<add> status = "PASS";
<add> rationale = "correct analysis";
<add> } else {
<add> status = "FAIL";
<add> rationale = "UNKNOWN";
<ide> }
<del>
<del> HashMap<String,Set<String>> analysis = new HashMap<String,Set<String>>();
<del> scanner = new Scanner(analysisResult);
<del> while(scanner.hasNextLine()){
<del> String line = scanner.nextLine();
<del> for(String field : mutations.keySet()){
<del> if(line.contains("\t" + field + "\t")){
<del> if(!analysis.containsKey(field)){
<del> analysis.put(field, new HashSet<String>());
<del> }
<del> if(line.contains("@Readonly")){
<del> analysis.get(field).add("READONLY");
<del> }
<del> if(line.contains("@Mutable")){
<del> analysis.get(field).add("MUTABLE");
<del> }
<del> if(line.contains("@Polyread")){
<del> analysis.get(field).add("POLYREAD");
<del> }
<del> if(analysis.get(field).isEmpty()) {
<del> throw new RuntimeException("Unexpected input: " + line);
<del> }
<del> break;
<del> }
<del> }
<del> }
<del>
<del> FileWriter writer = new FileWriter(new File(inputDirectory.getAbsolutePath() + File.separator + "grader-logic.txt"));
<del> writer.write("Comparisons: " + comparisons.toString() + "\n");
<del> writer.write("Mutations: " + mutations.toString() + "\n");
<del> writer.write("Analysis: " + analysis.toString() + "\n");
<del> writer.close();
<del>
<del> for(Entry<String,Set<String>> result : analysis.entrySet()){
<del> String key = result.getKey();
<del> if(result.getValue().contains("READONLY") && result.getValue().size()==1 && mutations.containsKey(key) && mutations.get(key) == true){
<del> // analysis reported readonly but there was a mutation
<del> System.out.println("FAIL");
<del> summary.write(inputDirectory.getName() + ",FAIL\n");
<del> summary.close();
<del> return;
<del> } else if(result.getValue().contains("MUTABLE") && result.getValue().size()==1 && mutations.containsKey(key) && mutations.get(key) == false){
<del> // analysis reported mutable, but there was no mutation
<del> System.out.println("FAIL");
<del> summary.write(inputDirectory.getName() + ",FAIL\n");
<del> summary.close();
<del> return;
<del> }
<del>// else if(result.getValue().equals("POLYREAD") && mutations.containsKey(key) && mutations.get(key) == false){
<del>// // analysis reported polyread but there was no mutation
<del>// System.out.println("FAIL");
<del>// return;
<del>// }
<del> }
<del> System.out.println("PASS");
<del> summary.write(inputDirectory.getName() + ",PASS\n");
<del> summary.close();
<del> } catch (Exception e){
<del> e.printStackTrace();
<del> System.out.println("GRADER ERROR");
<del> summary.write(inputDirectory.getName() + ",GRADER ERROR\n");
<del> summary.close();
<ide> }
<add> System.out.println("Score: " + status + "," + rationale);
<add> summary.write(inputDirectory.getName() + "," + status + "," + rationale + "\n");
<add> summary.close();
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | dcf76f37552983084e7923568e9dd14928f2c425 | 0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,gerrit-review/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.notedb;
import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage;
/**
* Possible high-level states of the NoteDb migration for changes.
*
* <p>This class describes the series of states required to migrate a site from ReviewDb-only to
* NoteDb-only. This process has several steps, and covers only a small subset of the theoretically
* possible combinations of {@link NotesMigration} return values.
*
* <p>These states are ordered: a one-way migration from ReviewDb to NoteDb will pass through states
* in the order in which they are defined.
*/
public enum NotesMigrationState {
REVIEW_DB(false, false, false, PrimaryStorage.REVIEW_DB, false, false),
WRITE(false, true, false, PrimaryStorage.REVIEW_DB, false, false),
READ_WRITE_NO_SEQUENCE(true, true, false, PrimaryStorage.REVIEW_DB, false, false),
READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY(
true, true, true, PrimaryStorage.REVIEW_DB, false, false),
READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY(true, true, true, PrimaryStorage.NOTE_DB, false, false),
// TODO(dborowitz): This only exists as a separate state to support testing in different
// NoteDbModes. Once FileRepository fuses BatchRefUpdates, we won't have separate fused/unfused
// states.
NOTE_DB_UNFUSED(true, true, true, PrimaryStorage.NOTE_DB, true, false),
NOTE_DB(true, true, true, PrimaryStorage.NOTE_DB, true, true);
private final NotesMigration migration;
NotesMigrationState(
// Arguments match abstract methods in NotesMigration.
boolean readChanges,
boolean rawWriteChangesSetting,
boolean readChangeSequence,
PrimaryStorage changePrimaryStorage,
boolean disableChangeReviewDb,
boolean fuseUpdates) {
this.migration =
new NotesMigration() {
@Override
public boolean readChanges() {
return readChanges;
}
@Override
public boolean rawWriteChangesSetting() {
return rawWriteChangesSetting;
}
@Override
public boolean readChangeSequence() {
return readChangeSequence;
}
@Override
public PrimaryStorage changePrimaryStorage() {
return changePrimaryStorage;
}
@Override
public boolean disableChangeReviewDb() {
return disableChangeReviewDb;
}
@Override
public boolean fuseUpdates() {
return fuseUpdates;
}
};
}
public NotesMigration migration() {
return migration;
}
}
| gerrit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigrationState.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.notedb;
import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage;
/**
* Possible high-level states of the NoteDb migration for changes.
*
* <p>This class describes the series of states required to migrate a site from ReviewDb-only to
* NoteDb-only. This process has several steps, and covers only a small subset of the theoretically
* possible combinations of {@link NotesMigration} return values.
*
* <p>These states are ordered: a one-way migration from ReviewDb to NoteDb will pass through states
* in the order in which they are defined.
*/
public enum NotesMigrationState {
REVIEW_DB(false, false, false, PrimaryStorage.REVIEW_DB, false, false),
WRITE(false, true, false, PrimaryStorage.REVIEW_DB, false, false),
READ_WRITE_NO_SEQUENCE(true, true, false, PrimaryStorage.REVIEW_DB, false, false),
READ_WRITE_WITH_SEQUENCE_REVIEW_DB_PRIMARY(
true, true, true, PrimaryStorage.REVIEW_DB, false, false),
READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY(true, true, true, PrimaryStorage.NOTE_DB, false, false),
NOTE_DB_UNFUSED(true, true, true, PrimaryStorage.NOTE_DB, true, false),
NOTE_DB(true, true, true, PrimaryStorage.NOTE_DB, true, true);
private final NotesMigration migration;
NotesMigrationState(
// Arguments match abstract methods in NotesMigration.
boolean readChanges,
boolean rawWriteChangesSetting,
boolean readChangeSequence,
PrimaryStorage changePrimaryStorage,
boolean disableChangeReviewDb,
boolean fuseUpdates) {
this.migration =
new NotesMigration() {
@Override
public boolean readChanges() {
return readChanges;
}
@Override
public boolean rawWriteChangesSetting() {
return rawWriteChangesSetting;
}
@Override
public boolean readChangeSequence() {
return readChangeSequence;
}
@Override
public PrimaryStorage changePrimaryStorage() {
return changePrimaryStorage;
}
@Override
public boolean disableChangeReviewDb() {
return disableChangeReviewDb;
}
@Override
public boolean fuseUpdates() {
return fuseUpdates;
}
};
}
public NotesMigration migration() {
return migration;
}
}
| NotesMigrationState: Clarify plans for fused/unfused states
Change-Id: Ifb98a43d3a36b20dde9174332938b4ae6b94f0e6
| gerrit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigrationState.java | NotesMigrationState: Clarify plans for fused/unfused states | <ide><path>errit-server/src/main/java/com/google/gerrit/server/notedb/NotesMigrationState.java
<ide>
<ide> READ_WRITE_WITH_SEQUENCE_NOTE_DB_PRIMARY(true, true, true, PrimaryStorage.NOTE_DB, false, false),
<ide>
<add> // TODO(dborowitz): This only exists as a separate state to support testing in different
<add> // NoteDbModes. Once FileRepository fuses BatchRefUpdates, we won't have separate fused/unfused
<add> // states.
<ide> NOTE_DB_UNFUSED(true, true, true, PrimaryStorage.NOTE_DB, true, false),
<ide>
<ide> NOTE_DB(true, true, true, PrimaryStorage.NOTE_DB, true, true); |
|
Java | apache-2.0 | 6d75c319582b17ae76d26c1052d29264a0d22c52 | 0 | GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,resmo/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,jcshen007/cloudstack,resmo/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack | // 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.cloud.vm;
import java.net.URI;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.deploy.DeploymentPlanner;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.jobs.AsyncJob;
import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.framework.jobs.Outcome;
import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao;
import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper;
import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.MessageHandler;
import org.apache.cloudstack.jobs.JobInfo;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.ClusterSyncAnswer;
import com.cloud.agent.api.ClusterSyncCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PlugNicAnswer;
import com.cloud.agent.api.PlugNicCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupRoutingCommand.VmState;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.UnPlugNicAnswer;
import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.manager.Commands;
import com.cloud.agent.manager.allocator.HostAllocator;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.CapacityManager;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterDetailsVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Pod;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.deploy.DeploymentPlanningManager;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.AffinityConflictException;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.ha.HighAvailabilityManager.WorkType;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.network.Network;
import com.cloud.network.NetworkModel;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.resource.ResourceManager;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StoragePool;
import com.cloud.storage.Volume;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Journal;
import com.cloud.utils.Pair;
import com.cloud.utils.Predicate;
import com.cloud.utils.StringUtils;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.ItWorkVO.Step;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshot;
import com.cloud.vm.snapshot.VMSnapshotManager;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
@Local(value = VirtualMachineManager.class)
public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, VmWorkJobHandler, Listener, Configurable {
private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
public static final String VM_WORK_JOB_HANDLER = VirtualMachineManagerImpl.class.getSimpleName();
private static final String VM_SYNC_ALERT_SUBJECT = "VM state sync alert";
@Inject
DataStoreManager dataStoreMgr;
@Inject
protected NetworkOrchestrationService _networkMgr;
@Inject
protected NetworkModel _networkModel;
@Inject
protected AgentManager _agentMgr;
@Inject
protected VMInstanceDao _vmDao;
@Inject
protected ServiceOfferingDao _offeringDao;
@Inject
protected DiskOfferingDao _diskOfferingDao;
@Inject
protected VMTemplateDao _templateDao;
@Inject
protected DomainDao _domainDao;
@Inject
protected ItWorkDao _workDao;
@Inject
protected UserVmDao _userVmDao;
@Inject
protected CapacityManager _capacityMgr;
@Inject
protected NicDao _nicsDao;
@Inject
protected HostDao _hostDao;
@Inject
protected AlertManager _alertMgr;
@Inject
protected GuestOSCategoryDao _guestOsCategoryDao;
@Inject
protected GuestOSDao _guestOsDao;
@Inject
protected VolumeDao _volsDao;
@Inject
protected HighAvailabilityManager _haMgr;
@Inject
protected HostPodDao _podDao;
@Inject
protected DataCenterDao _dcDao;
@Inject
protected ClusterDao _clusterDao;
@Inject
protected PrimaryDataStoreDao _storagePoolDao;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject
protected NetworkDao _networkDao;
@Inject
protected StoragePoolHostDao _poolHostDao;
@Inject
protected VMSnapshotDao _vmSnapshotDao;
@Inject
protected RulesManager rulesMgr;
@Inject
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
protected EntityManager _entityMgr;
@Inject
ConfigDepot _configDepot;
protected List<HostAllocator> hostAllocators;
public List<HostAllocator> getHostAllocators() {
return hostAllocators;
}
public void setHostAllocators(List<HostAllocator> hostAllocators) {
this.hostAllocators = hostAllocators;
}
protected List<StoragePoolAllocator> _storagePoolAllocators;
@Inject
protected ResourceManager _resourceMgr;
@Inject
protected VMSnapshotManager _vmSnapshotMgr = null;
@Inject
protected ClusterDetailsDao _clusterDetailsDao;
@Inject
protected UserVmDetailsDao _uservmDetailsDao;
@Inject
protected ConfigurationDao _configDao;
@Inject
VolumeOrchestrationService volumeMgr;
@Inject
DeploymentPlanningManager _dpMgr;
@Inject
protected MessageBus _messageBus;
@Inject
protected VirtualMachinePowerStateSync _syncMgr;
@Inject
protected VmWorkJobDao _workJobDao;
@Inject
protected AsyncJobManager _jobMgr;
Map<VirtualMachine.Type, VirtualMachineGuru> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru>();
protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine;
static final ConfigKey<Integer> StartRetry = new ConfigKey<Integer>("Advanced", Integer.class, "start.retry", "10",
"Number of times to retry create and start commands", true);
static final ConfigKey<Integer> VmOpWaitInterval = new ConfigKey<Integer>("Advanced", Integer.class, "vm.op.wait.interval", "120",
"Time (in seconds) to wait before checking if a previous operation has succeeded", true);
static final ConfigKey<Integer> VmOpLockStateRetry = new ConfigKey<Integer>("Advanced", Integer.class, "vm.op.lock.state.retry", "5",
"Times to retry locking the state of a VM for operations, -1 means forever", true);
static final ConfigKey<Long> VmOpCleanupInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cleanup.interval", "86400",
"Interval to run the thread that cleans up the vm operations (in seconds)", false);
static final ConfigKey<Long> VmOpCleanupWait = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cleanup.wait", "3600",
"Time (in seconds) to wait before cleanuping up any vm work items", true);
static final ConfigKey<Long> VmOpCancelInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cancel.interval", "3600",
"Time (in seconds) to wait before cancelling a operation", false);
static final ConfigKey<Boolean> VmDestroyForcestop = new ConfigKey<Boolean>("Advanced", Boolean.class, "vm.destroy.forcestop", "false",
"On destroy, force-stop takes this value ", true);
static final ConfigKey<Integer> ClusterDeltaSyncInterval = new ConfigKey<Integer>("Advanced", Integer.class, "sync.interval", "60",
"Cluster Delta sync interval in seconds",
false);
static final ConfigKey<Boolean> VmJobEnabled = new ConfigKey<Boolean>("Advanced",
Boolean.class, "vm.job.enabled", "false",
"True to enable new VM sync model. false to use the old way", false);
static final ConfigKey<Long> VmJobCheckInterval = new ConfigKey<Long>("Advanced",
Long.class, "vm.job.check.interval", "3000",
"Interval in milliseconds to check if the job is complete", false);
static final ConfigKey<Long> VmJobTimeout = new ConfigKey<Long>("Advanced",
Long.class, "vm.job.timeout", "600000",
"Time in milliseconds to wait before attempting to cancel a job", false);
static final ConfigKey<Integer> VmJobStateReportInterval = new ConfigKey<Integer>("Advanced",
Integer.class, "vm.job.report.interval", "60",
"Interval to send application level pings to make sure the connection is still working", false);
ScheduledExecutorService _executor = null;
protected long _nodeId;
@Override
public void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru) {
synchronized (_vmGurus) {
_vmGurus.put(type, guru);
}
}
@Override
@DB
public void allocate(String vmInstanceName, final VirtualMachineTemplate template, ServiceOffering serviceOffering,
final Pair<? extends DiskOffering, Long> rootDiskOffering, LinkedHashMap<? extends DiskOffering, Long> dataDiskOfferings,
final LinkedHashMap<? extends Network, ? extends NicProfile> auxiliaryNetworks, DeploymentPlan plan, HypervisorType hyperType)
throws InsufficientCapacityException {
VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
final Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating entries for VM: " + vm);
}
vm.setDataCenterId(plan.getDataCenterId());
if (plan.getPodId() != null) {
vm.setPodId(plan.getPodId());
}
assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet";
final VMInstanceVO vmFinal = _vmDao.persist(vm);
final LinkedHashMap<? extends DiskOffering, Long> dataDiskOfferingsFinal =
dataDiskOfferings == null ? new LinkedHashMap<DiskOffering, Long>() : dataDiskOfferings;
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null);
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientCapacityException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating nics for " + vmFinal);
}
try {
_networkMgr.allocate(vmProfile, auxiliaryNetworks);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating disks for " + vmFinal);
}
if (template.getFormat() == ImageFormat.ISO) {
volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vmFinal, template, owner);
} else if (template.getFormat() == ImageFormat.BAREMETAL) {
// Do nothing
} else {
volumeMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOffering.first(), rootDiskOffering.second(), template, vmFinal, owner);
}
for (Map.Entry<? extends DiskOffering, Long> offering : dataDiskOfferingsFinal.entrySet()) {
volumeMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vmFinal.getId(), offering.getKey(), offering.getValue(), vmFinal, template, owner);
}
}
});
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocation completed for VM: " + vmFinal);
}
}
@Override
public void allocate(String vmInstanceName, VirtualMachineTemplate template, ServiceOffering serviceOffering,
LinkedHashMap<? extends Network, ? extends NicProfile> networks, DeploymentPlan plan, HypervisorType hyperType) throws InsufficientCapacityException {
allocate(vmInstanceName, template, serviceOffering, new Pair<DiskOffering, Long>(serviceOffering, null), null, networks, plan, hyperType);
}
private VirtualMachineGuru getVmGuru(VirtualMachine vm) {
return _vmGurus.get(vm.getType());
}
@Override
public void expunge(String vmUuid) throws ResourceUnavailableException {
try {
advanceExpunge(vmUuid);
} catch (OperationTimedoutException e) {
throw new CloudRuntimeException("Operation timed out", e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation ", e);
}
}
@Override
public void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
advanceExpunge(vm);
}
protected void advanceExpunge(VMInstanceVO vm) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
if (vm == null || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return;
}
advanceStop(vm.getUuid(), false);
try {
if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
throw new CloudRuntimeException("Unable to destroy " + vm);
}
} catch (NoTransitionException e) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
throw new CloudRuntimeException("Unable to destroy " + vm, e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
s_logger.debug("Cleaning up NICS");
List<Command> nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, profile.getNics());
_networkMgr.cleanupNics(profile);
// Clean up volumes based on the vm's instance id
volumeMgr.cleanupVolumes(vm.getId());
VirtualMachineGuru guru = getVmGuru(vm);
guru.finalizeExpunge(vm);
//remove the overcommit detials from the uservm details
_uservmDetailsDao.removeDetails(vm.getId());
// send hypervisor-dependent commands before removing
List<Command> finalizeExpungeCommands = hvGuru.finalizeExpunge(vm);
if (finalizeExpungeCommands != null && finalizeExpungeCommands.size() > 0) {
Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
if (hostId != null) {
Commands cmds = new Commands(Command.OnError.Stop);
for (Command command : finalizeExpungeCommands) {
cmds.addCommand(command);
}
if (nicExpungeCommands != null) {
for (Command command : nicExpungeCommands) {
cmds.addCommand(command);
}
}
_agentMgr.send(hostId, cmds);
if (!cmds.isSuccessful()) {
for (Answer answer : cmds.getAnswers()) {
if (!answer.getResult()) {
s_logger.warn("Failed to expunge vm due to: " + answer.getDetails());
throw new CloudRuntimeException("Unable to expunge " + vm + " due to " + answer.getDetails());
}
}
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunged " + vm);
}
}
@Override
public boolean start() {
_executor.scheduleAtFixedRate(new CleanupTask(), VmOpCleanupInterval.value(), VmOpCleanupInterval.value(), TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
ReservationContextImpl.init(_entityMgr);
VirtualMachineProfileImpl.init(_entityMgr);
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
_nodeId = ManagementServerNode.getManagementServerId();
_agentMgr.registerForHostEvents(this, true, true, true);
return true;
}
protected VirtualMachineManagerImpl() {
setStateMachine();
}
@Override
public void start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) {
start(vmUuid, params, null);
}
@Override
public void start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy) {
try {
advanceStart(vmUuid, params, planToDeploy, null);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid);
} catch (InsufficientCapacityException e) {
throw new CloudRuntimeException("Unable to start a VM due to insufficient capacity", e).add(VirtualMachine.class, vmUuid);
} catch (ResourceUnavailableException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid);
}
}
protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException {
while (true) {
ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state);
if (vo == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state);
}
return true;
}
if (vo.getStep() == Step.Done) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Work for " + vm + " is " + vo.getStep());
}
return true;
}
if (vo.getSecondsTaskIsInactive() > VmOpCancelInterval.value()) {
s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive());
return false;
}
try {
Thread.sleep(VmOpWaitInterval.value());
} catch (InterruptedException e) {
s_logger.info("Waiting for " + vm + " but is interrupted");
throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted");
}
s_logger.debug("Waiting some more to make sure there's no activity on " + vm);
}
}
@DB
protected Ternary<VMInstanceVO, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru vmGuru, final VMInstanceVO vm, final User caller,
final Account account) throws ConcurrentOperationException {
long vmId = vm.getId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
int retry = VmOpLockStateRetry.value();
while (retry-- != 0) {
try {
final ItWorkVO workFinal = work;
Ternary<VMInstanceVO, ReservationContext, ItWorkVO> result =
Transaction.execute(new TransactionCallbackWithException<Ternary<VMInstanceVO, ReservationContext, ItWorkVO>, NoTransitionException>() {
@Override
public Ternary<VMInstanceVO, ReservationContext, ItWorkVO> doInTransaction(TransactionStatus status) throws NoTransitionException {
Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
ItWorkVO work = _workDao.persist(workFinal);
ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
}
return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(vm, context, work);
}
return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(null, null, work);
}
});
work = result.third();
if (result.first() != null)
return result;
} catch (NoTransitionException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
}
}
VMInstanceVO instance = _vmDao.findById(vmId);
if (instance == null) {
throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ". Retry=" + retry);
}
State state = instance.getState();
if (state == State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already started: " + vm);
}
return null;
}
if (state.isTransitional()) {
if (!checkWorkItems(vm, state)) {
throw new ConcurrentOperationException("There are concurrent operations on " + vm);
} else {
continue;
}
}
if (state != State.Stopped) {
s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
return null;
}
}
throw new ConcurrentOperationException("Unable to change the state of " + vm);
}
protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException {
// FIXME: We should do this better.
Step previousStep = work.getStep();
_workDao.updateStep(work, step);
boolean result = false;
try {
result = stateTransitTo(vm, event, hostId);
return result;
} finally {
if (!result) {
_workDao.updateStep(work, previousStep);
}
}
}
protected boolean areAffinityGroupsAssociated(VirtualMachineProfile vmProfile) {
VirtualMachine vm = vmProfile.getVirtualMachine();
long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
if (vmGroupCount > 0) {
return true;
}
return false;
}
@Override
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlanner planner)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
advanceStart(vmUuid, params, null, planner);
}
@Override
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStart(vmUuid, params, planToDeploy, planner);
} else {
Outcome<VirtualMachine> outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
}
}
}
@Override
public void orchestrateStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy, DeploymentPlanner planner)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
CallContext cctxt = CallContext.current();
Account account = cctxt.getCallingAccount();
User caller = cctxt.getCallingUser();
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
VirtualMachineGuru vmGuru = getVmGuru(vm);
Ternary<VMInstanceVO, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account);
if (start == null) {
return;
}
vm = start.first();
ReservationContext ctx = start.second();
ItWorkVO work = start.third();
VMInstanceVO startedVm = null;
ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, vm.getTemplateId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to deploy VM, vm has dcId: " + vm.getDataCenterId() + " and podId: " + vm.getPodIdToDeployIn());
}
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null, ctx);
if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:" + planToDeploy.getDataCenterId() + ", podId: " + planToDeploy.getPodId() +
", clusterId: " + planToDeploy.getClusterId() + ", hostId: " + planToDeploy.getHostId() + ", poolId: " + planToDeploy.getPoolId());
}
plan =
new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(),
planToDeploy.getPoolId(), planToDeploy.getPhysicalNetworkId(), ctx);
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
boolean canRetry = true;
ExcludeList avoids = null;
try {
Journal journal = start.second().getJournal();
if (planToDeploy != null) {
avoids = planToDeploy.getAvoids();
}
if (avoids == null) {
avoids = new ExcludeList();
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deploy avoids pods: " + avoids.getPodsToAvoid() + ", clusters: " + avoids.getClustersToAvoid() + ", hosts: " + avoids.getHostsToAvoid());
}
boolean planChangedByVolume = false;
boolean reuseVolume = true;
DataCenterDeployment originalPlan = plan;
int retry = StartRetry.value();
while (retry-- != 0) { // It's != so that it can match -1.
if (reuseVolume) {
// edit plan if this vm's ROOT volume is in READY state already
List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
for (VolumeVO vol : vols) {
// make sure if the templateId is unchanged. If it is changed,
// let planner
// reassign pool for the volume even if it ready.
Long volTemplateId = vol.getTemplateId();
if (volTemplateId != null && volTemplateId.longValue() != template.getId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool");
}
continue;
}
StoragePool pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
if (!pool.isInMaintenance()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Root volume is ready, need to place VM in volume's cluster");
}
long rootVolDcId = pool.getDataCenterId();
Long rootVolPodId = pool.getPodId();
Long rootVolClusterId = pool.getClusterId();
if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
Long clusterIdSpecified = planToDeploy.getClusterId();
if (clusterIdSpecified != null && rootVolClusterId != null) {
if (rootVolClusterId.longValue() != clusterIdSpecified.longValue()) {
// cannot satisfy the plan passed in to the
// planner
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: " +
rootVolClusterId + ", cluster specified: " + clusterIdSpecified);
}
throw new ResourceUnavailableException(
"Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " +
vm, Cluster.class, clusterIdSpecified);
}
}
plan =
new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(),
planToDeploy.getHostId(), vol.getPoolId(), null, ctx);
} else {
plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId(), null, ctx);
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId +
" , and clusterId: " + rootVolClusterId);
}
planChangedByVolume = true;
}
}
}
}
Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params);
DeployDestination dest = null;
try {
dest = _dpMgr.planDeployment(vmProfile, plan, avoids, planner);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest == null) {
if (planChangedByVolume) {
plan = originalPlan;
planChangedByVolume = false;
//do not enter volume reuse for next retry, since we want to look for resorces outside the volume's cluster
reuseVolume = false;
continue;
}
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId(),
areAffinityGroupsAssociated(vmProfile));
}
if (dest != null) {
avoids.addHost(dest.getHost().getId());
journal.record("Deployment found ", vmProfile, dest);
}
long destHostId = dest.getHost().getId();
vm.setPodId(dest.getPod().getId());
Long cluster_id = dest.getCluster().getId();
ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
//storing the value of overcommit in the vm_details table for doing a capacity check in case the cluster overcommit ratio is changed.
if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") == null &&
((Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f))) {
_uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue());
_uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue());
} else if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") != null) {
_uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue());
_uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue());
}
vmProfile.setCpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
vmProfile.setMemoryOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
StartAnswer startAnswer = null;
try {
if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine");
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException(e1.getMessage());
}
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is being created in podId: " + vm.getPodIdToDeployIn());
}
_networkMgr.prepare(vmProfile, dest, ctx);
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
volumeMgr.prepare(vmProfile, dest);
}
//since StorageMgr succeeded in volume creation, reuse Volume for further tries until current cluster has capacity
if (!reuseVolume) {
reuseVolume = true;
}
Commands cmds = null;
vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx);
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
handlePath(vmTO.getDisks(), vm.getHypervisorType());
cmds = new Commands(Command.OnError.Stop);
cmds.addCommand(new StartCommand(vmTO, dest.getHost(), ExecuteInSequence.value()));
vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx);
work = _workDao.findById(work.getId());
if (work == null || work.getStep() != Step.Prepare) {
throw new ConcurrentOperationException("Work steps have been changed: " + work);
}
_workDao.updateStep(work, Step.Starting);
_agentMgr.send(destHostId, cmds);
_workDao.updateStep(work, Step.Started);
startAnswer = cmds.getAnswer(StartAnswer.class);
if (startAnswer != null && startAnswer.getResult()) {
handlePath(vmTO.getDisks(), startAnswer.getIqnToPath());
String host_guid = startAnswer.getHost_guid();
if (host_guid != null) {
HostVO finalHost = _resourceMgr.findHostByGuid(host_guid);
if (finalHost == null) {
throw new CloudRuntimeException("Host Guid " + host_guid + " doesn't exist in DB, something wrong here");
}
destHostId = finalHost.getId();
}
if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) {
syncDiskChainChange(startAnswer);
if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) {
throw new ConcurrentOperationException("Unable to transition to a new state.");
}
startedVm = vm;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Start completed for VM " + vm);
}
return;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.info("The guru did not like the answers so stopping " + vm);
}
StopCommand cmd = new StopCommand(vm, ExecuteInSequence.value());
StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd);
if (answer != null) {
if (vm.getType() == VirtualMachine.Type.User) {
String platform = answer.getPlatform();
if (platform != null) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", platform);
_userVmDao.saveDetails(userVm);
}
}
}
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
_haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop);
throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation");
}
throw new ExecutionException("Unable to start " + vm + " due to error in finalizeStart, not retrying");
}
}
s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to send the start command to host " + dest.getHost());
if (e.isActive()) {
_haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop);
}
canRetry = false;
throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e);
} catch (ResourceUnavailableException e) {
s_logger.info("Unable to contact resource.", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e);
throw e;
}
}
} catch (InsufficientCapacityException e) {
s_logger.info("Insufficient capacity ", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e);
}
}
} catch (Exception e) {
s_logger.error("Failed to start instance " + vm, e);
throw new AgentUnavailableException("Unable to start instance due to " + e.getMessage(), destHostId, e);
} finally {
if (startedVm == null && canRetry) {
Step prevStep = work.getStep();
_workDao.updateStep(work, Step.Release);
// If previous step was started/ing && we got a valid answer
if ((prevStep == Step.Started || prevStep == Step.Starting) && (startAnswer != null && startAnswer.getResult())) { //TODO check the response of cleanup and record it in DB for retry
cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false);
} else {
//if step is not starting/started, send cleanup command with force=true
cleanup(vmGuru, vmProfile, work, Event.OperationFailed, true);
}
}
}
}
} finally {
if (startedVm == null) {
if (canRetry) {
try {
changeState(vm, Event.OperationFailed, null, work, Step.Done);
} catch (NoTransitionException e) {
throw new ConcurrentOperationException(e.getMessage());
}
}
}
if (planToDeploy != null) {
planToDeploy.setAvoids(avoids);
}
}
if (startedVm == null) {
throw new CloudRuntimeException("Unable to start instance '" + vm.getHostName() + "' (" + vm.getUuid() + "), see management server log for details");
}
}
// for managed storage on KVM, need to make sure the path field of the volume in question is populated with the IQN
private void handlePath(DiskTO[] disks, HypervisorType hypervisorType) {
if (hypervisorType != HypervisorType.KVM) {
return;
}
if (disks != null) {
for (DiskTO disk : disks) {
Map<String, String> details = disk.getDetails();
boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED));
if (isManaged && disk.getPath() == null) {
Long volumeId = disk.getData().getId();
VolumeVO volume = _volsDao.findById(volumeId);
disk.setPath(volume.get_iScsiName());
volume.setPath(volume.get_iScsiName());
_volsDao.update(volumeId, volume);
}
}
}
}
// for managed storage on XenServer and VMware, need to update the DB with a path if the VDI/VMDK file was newly created
private void handlePath(DiskTO[] disks, Map<String, String> iqnToPath) {
if (disks != null) {
for (DiskTO disk : disks) {
Map<String, String> details = disk.getDetails();
boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED));
if (isManaged && disk.getPath() == null) {
Long volumeId = disk.getData().getId();
VolumeVO volume = _volsDao.findById(volumeId);
String iScsiName = volume.get_iScsiName();
String path = iqnToPath.get(iScsiName);
volume.setPath(path);
_volsDao.update(volumeId, volume);
}
}
}
}
private void syncDiskChainChange(StartAnswer answer) {
VirtualMachineTO vmSpec = answer.getVirtualMachine();
for (DiskTO disk : vmSpec.getDisks()) {
if (disk.getType() != Volume.Type.ISO) {
VolumeObjectTO vol = (VolumeObjectTO)disk.getData();
VolumeVO volume = _volsDao.findById(vol.getId());
// Use getPath() from VolumeVO to get a fresh copy of what's in the DB.
// Before doing this, in a certain situation, getPath() from VolumeObjectTO
// returned null instead of an actual path (because it was out of date with the DB).
volumeMgr.updateVolumeDiskChain(vol.getId(), volume.getPath(), vol.getChainInfo());
}
}
}
@Override
public void stop(String vmUuid) throws ResourceUnavailableException {
try {
advanceStop(vmUuid, false);
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", e.getAgentId(), e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e);
}
}
protected boolean sendStop(VirtualMachineGuru guru, VirtualMachineProfile profile, boolean force) {
VirtualMachine vm = profile.getVirtualMachine();
StopCommand stop = new StopCommand(vm, ExecuteInSequence.value());
try {
StopAnswer answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop);
if (answer != null) {
if (vm.getType() == VirtualMachine.Type.User) {
String platform = answer.getPlatform();
if (platform != null) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", platform);
_userVmDao.saveDetails(userVm);
}
}
}
if (!answer.getResult()) {
s_logger.debug("Unable to stop VM due to " + answer.getDetails());
return false;
}
guru.finalizeStop(profile, answer);
} catch (AgentUnavailableException e) {
if (!force) {
return false;
}
} catch (OperationTimedoutException e) {
if (!force) {
return false;
}
}
return true;
}
protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile profile, ItWorkVO work, Event event, boolean cleanUpEvenIfUnableToStop) {
VirtualMachine vm = profile.getVirtualMachine();
State state = vm.getState();
s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
if (state == State.Starting) {
Step step = work.getStep();
if (step == Step.Starting && !cleanUpEvenIfUnableToStop) {
s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step);
return false;
}
if (step == Step.Started || step == Step.Starting || step == Step.Release) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
return false;
}
}
}
if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) {
s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step);
return true;
}
} else if (state == State.Stopping) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Migrating) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
if (vm.getLastHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Running) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process");
return false;
}
}
try {
_networkMgr.release(profile, cleanUpEvenIfUnableToStop);
s_logger.debug("Successfully released network resources for the vm " + vm);
} catch (Exception e) {
s_logger.warn("Unable to release some network resources.", e);
}
volumeMgr.release(profile);
s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state");
return true;
}
@Override
public void advanceStop(String vmUuid, boolean cleanUpEvenIfUnableToStop)
throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop);
} else {
Outcome<VirtualMachine> outcome = stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof AgentUnavailableException)
throw (AgentUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof OperationTimedoutException)
throw (OperationTimedoutException)jobException;
}
}
}
private void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
advanceStop(vm, cleanUpEvenIfUnableToStop);
}
private void advanceStop(VMInstanceVO vm, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException,
ConcurrentOperationException {
State state = vm.getState();
if (state == State.Stopped) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already stopped: " + vm);
}
return;
}
if (state == State.Destroyed || state == State.Expunging || state == State.Error) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopped called on " + vm + " but the state is " + state);
}
return;
}
// grab outstanding work item if any
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found an outstanding work item for this vm " + vm + " with state:" + vm.getState() + ", work id:" + work.getId());
}
}
Long hostId = vm.getHostId();
if (hostId == null) {
if (!cleanUpEvenIfUnableToStop) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("HostId is null but this is not a forced stop, cannot stop vm " + vm + " with state:" + vm.getState());
}
throw new CloudRuntimeException("Unable to stop " + vm);
}
try {
stateTransitTo(vm, Event.AgentReportStopped, null, null);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
// mark outstanding work item if any as done
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
return;
}
VirtualMachineGuru vmGuru = getVmGuru(vm);
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
try {
if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
throw new ConcurrentOperationException("VM is being operated on.");
}
} catch (NoTransitionException e1) {
if (!cleanUpEvenIfUnableToStop) {
throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState());
}
boolean doCleanup = false;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to transition the state but we're moving on because it's forced stop");
}
if (state == State.Starting || state == State.Migrating) {
if (work != null) {
doCleanup = true;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to cleanup VM: " + vm + " ,since outstanding work item is not found");
}
throw new CloudRuntimeException("Work item not found, We cannot stop " + vm + " when it is in state " + vm.getState());
}
} else if (state == State.Stopping) {
doCleanup = true;
}
if (doCleanup) {
if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.StopRequested, cleanUpEvenIfUnableToStop)) {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating work item to Done, id:" + work.getId());
}
if (!changeState(vm, Event.AgentReportStopped, null, work, Step.Done)) {
throw new CloudRuntimeException("Unable to stop " + vm);
}
} catch (NoTransitionException e) {
s_logger.warn("Unable to cleanup " + vm);
throw new CloudRuntimeException("Unable to stop " + vm, e);
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Failed to cleanup VM: " + vm);
}
throw new CloudRuntimeException("Failed to cleanup " + vm + " , current state " + vm.getState());
}
}
}
if (vm.getState() != State.Stopping) {
throw new CloudRuntimeException("We cannot proceed with stop VM " + vm + " since it is not in 'Stopping' state, current state: " + vm.getState());
}
vmGuru.prepareStop(profile);
StopCommand stop = new StopCommand(vm, ExecuteInSequence.value());
boolean stopped = false;
StopAnswer answer = null;
try {
answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop);
if (answer != null) {
if (vm.getType() == VirtualMachine.Type.User) {
String platform = answer.getPlatform();
if (platform != null) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", platform);
_userVmDao.saveDetails(userVm);
}
}
}
stopped = answer.getResult();
if (!stopped) {
throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails());
}
vmGuru.finalizeStop(profile, answer);
} catch (AgentUnavailableException e) {
s_logger.warn("Unable to stop vm, agent unavailable: " + e.toString());
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to stop vm, operation timed out: " + e.toString());
} finally {
if (!stopped) {
if (!cleanUpEvenIfUnableToStop) {
s_logger.warn("Unable to stop vm " + vm);
try {
stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unable to transition the state " + vm);
}
throw new CloudRuntimeException("Unable to stop " + vm);
} else {
s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop");
vmGuru.finalizeStop(profile, answer);
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held.");
}
try {
_networkMgr.release(profile, cleanUpEvenIfUnableToStop);
s_logger.debug("Successfully released network resources for the vm " + vm);
} catch (Exception e) {
s_logger.warn("Unable to release some network resources.", e);
}
try {
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
volumeMgr.release(profile);
s_logger.debug("Successfully released storage resources for the vm " + vm);
}
} catch (Exception e) {
s_logger.warn("Unable to release storage resources.", e);
}
try {
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating the outstanding work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
if (!stateTransitTo(vm, Event.OperationSucceeded, null)) {
throw new CloudRuntimeException("unable to stop " + vm);
}
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
throw new CloudRuntimeException("Unable to stop " + vm);
}
}
private void setStateMachine() {
_stateMachine = VirtualMachine.State.getStateMachine();
}
protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException {
vm.setReservationId(reservationId);
return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
}
@Override
public boolean stateTransitTo(VirtualMachine vm1, VirtualMachine.Event e, Long hostId) throws NoTransitionException {
VMInstanceVO vm = (VMInstanceVO)vm1;
// if there are active vm snapshots task, state change is not allowed
if (_vmSnapshotMgr.hasActiveVMSnapshotTasks(vm.getId())) {
s_logger.error("State transit with event: " + e + " failed due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
return false;
}
State oldState = vm.getState();
if (oldState == State.Starting) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(hostId);
}
} else if (oldState == State.Stopping) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(vm.getHostId());
}
}
return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
}
@Override
public void destroy(String vmUuid) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
advanceStop(vmUuid, VmDestroyForcestop.value());
if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(), null)) {
s_logger.debug("Unable to delete all snapshots for " + vm);
throw new CloudRuntimeException("Unable to delete vm snapshots for " + vm);
}
// reload the vm object from db
vm = _vmDao.findByUuid(vmUuid);
try {
if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
throw new CloudRuntimeException("Unable to destroy " + vm);
}
} catch (NoTransitionException e) {
s_logger.debug(e.getMessage());
throw new CloudRuntimeException("Unable to destroy " + vm, e);
}
}
protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException {
CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer)_agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName()));
if (!answer.getResult() || answer.getState() == State.Stopped) {
return false;
}
return true;
}
@Override
public void storageMigration(String vmUuid, StoragePool destPool) {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStorageMigration(vmUuid, destPool);
} else {
Outcome<VirtualMachine> outcome = migrateVmStorageThroughJobQueue(vmUuid, destPool);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
}
}
private void orchestrateStorageMigration(String vmUuid, StoragePool destPool) {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
try {
stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null);
} catch (NoTransitionException e) {
s_logger.debug("Unable to migrate vm: " + e.toString());
throw new CloudRuntimeException("Unable to migrate vm: " + e.toString());
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
boolean migrationResult = false;
try {
migrationResult = volumeMgr.storageMigration(profile, destPool);
if (migrationResult) {
//if the vm is migrated to different pod in basic mode, need to reallocate ip
if (!vm.getPodIdToDeployIn().equals(destPool.getPodId())) {
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null);
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null);
_networkMgr.reallocate(vmProfile, plan);
}
//when start the vm next time, don;'t look at last_host_id, only choose the host based on volume/storage pool
vm.setLastHostId(null);
vm.setPodId(destPool.getPodId());
} else {
s_logger.debug("Storage migration failed");
}
} catch (ConcurrentOperationException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (InsufficientVirtualNetworkCapcityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (InsufficientAddressCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (InsufficientCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (StorageUnavailableException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} finally {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
} catch (NoTransitionException e) {
s_logger.debug("Failed to change vm state: " + e.toString());
throw new CloudRuntimeException("Failed to change vm state: " + e.toString());
}
}
}
@Override
public void migrate(String vmUuid, long srcHostId, DeployDestination dest)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrate(vmUuid, srcHostId, dest);
} else {
Outcome<VirtualMachine> outcome = migrateVmThroughJobQueue(vmUuid, srcHostId, dest);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
}
}
private void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the vm " + vmUuid);
}
throw new CloudRuntimeException("Unable to find a virtual machine with id " + vmUuid);
}
migrate(vm, srcHostId, dest);
}
protected void migrate(VMInstanceVO vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
s_logger.info("Migrating " + vm + " to " + dest);
long dstHostId = dest.getHost().getId();
Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
}
VirtualMachineGuru vmGuru = getVmGuru(vm);
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm);
for (NicProfile nic : _networkMgr.getNicProfiles(vm)) {
vmSrc.addNic(nic);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
_networkMgr.prepareNicForMigration(profile, dest);
volumeMgr.prepareForMigration(profile, dest);
VirtualMachineTO to = toVmTO(profile);
PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
PrepareForMigrationAnswer pfma = null;
try {
pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc);
if (!pfma.getResult()) {
String msg = "Unable to prepare for migration due to " + pfma.getDetails();
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, ExecuteInSequence.value());
mc.setHostGuid(dest.getHost().getGuid());
try {
MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc);
if (!ma.getResult()) {
throw new CloudRuntimeException("Unable to migrate due to " + ma.getDetails());
}
} catch (OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm)), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("Unable to complete migration for " + vm);
}
} catch (OperationTimedoutException e) {
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_networkMgr.rollbackNicForMigration(vmSrc, profile);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(),
"Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " +
dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
} catch (AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
} else {
_networkMgr.commitNicForMigration(vmSrc, profile);
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
private Map<Volume, StoragePool> getPoolListForVolumesForMigration(VirtualMachineProfile profile, Host host, Map<Volume, StoragePool> volumeToPool) {
List<VolumeVO> allVolumes = _volsDao.findUsableVolumesForInstance(profile.getId());
for (VolumeVO volume : allVolumes) {
StoragePool pool = volumeToPool.get(volume);
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
StoragePoolVO currentPool = _storagePoolDao.findById(volume.getPoolId());
if (pool != null) {
// Check if pool is accessible from the destination host and disk offering with which the volume was
// created is compliant with the pool type.
if (_poolHostDao.findByPoolHost(pool.getId(), host.getId()) == null || pool.isLocal() != diskOffering.getUseLocalStorage()) {
// Cannot find a pool for the volume. Throw an exception.
throw new CloudRuntimeException("Cannot migrate volume " + volume + " to storage pool " + pool + " while migrating vm to host " + host +
". Either the pool is not accessible from the " + "host or because of the offering with which the volume is created it cannot be placed on " +
"the given pool.");
} else if (pool.getId() == currentPool.getId()) {
// If the pool to migrate too is the same as current pool, remove the volume from the list of
// volumes to be migrated.
volumeToPool.remove(volume);
}
} else {
// Find a suitable pool for the volume. Call the storage pool allocator to find the list of pools.
DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType());
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), null, null);
ExcludeList avoid = new ExcludeList();
boolean currentPoolAvailable = false;
for (StoragePoolAllocator allocator : _storagePoolAllocators) {
List<StoragePool> poolList = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL);
if (poolList != null && !poolList.isEmpty()) {
// Volume needs to be migrated. Pick the first pool from the list. Add a mapping to migrate the
// volume to a pool only if it is required; that is the current pool on which the volume resides
// is not available on the destination host.
if (poolList.contains(currentPool)) {
currentPoolAvailable = true;
} else {
volumeToPool.put(volume, _storagePoolDao.findByUuid(poolList.get(0).getUuid()));
}
break;
}
}
if (!currentPoolAvailable && !volumeToPool.containsKey(volume)) {
// Cannot find a pool for the volume. Throw an exception.
throw new CloudRuntimeException("Cannot find a storage pool which is available for volume " + volume + " while migrating virtual machine " +
profile.getVirtualMachine() + " to host " + host);
}
}
}
return volumeToPool;
}
private <T extends VMInstanceVO> void moveVmToMigratingState(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException {
// Put the vm in migrating state.
try {
if (!changeState(vm, Event.MigrationRequested, hostId, work, Step.Migrating)) {
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e) {
s_logger.info("Migration cancelled because " + e.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e.getMessage());
}
}
private <T extends VMInstanceVO> void moveVmOutofMigratingStateOnSuccess(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException {
// Put the vm in running state.
try {
if (!changeState(vm, Event.OperationSucceeded, hostId, work, Step.Started)) {
s_logger.error("Unable to change the state for " + vm);
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (NoTransitionException e) {
s_logger.error("Unable to change state due to " + e.getMessage());
throw new ConcurrentOperationException("Unable to change state due to " + e.getMessage());
}
}
@Override
public void migrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map<Volume, StoragePool> volumeToPool)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool);
} else {
Outcome<VirtualMachine> outcome = migrateVmWithStorageThroughJobQueue(vmUuid, srcHostId, destHostId, volumeToPool);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
}
}
}
private void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map<Volume, StoragePool> volumeToPool) throws ResourceUnavailableException,
ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
HostVO srcHost = _hostDao.findById(srcHostId);
HostVO destHost = _hostDao.findById(destHostId);
VirtualMachineGuru vmGuru = getVmGuru(vm);
DataCenterVO dc = _dcDao.findById(destHost.getDataCenterId());
HostPodVO pod = _podDao.findById(destHost.getPodId());
Cluster cluster = _clusterDao.findById(destHost.getClusterId());
DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost);
// Create a map of which volume should go in which storage pool.
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
volumeToPool = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
// If none of the volumes have to be migrated, fail the call. Administrator needs to make a call for migrating
// a vm and not migrating a vm with storage.
if (volumeToPool.isEmpty()) {
throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost +
" doesn't involve migrating the volumes.");
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
_networkMgr.prepareNicForMigration(profile, destination);
volumeMgr.prepareForMigration(profile, destination);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
VirtualMachineTO to = hvGuru.implement(profile);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(destHostId);
work = _workDao.persist(work);
// Put the vm in migrating state.
vm.setLastHostId(srcHostId);
moveVmToMigratingState(vm, destHostId, work);
boolean migrated = false;
try {
// Migrate the vm and its volume.
volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPool);
// Put the vm back to running state.
moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
try {
if (!checkVmOnHost(vm, destHostId)) {
s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm);
}
} catch (OperationTimedoutException e) {
s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(),
"Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + dc.getName() + " and pod " + dc.getName(),
"Migrate Command failed. Please check logs.");
try {
_agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (AgentUnavailableException e) {
s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
} catch (NoTransitionException e) {
s_logger.error("Error while transitioning vm from migrating to running state.", e);
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
@Override
public VirtualMachineTO toVmTO(VirtualMachineProfile profile) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(profile.getVirtualMachine().getHypervisorType());
VirtualMachineTO to = hvGuru.implement(profile);
return to;
}
protected void cancelWorkItems(long nodeId) {
GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem");
try {
if (scanLock.lock(3)) {
try {
List<ItWorkVO> works = _workDao.listWorkInProgressFor(nodeId);
for (ItWorkVO work : works) {
s_logger.info("Handling unfinished work item: " + work);
try {
VMInstanceVO vm = _vmDao.findById(work.getInstanceId());
if (vm != null) {
if (work.getType() == State.Starting) {
_haMgr.scheduleRestart(vm, true);
work.setManagementServerId(_nodeId);
_workDao.update(work.getId(), work);
} else if (work.getType() == State.Stopping) {
_haMgr.scheduleStop(vm, vm.getHostId(), WorkType.CheckStop);
work.setManagementServerId(_nodeId);
_workDao.update(work.getId(), work);
} else if (work.getType() == State.Migrating) {
_haMgr.scheduleMigration(vm);
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
} catch (Exception e) {
s_logger.error("Error while handling " + work, e);
}
}
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
@Override
public void migrateAway(String vmUuid, long srcHostId, DeploymentPlanner planner) throws InsufficientServerCapacityException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
s_logger.debug("Unable to find a VM for " + vmUuid);
throw new CloudRuntimeException("Unable to find " + vmUuid);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
Long hostId = vm.getHostId();
if (hostId == null) {
s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm);
throw new CloudRuntimeException("Unable to migrate " + vmUuid);
}
Host host = _hostDao.findById(hostId);
Long poolId = null;
List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
for (VolumeVO rootVolumeOfVm : vols) {
StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId());
if (rootDiskPool != null) {
poolId = rootDiskPool.getId();
}
}
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, poolId, null);
ExcludeList excludes = new ExcludeList();
excludes.addHost(hostId);
DeployDestination dest = null;
while (true) {
try {
dest = _dpMgr.planDeployment(profile, plan, excludes, planner);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found destination " + dest + " for migrating to.");
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find destination for migrating the vm " + profile);
}
throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId());
}
excludes.addHost(dest.getHost().getId());
try {
migrate(vm, srcHostId, dest);
return;
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to migrate to unavailable " + dest);
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
}
try {
advanceStop(vmUuid, true);
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
throw new CloudRuntimeException("Unable to migrate " + vm);
}
}
}
protected class CleanupTask extends ManagedContextRunnable {
@Override
protected void runInContext() {
s_logger.trace("VM Operation Thread Running");
try {
_workDao.cleanup(VmOpCleanupWait.value());
} catch (Exception e) {
s_logger.error("VM Operations failed due to ", e);
}
}
}
@Override
public boolean isVirtualMachineUpgradable(VirtualMachine vm, ServiceOffering offering) {
boolean isMachineUpgradable = true;
for (HostAllocator allocator : hostAllocators) {
isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering);
if (isMachineUpgradable)
continue;
else
break;
}
return isMachineUpgradable;
}
@Override
public void reboot(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) throws InsufficientCapacityException, ResourceUnavailableException {
try {
advanceReboot(vmUuid, params);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e);
}
}
@Override
public void advanceReboot(String vmUuid, Map<VirtualMachineProfile.Param, Object> params)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateReboot(vmUuid, params);
} else {
Outcome<VirtualMachine> outcome = rebootVmThroughJobQueue(vmUuid, params);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof InsufficientCapacityException)
throw (InsufficientCapacityException)jobException;
}
}
}
private void orchestrateReboot(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
DataCenter dc = _entityMgr.findById(DataCenter.class, vm.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
Cluster cluster = null;
if (host != null) {
cluster = _entityMgr.findById(Cluster.class, host.getClusterId());
}
Pod pod = _entityMgr.findById(Pod.class, host.getPodId());
DeployDestination dest = new DeployDestination(dc, pod, cluster, host);
try {
Commands cmds = new Commands(Command.OnError.Stop);
cmds.addCommand(new RebootCommand(vm.getInstanceName()));
_agentMgr.send(host.getId(), cmds);
Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class);
if (rebootAnswer != null && rebootAnswer.getResult()) {
return;
}
s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e);
throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost());
}
}
public Command cleanup(VirtualMachine vm) {
return new StopCommand(vm, ExecuteInSequence.value());
}
public Command cleanup(String vmName) {
return new StopCommand(vmName, ExecuteInSequence.value());
}
public Commands fullHostSync(final long hostId, StartupRoutingCommand startup) {
Commands commands = new Commands(Command.OnError.Continue);
Map<Long, AgentVmInfo> infos = convertToInfos(startup);
final List<? extends VMInstanceVO> vms = _vmDao.listByHostId(hostId);
s_logger.debug("Found " + vms.size() + " VMs for host " + hostId);
for (VMInstanceVO vm : vms) {
AgentVmInfo info = infos.remove(vm.getId());
// sync VM Snapshots related transient states
List<VMSnapshotVO> vmSnapshotsInTrasientStates =
_vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Reverting, VMSnapshot.State.Creating);
if (vmSnapshotsInTrasientStates.size() > 1) {
s_logger.info("Found vm " + vm.getInstanceName() + " with VM snapshots in transient states, needs to sync VM snapshot state");
if (!_vmSnapshotMgr.syncVMSnapshot(vm, hostId)) {
s_logger.warn("Failed to sync VM in a transient snapshot related state: " + vm.getInstanceName());
continue;
} else {
s_logger.info("Successfully sync VM with transient snapshot: " + vm.getInstanceName());
}
}
if (info == null) {
info = new AgentVmInfo(vm.getInstanceName(), vm, State.Stopped);
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
Command command = compareState(hostId, vm, info, true, hvGuru.trackVmHostChange());
if (command != null) {
commands.addCommand(command);
}
}
for (final AgentVmInfo left : infos.values()) {
boolean found = false;
VMInstanceVO vm = _vmDao.findVMByInstanceName(left.name);
if (vm != null) {
found = true;
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
if (hvGuru.trackVmHostChange()) {
Command command = compareState(hostId, vm, left, true, true);
if (command != null) {
commands.addCommand(command);
}
} else {
s_logger.warn("Stopping a VM, VM " + left.name + " migrate from Host " + vm.getHostId() + " to Host " + hostId);
commands.addCommand(cleanup(left.name));
}
}
if (!found) {
s_logger.warn("Stopping a VM that we have no record of <fullHostSync>: " + left.name);
commands.addCommand(cleanup(left.name));
}
}
return commands;
}
public Commands deltaHostSync(long hostId, Map<String, State> newStates) {
Map<Long, AgentVmInfo> states = convertDeltaToInfos(newStates);
Commands commands = new Commands(Command.OnError.Continue);
for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) {
AgentVmInfo info = entry.getValue();
VMInstanceVO vm = info.vm;
Command command = null;
if (vm != null) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
command = compareState(hostId, vm, info, false, hvGuru.trackVmHostChange());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleaning up a VM that is no longer found: " + info.name);
}
command = cleanup(info.name);
}
if (command != null) {
commands.addCommand(command);
}
}
return commands;
}
public void deltaSync(Map<String, Ternary<String, State, String>> newStates) {
Map<Long, AgentVmInfo> states = convertToInfos(newStates);
for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) {
AgentVmInfo info = entry.getValue();
VMInstanceVO vm = info.vm;
Command command = null;
if (vm != null) {
Host host = _resourceMgr.findHostByGuid(info.getHostUuid());
long hId = host.getId();
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
command = compareState(hId, vm, info, false, hvGuru.trackVmHostChange());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleaning up a VM that is no longer found <deltaSync>: " + info.name);
}
command = cleanup(info.name);
}
if (command != null) {
try {
Host host = _resourceMgr.findHostByGuid(info.getHostUuid());
if (host != null) {
Answer answer = _agentMgr.send(host.getId(), cleanup(info.name));
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
}
}
} catch (Exception e) {
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
}
}
public void fullSync(final long clusterId, Map<String, Ternary<String, State, String>> newStates) {
if (newStates == null)
return;
Map<Long, AgentVmInfo> infos = convertToInfos(newStates);
Set<VMInstanceVO> set_vms = Collections.synchronizedSet(new HashSet<VMInstanceVO>());
set_vms.addAll(_vmDao.listByClusterId(clusterId));
set_vms.addAll(_vmDao.listLHByClusterId(clusterId));
for (VMInstanceVO vm : set_vms) {
AgentVmInfo info = infos.remove(vm.getId());
// sync VM Snapshots related transient states
List<VMSnapshotVO> vmSnapshotsInExpungingStates =
_vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Creating, VMSnapshot.State.Reverting);
if (vmSnapshotsInExpungingStates.size() > 0) {
s_logger.info("Found vm " + vm.getInstanceName() + " in state. " + vm.getState() + ", needs to sync VM snapshot state");
Long hostId = null;
Host host = null;
if (info != null && info.getHostUuid() != null) {
host = _hostDao.findByGuid(info.getHostUuid());
}
hostId = host == null ? (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()) : host.getId();
if (!_vmSnapshotMgr.syncVMSnapshot(vm, hostId)) {
s_logger.warn("Failed to sync VM with transient snapshot: " + vm.getInstanceName());
continue;
} else {
s_logger.info("Successfully sync VM with transient snapshot: " + vm.getInstanceName());
}
}
if ((info == null && (vm.getState() == State.Running || vm.getState() == State.Starting)) ||
(info != null && (info.state == State.Running && vm.getState() == State.Starting))) {
s_logger.info("Found vm " + vm.getInstanceName() + " in inconsistent state. " + vm.getState() + " on CS while " + (info == null ? "Stopped" : "Running") +
" on agent");
info = new AgentVmInfo(vm.getInstanceName(), vm, State.Stopped);
// Bug 13850- grab outstanding work item if any for this VM state so that we mark it as DONE after we change VM state, else it will remain pending
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found an outstanding work item for this vm " + vm + " in state:" + vm.getState() + ", work id:" + work.getId());
}
}
vm.setState(State.Running); // set it as running and let HA take care of it
_vmDao.persist(vm);
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating outstanding work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
try {
Host host = _hostDao.findByGuid(info.getHostUuid());
long hostId = host == null ? (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()) : host.getId();
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
Command command = compareState(hostId, vm, info, true, hvGuru.trackVmHostChange());
if (command != null) {
Answer answer = _agentMgr.send(hostId, command);
if (!answer.getResult()) {
s_logger.warn("Failed to update state of the VM due to " + answer.getDetails());
}
}
} catch (Exception e) {
s_logger.warn("Unable to update state of the VM due to exception " + e.getMessage());
e.printStackTrace();
}
} else if (info != null &&
(vm.getState() == State.Stopped || vm.getState() == State.Stopping || vm.isRemoved() || vm.getState() == State.Destroyed || vm.getState() == State.Expunging)) {
Host host = _hostDao.findByGuid(info.getHostUuid());
if (host != null) {
s_logger.warn("Stopping a VM which is stopped/stopping/destroyed/expunging " + info.name);
if (vm.getState() == State.Stopped || vm.getState() == State.Stopping) {
vm.setState(State.Stopped); // set it as stop and clear it from host
vm.setHostId(null);
_vmDao.persist(vm);
}
try {
Answer answer = _agentMgr.send(host.getId(), cleanup(info.name));
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
}
} catch (Exception e) {
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
} else
// host id can change
if (info != null && vm.getState() == State.Running) {
// check for host id changes
Host host = _hostDao.findByGuid(info.getHostUuid());
if (host != null && (vm.getHostId() == null || host.getId() != vm.getHostId())) {
s_logger.info("Found vm " + vm.getInstanceName() + " with inconsistent host in db, new host is " + host.getId());
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, host.getId());
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
}
/* else if(info == null && vm.getState() == State.Stopping) { //Handling CS-13376
s_logger.warn("Marking the VM as Stopped as it was still stopping on the CS" +vm.getName());
vm.setState(State.Stopped); // Setting the VM as stopped on the DB and clearing it from the host
vm.setLastHostId(vm.getHostId());
vm.setHostId(null);
_vmDao.persist(vm);
}*/
}
for (final AgentVmInfo left : infos.values()) {
if (!VirtualMachineName.isValidVmName(left.name))
continue; // if the vm doesn't follow CS naming ignore it for stopping
try {
Host host = _hostDao.findByGuid(left.getHostUuid());
if (host != null) {
s_logger.warn("Stopping a VM which we do not have any record of " + left.name);
Answer answer = _agentMgr.send(host.getId(), cleanup(left.name));
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
}
}
} catch (Exception e) {
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
}
protected Map<Long, AgentVmInfo> convertToInfos(final Map<String, Ternary<String, State, String>> newStates) {
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (newStates == null) {
return map;
}
boolean is_alien_vm = true;
long alien_vm_count = -1;
for (Map.Entry<String, Ternary<String, State, String>> entry : newStates.entrySet()) {
is_alien_vm = true;
String name = entry.getKey();
VMInstanceVO vm = _vmDao.findVMByInstanceName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vm, entry.getValue().second(), entry.getValue().first(), entry.getValue().third()));
is_alien_vm = false;
}
// alien VMs
if (is_alien_vm) {
map.put(alien_vm_count--, new AgentVmInfo(entry.getKey(), null, entry.getValue().second(), entry.getValue().first(), entry.getValue().third()));
s_logger.warn("Found an alien VM " + entry.getKey());
}
}
return map;
}
protected Map<Long, AgentVmInfo> convertToInfos(StartupRoutingCommand cmd) {
final Map<String, VmState> states = cmd.getVmStates();
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (states == null) {
return map;
}
for (Map.Entry<String, VmState> entry : states.entrySet()) {
String name = entry.getKey();
VMInstanceVO vm = _vmDao.findVMByInstanceName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vm, entry.getValue().getState(), entry.getValue().getHost()));
}
}
return map;
}
protected Map<Long, AgentVmInfo> convertDeltaToInfos(final Map<String, State> states) {
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (states == null) {
return map;
}
for (Map.Entry<String, State> entry : states.entrySet()) {
String name = entry.getKey();
VMInstanceVO vm = _vmDao.findVMByInstanceName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vm, entry.getValue()));
}
}
return map;
}
/**
* compareState does as its name suggests and compares the states between
* management server and agent. It returns whether something should be
* cleaned up
*
*/
protected Command compareState(long hostId, VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync, boolean trackExternalChange) {
State agentState = info.state;
final State serverState = vm.getState();
final String serverName = vm.getInstanceName();
Command command = null;
s_logger.debug("VM " + serverName + ": cs state = " + serverState + " and realState = " + agentState);
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM " + serverName + ": cs state = " + serverState + " and realState = " + agentState);
}
if (agentState == State.Error) {
agentState = State.Stopped;
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY;
} else if (VirtualMachine.Type.SecondaryStorageVm.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_SSVM;
}
HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn());
DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterId());
HostVO hostVO = _hostDao.findById(vm.getHostId());
String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(alertType, vm.getDataCenterId(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() +
") stopped on host " + hostDesc + " due to storage failure", "Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" +
vm.getHostId() + "] stopped due to storage failure.");
}
// track platform info
if (info.platform != null && !info.platform.isEmpty()) {
if (vm.getType() == VirtualMachine.Type.User) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", info.platform);
_userVmDao.saveDetails(userVm);
}
}
if (trackExternalChange) {
if (serverState == State.Starting) {
if (vm.getHostId() != null && vm.getHostId() != hostId) {
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId +
", skip status sync for vm: " + vm.getInstanceName());
return null;
}
}
if (vm.getHostId() == null || hostId != vm.getHostId()) {
try {
ItWorkVO workItem = _workDao.findByOutstandingWork(vm.getId(), State.Migrating);
if (workItem == null) {
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId);
}
} catch (NoTransitionException e) {
}
}
}
// during VM migration time, don't sync state will agent status update
if (serverState == State.Migrating) {
s_logger.debug("Skipping vm in migrating state: " + vm);
return null;
}
if (trackExternalChange) {
if (serverState == State.Starting) {
if (vm.getHostId() != null && vm.getHostId() != hostId) {
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId +
", skip status sync for vm: " + vm.getInstanceName());
return null;
}
}
if (serverState == State.Running) {
try {
//
// we had a bug that sometimes VM may be at Running State
// but host_id is null, we will cover it here.
// means that when CloudStack DB lost of host information,
// we will heal it with the info reported from host
//
if (vm.getHostId() == null || hostId != vm.getHostId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("detected host change when VM " + vm + " is at running state, VM could be live-migrated externally from host " +
vm.getHostId() + " to host " + hostId);
}
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId);
}
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
}
if (agentState == serverState) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Both states are " + agentState + " for " + vm);
}
assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed.";
if (agentState == State.Running) {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, hostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
// FIXME: What if someone comes in and sets it to stopping? Then
// what?
return null;
}
s_logger.debug("State matches but the agent said stopped so let's send a cleanup command anyways.");
return cleanup(vm);
}
if (agentState == State.Shutdowned) {
if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) {
try {
advanceStop(vm.getUuid(), true);
} catch (AgentUnavailableException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (OperationTimedoutException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (ConcurrentOperationException e) {
assert (false) : "How do we hit this with forced on?";
return null;
}
} else {
s_logger.debug("Sending cleanup to a shutdowned vm: " + vm.getInstanceName());
command = cleanup(vm);
}
} else if (agentState == State.Stopped) {
// This state means the VM on the agent was detected previously
// and now is gone. This is slightly different than if the VM
// was never completed but we still send down a Stop Command
// to ensure there's cleanup.
if (serverState == State.Running) {
// Our records showed that it should be running so let's restart
// it.
_haMgr.scheduleRestart(vm, false);
} else if (serverState == State.Stopping) {
_haMgr.scheduleStop(vm, hostId, WorkType.ForceStop);
s_logger.debug("Scheduling a check stop for VM in stopping mode: " + vm);
} else if (serverState == State.Starting) {
s_logger.debug("Ignoring VM in starting mode: " + vm.getInstanceName());
_haMgr.scheduleRestart(vm, false);
}
command = cleanup(vm);
} else if (agentState == State.Running) {
if (serverState == State.Starting) {
if (fullSync) {
try {
ensureVmRunningContext(hostId, vm, Event.AgentReportRunning);
} catch (OperationTimedoutException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (ResourceUnavailableException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (InsufficientAddressCapacityException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
} else if (serverState == State.Stopping) {
s_logger.debug("Scheduling a stop command for " + vm);
_haMgr.scheduleStop(vm, hostId, WorkType.Stop);
} else {
s_logger.debug("server VM state " + serverState + " does not meet expectation of a running VM report from agent");
// just be careful not to stop VM for things we don't handle
// command = cleanup(vm);
}
}
return command;
}
private void ensureVmRunningContext(long hostId, VMInstanceVO vm, Event cause) throws OperationTimedoutException, ResourceUnavailableException,
NoTransitionException, InsufficientAddressCapacityException {
VirtualMachineGuru vmGuru = getVmGuru(vm);
s_logger.debug("VM state is starting on full sync so updating it to running");
vm = _vmDao.findById(vm.getId());
// grab outstanding work item if any
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found an outstanding work item for this vm " + vm + " in state:" + vm.getState() + ", work id:" + work.getId());
}
}
try {
stateTransitTo(vm, cause, hostId);
} catch (NoTransitionException e1) {
s_logger.warn(e1.getMessage());
}
s_logger.debug("VM's " + vm + " state is starting on full sync so updating it to Running");
vm = _vmDao.findById(vm.getId()); // this should ensure vm has the most
// up to date info
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
List<NicVO> nics = _nicsDao.listByVmId(profile.getId());
for (NicVO nic : nics) {
Network network = _networkModel.getNetwork(nic.getNetworkId());
NicProfile nicProfile =
new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.isSecurityGroupSupportedInNetwork(network),
_networkModel.getNetworkTag(profile.getHypervisorType(), network));
profile.addNic(nicProfile);
}
Commands cmds = new Commands(Command.OnError.Stop);
s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm);
if (vmGuru.finalizeCommandsOnStart(cmds, profile)) {
if (cmds.size() != 0) {
_agentMgr.send(vm.getHostId(), cmds);
}
if (vmGuru.finalizeStart(profile, vm.getHostId(), cmds, null)) {
stateTransitTo(vm, cause, vm.getHostId());
} else {
s_logger.error("Unable to finish finialization for running vm: " + vm);
}
} else {
s_logger.error("Unable to finalize commands on start for vm: " + vm);
}
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating outstanding work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
@Override
public boolean isRecurring() {
return true;
}
@Override
public boolean processAnswers(long agentId, long seq, Answer[] answers) {
for (final Answer answer : answers) {
if (answer instanceof ClusterSyncAnswer) {
ClusterSyncAnswer hs = (ClusterSyncAnswer)answer;
if (!hs.isExceuted()) {
deltaSync(hs.getNewStates());
hs.setExecuted();
}
}
}
return true;
}
@Override
public boolean processTimeout(long agentId, long seq) {
return true;
}
@Override
public int getTimeout() {
return -1;
}
@Override
public boolean processCommands(long agentId, long seq, Command[] cmds) {
boolean processed = false;
for (Command cmd : cmds) {
if (cmd instanceof PingRoutingCommand) {
PingRoutingCommand ping = (PingRoutingCommand)cmd;
if (ping.getNewStates() != null && ping.getNewStates().size() > 0) {
Commands commands = deltaHostSync(agentId, ping.getNewStates());
if (commands.size() > 0) {
try {
_agentMgr.send(agentId, commands, this);
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is now unavailable", e);
}
}
}
if(VmJobEnabled.value()) {
if (ping.getHostVmStateReport() != null && ping.getHostVmStateReport().size() > 0) {
_syncMgr.processHostVmStatePingReport(agentId, ping.getHostVmStateReport());
}
}
// take the chance to scan VMs that are stuck in transitional states
// and are missing from the report
scanStalledVMInTransitionStateOnUpHost(agentId);
processed = true;
}
}
return processed;
}
@Override
public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) {
return null;
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return true;
}
@Override
public void processConnect(Host agent, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
if (!(cmd instanceof StartupRoutingCommand)) {
return;
}
if (s_logger.isDebugEnabled())
s_logger.debug("Received startup command from hypervisor host. host id: " + agent.getId());
if (VmJobEnabled.value()) {
_syncMgr.resetHostSyncState(agent.getId());
}
if (forRebalance) {
s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process");
return;
}
if (forRebalance) {
s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process");
return;
}
Long clusterId = agent.getClusterId();
long agentId = agent.getId();
if (agent.getHypervisorType() == HypervisorType.XenServer) { // only for Xen
StartupRoutingCommand startup = (StartupRoutingCommand)cmd;
HashMap<String, Ternary<String, State, String>> allStates = startup.getClusterVMStateChanges();
if (allStates != null) {
fullSync(clusterId, allStates);
}
// initiate the cron job
ClusterSyncCommand syncCmd = new ClusterSyncCommand(ClusterDeltaSyncInterval.value(), clusterId);
try {
long seq_no = _agentMgr.send(agentId, new Commands(syncCmd), this);
s_logger.debug("Cluster VM sync started with jobid " + seq_no);
} catch (AgentUnavailableException e) {
s_logger.fatal("The Cluster VM sync process failed for cluster id " + clusterId + " with ", e);
}
} else { // for others KVM and VMWare
StartupRoutingCommand startup = (StartupRoutingCommand)cmd;
Commands commands = fullHostSync(agentId, startup);
if (commands.size() > 0) {
s_logger.debug("Sending clean commands to the agent");
try {
boolean error = false;
Answer[] answers = _agentMgr.send(agentId, commands);
for (Answer answer : answers) {
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
error = true;
}
}
if (error) {
throw new ConnectionException(true, "Unable to stop VMs");
}
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
} catch (final OperationTimedoutException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
}
}
}
}
protected class TransitionTask extends ManagedContextRunnable {
@Override
protected void runInContext() {
GlobalLock lock = GlobalLock.getInternLock("TransitionChecking");
if (lock == null) {
s_logger.debug("Couldn't get the global lock");
return;
}
if (!lock.lock(30)) {
s_logger.debug("Couldn't lock the db");
return;
}
try {
lock.addRef();
List<VMInstanceVO> instances =
_vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping);
for (VMInstanceVO instance : instances) {
State state = instance.getState();
if (state == State.Stopping) {
_haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop);
} else if (state == State.Starting) {
_haMgr.scheduleRestart(instance, true);
}
}
} catch (Exception e) {
s_logger.warn("Caught the following exception on transition checking", e);
} finally {
lock.unlock();
}
}
}
protected class AgentVmInfo {
public String name;
public State state;
public String hostUuid;
public VMInstanceVO vm;
public String platform;
@SuppressWarnings("unchecked")
public AgentVmInfo(String name, VMInstanceVO vm, State state, String host, String platform) {
this.name = name;
this.state = state;
this.vm = vm;
hostUuid = host;
this.platform = platform;
}
public AgentVmInfo(String name, VMInstanceVO vm, State state, String host) {
this(name, vm, state, host, null);
}
public AgentVmInfo(String name, VMInstanceVO vm, State state) {
this(name, vm, state, null, null);
}
public String getHostUuid() {
return hostUuid;
}
public String getPlatform() {
return platform;
}
}
@Override
public VMInstanceVO findById(long vmId) {
return _vmDao.findById(vmId);
}
@Override
public void checkIfCanUpgrade(VirtualMachine vmInstance, ServiceOffering newServiceOffering) {
if (newServiceOffering == null) {
throw new InvalidParameterValueException("Unable to find a service offering with id " + newServiceOffering.getId());
}
// Check that the VM is stopped / running
if (!(vmInstance.getState().equals(State.Stopped) || vmInstance.getState().equals(State.Running))) {
s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() +
"; make sure the virtual machine is stopped/running");
}
// Check if the service offering being upgraded to is what the VM is already running with
if (!newServiceOffering.isDynamic() && vmInstance.getServiceOfferingId() == newServiceOffering.getId()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested " + "service offering (" + newServiceOffering.getName() +
")");
}
throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already " + "has the requested service offering (" +
newServiceOffering.getName() + ")");
}
ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
// Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering
// NOTE: With the new network refactoring in 2.2, we shouldn't need the check for same guest IP type anymore.
/*
* if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) { String errorMsg =
* "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType(); errorMsg +=
* ". Please select a service offering with the same guest IP type as the VM's current service offering (" +
* currentServiceOffering.getGuestIpType() + ")."; throw new InvalidParameterValueException(errorMsg); }
*/
// Check that the service offering being upgraded to has the same storage pool preference as the VM's current service
// offering
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() +
", cannot switch between local storage and shared storage service offerings. Current offering " + "useLocalStorage=" +
currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage());
}
// if vm is a system vm, check if it is a system service offering, if yes return with error as it cannot be used for user vms
if (currentServiceOffering.getSystemUse() != newServiceOffering.getSystemUse()) {
throw new InvalidParameterValueException("isSystem property is different for current service offering and new service offering");
}
// Check that there are enough resources to upgrade the service offering
if (!isVirtualMachineUpgradable(vmInstance, newServiceOffering)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available " + "for an offering of " +
newServiceOffering.getCpu() + " cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory");
}
// Check that the service offering being upgraded to has all the tags of the current service offering
List<String> currentTags = StringUtils.csvTagsToList(currentServiceOffering.getTags());
List<String> newTags = StringUtils.csvTagsToList(newServiceOffering.getTags());
if (!newTags.containsAll(currentTags)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering " + "does not have all the tags of the " +
"current service offering. Current service offering tags: " + currentTags + "; " + "new service " + "offering tags: " + newTags);
}
}
@Override
public boolean upgradeVmDb(long vmId, long serviceOfferingId) {
VMInstanceVO vmForUpdate = _vmDao.createForUpdate();
vmForUpdate.setServiceOfferingId(serviceOfferingId);
ServiceOffering newSvcOff = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
vmForUpdate.setHaEnabled(newSvcOff.getOfferHA());
vmForUpdate.setLimitCpuUse(newSvcOff.getLimitCpuUse());
vmForUpdate.setServiceOfferingId(newSvcOff.getId());
return _vmDao.update(vmId, vmForUpdate);
}
@Override
public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested)
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateAddVmToNetwork(vm, network, requested);
} else {
Outcome<VirtualMachine> outcome = addVmToNetworkThroughJobQueue(vm, network, requested);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
NicProfile nic = (NicProfile)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult());
return nic;
} else {
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof InsufficientCapacityException)
throw (InsufficientCapacityException)jobException;
else if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
throw new RuntimeException("Job failed with unhandled exception");
}
}
}
private NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
CallContext cctx = CallContext.current();
s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested);
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
//check vm state
if (vm.getState() == State.Running) {
//1) allocate and prepare nic
NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true);
//2) Convert vmProfile to vmTO
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
//3) Convert nicProfile to NicTO
NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType());
//4) plug the nic to the vm
s_logger.debug("Plugging nic for vm " + vm + " in network " + network);
boolean result = false;
try {
result = plugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm is a part of network now");
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
// insert nic's Id into DB as resource_name
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmVO.getAccountId(), vmVO.getDataCenterId(), vmVO.getId(),
Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid());
return nic;
} else {
s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
return null;
}
} finally {
if (!result) {
s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine() + " as nic plug failed on the backend");
_networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
}
}
} else if (vm.getState() == State.Stopped) {
//1) allocate nic
return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
} else {
s_logger.warn("Unable to add vm " + vm + " to network " + network);
throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
}
@Override
public NicTO toNicTO(NicProfile nic, HypervisorType hypervisorType) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(hypervisorType);
NicTO nicTO = hvGuru.toNicTO(nic);
return nicTO;
}
@Override
public boolean removeNicFromVm(VirtualMachine vm, Nic nic)
throws ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateRemoveNicFromVm(vm, nic);
} else {
Outcome<VirtualMachine> outcome = removeNicFromVmThroughJobQueue(vm, nic);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
Boolean result = (Boolean)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult());
return result;
} else {
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
throw new RuntimeException("Job failed with un-handled exception");
}
}
}
private boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
NetworkVO network = _networkDao.findById(nic.getNetworkId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
// don't delete default NIC on a user VM
if (nic.isDefaultNic() && vm.getType() == VirtualMachine.Type.User) {
s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
}
// if specified nic is associated with PF/LB/Static NAT
if (rulesMgr.listAssociatedRulesForGuestNic(nic).size() > 0) {
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network +
", nic has associated Port forwarding or Load balancer or Static NAT rules.");
}
NicProfile nicProfile =
new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
//1) Unplug the nic
if (vm.getState() == State.Running) {
NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
s_logger.debug("Un-plugging nic " + nic + " for vm " + vm + " from network " + network);
boolean result = unplugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(),
Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
return false;
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
//2) Release the nic
_networkMgr.releaseNic(vmProfile, nic);
s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
//3) Remove the nic
_networkMgr.removeNic(vmProfile, nic);
_nicsDao.expunge(nic.getId());
return true;
}
@Override
@DB
public boolean removeVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
// TODO will serialize on the VM object later to resolve operation conflicts
return orchestrateRemoveVmFromNetwork(vm, network, broadcastUri);
}
@DB
private boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
Nic nic = null;
if (broadcastUri != null) {
nic = _nicsDao.findByNetworkIdInstanceIdAndBroadcastUri(network.getId(), vm.getId(), broadcastUri.toString());
} else {
nic = _networkModel.getNicInNetwork(vm.getId(), network.getId());
}
if (nic == null) {
s_logger.warn("Could not get a nic with " + network);
return false;
}
// don't delete default NIC on a user VM
if (nic.isDefaultNic() && vm.getType() == VirtualMachine.Type.User) {
s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
}
//Lock on nic is needed here
Nic lock = _nicsDao.acquireInLockTable(nic.getId());
if (lock == null) {
//check if nic is still there. Return if it was released already
if (_nicsDao.findById(nic.getId()) == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Not need to remove the vm " + vm + " from network " + network + " as the vm doesn't have nic in this network");
}
return true;
}
throw new ConcurrentOperationException("Unable to lock nic " + nic.getId());
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Lock is acquired for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
}
try {
NicProfile nicProfile =
new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
//1) Unplug the nic
if (vm.getState() == State.Running) {
NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
s_logger.debug("Un-plugging nic for vm " + vm + " from network " + network);
boolean result = unplugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
return false;
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
//2) Release the nic
_networkMgr.releaseNic(vmProfile, nic);
s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
//3) Remove the nic
_networkMgr.removeNic(vmProfile, nic);
return true;
} finally {
if (lock != null) {
_nicsDao.releaseFromLockTable(lock.getId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Lock is released for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
}
}
}
}
@Override
public void findHostAndMigrate(String vmUuid, Long newSvcOfferingId, ExcludeList excludes) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
throw new CloudRuntimeException("Unable to find " + vmUuid);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
Long srcHostId = vm.getHostId();
Long oldSvcOfferingId = vm.getServiceOfferingId();
if (srcHostId == null) {
throw new CloudRuntimeException("Unable to scale the vm because it doesn't have a host id");
}
Host host = _hostDao.findById(srcHostId);
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null);
excludes.addHost(vm.getHostId());
vm.setServiceOfferingId(newSvcOfferingId); // Need to find the destination host based on new svc offering
DeployDestination dest = null;
try {
dest = _dpMgr.planDeployment(profile, plan, excludes, null);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(" Found " + dest + " for scaling the vm to.");
}
}
if (dest == null) {
throw new InsufficientServerCapacityException("Unable to find a server to scale the vm to.", host.getClusterId());
}
excludes.addHost(dest.getHost().getId());
try {
migrateForScale(vm.getUuid(), srcHostId, dest, oldSvcOfferingId);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to migrate to unavailable " + dest);
throw e;
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
throw e;
}
}
@Override
public void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId);
} else {
Outcome<VirtualMachine> outcome = migrateVmForScaleThroughJobQueue(vmUuid, srcHostId, dest, oldSvcOfferingId);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
}
}
}
private void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
throws ResourceUnavailableException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
s_logger.info("Migrating " + vm + " to " + dest);
vm.getServiceOfferingId();
long dstHostId = dest.getHost().getId();
Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
}
VirtualMachineGuru vmGuru = getVmGuru(vm);
long vmId = vm.getId();
vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the vm " + vm);
}
throw new CloudRuntimeException("Unable to find a virtual machine with id " + vmId);
}
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
_networkMgr.prepareNicForMigration(profile, dest);
volumeMgr.prepareForMigration(profile, dest);
VirtualMachineTO to = toVmTO(profile);
PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
PrepareForMigrationAnswer pfma = null;
try {
pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc);
if (!pfma.getResult()) {
String msg = "Unable to prepare for migration due to " + pfma.getDetails();
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, ExecuteInSequence.value());
mc.setHostGuid(dest.getHost().getGuid());
try {
MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc);
if (!ma.getResult()) {
s_logger.error("Unable to migrate due to " + ma.getDetails());
throw new CloudRuntimeException("Unable to migrate due to " + ma.getDetails());
}
} catch (OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
long newServiceOfferingId = vm.getServiceOfferingId();
vm.setServiceOfferingId(oldSvcOfferingId); // release capacity for the old service offering only
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
vm.setServiceOfferingId(newServiceOfferingId);
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("Unable to complete migration for " + vm);
}
} catch (OperationTimedoutException e) {
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(),
"Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " +
dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
boolean result = true;
VMInstanceVO router = _vmDao.findById(vm.getId());
if (router.getState() == State.Running) {
try {
PlugNicCommand plugNicCmd = new PlugNicCommand(nic, vm.getName(), vm.getType());
Commands cmds = new Commands(Command.OnError.Stop);
cmds.addCommand("plugnic", plugNicCmd);
_agentMgr.send(dest.getHost().getId(), cmds);
PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class);
if (!(plugNicAnswer != null && plugNicAnswer.getResult())) {
s_logger.warn("Unable to plug nic for vm " + vm.getName());
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network, dest.getHost().getId(), e);
}
} else {
s_logger.warn("Unable to apply PlugNic, vm " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to apply PlugNic on the backend," + " vm " + vm + " is not in the right state", DataCenter.class,
router.getDataCenterId());
}
return result;
}
public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException,
ResourceUnavailableException {
boolean result = true;
VMInstanceVO router = _vmDao.findById(vm.getId());
if (router.getState() == State.Running) {
try {
Commands cmds = new Commands(Command.OnError.Stop);
UnPlugNicCommand unplugNicCmd = new UnPlugNicCommand(nic, vm.getName());
cmds.addCommand("unplugnic", unplugNicCmd);
_agentMgr.send(dest.getHost().getId(), cmds);
UnPlugNicAnswer unplugNicAnswer = cmds.getAnswer(UnPlugNicAnswer.class);
if (!(unplugNicAnswer != null && unplugNicAnswer.getResult())) {
s_logger.warn("Unable to unplug nic from router " + router);
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network, dest.getHost().getId(), e);
}
} else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {
s_logger.debug("Vm " + router.getInstanceName() + " is in " + router.getState() + ", so not sending unplug nic command to the backend");
} else {
s_logger.warn("Unable to apply unplug nic, Vm " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to apply unplug nic on the backend," + " vm " + router + " is not in the right state", DataCenter.class,
router.getDataCenterId());
}
return result;
}
@Override
public VMInstanceVO reConfigureVm(String vmUuid, ServiceOffering oldServiceOffering,
boolean reconfiguringOnExistingHost)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
} else {
Outcome<VirtualMachine> outcome = reconfigureVmThroughJobQueue(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
VirtualMachine vm = null;
try {
vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
return _entityMgr.findById(VMInstanceVO.class, vm.getId());
} else {
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
}
throw new RuntimeException("Failed with un-handled exception");
}
}
}
private VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException,
ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
long newServiceofferingId = vm.getServiceOfferingId();
ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), newServiceofferingId);
HostVO hostVo = _hostDao.findById(vm.getHostId());
Float memoryOvercommitRatio = CapacityManager.MemOverprovisioningFactor.valueIn(hostVo.getClusterId());
Float cpuOvercommitRatio = CapacityManager.CpuOverprovisioningFactor.valueIn(hostVo.getClusterId());
long minMemory = (long)(newServiceOffering.getRamSize() / memoryOvercommitRatio);
ScaleVmCommand reconfigureCmd =
new ScaleVmCommand(vm.getInstanceName(), newServiceOffering.getCpu(), (int)(newServiceOffering.getSpeed() / cpuOvercommitRatio),
newServiceOffering.getSpeed(), minMemory * 1024L * 1024L, newServiceOffering.getRamSize() * 1024L * 1024L, newServiceOffering.getLimitCpuUse());
Long dstHostId = vm.getHostId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Running, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(vm.getHostId());
work = _workDao.persist(work);
boolean success = false;
try {
if (reconfiguringOnExistingHost) {
vm.setServiceOfferingId(oldServiceOffering.getId());
_capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); //release the old capacity
vm.setServiceOfferingId(newServiceofferingId);
_capacityMgr.allocateVmCapacity(vm, false); // lock the new capacity
}
Answer reconfigureAnswer = _agentMgr.send(vm.getHostId(), reconfigureCmd);
if (reconfigureAnswer == null || !reconfigureAnswer.getResult()) {
s_logger.error("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails()));
throw new CloudRuntimeException("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails()));
}
success = true;
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Operation timed out on reconfiguring " + vm, dstHostId);
} catch (AgentUnavailableException e) {
throw e;
} finally {
// work.setStep(Step.Done);
//_workDao.update(work.getId(), work);
if (!success) {
_capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); // release the new capacity
vm.setServiceOfferingId(oldServiceOffering.getId());
_capacityMgr.allocateVmCapacity(vm, false); // allocate the old capacity
}
}
return vm;
}
@Override
public String getConfigComponentName() {
return VirtualMachineManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {ClusterDeltaSyncInterval, StartRetry, VmDestroyForcestop, VmOpCancelInterval, VmOpCleanupInterval, VmOpCleanupWait,
VmOpLockStateRetry,
VmOpWaitInterval, ExecuteInSequence, VmJobCheckInterval, VmJobTimeout, VmJobStateReportInterval};
}
public List<StoragePoolAllocator> getStoragePoolAllocators() {
return _storagePoolAllocators;
}
@Inject
public void setStoragePoolAllocators(List<StoragePoolAllocator> storagePoolAllocators) {
_storagePoolAllocators = storagePoolAllocators;
}
//
// PowerState report handling for out-of-band changes and handling of left-over transitional VM states
//
@MessageHandler(topic = Topics.VM_POWER_STATE)
private void HandlePownerStateReport(Object target, String subject, String senderAddress, Object args) {
assert (args != null);
Long vmId = (Long)args;
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vmId);
if (pendingWorkJobs.size() == 0) {
// there is no pending operation job
VMInstanceVO vm = _vmDao.findById(vmId);
if (vm != null) {
switch (vm.getPowerState()) {
case PowerOn:
handlePowerOnReportWithNoPendingJobsOnVM(vm);
break;
case PowerOff:
handlePowerOffReportWithNoPendingJobsOnVM(vm);
break;
// PowerUnknown shouldn't be reported, it is a derived
// VM power state from host state (host un-reachable
case PowerUnknown:
default:
assert (false);
break;
}
} else {
s_logger.warn("VM " + vmId + " no longer exists when processing VM state report");
}
} else {
// TODO, do job wake-up signalling, since currently async job wake-up is not in use
// we will skip it for nows
}
}
private void handlePowerOnReportWithNoPendingJobsOnVM(VMInstanceVO vm) {
//
// 1) handle left-over transitional VM states
// 2) handle out of band VM live migration
// 3) handle out of sync stationary states, marking VM from Stopped to Running with
// alert messages
//
switch (vm.getState()) {
case Starting:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
// we need to alert admin or user about this risky state transition
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName()
+ ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset");
break;
case Running:
try {
if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue())
s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId());
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
break;
case Stopping:
case Stopped:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState()
+ " -> Running) from out-of-context transition. VM network environment may need to be reset");
break;
case Destroyed:
case Expunging:
s_logger.info("Receive power on report when VM is in destroyed or expunging state. vm: "
+ vm.getId() + ", state: " + vm.getState());
break;
case Migrating:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
break;
case Error:
default:
s_logger.info("Receive power on report when VM is in error or unexpected state. vm: "
+ vm.getId() + ", state: " + vm.getState());
break;
}
}
private void handlePowerOffReportWithNoPendingJobsOnVM(VMInstanceVO vm) {
// 1) handle left-over transitional VM states
// 2) handle out of sync stationary states, schedule force-stop to release resources
//
switch (vm.getState()) {
case Starting:
case Stopping:
case Stopped:
case Migrating:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState()
+ " -> Stopped) from out-of-context transition.");
// TODO: we need to forcely release all resource allocation
break;
case Running:
case Destroyed:
case Expunging:
break;
case Error:
default:
break;
}
}
private void scanStalledVMInTransitionStateOnUpHost(long hostId) {
//
// Check VM that is stuck in Starting, Stopping, Migrating states, we won't check
// VMs in expunging state (this need to be handled specially)
//
// checking condition
// 1) no pending VmWork job
// 2) on hostId host and host is UP
//
// When host is UP, soon or later we will get a report from the host about the VM,
// however, if VM is missing from the host report (it may happen in out of band changes
// or from designed behave of XS/KVM), the VM may not get a chance to run the state-sync logic
//
// Therefor, we will scan thoses VMs on UP host based on last update timestamp, if the host is UP
// and a VM stalls for status update, we will consider them to be powered off
// (which is relatively safe to do so)
long stallThresholdInMs = VmJobStateReportInterval.value() + (VmJobStateReportInterval.value() >> 1);
Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - stallThresholdInMs);
List<Long> mostlikelyStoppedVMs = listStalledVMInTransitionStateOnUpHost(hostId, cutTime);
for (Long vmId : mostlikelyStoppedVMs) {
VMInstanceVO vm = _vmDao.findById(vmId);
assert (vm != null);
handlePowerOffReportWithNoPendingJobsOnVM(vm);
}
List<Long> vmsWithRecentReport = listVMInTransitionStateWithRecentReportOnUpHost(hostId, cutTime);
for (Long vmId : vmsWithRecentReport) {
VMInstanceVO vm = _vmDao.findById(vmId);
assert (vm != null);
if (vm.getPowerState() == PowerState.PowerOn)
handlePowerOnReportWithNoPendingJobsOnVM(vm);
else
handlePowerOffReportWithNoPendingJobsOnVM(vm);
}
}
private void scanStalledVMInTransitionStateOnDisconnectedHosts() {
Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - VmOpWaitInterval.value() * 1000);
List<Long> stuckAndUncontrollableVMs = listStalledVMInTransitionStateOnDisconnectedHosts(cutTime);
for (Long vmId : stuckAndUncontrollableVMs) {
VMInstanceVO vm = _vmDao.findById(vmId);
// We now only alert administrator about this situation
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState()
+ " state and its host is unreachable for too long");
}
}
// VMs that in transitional state without recent power state report
private List<Long> listStalledVMInTransitionStateOnUpHost(long hostId, Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " +
"AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " +
"AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
"AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List<Long> l = new ArrayList<Long>();
TransactionLegacy txn = null;
try {
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, hostId);
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime));
pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
} finally {
if (txn != null)
txn.close();
}
return l;
}
// VMs that in transitional state and recently have power state update
private List<Long> listVMInTransitionStateWithRecentReportOnUpHost(long hostId, Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " +
"AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " +
"AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
"AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List<Long> l = new ArrayList<Long>();
TransactionLegacy txn = null;
try {
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, hostId);
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime));
pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
return l;
} finally {
if (txn != null)
txn.close();
}
}
private List<Long> listStalledVMInTransitionStateOnDisconnectedHosts(Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status != 'UP' " +
"AND i.power_state_update_time < ? AND i.host_id = h.id " +
"AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
"AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List<Long> l = new ArrayList<Long>();
TransactionLegacy txn = null;
try {
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime));
pstmt.setInt(2, JobInfo.Status.IN_PROGRESS.ordinal());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
return l;
} finally {
if (txn != null)
txn.close();
}
}
//
// VM operation based on new sync model
//
public class VmStateSyncOutcome extends OutcomeImpl<VirtualMachine> {
private long _vmId;
public VmStateSyncOutcome(final AsyncJob job, final PowerState desiredPowerState, final long vmId, final Long srcHostIdForMigration) {
super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
VMInstanceVO instance = _vmDao.findById(vmId);
if (instance.getPowerState() == desiredPowerState && (srcHostIdForMigration != null && instance.getPowerHostId() != srcHostIdForMigration))
return true;
return false;
}
}, Topics.VM_POWER_STATE, AsyncJob.Topics.JOB_STATE);
_vmId = vmId;
}
@Override
protected VirtualMachine retrieve() {
return _vmDao.findById(_vmId);
}
}
public class VmJobSyncOutcome extends OutcomeImpl<VirtualMachine> {
private long _vmId;
public VmJobSyncOutcome(final AsyncJob job, final long vmId) {
super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
_vmId = vmId;
}
@Override
protected VirtualMachine retrieve() {
return _vmDao.findById(_vmId);
}
}
public Throwable retrieveExecutionException(AsyncJob job) {
assert (job != null);
assert (job.getDispatcher().equals(VmWorkConstants.VM_WORK_JOB_DISPATCHER));
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
if (jobVo != null && jobVo.getResult() != null) {
Object obj = JobSerializerHelper.fromSerializedString(job.getResult());
if (obj != null && obj instanceof Throwable)
return (Throwable)obj;
}
return null;
}
//
// TODO build a common pattern to reduce code duplication in following methods
// no time for this at current iteration
//
public Outcome<VirtualMachine> startVmThroughJobQueue(final String vmUuid,
final Map<VirtualMachineProfile.Param, Object> params,
final DeploymentPlan planToDeploy) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
VmWorkJobVO workJob = null;
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance,
vm.getId(), VmWorkStart.class.getName());
if (pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkStart.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER);
workInfo.setPlan(planToDeploy);
workInfo.setParams(params);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
// Transaction syntax sugar has a cost here
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOn, vm.getId(), null);
}
public Outcome<VirtualMachine> stopVmThroughJobQueue(final String vmUuid, final boolean cleanup) {
final CallContext context = CallContext.current();
final Account account = context.getCallingAccount();
final User user = context.getCallingUser();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
vm.getType(), vm.getId(),
VmWorkStop.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkStop.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setStep(VmWorkJobVO.Step.Prepare);
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, cleanup);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOff, vm.getId(), null);
}
public Outcome<VirtualMachine> rebootVmThroughJobQueue(final String vmUuid,
final Map<VirtualMachineProfile.Param, Object> params) {
final CallContext context = CallContext.current();
final Account account = context.getCallingAccount();
final User user = context.getCallingUser();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkReboot.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkReboot.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setStep(VmWorkJobVO.Step.Prepare);
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, params);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
vm.getId());
}
public Outcome<VirtualMachine> migrateVmThroughJobQueue(final String vmUuid, final long srcHostId, final DeployDestination dest) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkMigrate.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrate.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId());
}
public Outcome<VirtualMachine> migrateVmWithStorageThroughJobQueue(
final String vmUuid, final long srcHostId, final long destHostId,
final Map<Volume, StoragePool> volumeToPool) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkMigrateWithStorage.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrate.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, destHostId, volumeToPool);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId);
}
public Outcome<VirtualMachine> migrateVmForScaleThroughJobQueue(
final String vmUuid, final long srcHostId, final DeployDestination dest, final Long newSvcOfferingId) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkMigrateForScale.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrate.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest, newSvcOfferingId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> migrateVmStorageThroughJobQueue(
final String vmUuid, final StoragePool destPool) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkStorageMigration.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkStorageMigration.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, destPool);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> addVmToNetworkThroughJobQueue(
final VirtualMachine vm, final Network network, final NicProfile requested) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkAddVmToNetwork.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkAddVmToNetwork.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, requested);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> removeNicFromVmThroughJobQueue(
final VirtualMachine vm, final Nic nic) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkRemoveNicFromVm.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkRemoveNicFromVm.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, nic);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> removeVmFromNetworkThroughJobQueue(
final VirtualMachine vm, final Network network, final URI broadcastUri) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkRemoveVmFromNetwork.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, broadcastUri);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> reconfigureVmThroughJobQueue(
final String vmUuid, final ServiceOffering oldServiceOffering, final boolean reconfiguringOnExistingHost) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkReconfigure.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkReconfigure.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, oldServiceOffering, reconfiguringOnExistingHost);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
@Override
public Pair<JobInfo.Status, String> handleVmWorkJob(AsyncJob job, VmWork work) throws Exception {
VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId());
if (vm == null) {
s_logger.info("Unable to find vm " + work.getVmId());
}
assert (vm != null);
if (work instanceof VmWorkStart) {
VmWorkStart workStart = (VmWorkStart)work;
orchestrateStart(vm.getUuid(), workStart.getParams(), workStart.getPlan(), null);
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkStop) {
VmWorkStop workStop = (VmWorkStop)work;
orchestrateStop(vm.getUuid(), workStop.isCleanup());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkMigrate) {
VmWorkMigrate workMigrate = (VmWorkMigrate)work;
orchestrateMigrate(vm.getUuid(), workMigrate.getSrcHostId(), workMigrate.getDeployDestination());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkMigrateWithStorage) {
VmWorkMigrateWithStorage workMigrateWithStorage = (VmWorkMigrateWithStorage)work;
orchestrateMigrateWithStorage(vm.getUuid(),
workMigrateWithStorage.getSrcHostId(),
workMigrateWithStorage.getDestHostId(),
workMigrateWithStorage.getVolumeToPool());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkMigrateForScale) {
VmWorkMigrateForScale workMigrateForScale = (VmWorkMigrateForScale)work;
orchestrateMigrateForScale(vm.getUuid(),
workMigrateForScale.getSrcHostId(),
workMigrateForScale.getDeployDestination(),
workMigrateForScale.getNewServiceOfferringId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkReboot) {
VmWorkReboot workReboot = (VmWorkReboot)work;
orchestrateReboot(vm.getUuid(), workReboot.getParams());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkAddVmToNetwork) {
VmWorkAddVmToNetwork workAddVmToNetwork = (VmWorkAddVmToNetwork)work;
NicProfile nic = orchestrateAddVmToNetwork(vm, workAddVmToNetwork.getNetwork(),
workAddVmToNetwork.getRequestedNicProfile());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, JobSerializerHelper.toObjectSerializedString(nic));
} else if (work instanceof VmWorkRemoveNicFromVm) {
VmWorkRemoveNicFromVm workRemoveNicFromVm = (VmWorkRemoveNicFromVm)work;
boolean result = orchestrateRemoveNicFromVm(vm, workRemoveNicFromVm.getNic());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
JobSerializerHelper.toObjectSerializedString(new Boolean(result)));
} else if (work instanceof VmWorkRemoveVmFromNetwork) {
VmWorkRemoveVmFromNetwork workRemoveVmFromNetwork = (VmWorkRemoveVmFromNetwork)work;
boolean result = orchestrateRemoveVmFromNetwork(vm,
workRemoveVmFromNetwork.getNetwork(), workRemoveVmFromNetwork.getBroadcastUri());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
JobSerializerHelper.toObjectSerializedString(new Boolean(result)));
} else if (work instanceof VmWorkReconfigure) {
VmWorkReconfigure workReconfigure = (VmWorkReconfigure)work;
reConfigureVm(vm.getUuid(), workReconfigure.getNewServiceOffering(),
workReconfigure.isSameHost());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkStorageMigration) {
VmWorkStorageMigration workStorageMigration = (VmWorkStorageMigration)work;
orchestrateStorageMigration(vm.getUuid(), workStorageMigration.getDestStoragePool());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else {
RuntimeException e = new RuntimeException("Unsupported VM work command: " + job.getCmd());
String exceptionJson = JobSerializerHelper.toSerializedString(e);
s_logger.error("Serialize exception object into json: " + exceptionJson);
return new Pair<JobInfo.Status, String>(JobInfo.Status.FAILED, exceptionJson);
}
}
}
| engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.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.cloud.vm;
import java.net.URI;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.deploy.DeploymentPlanner;
import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
import org.apache.cloudstack.framework.config.ConfigDepot;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.Configurable;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.jobs.AsyncJob;
import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.framework.jobs.Outcome;
import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao;
import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
import org.apache.cloudstack.framework.jobs.impl.JobSerializerHelper;
import org.apache.cloudstack.framework.jobs.impl.OutcomeImpl;
import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.MessageHandler;
import org.apache.cloudstack.jobs.JobInfo;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.cloudstack.utils.identity.ManagementServerNode;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckVirtualMachineAnswer;
import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.ClusterSyncAnswer;
import com.cloud.agent.api.ClusterSyncCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.MigrateAnswer;
import com.cloud.agent.api.MigrateCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.PlugNicAnswer;
import com.cloud.agent.api.PlugNicCommand;
import com.cloud.agent.api.PrepareForMigrationAnswer;
import com.cloud.agent.api.PrepareForMigrationCommand;
import com.cloud.agent.api.RebootAnswer;
import com.cloud.agent.api.RebootCommand;
import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.StartAnswer;
import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupRoutingCommand.VmState;
import com.cloud.agent.api.StopAnswer;
import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.UnPlugNicAnswer;
import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.to.DiskTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.manager.Commands;
import com.cloud.agent.manager.allocator.HostAllocator;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.CapacityManager;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterDetailsVO;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Pod;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.deploy.DataCenterDeployment;
import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.deploy.DeploymentPlanner.ExcludeList;
import com.cloud.deploy.DeploymentPlanningManager;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.AffinityConflictException;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.ha.HighAvailabilityManager.WorkType;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuru;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.network.Network;
import com.cloud.network.NetworkModel;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkVO;
import com.cloud.network.rules.RulesManager;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.org.Cluster;
import com.cloud.resource.ResourceManager;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StoragePool;
import com.cloud.storage.Volume;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.template.VirtualMachineTemplate;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.DateUtil;
import com.cloud.utils.Journal;
import com.cloud.utils.Pair;
import com.cloud.utils.Predicate;
import com.cloud.utils.StringUtils;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionCallbackWithException;
import com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExecutionException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.vm.ItWorkVO.Step;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshot;
import com.cloud.vm.snapshot.VMSnapshotManager;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
@Local(value = VirtualMachineManager.class)
public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMachineManager, VmWorkJobHandler, Listener, Configurable {
private static final Logger s_logger = Logger.getLogger(VirtualMachineManagerImpl.class);
public static final String VM_WORK_JOB_HANDLER = VirtualMachineManagerImpl.class.getSimpleName();
private static final String VM_SYNC_ALERT_SUBJECT = "VM state sync alert";
@Inject
DataStoreManager dataStoreMgr;
@Inject
protected NetworkOrchestrationService _networkMgr;
@Inject
protected NetworkModel _networkModel;
@Inject
protected AgentManager _agentMgr;
@Inject
protected VMInstanceDao _vmDao;
@Inject
protected ServiceOfferingDao _offeringDao;
@Inject
protected DiskOfferingDao _diskOfferingDao;
@Inject
protected VMTemplateDao _templateDao;
@Inject
protected DomainDao _domainDao;
@Inject
protected ItWorkDao _workDao;
@Inject
protected UserVmDao _userVmDao;
@Inject
protected CapacityManager _capacityMgr;
@Inject
protected NicDao _nicsDao;
@Inject
protected HostDao _hostDao;
@Inject
protected AlertManager _alertMgr;
@Inject
protected GuestOSCategoryDao _guestOsCategoryDao;
@Inject
protected GuestOSDao _guestOsDao;
@Inject
protected VolumeDao _volsDao;
@Inject
protected HighAvailabilityManager _haMgr;
@Inject
protected HostPodDao _podDao;
@Inject
protected DataCenterDao _dcDao;
@Inject
protected ClusterDao _clusterDao;
@Inject
protected PrimaryDataStoreDao _storagePoolDao;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject
protected NetworkDao _networkDao;
@Inject
protected StoragePoolHostDao _poolHostDao;
@Inject
protected VMSnapshotDao _vmSnapshotDao;
@Inject
protected RulesManager rulesMgr;
@Inject
protected AffinityGroupVMMapDao _affinityGroupVMMapDao;
@Inject
protected EntityManager _entityMgr;
@Inject
ConfigDepot _configDepot;
protected List<HostAllocator> hostAllocators;
public List<HostAllocator> getHostAllocators() {
return hostAllocators;
}
public void setHostAllocators(List<HostAllocator> hostAllocators) {
this.hostAllocators = hostAllocators;
}
protected List<StoragePoolAllocator> _storagePoolAllocators;
@Inject
protected ResourceManager _resourceMgr;
@Inject
protected VMSnapshotManager _vmSnapshotMgr = null;
@Inject
protected ClusterDetailsDao _clusterDetailsDao;
@Inject
protected UserVmDetailsDao _uservmDetailsDao;
@Inject
protected ConfigurationDao _configDao;
@Inject
VolumeOrchestrationService volumeMgr;
@Inject
DeploymentPlanningManager _dpMgr;
@Inject
protected MessageBus _messageBus;
@Inject
protected VirtualMachinePowerStateSync _syncMgr;
@Inject
protected VmWorkJobDao _workJobDao;
@Inject
protected AsyncJobManager _jobMgr;
Map<VirtualMachine.Type, VirtualMachineGuru> _vmGurus = new HashMap<VirtualMachine.Type, VirtualMachineGuru>();
protected StateMachine2<State, VirtualMachine.Event, VirtualMachine> _stateMachine;
static final ConfigKey<Integer> StartRetry = new ConfigKey<Integer>("Advanced", Integer.class, "start.retry", "10",
"Number of times to retry create and start commands", true);
static final ConfigKey<Integer> VmOpWaitInterval = new ConfigKey<Integer>("Advanced", Integer.class, "vm.op.wait.interval", "120",
"Time (in seconds) to wait before checking if a previous operation has succeeded", true);
static final ConfigKey<Integer> VmOpLockStateRetry = new ConfigKey<Integer>("Advanced", Integer.class, "vm.op.lock.state.retry", "5",
"Times to retry locking the state of a VM for operations, -1 means forever", true);
static final ConfigKey<Long> VmOpCleanupInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cleanup.interval", "86400",
"Interval to run the thread that cleans up the vm operations (in seconds)", false);
static final ConfigKey<Long> VmOpCleanupWait = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cleanup.wait", "3600",
"Time (in seconds) to wait before cleanuping up any vm work items", true);
static final ConfigKey<Long> VmOpCancelInterval = new ConfigKey<Long>("Advanced", Long.class, "vm.op.cancel.interval", "3600",
"Time (in seconds) to wait before cancelling a operation", false);
static final ConfigKey<Boolean> VmDestroyForcestop = new ConfigKey<Boolean>("Advanced", Boolean.class, "vm.destroy.forcestop", "false",
"On destroy, force-stop takes this value ", true);
static final ConfigKey<Integer> ClusterDeltaSyncInterval = new ConfigKey<Integer>("Advanced", Integer.class, "sync.interval", "60",
"Cluster Delta sync interval in seconds",
false);
static final ConfigKey<Boolean> VmJobEnabled = new ConfigKey<Boolean>("Advanced",
Boolean.class, "vm.job.enabled", "false",
"True to enable new VM sync model. false to use the old way", false);
static final ConfigKey<Long> VmJobCheckInterval = new ConfigKey<Long>("Advanced",
Long.class, "vm.job.check.interval", "3000",
"Interval in milliseconds to check if the job is complete", false);
static final ConfigKey<Long> VmJobTimeout = new ConfigKey<Long>("Advanced",
Long.class, "vm.job.timeout", "600000",
"Time in milliseconds to wait before attempting to cancel a job", false);
static final ConfigKey<Integer> VmJobStateReportInterval = new ConfigKey<Integer>("Advanced",
Integer.class, "vm.job.report.interval", "60",
"Interval to send application level pings to make sure the connection is still working", false);
ScheduledExecutorService _executor = null;
protected long _nodeId;
@Override
public void registerGuru(VirtualMachine.Type type, VirtualMachineGuru guru) {
synchronized (_vmGurus) {
_vmGurus.put(type, guru);
}
}
@Override
@DB
public void allocate(String vmInstanceName, final VirtualMachineTemplate template, ServiceOffering serviceOffering,
final Pair<? extends DiskOffering, Long> rootDiskOffering, LinkedHashMap<? extends DiskOffering, Long> dataDiskOfferings,
final LinkedHashMap<? extends Network, ? extends NicProfile> auxiliaryNetworks, DeploymentPlan plan, HypervisorType hyperType)
throws InsufficientCapacityException {
VMInstanceVO vm = _vmDao.findVMByInstanceName(vmInstanceName);
final Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating entries for VM: " + vm);
}
vm.setDataCenterId(plan.getDataCenterId());
if (plan.getPodId() != null) {
vm.setPodId(plan.getPodId());
}
assert (plan.getClusterId() == null && plan.getPoolId() == null) : "We currently don't support cluster and pool preset yet";
final VMInstanceVO vmFinal = _vmDao.persist(vm);
final LinkedHashMap<? extends DiskOffering, Long> dataDiskOfferingsFinal =
dataDiskOfferings == null ? new LinkedHashMap<DiskOffering, Long>() : dataDiskOfferings;
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmFinal, template, serviceOffering, null, null);
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientCapacityException {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating nics for " + vmFinal);
}
try {
_networkMgr.allocate(vmProfile, auxiliaryNetworks);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation while trying to allocate resources for the VM", e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocating disks for " + vmFinal);
}
if (template.getFormat() == ImageFormat.ISO) {
volumeMgr.allocateRawVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOffering.first(), rootDiskOffering.second(), vmFinal, template, owner);
} else if (template.getFormat() == ImageFormat.BAREMETAL) {
// Do nothing
} else {
volumeMgr.allocateTemplatedVolume(Type.ROOT, "ROOT-" + vmFinal.getId(), rootDiskOffering.first(), rootDiskOffering.second(), template, vmFinal, owner);
}
for (Map.Entry<? extends DiskOffering, Long> offering : dataDiskOfferingsFinal.entrySet()) {
volumeMgr.allocateRawVolume(Type.DATADISK, "DATA-" + vmFinal.getId(), offering.getKey(), offering.getValue(), vmFinal, template, owner);
}
}
});
if (s_logger.isDebugEnabled()) {
s_logger.debug("Allocation completed for VM: " + vmFinal);
}
}
@Override
public void allocate(String vmInstanceName, VirtualMachineTemplate template, ServiceOffering serviceOffering,
LinkedHashMap<? extends Network, ? extends NicProfile> networks, DeploymentPlan plan, HypervisorType hyperType) throws InsufficientCapacityException {
allocate(vmInstanceName, template, serviceOffering, new Pair<DiskOffering, Long>(serviceOffering, null), null, networks, plan, hyperType);
}
private VirtualMachineGuru getVmGuru(VirtualMachine vm) {
return _vmGurus.get(vm.getType());
}
@Override
public void expunge(String vmUuid) throws ResourceUnavailableException {
try {
advanceExpunge(vmUuid);
} catch (OperationTimedoutException e) {
throw new CloudRuntimeException("Operation timed out", e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Concurrent operation ", e);
}
}
@Override
public void advanceExpunge(String vmUuid) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
advanceExpunge(vm);
}
protected void advanceExpunge(VMInstanceVO vm) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException {
if (vm == null || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return;
}
advanceStop(vm, false);
try {
if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
throw new CloudRuntimeException("Unable to destroy " + vm);
}
} catch (NoTransitionException e) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
throw new CloudRuntimeException("Unable to destroy " + vm, e);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
s_logger.debug("Cleaning up NICS");
List<Command> nicExpungeCommands = hvGuru.finalizeExpungeNics(vm, profile.getNics());
_networkMgr.cleanupNics(profile);
// Clean up volumes based on the vm's instance id
volumeMgr.cleanupVolumes(vm.getId());
VirtualMachineGuru guru = getVmGuru(vm);
guru.finalizeExpunge(vm);
//remove the overcommit detials from the uservm details
_uservmDetailsDao.removeDetails(vm.getId());
// send hypervisor-dependent commands before removing
List<Command> finalizeExpungeCommands = hvGuru.finalizeExpunge(vm);
if (finalizeExpungeCommands != null && finalizeExpungeCommands.size() > 0) {
Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
if (hostId != null) {
Commands cmds = new Commands(Command.OnError.Stop);
for (Command command : finalizeExpungeCommands) {
cmds.addCommand(command);
}
if (nicExpungeCommands != null) {
for (Command command : nicExpungeCommands) {
cmds.addCommand(command);
}
}
_agentMgr.send(hostId, cmds);
if (!cmds.isSuccessful()) {
for (Answer answer : cmds.getAnswers()) {
if (!answer.getResult()) {
s_logger.warn("Failed to expunge vm due to: " + answer.getDetails());
throw new CloudRuntimeException("Unable to expunge " + vm + " due to " + answer.getDetails());
}
}
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunged " + vm);
}
}
@Override
public boolean start() {
_executor.scheduleAtFixedRate(new CleanupTask(), VmOpCleanupInterval.value(), VmOpCleanupInterval.value(), TimeUnit.SECONDS);
cancelWorkItems(_nodeId);
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> xmlParams) throws ConfigurationException {
ReservationContextImpl.init(_entityMgr);
VirtualMachineProfileImpl.init(_entityMgr);
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vm-Operations-Cleanup"));
_nodeId = ManagementServerNode.getManagementServerId();
_agentMgr.registerForHostEvents(this, true, true, true);
return true;
}
protected VirtualMachineManagerImpl() {
setStateMachine();
}
@Override
public void start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) {
start(vmUuid, params, null);
}
@Override
public void start(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy) {
try {
advanceStart(vmUuid, params, planToDeploy, null);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid);
} catch (InsufficientCapacityException e) {
throw new CloudRuntimeException("Unable to start a VM due to insufficient capacity", e).add(VirtualMachine.class, vmUuid);
} catch (ResourceUnavailableException e) {
throw new CloudRuntimeException("Unable to start a VM due to concurrent operation", e).add(VirtualMachine.class, vmUuid);
}
}
protected boolean checkWorkItems(VMInstanceVO vm, State state) throws ConcurrentOperationException {
while (true) {
ItWorkVO vo = _workDao.findByOutstandingWork(vm.getId(), state);
if (vo == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find work for VM: " + vm + " and state: " + state);
}
return true;
}
if (vo.getStep() == Step.Done) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Work for " + vm + " is " + vo.getStep());
}
return true;
}
if (vo.getSecondsTaskIsInactive() > VmOpCancelInterval.value()) {
s_logger.warn("The task item for vm " + vm + " has been inactive for " + vo.getSecondsTaskIsInactive());
return false;
}
try {
Thread.sleep(VmOpWaitInterval.value());
} catch (InterruptedException e) {
s_logger.info("Waiting for " + vm + " but is interrupted");
throw new ConcurrentOperationException("Waiting for " + vm + " but is interrupted");
}
s_logger.debug("Waiting some more to make sure there's no activity on " + vm);
}
}
@DB
protected Ternary<VMInstanceVO, ReservationContext, ItWorkVO> changeToStartState(VirtualMachineGuru vmGuru, final VMInstanceVO vm, final User caller,
final Account account) throws ConcurrentOperationException {
long vmId = vm.getId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Starting, vm.getType(), vm.getId());
int retry = VmOpLockStateRetry.value();
while (retry-- != 0) {
try {
final ItWorkVO workFinal = work;
Ternary<VMInstanceVO, ReservationContext, ItWorkVO> result =
Transaction.execute(new TransactionCallbackWithException<Ternary<VMInstanceVO, ReservationContext, ItWorkVO>, NoTransitionException>() {
@Override
public Ternary<VMInstanceVO, ReservationContext, ItWorkVO> doInTransaction(TransactionStatus status) throws NoTransitionException {
Journal journal = new Journal.LogJournal("Creating " + vm, s_logger);
ItWorkVO work = _workDao.persist(workFinal);
ReservationContextImpl context = new ReservationContextImpl(work.getId(), journal, caller, account);
if (stateTransitTo(vm, Event.StartRequested, null, work.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully transitioned to start state for " + vm + " reservation id = " + work.getId());
}
return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(vm, context, work);
}
return new Ternary<VMInstanceVO, ReservationContext, ItWorkVO>(null, null, work);
}
});
work = result.third();
if (result.first() != null)
return result;
} catch (NoTransitionException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to transition into Starting state due to " + e.getMessage());
}
}
VMInstanceVO instance = _vmDao.findById(vmId);
if (instance == null) {
throw new ConcurrentOperationException("Unable to acquire lock on " + vm);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Determining why we're unable to update the state to Starting for " + instance + ". Retry=" + retry);
}
State state = instance.getState();
if (state == State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already started: " + vm);
}
return null;
}
if (state.isTransitional()) {
if (!checkWorkItems(vm, state)) {
throw new ConcurrentOperationException("There are concurrent operations on " + vm);
} else {
continue;
}
}
if (state != State.Stopped) {
s_logger.debug("VM " + vm + " is not in a state to be started: " + state);
return null;
}
}
throw new ConcurrentOperationException("Unable to change the state of " + vm);
}
protected <T extends VMInstanceVO> boolean changeState(T vm, Event event, Long hostId, ItWorkVO work, Step step) throws NoTransitionException {
// FIXME: We should do this better.
Step previousStep = work.getStep();
_workDao.updateStep(work, step);
boolean result = false;
try {
result = stateTransitTo(vm, event, hostId);
return result;
} finally {
if (!result) {
_workDao.updateStep(work, previousStep);
}
}
}
protected boolean areAffinityGroupsAssociated(VirtualMachineProfile vmProfile) {
VirtualMachine vm = vmProfile.getVirtualMachine();
long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
if (vmGroupCount > 0) {
return true;
}
return false;
}
@Override
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlanner planner)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
advanceStart(vmUuid, params, null, planner);
}
@Override
public void advanceStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy, DeploymentPlanner planner) throws InsufficientCapacityException,
ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStart(vmUuid, params, planToDeploy, planner);
} else {
Outcome<VirtualMachine> outcome = startVmThroughJobQueue(vmUuid, params, planToDeploy);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
}
}
}
@Override
public void orchestrateStart(String vmUuid, Map<VirtualMachineProfile.Param, Object> params, DeploymentPlan planToDeploy, DeploymentPlanner planner)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
CallContext cctxt = CallContext.current();
Account account = cctxt.getCallingAccount();
User caller = cctxt.getCallingUser();
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
VirtualMachineGuru vmGuru = getVmGuru(vm);
Ternary<VMInstanceVO, ReservationContext, ItWorkVO> start = changeToStartState(vmGuru, vm, caller, account);
if (start == null) {
return;
}
vm = start.first();
ReservationContext ctx = start.second();
ItWorkVO work = start.third();
VMInstanceVO startedVm = null;
ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId());
VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, vm.getTemplateId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Trying to deploy VM, vm has dcId: " + vm.getDataCenterId() + " and podId: " + vm.getPodIdToDeployIn());
}
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), vm.getPodIdToDeployIn(), null, null, null, null, ctx);
if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("advanceStart: DeploymentPlan is provided, using dcId:" + planToDeploy.getDataCenterId() + ", podId: " + planToDeploy.getPodId() +
", clusterId: " + planToDeploy.getClusterId() + ", hostId: " + planToDeploy.getHostId() + ", poolId: " + planToDeploy.getPoolId());
}
plan =
new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(), planToDeploy.getHostId(),
planToDeploy.getPoolId(), planToDeploy.getPhysicalNetworkId(), ctx);
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
boolean canRetry = true;
ExcludeList avoids = null;
try {
Journal journal = start.second().getJournal();
if (planToDeploy != null) {
avoids = planToDeploy.getAvoids();
}
if (avoids == null) {
avoids = new ExcludeList();
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deploy avoids pods: " + avoids.getPodsToAvoid() + ", clusters: " + avoids.getClustersToAvoid() + ", hosts: " + avoids.getHostsToAvoid());
}
boolean planChangedByVolume = false;
boolean reuseVolume = true;
DataCenterDeployment originalPlan = plan;
int retry = StartRetry.value();
while (retry-- != 0) { // It's != so that it can match -1.
if (reuseVolume) {
// edit plan if this vm's ROOT volume is in READY state already
List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
for (VolumeVO vol : vols) {
// make sure if the templateId is unchanged. If it is changed,
// let planner
// reassign pool for the volume even if it ready.
Long volTemplateId = vol.getTemplateId();
if (volTemplateId != null && volTemplateId.longValue() != template.getId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " of " + vm + " is READY, but template ids don't match, let the planner reassign a new pool");
}
continue;
}
StoragePool pool = (StoragePool)dataStoreMgr.getPrimaryDataStore(vol.getPoolId());
if (!pool.isInMaintenance()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Root volume is ready, need to place VM in volume's cluster");
}
long rootVolDcId = pool.getDataCenterId();
Long rootVolPodId = pool.getPodId();
Long rootVolClusterId = pool.getClusterId();
if (planToDeploy != null && planToDeploy.getDataCenterId() != 0) {
Long clusterIdSpecified = planToDeploy.getClusterId();
if (clusterIdSpecified != null && rootVolClusterId != null) {
if (rootVolClusterId.longValue() != clusterIdSpecified.longValue()) {
// cannot satisfy the plan passed in to the
// planner
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot satisfy the deployment plan passed in since the ready Root volume is in different cluster. volume's cluster: " +
rootVolClusterId + ", cluster specified: " + clusterIdSpecified);
}
throw new ResourceUnavailableException(
"Root volume is ready in different cluster, Deployment plan provided cannot be satisfied, unable to create a deployment for " +
vm, Cluster.class, clusterIdSpecified);
}
}
plan =
new DataCenterDeployment(planToDeploy.getDataCenterId(), planToDeploy.getPodId(), planToDeploy.getClusterId(),
planToDeploy.getHostId(), vol.getPoolId(), null, ctx);
} else {
plan = new DataCenterDeployment(rootVolDcId, rootVolPodId, rootVolClusterId, null, vol.getPoolId(), null, ctx);
if (s_logger.isDebugEnabled()) {
s_logger.debug(vol + " is READY, changing deployment plan to use this pool's dcId: " + rootVolDcId + " , podId: " + rootVolPodId +
" , and clusterId: " + rootVolClusterId);
}
planChangedByVolume = true;
}
}
}
}
Account owner = _entityMgr.findById(Account.class, vm.getAccountId());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, params);
DeployDestination dest = null;
try {
dest = _dpMgr.planDeployment(vmProfile, plan, avoids, planner);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest == null) {
if (planChangedByVolume) {
plan = originalPlan;
planChangedByVolume = false;
//do not enter volume reuse for next retry, since we want to look for resorces outside the volume's cluster
reuseVolume = false;
continue;
}
throw new InsufficientServerCapacityException("Unable to create a deployment for " + vmProfile, DataCenter.class, plan.getDataCenterId(),
areAffinityGroupsAssociated(vmProfile));
}
if (dest != null) {
avoids.addHost(dest.getHost().getId());
journal.record("Deployment found ", vmProfile, dest);
}
long destHostId = dest.getHost().getId();
vm.setPodId(dest.getPod().getId());
Long cluster_id = dest.getCluster().getId();
ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
//storing the value of overcommit in the vm_details table for doing a capacity check in case the cluster overcommit ratio is changed.
if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") == null &&
((Float.parseFloat(cluster_detail_cpu.getValue()) > 1f || Float.parseFloat(cluster_detail_ram.getValue()) > 1f))) {
_uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue());
_uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue());
} else if (_uservmDetailsDao.findDetail(vm.getId(), "cpuOvercommitRatio") != null) {
_uservmDetailsDao.addDetail(vm.getId(), "cpuOvercommitRatio", cluster_detail_cpu.getValue());
_uservmDetailsDao.addDetail(vm.getId(), "memoryOvercommitRatio", cluster_detail_ram.getValue());
}
vmProfile.setCpuOvercommitRatio(Float.parseFloat(cluster_detail_cpu.getValue()));
vmProfile.setMemoryOvercommitRatio(Float.parseFloat(cluster_detail_ram.getValue()));
StartAnswer startAnswer = null;
try {
if (!changeState(vm, Event.OperationRetry, destHostId, work, Step.Prepare)) {
throw new ConcurrentOperationException("Unable to update the state of the Virtual Machine");
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException(e1.getMessage());
}
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is being created in podId: " + vm.getPodIdToDeployIn());
}
_networkMgr.prepare(vmProfile, dest, ctx);
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
volumeMgr.prepare(vmProfile, dest);
}
//since StorageMgr succeeded in volume creation, reuse Volume for further tries until current cluster has capacity
if (!reuseVolume) {
reuseVolume = true;
}
Commands cmds = null;
vmGuru.finalizeVirtualMachineProfile(vmProfile, dest, ctx);
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
handlePath(vmTO.getDisks(), vm.getHypervisorType());
cmds = new Commands(Command.OnError.Stop);
cmds.addCommand(new StartCommand(vmTO, dest.getHost(), ExecuteInSequence.value()));
vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx);
work = _workDao.findById(work.getId());
if (work == null || work.getStep() != Step.Prepare) {
throw new ConcurrentOperationException("Work steps have been changed: " + work);
}
_workDao.updateStep(work, Step.Starting);
_agentMgr.send(destHostId, cmds);
_workDao.updateStep(work, Step.Started);
startAnswer = cmds.getAnswer(StartAnswer.class);
if (startAnswer != null && startAnswer.getResult()) {
handlePath(vmTO.getDisks(), startAnswer.getIqnToPath());
String host_guid = startAnswer.getHost_guid();
if (host_guid != null) {
HostVO finalHost = _resourceMgr.findHostByGuid(host_guid);
if (finalHost == null) {
throw new CloudRuntimeException("Host Guid " + host_guid + " doesn't exist in DB, something wrong here");
}
destHostId = finalHost.getId();
}
if (vmGuru.finalizeStart(vmProfile, destHostId, cmds, ctx)) {
syncDiskChainChange(startAnswer);
if (!changeState(vm, Event.OperationSucceeded, destHostId, work, Step.Done)) {
throw new ConcurrentOperationException("Unable to transition to a new state.");
}
startedVm = vm;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Start completed for VM " + vm);
}
return;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.info("The guru did not like the answers so stopping " + vm);
}
StopCommand cmd = new StopCommand(vm, ExecuteInSequence.value());
StopAnswer answer = (StopAnswer)_agentMgr.easySend(destHostId, cmd);
if (answer != null) {
if (vm.getType() == VirtualMachine.Type.User) {
String platform = answer.getPlatform();
if (platform != null) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", platform);
_userVmDao.saveDetails(userVm);
}
}
}
if (answer == null || !answer.getResult()) {
s_logger.warn("Unable to stop " + vm + " due to " + (answer != null ? answer.getDetails() : "no answers"));
_haMgr.scheduleStop(vm, destHostId, WorkType.ForceStop);
throw new ExecutionException("Unable to stop " + vm + " so we are unable to retry the start operation");
}
throw new ExecutionException("Unable to start " + vm + " due to error in finalizeStart, not retrying");
}
}
s_logger.info("Unable to start VM on " + dest.getHost() + " due to " + (startAnswer == null ? " no start answer" : startAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to send the start command to host " + dest.getHost());
if (e.isActive()) {
_haMgr.scheduleStop(vm, destHostId, WorkType.CheckStop);
}
canRetry = false;
throw new AgentUnavailableException("Unable to start " + vm.getHostName(), destHostId, e);
} catch (ResourceUnavailableException e) {
s_logger.info("Unable to contact resource.", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected ResourceUnavailableException : " + e.getScope().getName(), e);
throw e;
}
}
} catch (InsufficientCapacityException e) {
s_logger.info("Insufficient capacity ", e);
if (!avoids.add(e)) {
if (e.getScope() == Volume.class || e.getScope() == Nic.class) {
throw e;
} else {
s_logger.warn("unexpected InsufficientCapacityException : " + e.getScope().getName(), e);
}
}
} catch (Exception e) {
s_logger.error("Failed to start instance " + vm, e);
throw new AgentUnavailableException("Unable to start instance due to " + e.getMessage(), destHostId, e);
} finally {
if (startedVm == null && canRetry) {
Step prevStep = work.getStep();
_workDao.updateStep(work, Step.Release);
// If previous step was started/ing && we got a valid answer
if ((prevStep == Step.Started || prevStep == Step.Starting) && (startAnswer != null && startAnswer.getResult())) { //TODO check the response of cleanup and record it in DB for retry
cleanup(vmGuru, vmProfile, work, Event.OperationFailed, false);
} else {
//if step is not starting/started, send cleanup command with force=true
cleanup(vmGuru, vmProfile, work, Event.OperationFailed, true);
}
}
}
}
} finally {
if (startedVm == null) {
if (canRetry) {
try {
changeState(vm, Event.OperationFailed, null, work, Step.Done);
} catch (NoTransitionException e) {
throw new ConcurrentOperationException(e.getMessage());
}
}
}
if (planToDeploy != null) {
planToDeploy.setAvoids(avoids);
}
}
if (startedVm == null) {
throw new CloudRuntimeException("Unable to start instance '" + vm.getHostName() + "' (" + vm.getUuid() + "), see management server log for details");
}
}
// for managed storage on KVM, need to make sure the path field of the volume in question is populated with the IQN
private void handlePath(DiskTO[] disks, HypervisorType hypervisorType) {
if (hypervisorType != HypervisorType.KVM) {
return;
}
if (disks != null) {
for (DiskTO disk : disks) {
Map<String, String> details = disk.getDetails();
boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED));
if (isManaged && disk.getPath() == null) {
Long volumeId = disk.getData().getId();
VolumeVO volume = _volsDao.findById(volumeId);
disk.setPath(volume.get_iScsiName());
volume.setPath(volume.get_iScsiName());
_volsDao.update(volumeId, volume);
}
}
}
}
// for managed storage on XenServer and VMware, need to update the DB with a path if the VDI/VMDK file was newly created
private void handlePath(DiskTO[] disks, Map<String, String> iqnToPath) {
if (disks != null) {
for (DiskTO disk : disks) {
Map<String, String> details = disk.getDetails();
boolean isManaged = details != null && Boolean.parseBoolean(details.get(DiskTO.MANAGED));
if (isManaged && disk.getPath() == null) {
Long volumeId = disk.getData().getId();
VolumeVO volume = _volsDao.findById(volumeId);
String iScsiName = volume.get_iScsiName();
String path = iqnToPath.get(iScsiName);
volume.setPath(path);
_volsDao.update(volumeId, volume);
}
}
}
}
private void syncDiskChainChange(StartAnswer answer) {
VirtualMachineTO vmSpec = answer.getVirtualMachine();
for (DiskTO disk : vmSpec.getDisks()) {
if (disk.getType() != Volume.Type.ISO) {
VolumeObjectTO vol = (VolumeObjectTO)disk.getData();
VolumeVO volume = _volsDao.findById(vol.getId());
// Use getPath() from VolumeVO to get a fresh copy of what's in the DB.
// Before doing this, in a certain situation, getPath() from VolumeObjectTO
// returned null instead of an actual path (because it was out of date with the DB).
volumeMgr.updateVolumeDiskChain(vol.getId(), volume.getPath(), vol.getChainInfo());
}
}
}
@Override
public void stop(String vmUuid) throws ResourceUnavailableException {
try {
advanceStop(vmUuid, false);
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to stop vm because the operation to stop timed out", e.getAgentId(), e);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to stop vm because of a concurrent operation", e);
}
}
protected boolean sendStop(VirtualMachineGuru guru, VirtualMachineProfile profile, boolean force) {
VirtualMachine vm = profile.getVirtualMachine();
StopCommand stop = new StopCommand(vm, ExecuteInSequence.value());
try {
StopAnswer answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop);
if (answer != null) {
if (vm.getType() == VirtualMachine.Type.User) {
String platform = answer.getPlatform();
if (platform != null) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", platform);
_userVmDao.saveDetails(userVm);
}
}
}
if (!answer.getResult()) {
s_logger.debug("Unable to stop VM due to " + answer.getDetails());
return false;
}
guru.finalizeStop(profile, answer);
} catch (AgentUnavailableException e) {
if (!force) {
return false;
}
} catch (OperationTimedoutException e) {
if (!force) {
return false;
}
}
return true;
}
protected boolean cleanup(VirtualMachineGuru guru, VirtualMachineProfile profile, ItWorkVO work, Event event, boolean cleanUpEvenIfUnableToStop) {
VirtualMachine vm = profile.getVirtualMachine();
State state = vm.getState();
s_logger.debug("Cleaning up resources for the vm " + vm + " in " + state + " state");
if (state == State.Starting) {
Step step = work.getStep();
if (step == Step.Starting && !cleanUpEvenIfUnableToStop) {
s_logger.warn("Unable to cleanup vm " + vm + "; work state is incorrect: " + step);
return false;
}
if (step == Step.Started || step == Step.Starting || step == Step.Release) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Starting + " state as a part of cleanup process");
return false;
}
}
}
if (step != Step.Release && step != Step.Prepare && step != Step.Started && step != Step.Starting) {
s_logger.debug("Cleanup is not needed for vm " + vm + "; work state is incorrect: " + step);
return true;
}
} else if (state == State.Stopping) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Stopping + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Migrating) {
if (vm.getHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
if (vm.getLastHostId() != null) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Migrating + " state as a part of cleanup process");
return false;
}
}
} else if (state == State.Running) {
if (!sendStop(guru, profile, cleanUpEvenIfUnableToStop)) {
s_logger.warn("Failed to stop vm " + vm + " in " + State.Running + " state as a part of cleanup process");
return false;
}
}
try {
_networkMgr.release(profile, cleanUpEvenIfUnableToStop);
s_logger.debug("Successfully released network resources for the vm " + vm);
} catch (Exception e) {
s_logger.warn("Unable to release some network resources.", e);
}
volumeMgr.release(profile);
s_logger.debug("Successfully cleanued up resources for the vm " + vm + " in " + state + " state");
return true;
}
@Override
public void advanceStop(String vmUuid, boolean cleanUpEvenIfUnableToStop)
throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStop(vmUuid, cleanUpEvenIfUnableToStop);
} else {
Outcome<VirtualMachine> outcome = stopVmThroughJobQueue(vmUuid, cleanUpEvenIfUnableToStop);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof AgentUnavailableException)
throw (AgentUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof OperationTimedoutException)
throw (OperationTimedoutException)jobException;
}
}
}
private void orchestrateStop(String vmUuid, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
advanceStop(vm, cleanUpEvenIfUnableToStop);
}
private void advanceStop(VMInstanceVO vm, boolean cleanUpEvenIfUnableToStop) throws AgentUnavailableException, OperationTimedoutException,
ConcurrentOperationException {
State state = vm.getState();
if (state == State.Stopped) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is already stopped: " + vm);
}
return;
}
if (state == State.Destroyed || state == State.Expunging || state == State.Error) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Stopped called on " + vm + " but the state is " + state);
}
return;
}
// grab outstanding work item if any
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found an outstanding work item for this vm " + vm + " with state:" + vm.getState() + ", work id:" + work.getId());
}
}
Long hostId = vm.getHostId();
if (hostId == null) {
if (!cleanUpEvenIfUnableToStop) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("HostId is null but this is not a forced stop, cannot stop vm " + vm + " with state:" + vm.getState());
}
throw new CloudRuntimeException("Unable to stop " + vm);
}
try {
stateTransitTo(vm, Event.AgentReportStopped, null, null);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
// mark outstanding work item if any as done
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
return;
}
VirtualMachineGuru vmGuru = getVmGuru(vm);
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
try {
if (!stateTransitTo(vm, Event.StopRequested, vm.getHostId())) {
throw new ConcurrentOperationException("VM is being operated on.");
}
} catch (NoTransitionException e1) {
if (!cleanUpEvenIfUnableToStop) {
throw new CloudRuntimeException("We cannot stop " + vm + " when it is in state " + vm.getState());
}
boolean doCleanup = false;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to transition the state but we're moving on because it's forced stop");
}
if (state == State.Starting || state == State.Migrating) {
if (work != null) {
doCleanup = true;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to cleanup VM: " + vm + " ,since outstanding work item is not found");
}
throw new CloudRuntimeException("Work item not found, We cannot stop " + vm + " when it is in state " + vm.getState());
}
} else if (state == State.Stopping) {
doCleanup = true;
}
if (doCleanup) {
if (cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.StopRequested, cleanUpEvenIfUnableToStop)) {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating work item to Done, id:" + work.getId());
}
if (!changeState(vm, Event.AgentReportStopped, null, work, Step.Done)) {
throw new CloudRuntimeException("Unable to stop " + vm);
}
} catch (NoTransitionException e) {
s_logger.warn("Unable to cleanup " + vm);
throw new CloudRuntimeException("Unable to stop " + vm, e);
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Failed to cleanup VM: " + vm);
}
throw new CloudRuntimeException("Failed to cleanup " + vm + " , current state " + vm.getState());
}
}
}
if (vm.getState() != State.Stopping) {
throw new CloudRuntimeException("We cannot proceed with stop VM " + vm + " since it is not in 'Stopping' state, current state: " + vm.getState());
}
vmGuru.prepareStop(profile);
StopCommand stop = new StopCommand(vm, ExecuteInSequence.value());
boolean stopped = false;
StopAnswer answer = null;
try {
answer = (StopAnswer)_agentMgr.send(vm.getHostId(), stop);
if (answer != null) {
if (vm.getType() == VirtualMachine.Type.User) {
String platform = answer.getPlatform();
if (platform != null) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", platform);
_userVmDao.saveDetails(userVm);
}
}
}
stopped = answer.getResult();
if (!stopped) {
throw new CloudRuntimeException("Unable to stop the virtual machine due to " + answer.getDetails());
}
vmGuru.finalizeStop(profile, answer);
} catch (AgentUnavailableException e) {
s_logger.warn("Unable to stop vm, agent unavailable: " + e.toString());
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to stop vm, operation timed out: " + e.toString());
} finally {
if (!stopped) {
if (!cleanUpEvenIfUnableToStop) {
s_logger.warn("Unable to stop vm " + vm);
try {
stateTransitTo(vm, Event.OperationFailed, vm.getHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unable to transition the state " + vm);
}
throw new CloudRuntimeException("Unable to stop " + vm);
} else {
s_logger.warn("Unable to actually stop " + vm + " but continue with release because it's a force stop");
vmGuru.finalizeStop(profile, answer);
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is stopped on the host. Proceeding to release resource held.");
}
try {
_networkMgr.release(profile, cleanUpEvenIfUnableToStop);
s_logger.debug("Successfully released network resources for the vm " + vm);
} catch (Exception e) {
s_logger.warn("Unable to release some network resources.", e);
}
try {
if (vm.getHypervisorType() != HypervisorType.BareMetal) {
volumeMgr.release(profile);
s_logger.debug("Successfully released storage resources for the vm " + vm);
}
} catch (Exception e) {
s_logger.warn("Unable to release storage resources.", e);
}
try {
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating the outstanding work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
if (!stateTransitTo(vm, Event.OperationSucceeded, null)) {
throw new CloudRuntimeException("unable to stop " + vm);
}
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
throw new CloudRuntimeException("Unable to stop " + vm);
}
}
private void setStateMachine() {
_stateMachine = VirtualMachine.State.getStateMachine();
}
protected boolean stateTransitTo(VMInstanceVO vm, VirtualMachine.Event e, Long hostId, String reservationId) throws NoTransitionException {
vm.setReservationId(reservationId);
return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
}
@Override
public boolean stateTransitTo(VirtualMachine vm1, VirtualMachine.Event e, Long hostId) throws NoTransitionException {
VMInstanceVO vm = (VMInstanceVO)vm1;
// if there are active vm snapshots task, state change is not allowed
if (_vmSnapshotMgr.hasActiveVMSnapshotTasks(vm.getId())) {
s_logger.error("State transit with event: " + e + " failed due to: " + vm.getInstanceName() + " has active VM snapshots tasks");
return false;
}
State oldState = vm.getState();
if (oldState == State.Starting) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(hostId);
}
} else if (oldState == State.Stopping) {
if (e == Event.OperationSucceeded) {
vm.setLastHostId(vm.getHostId());
}
}
return _stateMachine.transitTo(vm, e, new Pair<Long, Long>(vm.getHostId(), hostId), _vmDao);
}
@Override
public void destroy(String vmUuid) throws AgentUnavailableException, OperationTimedoutException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging || vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is destroyed: " + vm);
}
return;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Destroying vm " + vm);
}
advanceStop(vm, VmDestroyForcestop.value());
if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(), null)) {
s_logger.debug("Unable to delete all snapshots for " + vm);
throw new CloudRuntimeException("Unable to delete vm snapshots for " + vm);
}
try {
if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
throw new CloudRuntimeException("Unable to destroy " + vm);
}
} catch (NoTransitionException e) {
s_logger.debug(e.getMessage());
throw new CloudRuntimeException("Unable to destroy " + vm, e);
}
}
protected boolean checkVmOnHost(VirtualMachine vm, long hostId) throws AgentUnavailableException, OperationTimedoutException {
CheckVirtualMachineAnswer answer = (CheckVirtualMachineAnswer)_agentMgr.send(hostId, new CheckVirtualMachineCommand(vm.getInstanceName()));
if (!answer.getResult() || answer.getState() == State.Stopped) {
return false;
}
return true;
}
@Override
public void storageMigration(String vmUuid, StoragePool destPool) {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateStorageMigration(vmUuid, destPool);
} else {
Outcome<VirtualMachine> outcome = migrateVmStorageThroughJobQueue(vmUuid, destPool);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
}
}
private void orchestrateStorageMigration(String vmUuid, StoragePool destPool) {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
try {
stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null);
} catch (NoTransitionException e) {
s_logger.debug("Unable to migrate vm: " + e.toString());
throw new CloudRuntimeException("Unable to migrate vm: " + e.toString());
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
boolean migrationResult = false;
try {
migrationResult = volumeMgr.storageMigration(profile, destPool);
if (migrationResult) {
//if the vm is migrated to different pod in basic mode, need to reallocate ip
if (!vm.getPodIdToDeployIn().equals(destPool.getPodId())) {
DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null);
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null);
_networkMgr.reallocate(vmProfile, plan);
}
//when start the vm next time, don;'t look at last_host_id, only choose the host based on volume/storage pool
vm.setLastHostId(null);
vm.setPodId(destPool.getPodId());
} else {
s_logger.debug("Storage migration failed");
}
} catch (ConcurrentOperationException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (InsufficientVirtualNetworkCapcityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (InsufficientAddressCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (InsufficientCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (StorageUnavailableException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} finally {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
} catch (NoTransitionException e) {
s_logger.debug("Failed to change vm state: " + e.toString());
throw new CloudRuntimeException("Failed to change vm state: " + e.toString());
}
}
}
@Override
public void migrate(String vmUuid, long srcHostId, DeployDestination dest)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrate(vmUuid, srcHostId, dest);
} else {
Outcome<VirtualMachine> outcome = migrateVmThroughJobQueue(vmUuid, srcHostId, dest);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
}
}
private void orchestrateMigrate(String vmUuid, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the vm " + vmUuid);
}
throw new CloudRuntimeException("Unable to find a virtual machine with id " + vmUuid);
}
migrate(vm, srcHostId, dest);
}
protected void migrate(VMInstanceVO vm, long srcHostId, DeployDestination dest) throws ResourceUnavailableException, ConcurrentOperationException {
s_logger.info("Migrating " + vm + " to " + dest);
long dstHostId = dest.getHost().getId();
Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
}
VirtualMachineGuru vmGuru = getVmGuru(vm);
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile vmSrc = new VirtualMachineProfileImpl(vm);
for (NicProfile nic : _networkMgr.getNicProfiles(vm)) {
vmSrc.addNic(nic);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
_networkMgr.prepareNicForMigration(profile, dest);
volumeMgr.prepareForMigration(profile, dest);
VirtualMachineTO to = toVmTO(profile);
PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
PrepareForMigrationAnswer pfma = null;
try {
pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc);
if (!pfma.getResult()) {
String msg = "Unable to prepare for migration due to " + pfma.getDetails();
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
_networkMgr.rollbackNicForMigration(vmSrc, profile);
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, ExecuteInSequence.value());
mc.setHostGuid(dest.getHost().getGuid());
try {
MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc);
if (!ma.getResult()) {
throw new CloudRuntimeException("Unable to migrate due to " + ma.getDetails());
}
} catch (OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm)), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("Unable to complete migration for " + vm);
}
} catch (OperationTimedoutException e) {
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_networkMgr.rollbackNicForMigration(vmSrc, profile);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(),
"Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " +
dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm)), null);
} catch (AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
} else {
_networkMgr.commitNicForMigration(vmSrc, profile);
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
private Map<Volume, StoragePool> getPoolListForVolumesForMigration(VirtualMachineProfile profile, Host host, Map<Volume, StoragePool> volumeToPool) {
List<VolumeVO> allVolumes = _volsDao.findUsableVolumesForInstance(profile.getId());
for (VolumeVO volume : allVolumes) {
StoragePool pool = volumeToPool.get(volume);
DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
StoragePoolVO currentPool = _storagePoolDao.findById(volume.getPoolId());
if (pool != null) {
// Check if pool is accessible from the destination host and disk offering with which the volume was
// created is compliant with the pool type.
if (_poolHostDao.findByPoolHost(pool.getId(), host.getId()) == null || pool.isLocal() != diskOffering.getUseLocalStorage()) {
// Cannot find a pool for the volume. Throw an exception.
throw new CloudRuntimeException("Cannot migrate volume " + volume + " to storage pool " + pool + " while migrating vm to host " + host +
". Either the pool is not accessible from the " + "host or because of the offering with which the volume is created it cannot be placed on " +
"the given pool.");
} else if (pool.getId() == currentPool.getId()) {
// If the pool to migrate too is the same as current pool, remove the volume from the list of
// volumes to be migrated.
volumeToPool.remove(volume);
}
} else {
// Find a suitable pool for the volume. Call the storage pool allocator to find the list of pools.
DiskProfile diskProfile = new DiskProfile(volume, diskOffering, profile.getHypervisorType());
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), null, null);
ExcludeList avoid = new ExcludeList();
boolean currentPoolAvailable = false;
for (StoragePoolAllocator allocator : _storagePoolAllocators) {
List<StoragePool> poolList = allocator.allocateToPool(diskProfile, profile, plan, avoid, StoragePoolAllocator.RETURN_UPTO_ALL);
if (poolList != null && !poolList.isEmpty()) {
// Volume needs to be migrated. Pick the first pool from the list. Add a mapping to migrate the
// volume to a pool only if it is required; that is the current pool on which the volume resides
// is not available on the destination host.
if (poolList.contains(currentPool)) {
currentPoolAvailable = true;
} else {
volumeToPool.put(volume, _storagePoolDao.findByUuid(poolList.get(0).getUuid()));
}
break;
}
}
if (!currentPoolAvailable && !volumeToPool.containsKey(volume)) {
// Cannot find a pool for the volume. Throw an exception.
throw new CloudRuntimeException("Cannot find a storage pool which is available for volume " + volume + " while migrating virtual machine " +
profile.getVirtualMachine() + " to host " + host);
}
}
}
return volumeToPool;
}
private <T extends VMInstanceVO> void moveVmToMigratingState(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException {
// Put the vm in migrating state.
try {
if (!changeState(vm, Event.MigrationRequested, hostId, work, Step.Migrating)) {
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e) {
s_logger.info("Migration cancelled because " + e.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e.getMessage());
}
}
private <T extends VMInstanceVO> void moveVmOutofMigratingStateOnSuccess(T vm, Long hostId, ItWorkVO work) throws ConcurrentOperationException {
// Put the vm in running state.
try {
if (!changeState(vm, Event.OperationSucceeded, hostId, work, Step.Started)) {
s_logger.error("Unable to change the state for " + vm);
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
} catch (NoTransitionException e) {
s_logger.error("Unable to change state due to " + e.getMessage());
throw new ConcurrentOperationException("Unable to change state due to " + e.getMessage());
}
}
@Override
public void migrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map<Volume, StoragePool> volumeToPool)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateWithStorage(vmUuid, srcHostId, destHostId, volumeToPool);
} else {
Outcome<VirtualMachine> outcome = migrateVmWithStorageThroughJobQueue(vmUuid, srcHostId, destHostId, volumeToPool);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
}
}
}
private void orchestrateMigrateWithStorage(String vmUuid, long srcHostId, long destHostId, Map<Volume, StoragePool> volumeToPool) throws ResourceUnavailableException,
ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
HostVO srcHost = _hostDao.findById(srcHostId);
HostVO destHost = _hostDao.findById(destHostId);
VirtualMachineGuru vmGuru = getVmGuru(vm);
DataCenterVO dc = _dcDao.findById(destHost.getDataCenterId());
HostPodVO pod = _podDao.findById(destHost.getPodId());
Cluster cluster = _clusterDao.findById(destHost.getClusterId());
DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost);
// Create a map of which volume should go in which storage pool.
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
volumeToPool = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
// If none of the volumes have to be migrated, fail the call. Administrator needs to make a call for migrating
// a vm and not migrating a vm with storage.
if (volumeToPool.isEmpty()) {
throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost +
" doesn't involve migrating the volumes.");
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
_networkMgr.prepareNicForMigration(profile, destination);
volumeMgr.prepareForMigration(profile, destination);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
VirtualMachineTO to = hvGuru.implement(profile);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(destHostId);
work = _workDao.persist(work);
// Put the vm in migrating state.
vm.setLastHostId(srcHostId);
moveVmToMigratingState(vm, destHostId, work);
boolean migrated = false;
try {
// Migrate the vm and its volume.
volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPool);
// Put the vm back to running state.
moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
try {
if (!checkVmOnHost(vm, destHostId)) {
s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm);
}
} catch (OperationTimedoutException e) {
s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(),
"Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + dc.getName() + " and pod " + dc.getName(),
"Migrate Command failed. Please check logs.");
try {
_agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (AgentUnavailableException e) {
s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
} catch (NoTransitionException e) {
s_logger.error("Error while transitioning vm from migrating to running state.", e);
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
@Override
public VirtualMachineTO toVmTO(VirtualMachineProfile profile) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(profile.getVirtualMachine().getHypervisorType());
VirtualMachineTO to = hvGuru.implement(profile);
return to;
}
protected void cancelWorkItems(long nodeId) {
GlobalLock scanLock = GlobalLock.getInternLock("vmmgr.cancel.workitem");
try {
if (scanLock.lock(3)) {
try {
List<ItWorkVO> works = _workDao.listWorkInProgressFor(nodeId);
for (ItWorkVO work : works) {
s_logger.info("Handling unfinished work item: " + work);
try {
VMInstanceVO vm = _vmDao.findById(work.getInstanceId());
if (vm != null) {
if (work.getType() == State.Starting) {
_haMgr.scheduleRestart(vm, true);
work.setManagementServerId(_nodeId);
_workDao.update(work.getId(), work);
} else if (work.getType() == State.Stopping) {
_haMgr.scheduleStop(vm, vm.getHostId(), WorkType.CheckStop);
work.setManagementServerId(_nodeId);
_workDao.update(work.getId(), work);
} else if (work.getType() == State.Migrating) {
_haMgr.scheduleMigration(vm);
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
} catch (Exception e) {
s_logger.error("Error while handling " + work, e);
}
}
} finally {
scanLock.unlock();
}
}
} finally {
scanLock.releaseRef();
}
}
@Override
public void migrateAway(String vmUuid, long srcHostId, DeploymentPlanner planner) throws InsufficientServerCapacityException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
s_logger.debug("Unable to find a VM for " + vmUuid);
throw new CloudRuntimeException("Unable to find " + vmUuid);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
Long hostId = vm.getHostId();
if (hostId == null) {
s_logger.debug("Unable to migrate because the VM doesn't have a host id: " + vm);
throw new CloudRuntimeException("Unable to migrate " + vmUuid);
}
Host host = _hostDao.findById(hostId);
Long poolId = null;
List<VolumeVO> vols = _volsDao.findReadyRootVolumesByInstance(vm.getId());
for (VolumeVO rootVolumeOfVm : vols) {
StoragePoolVO rootDiskPool = _storagePoolDao.findById(rootVolumeOfVm.getPoolId());
if (rootDiskPool != null) {
poolId = rootDiskPool.getId();
}
}
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, poolId, null);
ExcludeList excludes = new ExcludeList();
excludes.addHost(hostId);
DeployDestination dest = null;
while (true) {
try {
dest = _dpMgr.planDeployment(profile, plan, excludes, planner);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found destination " + dest + " for migrating to.");
}
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find destination for migrating the vm " + profile);
}
throw new InsufficientServerCapacityException("Unable to find a server to migrate to.", host.getClusterId());
}
excludes.addHost(dest.getHost().getId());
try {
migrate(vm, srcHostId, dest);
return;
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to migrate to unavailable " + dest);
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
}
try {
advanceStop(vm, true);
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
throw new CloudRuntimeException("Unable to migrate " + vm);
} catch (OperationTimedoutException e) {
s_logger.debug("Unable to stop VM due to " + e.getMessage());
throw new CloudRuntimeException("Unable to migrate " + vm);
}
}
}
protected class CleanupTask extends ManagedContextRunnable {
@Override
protected void runInContext() {
s_logger.trace("VM Operation Thread Running");
try {
_workDao.cleanup(VmOpCleanupWait.value());
} catch (Exception e) {
s_logger.error("VM Operations failed due to ", e);
}
}
}
@Override
public boolean isVirtualMachineUpgradable(VirtualMachine vm, ServiceOffering offering) {
boolean isMachineUpgradable = true;
for (HostAllocator allocator : hostAllocators) {
isMachineUpgradable = allocator.isVirtualMachineUpgradable(vm, offering);
if (isMachineUpgradable)
continue;
else
break;
}
return isMachineUpgradable;
}
@Override
public void reboot(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) throws InsufficientCapacityException, ResourceUnavailableException {
try {
advanceReboot(vmUuid, params);
} catch (ConcurrentOperationException e) {
throw new CloudRuntimeException("Unable to reboot a VM due to concurrent operation", e);
}
}
@Override
public void advanceReboot(String vmUuid, Map<VirtualMachineProfile.Param, Object> params)
throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateReboot(vmUuid, params);
} else {
Outcome<VirtualMachine> outcome = rebootVmThroughJobQueue(vmUuid, params);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof InsufficientCapacityException)
throw (InsufficientCapacityException)jobException;
}
}
}
private void orchestrateReboot(String vmUuid, Map<VirtualMachineProfile.Param, Object> params) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
DataCenter dc = _entityMgr.findById(DataCenter.class, vm.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
Cluster cluster = null;
if (host != null) {
cluster = _entityMgr.findById(Cluster.class, host.getClusterId());
}
Pod pod = _entityMgr.findById(Pod.class, host.getPodId());
DeployDestination dest = new DeployDestination(dc, pod, cluster, host);
try {
Commands cmds = new Commands(Command.OnError.Stop);
cmds.addCommand(new RebootCommand(vm.getInstanceName()));
_agentMgr.send(host.getId(), cmds);
Answer rebootAnswer = cmds.getAnswer(RebootAnswer.class);
if (rebootAnswer != null && rebootAnswer.getResult()) {
return;
}
s_logger.info("Unable to reboot VM " + vm + " on " + dest.getHost() + " due to " + (rebootAnswer == null ? " no reboot answer" : rebootAnswer.getDetails()));
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to send the reboot command to host " + dest.getHost() + " for the vm " + vm + " due to operation timeout", e);
throw new CloudRuntimeException("Failed to reboot the vm on host " + dest.getHost());
}
}
public Command cleanup(VirtualMachine vm) {
return new StopCommand(vm, ExecuteInSequence.value());
}
public Command cleanup(String vmName) {
return new StopCommand(vmName, ExecuteInSequence.value());
}
public Commands fullHostSync(final long hostId, StartupRoutingCommand startup) {
Commands commands = new Commands(Command.OnError.Continue);
Map<Long, AgentVmInfo> infos = convertToInfos(startup);
final List<? extends VMInstanceVO> vms = _vmDao.listByHostId(hostId);
s_logger.debug("Found " + vms.size() + " VMs for host " + hostId);
for (VMInstanceVO vm : vms) {
AgentVmInfo info = infos.remove(vm.getId());
// sync VM Snapshots related transient states
List<VMSnapshotVO> vmSnapshotsInTrasientStates =
_vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Reverting, VMSnapshot.State.Creating);
if (vmSnapshotsInTrasientStates.size() > 1) {
s_logger.info("Found vm " + vm.getInstanceName() + " with VM snapshots in transient states, needs to sync VM snapshot state");
if (!_vmSnapshotMgr.syncVMSnapshot(vm, hostId)) {
s_logger.warn("Failed to sync VM in a transient snapshot related state: " + vm.getInstanceName());
continue;
} else {
s_logger.info("Successfully sync VM with transient snapshot: " + vm.getInstanceName());
}
}
if (info == null) {
info = new AgentVmInfo(vm.getInstanceName(), vm, State.Stopped);
}
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
Command command = compareState(hostId, vm, info, true, hvGuru.trackVmHostChange());
if (command != null) {
commands.addCommand(command);
}
}
for (final AgentVmInfo left : infos.values()) {
boolean found = false;
VMInstanceVO vm = _vmDao.findVMByInstanceName(left.name);
if (vm != null) {
found = true;
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
if (hvGuru.trackVmHostChange()) {
Command command = compareState(hostId, vm, left, true, true);
if (command != null) {
commands.addCommand(command);
}
} else {
s_logger.warn("Stopping a VM, VM " + left.name + " migrate from Host " + vm.getHostId() + " to Host " + hostId);
commands.addCommand(cleanup(left.name));
}
}
if (!found) {
s_logger.warn("Stopping a VM that we have no record of <fullHostSync>: " + left.name);
commands.addCommand(cleanup(left.name));
}
}
return commands;
}
public Commands deltaHostSync(long hostId, Map<String, State> newStates) {
Map<Long, AgentVmInfo> states = convertDeltaToInfos(newStates);
Commands commands = new Commands(Command.OnError.Continue);
for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) {
AgentVmInfo info = entry.getValue();
VMInstanceVO vm = info.vm;
Command command = null;
if (vm != null) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
command = compareState(hostId, vm, info, false, hvGuru.trackVmHostChange());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleaning up a VM that is no longer found: " + info.name);
}
command = cleanup(info.name);
}
if (command != null) {
commands.addCommand(command);
}
}
return commands;
}
public void deltaSync(Map<String, Ternary<String, State, String>> newStates) {
Map<Long, AgentVmInfo> states = convertToInfos(newStates);
for (Map.Entry<Long, AgentVmInfo> entry : states.entrySet()) {
AgentVmInfo info = entry.getValue();
VMInstanceVO vm = info.vm;
Command command = null;
if (vm != null) {
Host host = _resourceMgr.findHostByGuid(info.getHostUuid());
long hId = host.getId();
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
command = compareState(hId, vm, info, false, hvGuru.trackVmHostChange());
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cleaning up a VM that is no longer found <deltaSync>: " + info.name);
}
command = cleanup(info.name);
}
if (command != null) {
try {
Host host = _resourceMgr.findHostByGuid(info.getHostUuid());
if (host != null) {
Answer answer = _agentMgr.send(host.getId(), cleanup(info.name));
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
}
}
} catch (Exception e) {
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
}
}
public void fullSync(final long clusterId, Map<String, Ternary<String, State, String>> newStates) {
if (newStates == null)
return;
Map<Long, AgentVmInfo> infos = convertToInfos(newStates);
Set<VMInstanceVO> set_vms = Collections.synchronizedSet(new HashSet<VMInstanceVO>());
set_vms.addAll(_vmDao.listByClusterId(clusterId));
set_vms.addAll(_vmDao.listLHByClusterId(clusterId));
for (VMInstanceVO vm : set_vms) {
AgentVmInfo info = infos.remove(vm.getId());
// sync VM Snapshots related transient states
List<VMSnapshotVO> vmSnapshotsInExpungingStates =
_vmSnapshotDao.listByInstanceId(vm.getId(), VMSnapshot.State.Expunging, VMSnapshot.State.Creating, VMSnapshot.State.Reverting);
if (vmSnapshotsInExpungingStates.size() > 0) {
s_logger.info("Found vm " + vm.getInstanceName() + " in state. " + vm.getState() + ", needs to sync VM snapshot state");
Long hostId = null;
Host host = null;
if (info != null && info.getHostUuid() != null) {
host = _hostDao.findByGuid(info.getHostUuid());
}
hostId = host == null ? (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()) : host.getId();
if (!_vmSnapshotMgr.syncVMSnapshot(vm, hostId)) {
s_logger.warn("Failed to sync VM with transient snapshot: " + vm.getInstanceName());
continue;
} else {
s_logger.info("Successfully sync VM with transient snapshot: " + vm.getInstanceName());
}
}
if ((info == null && (vm.getState() == State.Running || vm.getState() == State.Starting)) ||
(info != null && (info.state == State.Running && vm.getState() == State.Starting))) {
s_logger.info("Found vm " + vm.getInstanceName() + " in inconsistent state. " + vm.getState() + " on CS while " + (info == null ? "Stopped" : "Running") +
" on agent");
info = new AgentVmInfo(vm.getInstanceName(), vm, State.Stopped);
// Bug 13850- grab outstanding work item if any for this VM state so that we mark it as DONE after we change VM state, else it will remain pending
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found an outstanding work item for this vm " + vm + " in state:" + vm.getState() + ", work id:" + work.getId());
}
}
vm.setState(State.Running); // set it as running and let HA take care of it
_vmDao.persist(vm);
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating outstanding work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
try {
Host host = _hostDao.findByGuid(info.getHostUuid());
long hostId = host == null ? (vm.getHostId() == null ? vm.getLastHostId() : vm.getHostId()) : host.getId();
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
Command command = compareState(hostId, vm, info, true, hvGuru.trackVmHostChange());
if (command != null) {
Answer answer = _agentMgr.send(hostId, command);
if (!answer.getResult()) {
s_logger.warn("Failed to update state of the VM due to " + answer.getDetails());
}
}
} catch (Exception e) {
s_logger.warn("Unable to update state of the VM due to exception " + e.getMessage());
e.printStackTrace();
}
} else if (info != null &&
(vm.getState() == State.Stopped || vm.getState() == State.Stopping || vm.isRemoved() || vm.getState() == State.Destroyed || vm.getState() == State.Expunging)) {
Host host = _hostDao.findByGuid(info.getHostUuid());
if (host != null) {
s_logger.warn("Stopping a VM which is stopped/stopping/destroyed/expunging " + info.name);
if (vm.getState() == State.Stopped || vm.getState() == State.Stopping) {
vm.setState(State.Stopped); // set it as stop and clear it from host
vm.setHostId(null);
_vmDao.persist(vm);
}
try {
Answer answer = _agentMgr.send(host.getId(), cleanup(info.name));
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
}
} catch (Exception e) {
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
} else
// host id can change
if (info != null && vm.getState() == State.Running) {
// check for host id changes
Host host = _hostDao.findByGuid(info.getHostUuid());
if (host != null && (vm.getHostId() == null || host.getId() != vm.getHostId())) {
s_logger.info("Found vm " + vm.getInstanceName() + " with inconsistent host in db, new host is " + host.getId());
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, host.getId());
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
}
/* else if(info == null && vm.getState() == State.Stopping) { //Handling CS-13376
s_logger.warn("Marking the VM as Stopped as it was still stopping on the CS" +vm.getName());
vm.setState(State.Stopped); // Setting the VM as stopped on the DB and clearing it from the host
vm.setLastHostId(vm.getHostId());
vm.setHostId(null);
_vmDao.persist(vm);
}*/
}
for (final AgentVmInfo left : infos.values()) {
if (!VirtualMachineName.isValidVmName(left.name))
continue; // if the vm doesn't follow CS naming ignore it for stopping
try {
Host host = _hostDao.findByGuid(left.getHostUuid());
if (host != null) {
s_logger.warn("Stopping a VM which we do not have any record of " + left.name);
Answer answer = _agentMgr.send(host.getId(), cleanup(left.name));
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
}
}
} catch (Exception e) {
s_logger.warn("Unable to stop a VM due to " + e.getMessage());
}
}
}
protected Map<Long, AgentVmInfo> convertToInfos(final Map<String, Ternary<String, State, String>> newStates) {
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (newStates == null) {
return map;
}
boolean is_alien_vm = true;
long alien_vm_count = -1;
for (Map.Entry<String, Ternary<String, State, String>> entry : newStates.entrySet()) {
is_alien_vm = true;
String name = entry.getKey();
VMInstanceVO vm = _vmDao.findVMByInstanceName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vm, entry.getValue().second(), entry.getValue().first(), entry.getValue().third()));
is_alien_vm = false;
}
// alien VMs
if (is_alien_vm) {
map.put(alien_vm_count--, new AgentVmInfo(entry.getKey(), null, entry.getValue().second(), entry.getValue().first(), entry.getValue().third()));
s_logger.warn("Found an alien VM " + entry.getKey());
}
}
return map;
}
protected Map<Long, AgentVmInfo> convertToInfos(StartupRoutingCommand cmd) {
final Map<String, VmState> states = cmd.getVmStates();
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (states == null) {
return map;
}
for (Map.Entry<String, VmState> entry : states.entrySet()) {
String name = entry.getKey();
VMInstanceVO vm = _vmDao.findVMByInstanceName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vm, entry.getValue().getState(), entry.getValue().getHost()));
}
}
return map;
}
protected Map<Long, AgentVmInfo> convertDeltaToInfos(final Map<String, State> states) {
final HashMap<Long, AgentVmInfo> map = new HashMap<Long, AgentVmInfo>();
if (states == null) {
return map;
}
for (Map.Entry<String, State> entry : states.entrySet()) {
String name = entry.getKey();
VMInstanceVO vm = _vmDao.findVMByInstanceName(name);
if (vm != null) {
map.put(vm.getId(), new AgentVmInfo(entry.getKey(), vm, entry.getValue()));
}
}
return map;
}
/**
* compareState does as its name suggests and compares the states between
* management server and agent. It returns whether something should be
* cleaned up
*
*/
protected Command compareState(long hostId, VMInstanceVO vm, final AgentVmInfo info, final boolean fullSync, boolean trackExternalChange) {
State agentState = info.state;
final State serverState = vm.getState();
final String serverName = vm.getInstanceName();
Command command = null;
s_logger.debug("VM " + serverName + ": cs state = " + serverState + " and realState = " + agentState);
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM " + serverName + ": cs state = " + serverState + " and realState = " + agentState);
}
if (agentState == State.Error) {
agentState = State.Stopped;
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY;
} else if (VirtualMachine.Type.SecondaryStorageVm.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_SSVM;
}
HostPodVO podVO = _podDao.findById(vm.getPodIdToDeployIn());
DataCenterVO dcVO = _dcDao.findById(vm.getDataCenterId());
HostVO hostVO = _hostDao.findById(vm.getHostId());
String hostDesc = "name: " + hostVO.getName() + " (id:" + hostVO.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(alertType, vm.getDataCenterId(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getInstanceName() + ", id: " + vm.getId() +
") stopped on host " + hostDesc + " due to storage failure", "Virtual Machine " + vm.getInstanceName() + " (id: " + vm.getId() + ") running on host [" +
vm.getHostId() + "] stopped due to storage failure.");
}
// track platform info
if (info.platform != null && !info.platform.isEmpty()) {
if (vm.getType() == VirtualMachine.Type.User) {
UserVmVO userVm = _userVmDao.findById(vm.getId());
_userVmDao.loadDetails(userVm);
userVm.setDetail("platform", info.platform);
_userVmDao.saveDetails(userVm);
}
}
if (trackExternalChange) {
if (serverState == State.Starting) {
if (vm.getHostId() != null && vm.getHostId() != hostId) {
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId +
", skip status sync for vm: " + vm.getInstanceName());
return null;
}
}
if (vm.getHostId() == null || hostId != vm.getHostId()) {
try {
ItWorkVO workItem = _workDao.findByOutstandingWork(vm.getId(), State.Migrating);
if (workItem == null) {
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId);
}
} catch (NoTransitionException e) {
}
}
}
// during VM migration time, don't sync state will agent status update
if (serverState == State.Migrating) {
s_logger.debug("Skipping vm in migrating state: " + vm);
return null;
}
if (trackExternalChange) {
if (serverState == State.Starting) {
if (vm.getHostId() != null && vm.getHostId() != hostId) {
s_logger.info("CloudStack is starting VM on host " + vm.getHostId() + ", but status report comes from a different host " + hostId +
", skip status sync for vm: " + vm.getInstanceName());
return null;
}
}
if (serverState == State.Running) {
try {
//
// we had a bug that sometimes VM may be at Running State
// but host_id is null, we will cover it here.
// means that when CloudStack DB lost of host information,
// we will heal it with the info reported from host
//
if (vm.getHostId() == null || hostId != vm.getHostId()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("detected host change when VM " + vm + " is at running state, VM could be live-migrated externally from host " +
vm.getHostId() + " to host " + hostId);
}
stateTransitTo(vm, VirtualMachine.Event.AgentReportMigrated, hostId);
}
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
}
if (agentState == serverState) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Both states are " + agentState + " for " + vm);
}
assert (agentState == State.Stopped || agentState == State.Running) : "If the states we send up is changed, this must be changed.";
if (agentState == State.Running) {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportRunning, hostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
// FIXME: What if someone comes in and sets it to stopping? Then
// what?
return null;
}
s_logger.debug("State matches but the agent said stopped so let's send a cleanup command anyways.");
return cleanup(vm);
}
if (agentState == State.Shutdowned) {
if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) {
try {
advanceStop(vm, true);
} catch (AgentUnavailableException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (OperationTimedoutException e) {
assert (false) : "How do we hit this with forced on?";
return null;
} catch (ConcurrentOperationException e) {
assert (false) : "How do we hit this with forced on?";
return null;
}
} else {
s_logger.debug("Sending cleanup to a shutdowned vm: " + vm.getInstanceName());
command = cleanup(vm);
}
} else if (agentState == State.Stopped) {
// This state means the VM on the agent was detected previously
// and now is gone. This is slightly different than if the VM
// was never completed but we still send down a Stop Command
// to ensure there's cleanup.
if (serverState == State.Running) {
// Our records showed that it should be running so let's restart
// it.
_haMgr.scheduleRestart(vm, false);
} else if (serverState == State.Stopping) {
_haMgr.scheduleStop(vm, hostId, WorkType.ForceStop);
s_logger.debug("Scheduling a check stop for VM in stopping mode: " + vm);
} else if (serverState == State.Starting) {
s_logger.debug("Ignoring VM in starting mode: " + vm.getInstanceName());
_haMgr.scheduleRestart(vm, false);
}
command = cleanup(vm);
} else if (agentState == State.Running) {
if (serverState == State.Starting) {
if (fullSync) {
try {
ensureVmRunningContext(hostId, vm, Event.AgentReportRunning);
} catch (OperationTimedoutException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (ResourceUnavailableException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (InsufficientAddressCapacityException e) {
s_logger.error("Exception during update for running vm: " + vm, e);
return null;
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
} else if (serverState == State.Stopping) {
s_logger.debug("Scheduling a stop command for " + vm);
_haMgr.scheduleStop(vm, hostId, WorkType.Stop);
} else {
s_logger.debug("server VM state " + serverState + " does not meet expectation of a running VM report from agent");
// just be careful not to stop VM for things we don't handle
// command = cleanup(vm);
}
}
return command;
}
private void ensureVmRunningContext(long hostId, VMInstanceVO vm, Event cause) throws OperationTimedoutException, ResourceUnavailableException,
NoTransitionException, InsufficientAddressCapacityException {
VirtualMachineGuru vmGuru = getVmGuru(vm);
s_logger.debug("VM state is starting on full sync so updating it to running");
vm = _vmDao.findById(vm.getId());
// grab outstanding work item if any
ItWorkVO work = _workDao.findByOutstandingWork(vm.getId(), vm.getState());
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found an outstanding work item for this vm " + vm + " in state:" + vm.getState() + ", work id:" + work.getId());
}
}
try {
stateTransitTo(vm, cause, hostId);
} catch (NoTransitionException e1) {
s_logger.warn(e1.getMessage());
}
s_logger.debug("VM's " + vm + " state is starting on full sync so updating it to Running");
vm = _vmDao.findById(vm.getId()); // this should ensure vm has the most
// up to date info
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
List<NicVO> nics = _nicsDao.listByVmId(profile.getId());
for (NicVO nic : nics) {
Network network = _networkModel.getNetwork(nic.getNetworkId());
NicProfile nicProfile =
new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.isSecurityGroupSupportedInNetwork(network),
_networkModel.getNetworkTag(profile.getHypervisorType(), network));
profile.addNic(nicProfile);
}
Commands cmds = new Commands(Command.OnError.Stop);
s_logger.debug("Finalizing commands that need to be send to complete Start process for the vm " + vm);
if (vmGuru.finalizeCommandsOnStart(cmds, profile)) {
if (cmds.size() != 0) {
_agentMgr.send(vm.getHostId(), cmds);
}
if (vmGuru.finalizeStart(profile, vm.getHostId(), cmds, null)) {
stateTransitTo(vm, cause, vm.getHostId());
} else {
s_logger.error("Unable to finish finialization for running vm: " + vm);
}
} else {
s_logger.error("Unable to finalize commands on start for vm: " + vm);
}
if (work != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updating outstanding work item to Done, id:" + work.getId());
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
@Override
public boolean isRecurring() {
return true;
}
@Override
public boolean processAnswers(long agentId, long seq, Answer[] answers) {
for (final Answer answer : answers) {
if (answer instanceof ClusterSyncAnswer) {
ClusterSyncAnswer hs = (ClusterSyncAnswer)answer;
if (!hs.isExceuted()) {
deltaSync(hs.getNewStates());
hs.setExecuted();
}
}
}
return true;
}
@Override
public boolean processTimeout(long agentId, long seq) {
return true;
}
@Override
public int getTimeout() {
return -1;
}
@Override
public boolean processCommands(long agentId, long seq, Command[] cmds) {
boolean processed = false;
for (Command cmd : cmds) {
if (cmd instanceof PingRoutingCommand) {
PingRoutingCommand ping = (PingRoutingCommand)cmd;
if (ping.getNewStates() != null && ping.getNewStates().size() > 0) {
Commands commands = deltaHostSync(agentId, ping.getNewStates());
if (commands.size() > 0) {
try {
_agentMgr.send(agentId, commands, this);
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is now unavailable", e);
}
}
}
if(VmJobEnabled.value()) {
if (ping.getHostVmStateReport() != null && ping.getHostVmStateReport().size() > 0) {
_syncMgr.processHostVmStatePingReport(agentId, ping.getHostVmStateReport());
}
}
// take the chance to scan VMs that are stuck in transitional states
// and are missing from the report
scanStalledVMInTransitionStateOnUpHost(agentId);
processed = true;
}
}
return processed;
}
@Override
public AgentControlAnswer processControlCommand(long agentId, AgentControlCommand cmd) {
return null;
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return true;
}
@Override
public void processConnect(Host agent, StartupCommand cmd, boolean forRebalance) throws ConnectionException {
if (!(cmd instanceof StartupRoutingCommand)) {
return;
}
if (s_logger.isDebugEnabled())
s_logger.debug("Received startup command from hypervisor host. host id: " + agent.getId());
if (VmJobEnabled.value()) {
_syncMgr.resetHostSyncState(agent.getId());
}
if (forRebalance) {
s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process");
return;
}
if (forRebalance) {
s_logger.debug("Not processing listener " + this + " as connect happens on rebalance process");
return;
}
Long clusterId = agent.getClusterId();
long agentId = agent.getId();
if (agent.getHypervisorType() == HypervisorType.XenServer) { // only for Xen
StartupRoutingCommand startup = (StartupRoutingCommand)cmd;
HashMap<String, Ternary<String, State, String>> allStates = startup.getClusterVMStateChanges();
if (allStates != null) {
fullSync(clusterId, allStates);
}
// initiate the cron job
ClusterSyncCommand syncCmd = new ClusterSyncCommand(ClusterDeltaSyncInterval.value(), clusterId);
try {
long seq_no = _agentMgr.send(agentId, new Commands(syncCmd), this);
s_logger.debug("Cluster VM sync started with jobid " + seq_no);
} catch (AgentUnavailableException e) {
s_logger.fatal("The Cluster VM sync process failed for cluster id " + clusterId + " with ", e);
}
} else { // for others KVM and VMWare
StartupRoutingCommand startup = (StartupRoutingCommand)cmd;
Commands commands = fullHostSync(agentId, startup);
if (commands.size() > 0) {
s_logger.debug("Sending clean commands to the agent");
try {
boolean error = false;
Answer[] answers = _agentMgr.send(agentId, commands);
for (Answer answer : answers) {
if (!answer.getResult()) {
s_logger.warn("Unable to stop a VM due to " + answer.getDetails());
error = true;
}
}
if (error) {
throw new ConnectionException(true, "Unable to stop VMs");
}
} catch (final AgentUnavailableException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
} catch (final OperationTimedoutException e) {
s_logger.warn("Agent is unavailable now", e);
throw new ConnectionException(true, "Unable to sync", e);
}
}
}
}
protected class TransitionTask extends ManagedContextRunnable {
@Override
protected void runInContext() {
GlobalLock lock = GlobalLock.getInternLock("TransitionChecking");
if (lock == null) {
s_logger.debug("Couldn't get the global lock");
return;
}
if (!lock.lock(30)) {
s_logger.debug("Couldn't lock the db");
return;
}
try {
lock.addRef();
List<VMInstanceVO> instances =
_vmDao.findVMInTransition(new Date(new Date().getTime() - (AgentManager.Wait.value() * 1000)), State.Starting, State.Stopping);
for (VMInstanceVO instance : instances) {
State state = instance.getState();
if (state == State.Stopping) {
_haMgr.scheduleStop(instance, instance.getHostId(), WorkType.CheckStop);
} else if (state == State.Starting) {
_haMgr.scheduleRestart(instance, true);
}
}
} catch (Exception e) {
s_logger.warn("Caught the following exception on transition checking", e);
} finally {
lock.unlock();
}
}
}
protected class AgentVmInfo {
public String name;
public State state;
public String hostUuid;
public VMInstanceVO vm;
public String platform;
@SuppressWarnings("unchecked")
public AgentVmInfo(String name, VMInstanceVO vm, State state, String host, String platform) {
this.name = name;
this.state = state;
this.vm = vm;
hostUuid = host;
this.platform = platform;
}
public AgentVmInfo(String name, VMInstanceVO vm, State state, String host) {
this(name, vm, state, host, null);
}
public AgentVmInfo(String name, VMInstanceVO vm, State state) {
this(name, vm, state, null, null);
}
public String getHostUuid() {
return hostUuid;
}
public String getPlatform() {
return platform;
}
}
@Override
public VMInstanceVO findById(long vmId) {
return _vmDao.findById(vmId);
}
@Override
public void checkIfCanUpgrade(VirtualMachine vmInstance, ServiceOffering newServiceOffering) {
if (newServiceOffering == null) {
throw new InvalidParameterValueException("Unable to find a service offering with id " + newServiceOffering.getId());
}
// Check that the VM is stopped / running
if (!(vmInstance.getState().equals(State.Stopped) || vmInstance.getState().equals(State.Running))) {
s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " " + " in state " + vmInstance.getState() +
"; make sure the virtual machine is stopped/running");
}
// Check if the service offering being upgraded to is what the VM is already running with
if (!newServiceOffering.isDynamic() && vmInstance.getServiceOfferingId() == newServiceOffering.getId()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested " + "service offering (" + newServiceOffering.getName() +
")");
}
throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already " + "has the requested service offering (" +
newServiceOffering.getName() + ")");
}
ServiceOfferingVO currentServiceOffering = _offeringDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
// Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering
// NOTE: With the new network refactoring in 2.2, we shouldn't need the check for same guest IP type anymore.
/*
* if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) { String errorMsg =
* "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType(); errorMsg +=
* ". Please select a service offering with the same guest IP type as the VM's current service offering (" +
* currentServiceOffering.getGuestIpType() + ")."; throw new InvalidParameterValueException(errorMsg); }
*/
// Check that the service offering being upgraded to has the same storage pool preference as the VM's current service
// offering
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() +
", cannot switch between local storage and shared storage service offerings. Current offering " + "useLocalStorage=" +
currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage());
}
// if vm is a system vm, check if it is a system service offering, if yes return with error as it cannot be used for user vms
if (currentServiceOffering.getSystemUse() != newServiceOffering.getSystemUse()) {
throw new InvalidParameterValueException("isSystem property is different for current service offering and new service offering");
}
// Check that there are enough resources to upgrade the service offering
if (!isVirtualMachineUpgradable(vmInstance, newServiceOffering)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available " + "for an offering of " +
newServiceOffering.getCpu() + " cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory");
}
// Check that the service offering being upgraded to has all the tags of the current service offering
List<String> currentTags = StringUtils.csvTagsToList(currentServiceOffering.getTags());
List<String> newTags = StringUtils.csvTagsToList(newServiceOffering.getTags());
if (!newTags.containsAll(currentTags)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering " + "does not have all the tags of the " +
"current service offering. Current service offering tags: " + currentTags + "; " + "new service " + "offering tags: " + newTags);
}
}
@Override
public boolean upgradeVmDb(long vmId, long serviceOfferingId) {
VMInstanceVO vmForUpdate = _vmDao.createForUpdate();
vmForUpdate.setServiceOfferingId(serviceOfferingId);
ServiceOffering newSvcOff = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
vmForUpdate.setHaEnabled(newSvcOff.getOfferHA());
vmForUpdate.setLimitCpuUse(newSvcOff.getLimitCpuUse());
vmForUpdate.setServiceOfferingId(newSvcOff.getId());
return _vmDao.update(vmId, vmForUpdate);
}
@Override
public NicProfile addVmToNetwork(VirtualMachine vm, Network network, NicProfile requested)
throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateAddVmToNetwork(vm, network, requested);
} else {
Outcome<VirtualMachine> outcome = addVmToNetworkThroughJobQueue(vm, network, requested);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
NicProfile nic = (NicProfile)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult());
return nic;
} else {
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof InsufficientCapacityException)
throw (InsufficientCapacityException)jobException;
else if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
throw new RuntimeException("Job failed with unhandled exception");
}
}
}
private NicProfile orchestrateAddVmToNetwork(VirtualMachine vm, Network network, NicProfile requested) throws ConcurrentOperationException, ResourceUnavailableException,
InsufficientCapacityException {
CallContext cctx = CallContext.current();
s_logger.debug("Adding vm " + vm + " to network " + network + "; requested nic profile " + requested);
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
//check vm state
if (vm.getState() == State.Running) {
//1) allocate and prepare nic
NicProfile nic = _networkMgr.createNicForVm(network, requested, context, vmProfile, true);
//2) Convert vmProfile to vmTO
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
//3) Convert nicProfile to NicTO
NicTO nicTO = toNicTO(nic, vmProfile.getVirtualMachine().getHypervisorType());
//4) plug the nic to the vm
s_logger.debug("Plugging nic for vm " + vm + " in network " + network);
boolean result = false;
try {
result = plugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is plugged successfully for vm " + vm + " in network " + network + ". Vm is a part of network now");
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
// insert nic's Id into DB as resource_name
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_ASSIGN, vmVO.getAccountId(), vmVO.getDataCenterId(), vmVO.getId(),
Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vmVO.getUuid());
return nic;
} else {
s_logger.warn("Failed to plug nic to the vm " + vm + " in network " + network);
return null;
}
} finally {
if (!result) {
s_logger.debug("Removing nic " + nic + " from vm " + vmProfile.getVirtualMachine() + " as nic plug failed on the backend");
_networkMgr.removeNic(vmProfile, _nicsDao.findById(nic.getId()));
}
}
} else if (vm.getState() == State.Stopped) {
//1) allocate nic
return _networkMgr.createNicForVm(network, requested, context, vmProfile, false);
} else {
s_logger.warn("Unable to add vm " + vm + " to network " + network);
throw new ResourceUnavailableException("Unable to add vm " + vm + " to network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
}
@Override
public NicTO toNicTO(NicProfile nic, HypervisorType hypervisorType) {
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(hypervisorType);
NicTO nicTO = hvGuru.toNicTO(nic);
return nicTO;
}
@Override
public boolean removeNicFromVm(VirtualMachine vm, Nic nic)
throws ConcurrentOperationException, ResourceUnavailableException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateRemoveNicFromVm(vm, nic);
} else {
Outcome<VirtualMachine> outcome = removeNicFromVmThroughJobQueue(vm, nic);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
Boolean result = (Boolean)JobSerializerHelper.fromObjectSerializedString(jobVo.getResult());
return result;
} else {
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
else if (jobException instanceof RuntimeException)
throw (RuntimeException)jobException;
}
throw new RuntimeException("Job failed with un-handled exception");
}
}
}
private boolean orchestrateRemoveNicFromVm(VirtualMachine vm, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
NetworkVO network = _networkDao.findById(nic.getNetworkId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
// don't delete default NIC on a user VM
if (nic.isDefaultNic() && vm.getType() == VirtualMachine.Type.User) {
s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
}
// if specified nic is associated with PF/LB/Static NAT
if (rulesMgr.listAssociatedRulesForGuestNic(nic).size() > 0) {
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network +
", nic has associated Port forwarding or Load balancer or Static NAT rules.");
}
NicProfile nicProfile =
new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
//1) Unplug the nic
if (vm.getState() == State.Running) {
NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
s_logger.debug("Un-plugging nic " + nic + " for vm " + vm + " from network " + network);
boolean result = unplugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
long isDefault = (nic.isDefaultNic()) ? 1 : 0;
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NETWORK_OFFERING_REMOVE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(),
Long.toString(nic.getId()), network.getNetworkOfferingId(), null, isDefault, VirtualMachine.class.getName(), vm.getUuid());
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
return false;
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
//2) Release the nic
_networkMgr.releaseNic(vmProfile, nic);
s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
//3) Remove the nic
_networkMgr.removeNic(vmProfile, nic);
_nicsDao.expunge(nic.getId());
return true;
}
@Override
@DB
public boolean removeVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
// TODO will serialize on the VM object later to resolve operation conflicts
return orchestrateRemoveVmFromNetwork(vm, network, broadcastUri);
}
@DB
private boolean orchestrateRemoveVmFromNetwork(VirtualMachine vm, Network network, URI broadcastUri) throws ConcurrentOperationException, ResourceUnavailableException {
CallContext cctx = CallContext.current();
VMInstanceVO vmVO = _vmDao.findById(vm.getId());
ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmVO, null, null, null, null);
DataCenter dc = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vmProfile.getVirtualMachine().getHypervisorType());
VirtualMachineTO vmTO = hvGuru.implement(vmProfile);
Nic nic = null;
if (broadcastUri != null) {
nic = _nicsDao.findByNetworkIdInstanceIdAndBroadcastUri(network.getId(), vm.getId(), broadcastUri.toString());
} else {
nic = _networkModel.getNicInNetwork(vm.getId(), network.getId());
}
if (nic == null) {
s_logger.warn("Could not get a nic with " + network);
return false;
}
// don't delete default NIC on a user VM
if (nic.isDefaultNic() && vm.getType() == VirtualMachine.Type.User) {
s_logger.warn("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
throw new CloudRuntimeException("Failed to remove nic from " + vm + " in " + network + ", nic is default.");
}
//Lock on nic is needed here
Nic lock = _nicsDao.acquireInLockTable(nic.getId());
if (lock == null) {
//check if nic is still there. Return if it was released already
if (_nicsDao.findById(nic.getId()) == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Not need to remove the vm " + vm + " from network " + network + " as the vm doesn't have nic in this network");
}
return true;
}
throw new ConcurrentOperationException("Unable to lock nic " + nic.getId());
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Lock is acquired for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
}
try {
NicProfile nicProfile =
new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), _networkModel.getNetworkRate(network.getId(), vm.getId()),
_networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vmProfile.getVirtualMachine().getHypervisorType(), network));
//1) Unplug the nic
if (vm.getState() == State.Running) {
NicTO nicTO = toNicTO(nicProfile, vmProfile.getVirtualMachine().getHypervisorType());
s_logger.debug("Un-plugging nic for vm " + vm + " from network " + network);
boolean result = unplugNic(network, nicTO, vmTO, context, dest);
if (result) {
s_logger.debug("Nic is unplugged successfully for vm " + vm + " in network " + network);
} else {
s_logger.warn("Failed to unplug nic for the vm " + vm + " from network " + network);
return false;
}
} else if (vm.getState() != State.Stopped) {
s_logger.warn("Unable to remove vm " + vm + " from network " + network);
throw new ResourceUnavailableException("Unable to remove vm " + vm + " from network, is not in the right state", DataCenter.class, vm.getDataCenterId());
}
//2) Release the nic
_networkMgr.releaseNic(vmProfile, nic);
s_logger.debug("Successfully released nic " + nic + "for vm " + vm);
//3) Remove the nic
_networkMgr.removeNic(vmProfile, nic);
return true;
} finally {
if (lock != null) {
_nicsDao.releaseFromLockTable(lock.getId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Lock is released for nic id " + lock.getId() + " as a part of remove vm " + vm + " from network " + network);
}
}
}
}
@Override
public void findHostAndMigrate(String vmUuid, Long newSvcOfferingId, ExcludeList excludes) throws InsufficientCapacityException, ConcurrentOperationException,
ResourceUnavailableException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
throw new CloudRuntimeException("Unable to find " + vmUuid);
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
Long srcHostId = vm.getHostId();
Long oldSvcOfferingId = vm.getServiceOfferingId();
if (srcHostId == null) {
throw new CloudRuntimeException("Unable to scale the vm because it doesn't have a host id");
}
Host host = _hostDao.findById(srcHostId);
DataCenterDeployment plan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), null, null, null);
excludes.addHost(vm.getHostId());
vm.setServiceOfferingId(newSvcOfferingId); // Need to find the destination host based on new svc offering
DeployDestination dest = null;
try {
dest = _dpMgr.planDeployment(profile, plan, excludes, null);
} catch (AffinityConflictException e2) {
s_logger.warn("Unable to create deployment, affinity rules associted to the VM conflict", e2);
throw new CloudRuntimeException("Unable to create deployment, affinity rules associted to the VM conflict");
}
if (dest != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(" Found " + dest + " for scaling the vm to.");
}
}
if (dest == null) {
throw new InsufficientServerCapacityException("Unable to find a server to scale the vm to.", host.getClusterId());
}
excludes.addHost(dest.getHost().getId());
try {
migrateForScale(vm.getUuid(), srcHostId, dest, oldSvcOfferingId);
} catch (ResourceUnavailableException e) {
s_logger.debug("Unable to migrate to unavailable " + dest);
throw e;
} catch (ConcurrentOperationException e) {
s_logger.debug("Unable to migrate VM due to: " + e.getMessage());
throw e;
}
}
@Override
public void migrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
orchestrateMigrateForScale(vmUuid, srcHostId, dest, oldSvcOfferingId);
} else {
Outcome<VirtualMachine> outcome = migrateVmForScaleThroughJobQueue(vmUuid, srcHostId, dest, oldSvcOfferingId);
try {
VirtualMachine vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
}
}
}
private void orchestrateMigrateForScale(String vmUuid, long srcHostId, DeployDestination dest, Long oldSvcOfferingId)
throws ResourceUnavailableException, ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
s_logger.info("Migrating " + vm + " to " + dest);
vm.getServiceOfferingId();
long dstHostId = dest.getHost().getId();
Host fromHost = _hostDao.findById(srcHostId);
if (fromHost == null) {
s_logger.info("Unable to find the host to migrate from: " + srcHostId);
throw new CloudRuntimeException("Unable to find the host to migrate from: " + srcHostId);
}
if (fromHost.getClusterId().longValue() != dest.getCluster().getId()) {
s_logger.info("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
throw new CloudRuntimeException("Source and destination host are not in same cluster, unable to migrate to host: " + dest.getHost().getId());
}
VirtualMachineGuru vmGuru = getVmGuru(vm);
long vmId = vm.getId();
vm = _vmDao.findByUuid(vmUuid);
if (vm == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find the vm " + vm);
}
throw new CloudRuntimeException("Unable to find a virtual machine with id " + vmId);
}
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
throw new CloudRuntimeException("VM is not Running, unable to migrate the vm currently " + vm + " , current state: " + vm.getState().toString());
}
AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
}
VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
_networkMgr.prepareNicForMigration(profile, dest);
volumeMgr.prepareForMigration(profile, dest);
VirtualMachineTO to = toVmTO(profile);
PrepareForMigrationCommand pfmc = new PrepareForMigrationCommand(to);
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(dstHostId);
work = _workDao.persist(work);
PrepareForMigrationAnswer pfma = null;
try {
pfma = (PrepareForMigrationAnswer)_agentMgr.send(dstHostId, pfmc);
if (!pfma.getResult()) {
String msg = "Unable to prepare for migration due to " + pfma.getDetails();
pfma = null;
throw new AgentUnavailableException(msg, dstHostId);
}
} catch (OperationTimedoutException e1) {
throw new AgentUnavailableException("Operation timed out", dstHostId);
} finally {
if (pfma == null) {
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
vm.setLastHostId(srcHostId);
try {
if (vm == null || vm.getHostId() == null || vm.getHostId() != srcHostId || !changeState(vm, Event.MigrationRequested, dstHostId, work, Step.Migrating)) {
s_logger.info("Migration cancelled because state has changed: " + vm);
throw new ConcurrentOperationException("Migration cancelled because state has changed: " + vm);
}
} catch (NoTransitionException e1) {
s_logger.info("Migration cancelled because " + e1.getMessage());
throw new ConcurrentOperationException("Migration cancelled because " + e1.getMessage());
}
boolean migrated = false;
try {
boolean isWindows = _guestOsCategoryDao.findById(_guestOsDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
MigrateCommand mc = new MigrateCommand(vm.getInstanceName(), dest.getHost().getPrivateIpAddress(), isWindows, to, ExecuteInSequence.value());
mc.setHostGuid(dest.getHost().getGuid());
try {
MigrateAnswer ma = (MigrateAnswer)_agentMgr.send(vm.getLastHostId(), mc);
if (!ma.getResult()) {
s_logger.error("Unable to migrate due to " + ma.getDetails());
throw new CloudRuntimeException("Unable to migrate due to " + ma.getDetails());
}
} catch (OperationTimedoutException e) {
if (e.isActive()) {
s_logger.warn("Active migration command so scheduling a restart for " + vm);
_haMgr.scheduleRestart(vm, true);
}
throw new AgentUnavailableException("Operation timed out on migrating " + vm, dstHostId);
}
try {
long newServiceOfferingId = vm.getServiceOfferingId();
vm.setServiceOfferingId(oldSvcOfferingId); // release capacity for the old service offering only
if (!changeState(vm, VirtualMachine.Event.OperationSucceeded, dstHostId, work, Step.Started)) {
throw new ConcurrentOperationException("Unable to change the state for " + vm);
}
vm.setServiceOfferingId(newServiceOfferingId);
} catch (NoTransitionException e1) {
throw new ConcurrentOperationException("Unable to change state due to " + e1.getMessage());
}
try {
if (!checkVmOnHost(vm, dstHostId)) {
s_logger.error("Unable to complete migration for " + vm);
try {
_agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException e) {
s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
}
cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
throw new CloudRuntimeException("Unable to complete migration for " + vm);
}
} catch (OperationTimedoutException e) {
}
migrated = true;
} finally {
if (!migrated) {
s_logger.info("Migration was unsuccessful. Cleaning up: " + vm);
_alertMgr.sendAlert(alertType, fromHost.getDataCenterId(), fromHost.getPodId(),
"Unable to migrate vm " + vm.getInstanceName() + " from host " + fromHost.getName() + " in zone " + dest.getDataCenter().getName() + " and pod " +
dest.getPod().getName(), "Migrate Command failed. Please check logs.");
try {
_agentMgr.send(dstHostId, new Commands(cleanup(vm.getInstanceName())), null);
} catch (AgentUnavailableException ae) {
s_logger.info("Looks like the destination Host is unavailable for cleanup");
}
try {
stateTransitTo(vm, Event.OperationFailed, srcHostId);
} catch (NoTransitionException e) {
s_logger.warn(e.getMessage());
}
}
work.setStep(Step.Done);
_workDao.update(work.getId(), work);
}
}
public boolean plugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException,
ResourceUnavailableException, InsufficientCapacityException {
boolean result = true;
VMInstanceVO router = _vmDao.findById(vm.getId());
if (router.getState() == State.Running) {
try {
PlugNicCommand plugNicCmd = new PlugNicCommand(nic, vm.getName(), vm.getType());
Commands cmds = new Commands(Command.OnError.Stop);
cmds.addCommand("plugnic", plugNicCmd);
_agentMgr.send(dest.getHost().getId(), cmds);
PlugNicAnswer plugNicAnswer = cmds.getAnswer(PlugNicAnswer.class);
if (!(plugNicAnswer != null && plugNicAnswer.getResult())) {
s_logger.warn("Unable to plug nic for vm " + vm.getName());
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to plug nic for router " + vm.getName() + " in network " + network, dest.getHost().getId(), e);
}
} else {
s_logger.warn("Unable to apply PlugNic, vm " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to apply PlugNic on the backend," + " vm " + vm + " is not in the right state", DataCenter.class,
router.getDataCenterId());
}
return result;
}
public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException,
ResourceUnavailableException {
boolean result = true;
VMInstanceVO router = _vmDao.findById(vm.getId());
if (router.getState() == State.Running) {
try {
Commands cmds = new Commands(Command.OnError.Stop);
UnPlugNicCommand unplugNicCmd = new UnPlugNicCommand(nic, vm.getName());
cmds.addCommand("unplugnic", unplugNicCmd);
_agentMgr.send(dest.getHost().getId(), cmds);
UnPlugNicAnswer unplugNicAnswer = cmds.getAnswer(UnPlugNicAnswer.class);
if (!(unplugNicAnswer != null && unplugNicAnswer.getResult())) {
s_logger.warn("Unable to unplug nic from router " + router);
result = false;
}
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Unable to unplug nic from rotuer " + router + " from network " + network, dest.getHost().getId(), e);
}
} else if (router.getState() == State.Stopped || router.getState() == State.Stopping) {
s_logger.debug("Vm " + router.getInstanceName() + " is in " + router.getState() + ", so not sending unplug nic command to the backend");
} else {
s_logger.warn("Unable to apply unplug nic, Vm " + router + " is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to apply unplug nic on the backend," + " vm " + router + " is not in the right state", DataCenter.class,
router.getDataCenterId());
}
return result;
}
@Override
public VMInstanceVO reConfigureVm(String vmUuid, ServiceOffering oldServiceOffering,
boolean reconfiguringOnExistingHost)
throws ResourceUnavailableException, ConcurrentOperationException {
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (!VmJobEnabled.value() || jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
return orchestrateReConfigureVm(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
} else {
Outcome<VirtualMachine> outcome = reconfigureVmThroughJobQueue(vmUuid, oldServiceOffering, reconfiguringOnExistingHost);
VirtualMachine vm = null;
try {
vm = outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, outcome.getJob().getId());
if (jobVo.getResultCode() == JobInfo.Status.SUCCEEDED.ordinal()) {
return _entityMgr.findById(VMInstanceVO.class, vm.getId());
} else {
Throwable jobException = retrieveExecutionException(outcome.getJob());
if (jobException != null) {
if (jobException instanceof ResourceUnavailableException)
throw (ResourceUnavailableException)jobException;
else if (jobException instanceof ConcurrentOperationException)
throw (ConcurrentOperationException)jobException;
}
throw new RuntimeException("Failed with un-handled exception");
}
}
}
private VMInstanceVO orchestrateReConfigureVm(String vmUuid, ServiceOffering oldServiceOffering, boolean reconfiguringOnExistingHost) throws ResourceUnavailableException,
ConcurrentOperationException {
VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
long newServiceofferingId = vm.getServiceOfferingId();
ServiceOffering newServiceOffering = _offeringDao.findById(vm.getId(), newServiceofferingId);
HostVO hostVo = _hostDao.findById(vm.getHostId());
Float memoryOvercommitRatio = CapacityManager.MemOverprovisioningFactor.valueIn(hostVo.getClusterId());
Float cpuOvercommitRatio = CapacityManager.CpuOverprovisioningFactor.valueIn(hostVo.getClusterId());
long minMemory = (long)(newServiceOffering.getRamSize() / memoryOvercommitRatio);
ScaleVmCommand reconfigureCmd =
new ScaleVmCommand(vm.getInstanceName(), newServiceOffering.getCpu(), (int)(newServiceOffering.getSpeed() / cpuOvercommitRatio),
newServiceOffering.getSpeed(), minMemory * 1024L * 1024L, newServiceOffering.getRamSize() * 1024L * 1024L, newServiceOffering.getLimitCpuUse());
Long dstHostId = vm.getHostId();
ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Running, vm.getType(), vm.getId());
work.setStep(Step.Prepare);
work.setResourceType(ItWorkVO.ResourceType.Host);
work.setResourceId(vm.getHostId());
work = _workDao.persist(work);
boolean success = false;
try {
if (reconfiguringOnExistingHost) {
vm.setServiceOfferingId(oldServiceOffering.getId());
_capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); //release the old capacity
vm.setServiceOfferingId(newServiceofferingId);
_capacityMgr.allocateVmCapacity(vm, false); // lock the new capacity
}
Answer reconfigureAnswer = _agentMgr.send(vm.getHostId(), reconfigureCmd);
if (reconfigureAnswer == null || !reconfigureAnswer.getResult()) {
s_logger.error("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails()));
throw new CloudRuntimeException("Unable to scale vm due to " + (reconfigureAnswer == null ? "" : reconfigureAnswer.getDetails()));
}
success = true;
} catch (OperationTimedoutException e) {
throw new AgentUnavailableException("Operation timed out on reconfiguring " + vm, dstHostId);
} catch (AgentUnavailableException e) {
throw e;
} finally {
// work.setStep(Step.Done);
//_workDao.update(work.getId(), work);
if (!success) {
_capacityMgr.releaseVmCapacity(vm, false, false, vm.getHostId()); // release the new capacity
vm.setServiceOfferingId(oldServiceOffering.getId());
_capacityMgr.allocateVmCapacity(vm, false); // allocate the old capacity
}
}
return vm;
}
@Override
public String getConfigComponentName() {
return VirtualMachineManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[] {ClusterDeltaSyncInterval, StartRetry, VmDestroyForcestop, VmOpCancelInterval, VmOpCleanupInterval, VmOpCleanupWait,
VmOpLockStateRetry,
VmOpWaitInterval, ExecuteInSequence, VmJobCheckInterval, VmJobTimeout, VmJobStateReportInterval};
}
public List<StoragePoolAllocator> getStoragePoolAllocators() {
return _storagePoolAllocators;
}
@Inject
public void setStoragePoolAllocators(List<StoragePoolAllocator> storagePoolAllocators) {
_storagePoolAllocators = storagePoolAllocators;
}
//
// PowerState report handling for out-of-band changes and handling of left-over transitional VM states
//
@MessageHandler(topic = Topics.VM_POWER_STATE)
private void HandlePownerStateReport(Object target, String subject, String senderAddress, Object args) {
assert (args != null);
Long vmId = (Long)args;
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vmId);
if (pendingWorkJobs.size() == 0) {
// there is no pending operation job
VMInstanceVO vm = _vmDao.findById(vmId);
if (vm != null) {
switch (vm.getPowerState()) {
case PowerOn:
handlePowerOnReportWithNoPendingJobsOnVM(vm);
break;
case PowerOff:
handlePowerOffReportWithNoPendingJobsOnVM(vm);
break;
// PowerUnknown shouldn't be reported, it is a derived
// VM power state from host state (host un-reachable
case PowerUnknown:
default:
assert (false);
break;
}
} else {
s_logger.warn("VM " + vmId + " no longer exists when processing VM state report");
}
} else {
// TODO, do job wake-up signalling, since currently async job wake-up is not in use
// we will skip it for nows
}
}
private void handlePowerOnReportWithNoPendingJobsOnVM(VMInstanceVO vm) {
//
// 1) handle left-over transitional VM states
// 2) handle out of band VM live migration
// 3) handle out of sync stationary states, marking VM from Stopped to Running with
// alert messages
//
switch (vm.getState()) {
case Starting:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
// we need to alert admin or user about this risky state transition
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName()
+ ") state is sync-ed (Starting -> Running) from out-of-context transition. VM network environment may need to be reset");
break;
case Running:
try {
if (vm.getHostId() != null && vm.getHostId().longValue() != vm.getPowerHostId().longValue())
s_logger.info("Detected out of band VM migration from host " + vm.getHostId() + " to host " + vm.getPowerHostId());
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
break;
case Stopping:
case Stopped:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState()
+ " -> Running) from out-of-context transition. VM network environment may need to be reset");
break;
case Destroyed:
case Expunging:
s_logger.info("Receive power on report when VM is in destroyed or expunging state. vm: "
+ vm.getId() + ", state: " + vm.getState());
break;
case Migrating:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOnReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
break;
case Error:
default:
s_logger.info("Receive power on report when VM is in error or unexpected state. vm: "
+ vm.getId() + ", state: " + vm.getState());
break;
}
}
private void handlePowerOffReportWithNoPendingJobsOnVM(VMInstanceVO vm) {
// 1) handle left-over transitional VM states
// 2) handle out of sync stationary states, schedule force-stop to release resources
//
switch (vm.getState()) {
case Starting:
case Stopping:
case Stopped:
case Migrating:
try {
stateTransitTo(vm, VirtualMachine.Event.FollowAgentPowerOffReport, vm.getPowerHostId());
} catch (NoTransitionException e) {
s_logger.warn("Unexpected VM state transition exception, race-condition?", e);
}
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") state is sync-ed (" + vm.getState()
+ " -> Stopped) from out-of-context transition.");
// TODO: we need to forcely release all resource allocation
break;
case Running:
case Destroyed:
case Expunging:
break;
case Error:
default:
break;
}
}
private void scanStalledVMInTransitionStateOnUpHost(long hostId) {
//
// Check VM that is stuck in Starting, Stopping, Migrating states, we won't check
// VMs in expunging state (this need to be handled specially)
//
// checking condition
// 1) no pending VmWork job
// 2) on hostId host and host is UP
//
// When host is UP, soon or later we will get a report from the host about the VM,
// however, if VM is missing from the host report (it may happen in out of band changes
// or from designed behave of XS/KVM), the VM may not get a chance to run the state-sync logic
//
// Therefor, we will scan thoses VMs on UP host based on last update timestamp, if the host is UP
// and a VM stalls for status update, we will consider them to be powered off
// (which is relatively safe to do so)
long stallThresholdInMs = VmJobStateReportInterval.value() + (VmJobStateReportInterval.value() >> 1);
Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - stallThresholdInMs);
List<Long> mostlikelyStoppedVMs = listStalledVMInTransitionStateOnUpHost(hostId, cutTime);
for (Long vmId : mostlikelyStoppedVMs) {
VMInstanceVO vm = _vmDao.findById(vmId);
assert (vm != null);
handlePowerOffReportWithNoPendingJobsOnVM(vm);
}
List<Long> vmsWithRecentReport = listVMInTransitionStateWithRecentReportOnUpHost(hostId, cutTime);
for (Long vmId : vmsWithRecentReport) {
VMInstanceVO vm = _vmDao.findById(vmId);
assert (vm != null);
if (vm.getPowerState() == PowerState.PowerOn)
handlePowerOnReportWithNoPendingJobsOnVM(vm);
else
handlePowerOffReportWithNoPendingJobsOnVM(vm);
}
}
private void scanStalledVMInTransitionStateOnDisconnectedHosts() {
Date cutTime = new Date(DateUtil.currentGMTTime().getTime() - VmOpWaitInterval.value() * 1000);
List<Long> stuckAndUncontrollableVMs = listStalledVMInTransitionStateOnDisconnectedHosts(cutTime);
for (Long vmId : stuckAndUncontrollableVMs) {
VMInstanceVO vm = _vmDao.findById(vmId);
// We now only alert administrator about this situation
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_SYNC, vm.getDataCenterId(), vm.getPodIdToDeployIn(),
VM_SYNC_ALERT_SUBJECT, "VM " + vm.getHostName() + "(" + vm.getInstanceName() + ") is stuck in " + vm.getState()
+ " state and its host is unreachable for too long");
}
}
// VMs that in transitional state without recent power state report
private List<Long> listStalledVMInTransitionStateOnUpHost(long hostId, Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " +
"AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " +
"AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
"AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List<Long> l = new ArrayList<Long>();
TransactionLegacy txn = null;
try {
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, hostId);
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime));
pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
} finally {
if (txn != null)
txn.close();
}
return l;
}
// VMs that in transitional state and recently have power state update
private List<Long> listVMInTransitionStateWithRecentReportOnUpHost(long hostId, Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " +
"AND h.id = ? AND i.power_state_update_time > ? AND i.host_id = h.id " +
"AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
"AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List<Long> l = new ArrayList<Long>();
TransactionLegacy txn = null;
try {
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, hostId);
pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime));
pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
return l;
} finally {
if (txn != null)
txn.close();
}
}
private List<Long> listStalledVMInTransitionStateOnDisconnectedHosts(Date cutTime) {
String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status != 'UP' " +
"AND i.power_state_update_time < ? AND i.host_id = h.id " +
"AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " +
"AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)";
List<Long> l = new ArrayList<Long>();
TransactionLegacy txn = null;
try {
txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime));
pstmt.setInt(2, JobInfo.Status.IN_PROGRESS.ordinal());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
return l;
} finally {
if (txn != null)
txn.close();
}
}
//
// VM operation based on new sync model
//
public class VmStateSyncOutcome extends OutcomeImpl<VirtualMachine> {
private long _vmId;
public VmStateSyncOutcome(final AsyncJob job, final PowerState desiredPowerState, final long vmId, final Long srcHostIdForMigration) {
super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
VMInstanceVO instance = _vmDao.findById(vmId);
if (instance.getPowerState() == desiredPowerState && (srcHostIdForMigration != null && instance.getPowerHostId() != srcHostIdForMigration))
return true;
return false;
}
}, Topics.VM_POWER_STATE, AsyncJob.Topics.JOB_STATE);
_vmId = vmId;
}
@Override
protected VirtualMachine retrieve() {
return _vmDao.findById(_vmId);
}
}
public class VmJobSyncOutcome extends OutcomeImpl<VirtualMachine> {
private long _vmId;
public VmJobSyncOutcome(final AsyncJob job, final long vmId) {
super(VirtualMachine.class, job, VmJobCheckInterval.value(), new Predicate() {
@Override
public boolean checkCondition() {
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
assert (jobVo != null);
if (jobVo == null || jobVo.getStatus() != JobInfo.Status.IN_PROGRESS)
return true;
return false;
}
}, AsyncJob.Topics.JOB_STATE);
_vmId = vmId;
}
@Override
protected VirtualMachine retrieve() {
return _vmDao.findById(_vmId);
}
}
public Throwable retrieveExecutionException(AsyncJob job) {
assert (job != null);
assert (job.getDispatcher().equals(VmWorkConstants.VM_WORK_JOB_DISPATCHER));
AsyncJobVO jobVo = _entityMgr.findById(AsyncJobVO.class, job.getId());
if (jobVo != null && jobVo.getResult() != null) {
Object obj = JobSerializerHelper.fromSerializedString(job.getResult());
if (obj != null && obj instanceof Throwable)
return (Throwable)obj;
}
return null;
}
//
// TODO build a common pattern to reduce code duplication in following methods
// no time for this at current iteration
//
public Outcome<VirtualMachine> startVmThroughJobQueue(final String vmUuid,
final Map<VirtualMachineProfile.Param, Object> params,
final DeploymentPlan planToDeploy) {
final CallContext context = CallContext.current();
final User callingUser = context.getCallingUser();
final Account callingAccount = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
VmWorkJobVO workJob = null;
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance,
vm.getId(), VmWorkStart.class.getName());
if (pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkStart.class.getName());
workJob.setAccountId(callingAccount.getId());
workJob.setUserId(callingUser.getId());
workJob.setStep(VmWorkJobVO.Step.Starting);
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkStart workInfo = new VmWorkStart(callingUser.getId(), callingAccount.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER);
workInfo.setPlan(planToDeploy);
workInfo.setParams(params);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
// Transaction syntax sugar has a cost here
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOn, vm.getId(), null);
}
public Outcome<VirtualMachine> stopVmThroughJobQueue(final String vmUuid, final boolean cleanup) {
final CallContext context = CallContext.current();
final Account account = context.getCallingAccount();
final User user = context.getCallingUser();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkStop.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkStop.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setStep(VmWorkJobVO.Step.Prepare);
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, cleanup);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOff, vm.getId(), null);
}
public Outcome<VirtualMachine> rebootVmThroughJobQueue(final String vmUuid,
final Map<VirtualMachineProfile.Param, Object> params) {
final CallContext context = CallContext.current();
final Account account = context.getCallingAccount();
final User user = context.getCallingUser();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkReboot.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkReboot.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setStep(VmWorkJobVO.Step.Prepare);
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkReboot workInfo = new VmWorkReboot(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, params);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
vm.getId());
}
public Outcome<VirtualMachine> migrateVmThroughJobQueue(final String vmUuid, final long srcHostId, final DeployDestination dest) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkMigrate.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrate.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkMigrate workInfo = new VmWorkMigrate(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOn, vm.getId(), vm.getPowerHostId());
}
public Outcome<VirtualMachine> migrateVmWithStorageThroughJobQueue(
final String vmUuid, final long srcHostId, final long destHostId,
final Map<Volume, StoragePool> volumeToPool) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkMigrateWithStorage.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrate.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, destHostId, volumeToPool);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmStateSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"),
VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId);
}
public Outcome<VirtualMachine> migrateVmForScaleThroughJobQueue(
final String vmUuid, final long srcHostId, final DeployDestination dest, final Long newSvcOfferingId) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkMigrateForScale.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkMigrate.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkMigrateForScale workInfo = new VmWorkMigrateForScale(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, dest, newSvcOfferingId);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> migrateVmStorageThroughJobQueue(
final String vmUuid, final StoragePool destPool) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkStorageMigration.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkStorageMigration.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkStorageMigration workInfo = new VmWorkStorageMigration(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, destPool);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> addVmToNetworkThroughJobQueue(
final VirtualMachine vm, final Network network, final NicProfile requested) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkAddVmToNetwork.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkAddVmToNetwork.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkAddVmToNetwork workInfo = new VmWorkAddVmToNetwork(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, requested);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> removeNicFromVmThroughJobQueue(
final VirtualMachine vm, final Nic nic) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkRemoveNicFromVm.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkRemoveNicFromVm.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkRemoveNicFromVm workInfo = new VmWorkRemoveNicFromVm(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, nic);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> removeVmFromNetworkThroughJobQueue(
final VirtualMachine vm, final Network network, final URI broadcastUri) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkRemoveVmFromNetwork.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkRemoveVmFromNetwork.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkRemoveVmFromNetwork workInfo = new VmWorkRemoveVmFromNetwork(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, network, broadcastUri);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
public Outcome<VirtualMachine> reconfigureVmThroughJobQueue(
final String vmUuid, final ServiceOffering oldServiceOffering, final boolean reconfiguringOnExistingHost) {
final CallContext context = CallContext.current();
final User user = context.getCallingUser();
final Account account = context.getCallingAccount();
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_vmDao.lockRow(vm.getId(), true);
List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
VirtualMachine.Type.Instance, vm.getId(),
VmWorkReconfigure.class.getName());
VmWorkJobVO workJob = null;
if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
assert (pendingWorkJobs.size() == 1);
workJob = pendingWorkJobs.get(0);
} else {
workJob = new VmWorkJobVO(context.getContextId());
workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
workJob.setCmd(VmWorkReconfigure.class.getName());
workJob.setAccountId(account.getId());
workJob.setUserId(user.getId());
workJob.setVmType(vm.getType());
workJob.setVmInstanceId(vm.getId());
// save work context info (there are some duplications)
VmWorkReconfigure workInfo = new VmWorkReconfigure(user.getId(), account.getId(), vm.getId(),
VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, oldServiceOffering, reconfiguringOnExistingHost);
workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
_jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
}
context.putContextParameter("workJob", workJob);
context.putContextParameter("jobId", new Long(workJob.getId()));
}
});
final long jobId = (Long)context.getContextParameter("jobId");
AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(jobId);
return new VmJobSyncOutcome((VmWorkJobVO)context.getContextParameter("workJob"), vm.getId());
}
@Override
public Pair<JobInfo.Status, String> handleVmWorkJob(AsyncJob job, VmWork work) throws Exception {
VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId());
if (vm == null) {
s_logger.info("Unable to find vm " + work.getVmId());
}
assert (vm != null);
if (work instanceof VmWorkStart) {
VmWorkStart workStart = (VmWorkStart)work;
orchestrateStart(vm.getUuid(), workStart.getParams(), workStart.getPlan(), null);
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkStop) {
VmWorkStop workStop = (VmWorkStop)work;
orchestrateStop(vm.getUuid(), workStop.isCleanup());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkMigrate) {
VmWorkMigrate workMigrate = (VmWorkMigrate)work;
orchestrateMigrate(vm.getUuid(), workMigrate.getSrcHostId(), workMigrate.getDeployDestination());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkMigrateWithStorage) {
VmWorkMigrateWithStorage workMigrateWithStorage = (VmWorkMigrateWithStorage)work;
orchestrateMigrateWithStorage(vm.getUuid(),
workMigrateWithStorage.getSrcHostId(),
workMigrateWithStorage.getDestHostId(),
workMigrateWithStorage.getVolumeToPool());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkMigrateForScale) {
VmWorkMigrateForScale workMigrateForScale = (VmWorkMigrateForScale)work;
orchestrateMigrateForScale(vm.getUuid(),
workMigrateForScale.getSrcHostId(),
workMigrateForScale.getDeployDestination(),
workMigrateForScale.getNewServiceOfferringId());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkReboot) {
VmWorkReboot workReboot = (VmWorkReboot)work;
orchestrateReboot(vm.getUuid(), workReboot.getParams());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkAddVmToNetwork) {
VmWorkAddVmToNetwork workAddVmToNetwork = (VmWorkAddVmToNetwork)work;
NicProfile nic = orchestrateAddVmToNetwork(vm, workAddVmToNetwork.getNetwork(),
workAddVmToNetwork.getRequestedNicProfile());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, JobSerializerHelper.toObjectSerializedString(nic));
} else if (work instanceof VmWorkRemoveNicFromVm) {
VmWorkRemoveNicFromVm workRemoveNicFromVm = (VmWorkRemoveNicFromVm)work;
boolean result = orchestrateRemoveNicFromVm(vm, workRemoveNicFromVm.getNic());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
JobSerializerHelper.toObjectSerializedString(new Boolean(result)));
} else if (work instanceof VmWorkRemoveVmFromNetwork) {
VmWorkRemoveVmFromNetwork workRemoveVmFromNetwork = (VmWorkRemoveVmFromNetwork)work;
boolean result = orchestrateRemoveVmFromNetwork(vm,
workRemoveVmFromNetwork.getNetwork(), workRemoveVmFromNetwork.getBroadcastUri());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED,
JobSerializerHelper.toObjectSerializedString(new Boolean(result)));
} else if (work instanceof VmWorkReconfigure) {
VmWorkReconfigure workReconfigure = (VmWorkReconfigure)work;
reConfigureVm(vm.getUuid(), workReconfigure.getNewServiceOffering(),
workReconfigure.isSameHost());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else if (work instanceof VmWorkStorageMigration) {
VmWorkStorageMigration workStorageMigration = (VmWorkStorageMigration)work;
orchestrateStorageMigration(vm.getUuid(), workStorageMigration.getDestStoragePool());
return new Pair<JobInfo.Status, String>(JobInfo.Status.SUCCEEDED, null);
} else {
RuntimeException e = new RuntimeException("Unsupported VM work command: " + job.getCmd());
String exceptionJson = JobSerializerHelper.toSerializedString(e);
s_logger.error("Serialize exception object into json: " + exceptionJson);
return new Pair<JobInfo.Status, String>(JobInfo.Status.FAILED, exceptionJson);
}
}
}
| CLOUDSTACK-5002: unable to destroy vm ;VM destroy failed in Stop i-2-59-VM Command due to You gave an invalid object reference. The object may have recently been deleted.
This is happening as concurrent operations are happening on the same VM. Earlier this was not seen as all vm operations were synchronized at agent layer. By making execute.in.sequence
global config to false this restriction is no longer there. In the latest code operations to a single vm are synchronized by maintaining a job queue. In some scenarios the destroy vm operation
was not going through this job queue mechanism and so was resulting in failures due to simultaneous operations.
| engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java | CLOUDSTACK-5002: unable to destroy vm ;VM destroy failed in Stop i-2-59-VM Command due to You gave an invalid object reference. The object may have recently been deleted. | <ide><path>ngine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java
<ide> return;
<ide> }
<ide>
<del> advanceStop(vm, false);
<add> advanceStop(vm.getUuid(), false);
<ide>
<ide> try {
<ide> if (!stateTransitTo(vm, VirtualMachine.Event.ExpungeOperation, vm.getHostId())) {
<ide> s_logger.debug("Destroying vm " + vm);
<ide> }
<ide>
<del> advanceStop(vm, VmDestroyForcestop.value());
<add> advanceStop(vmUuid, VmDestroyForcestop.value());
<ide>
<ide> if (!_vmSnapshotMgr.deleteAllVMSnapshots(vm.getId(), null)) {
<ide> s_logger.debug("Unable to delete all snapshots for " + vm);
<ide> throw new CloudRuntimeException("Unable to delete vm snapshots for " + vm);
<ide> }
<ide>
<add> // reload the vm object from db
<add> vm = _vmDao.findByUuid(vmUuid);
<ide> try {
<ide> if (!stateTransitTo(vm, VirtualMachine.Event.DestroyRequested, vm.getHostId())) {
<ide> s_logger.debug("Unable to destroy the vm because it is not in the correct state: " + vm);
<ide> }
<ide>
<ide> try {
<del> advanceStop(vm, true);
<add> advanceStop(vmUuid, true);
<ide> throw new CloudRuntimeException("Unable to migrate " + vm);
<ide> } catch (ResourceUnavailableException e) {
<ide> s_logger.debug("Unable to stop VM due to " + e.getMessage());
<ide> if (agentState == State.Shutdowned) {
<ide> if (serverState == State.Running || serverState == State.Starting || serverState == State.Stopping) {
<ide> try {
<del> advanceStop(vm, true);
<add> advanceStop(vm.getUuid(), true);
<ide> } catch (AgentUnavailableException e) {
<ide> assert (false) : "How do we hit this with forced on?";
<ide> return null;
<ide> _vmDao.lockRow(vm.getId(), true);
<ide>
<ide> List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(
<del> VirtualMachine.Type.Instance, vm.getId(),
<add> vm.getType(), vm.getId(),
<ide> VmWorkStop.class.getName());
<ide>
<ide> VmWorkJobVO workJob = null; |
|
Java | apache-2.0 | c99f1835e3eab3b6cdfdf00ca679cb27f530d6e8 | 0 | lasombra/rhiot,rhiot/rhiot,rhiot/rhiot,rhiot/rhiot,rhiot/rhiot,rimolive/rhiot,finiteloopme/rhiot,rimolive/rhiot,rimolive/rhiot,lasombra/rhiot,krissman/rhiot,rhiot/rhiot,krissman/rhiot,krissman/rhiot,rimolive/rhiot,finiteloopme/rhiot,rhiot/rhiot,rhiot/rhiot,krissman/rhiot,rimolive/rhiot,rimolive/rhiot,krissman/rhiot,krissman/rhiot,finiteloopme/rhiot,krissman/rhiot,rimolive/rhiot,lasombra/rhiot,lasombra/rhiot,finiteloopme/rhiot | /**
* Licensed to the Rhiot under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rhiot.component.deviceio.gpio;
import io.rhiot.component.deviceio.DeviceIOConstants;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultProducer;
import jdk.dio.ClosedDeviceException;
import jdk.dio.UnavailableDeviceException;
import jdk.dio.gpio.GPIOPin;
import jdk.dio.gpio.GPIOPinConfig;
/**
* The DeviceIO GPIO producer.
*/
public class GPIOProducer extends DefaultProducer {
private GPIOPin pin = null;
private ExecutorService pool;
public GPIOProducer(GPIOEndpoint endpoint, GPIOPin pin) {
super(endpoint);
this.pin = pin;
this.pool = this.getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadExecutor(this,
DeviceIOConstants.CAMEL_DEVICE_IO_THREADPOOL + pin.getDescriptor().getID());
}
protected GPIOAction resolveAction(Message message) {
if (message.getHeaders().containsKey(DeviceIOConstants.CAMEL_DEVICE_IO_ACTION)) {
// Exchange Action
return message.getHeader(DeviceIOConstants.CAMEL_DEVICE_IO_ACTION, GPIOAction.class);
} else {
return getEndpoint().getAction(); // Endpoint Action
}
}
@Override
protected void doShutdown() throws Exception {
// 2 x (delay + timeout) + 5s
long timeToWait = (getEndpoint().getDelay() + getEndpoint().getDuration()) * 2 + 5000;
log.debug("Wait for {} ms", timeToWait);
pool.awaitTermination(timeToWait, TimeUnit.MILLISECONDS);
pin.setValue(getEndpoint().isShutdownState());
pin.close(); // TODO check this part
log.debug("Pin {} {}", pin.getDescriptor().getID(), pin.getValue());
}
/**
* Process the message
*/
@Override
public void process(Exchange exchange) throws Exception {
log.debug(exchange.toString());
if (pin instanceof GPIOPin) {
GPIOAction messageAction = resolveAction(exchange.getIn());
if (messageAction != null) {
switch (messageAction) {
case HIGH:
setValue(true);
break;
case LOW:
setValue(false);
break;
case TOGGLE:
setValue(!pin.getValue());
break;
case BLINK:
pool.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(getEndpoint().getDelay());
pin.setValue(!pin.getValue());
Thread.sleep(getEndpoint().getDuration());
pin.setValue(!pin.getValue());
} catch (Exception e) {
log.error("Thread interruption into BLINK sequence", e);
}
}
});
break;
default:
break;
}
} else {
if (pin.getDirection() == GPIOPinConfig.DIR_OUTPUT_ONLY && exchange.getIn().getBody() != null) {
setValue(exchange.getIn().getBody(Boolean.class));
} else if ((pin.getDirection() == GPIOPinConfig.DIR_OUTPUT_ONLY && exchange.getIn().getBody() == null)
|| pin.getDirection() == GPIOPinConfig.DIR_INPUT_ONLY) {
exchange.getIn().setBody(pin.getValue(), Boolean.class);
exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_PIN, pin.getDescriptor().getID());
exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_NAME, pin.getDescriptor().getName());
exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_TIMESTAMP, System.currentTimeMillis());
}
}
}
}
private void setValue(boolean b) throws UnavailableDeviceException, ClosedDeviceException, IOException {
pin.setValue(b);
}
public void setPin(GPIOPin pin) {
this.pin = pin;
}
public GPIOPin getPin() {
return pin;
}
@Override
public GPIOEndpoint getEndpoint() {
return (GPIOEndpoint) super.getEndpoint();
}
}
| components/camel-device-io/src/main/java/io/rhiot/component/deviceio/gpio/GPIOProducer.java | /**
* Licensed to the Rhiot under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rhiot.component.deviceio.gpio;
import io.rhiot.component.deviceio.DeviceIOConstants;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultProducer;
import jdk.dio.ClosedDeviceException;
import jdk.dio.UnavailableDeviceException;
import jdk.dio.gpio.GPIOPin;
import jdk.dio.gpio.GPIOPinConfig;
/**
* The DeviceIO GPIO producer.
*/
public class GPIOProducer extends DefaultProducer {
private GPIOEndpoint endpoint;
private GPIOPin pin = null;
private ExecutorService pool;
public GPIOProducer(GPIOEndpoint endpoint, GPIOPin pin) {
super(endpoint);
this.endpoint = endpoint;
this.pin = pin;
this.pool = this.getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadExecutor(this,
DeviceIOConstants.CAMEL_DEVICE_IO_THREADPOOL + pin.getDescriptor().getID());
}
protected GPIOAction resolveAction(Message message) {
if (message.getHeaders().containsKey(DeviceIOConstants.CAMEL_DEVICE_IO_ACTION)) {
// Exchange Action
return message.getHeader(DeviceIOConstants.CAMEL_DEVICE_IO_ACTION, GPIOAction.class);
} else {
return endpoint.getAction(); // Endpoint Action
}
}
@Override
protected void doShutdown() throws Exception {
// 2 x (delay + timeout) + 5s
long timeToWait = (((GPIOEndpoint) getEndpoint()).getDelay() + ((GPIOEndpoint) getEndpoint()).getDuration()) * 2
+ 5000;
log.debug("Wait for {} ms", timeToWait);
pool.awaitTermination(timeToWait, TimeUnit.MILLISECONDS);
pin.setValue(((GPIOEndpoint) getEndpoint()).isShutdownState());
pin.close(); // TODO check this part
log.debug("Pin {} {}", pin.getDescriptor().getID(), pin.getValue());
}
/**
* Process the message
*/
@Override
public void process(Exchange exchange) throws Exception {
log.debug(exchange.toString());
if (pin instanceof GPIOPin) {
GPIOAction messageAction = resolveAction(exchange.getIn());
if (messageAction != null) {
switch (messageAction) {
case HIGH:
setValue(true);
break;
case LOW:
setValue(false);
break;
case TOGGLE:
setValue(!pin.getValue());
break;
case BLINK:
pool.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(((GPIOEndpoint) getEndpoint()).getDelay());
pin.setValue(!pin.getValue());
Thread.sleep(((GPIOEndpoint) getEndpoint()).getDuration());
pin.setValue(!pin.getValue());
} catch (Exception e) {
log.error("Thread interruption into BLINK sequence", e);
}
}
});
break;
default:
break;
}
} else {
if (pin.getDirection() == GPIOPinConfig.DIR_OUTPUT_ONLY && exchange.getIn().getBody() != null) {
setValue(exchange.getIn().getBody(Boolean.class));
} else if ((pin.getDirection() == GPIOPinConfig.DIR_OUTPUT_ONLY && exchange.getIn().getBody() == null)
|| pin.getDirection() == GPIOPinConfig.DIR_INPUT_ONLY) {
exchange.getIn().setBody(pin.getValue(), Boolean.class);
exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_PIN, pin.getDescriptor().getID());
exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_NAME, pin.getDescriptor().getName());
exchange.getIn().setHeader(DeviceIOConstants.CAMEL_DEVICE_IO_TIMESTAMP, System.currentTimeMillis());
}
}
}
}
private void setValue(boolean b) throws UnavailableDeviceException, ClosedDeviceException, IOException {
pin.setValue(b);
}
public void setPin(GPIOPin pin) {
this.pin = pin;
}
public GPIOPin getPin() {
return pin;
}
}
| refactor
| components/camel-device-io/src/main/java/io/rhiot/component/deviceio/gpio/GPIOProducer.java | refactor | <ide><path>omponents/camel-device-io/src/main/java/io/rhiot/component/deviceio/gpio/GPIOProducer.java
<ide> */
<ide> public class GPIOProducer extends DefaultProducer {
<ide>
<del> private GPIOEndpoint endpoint;
<ide> private GPIOPin pin = null;
<ide> private ExecutorService pool;
<ide>
<ide> public GPIOProducer(GPIOEndpoint endpoint, GPIOPin pin) {
<ide> super(endpoint);
<del> this.endpoint = endpoint;
<ide> this.pin = pin;
<ide> this.pool = this.getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadExecutor(this,
<ide> DeviceIOConstants.CAMEL_DEVICE_IO_THREADPOOL + pin.getDescriptor().getID());
<ide> // Exchange Action
<ide> return message.getHeader(DeviceIOConstants.CAMEL_DEVICE_IO_ACTION, GPIOAction.class);
<ide> } else {
<del> return endpoint.getAction(); // Endpoint Action
<add> return getEndpoint().getAction(); // Endpoint Action
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> protected void doShutdown() throws Exception {
<ide> // 2 x (delay + timeout) + 5s
<del> long timeToWait = (((GPIOEndpoint) getEndpoint()).getDelay() + ((GPIOEndpoint) getEndpoint()).getDuration()) * 2
<del> + 5000;
<add> long timeToWait = (getEndpoint().getDelay() + getEndpoint().getDuration()) * 2 + 5000;
<ide> log.debug("Wait for {} ms", timeToWait);
<ide> pool.awaitTermination(timeToWait, TimeUnit.MILLISECONDS);
<del> pin.setValue(((GPIOEndpoint) getEndpoint()).isShutdownState());
<add> pin.setValue(getEndpoint().isShutdownState());
<ide> pin.close(); // TODO check this part
<ide> log.debug("Pin {} {}", pin.getDescriptor().getID(), pin.getValue());
<ide> }
<ide> @Override
<ide> public void run() {
<ide> try {
<del> Thread.sleep(((GPIOEndpoint) getEndpoint()).getDelay());
<add> Thread.sleep(getEndpoint().getDelay());
<ide> pin.setValue(!pin.getValue());
<del> Thread.sleep(((GPIOEndpoint) getEndpoint()).getDuration());
<add> Thread.sleep(getEndpoint().getDuration());
<ide> pin.setValue(!pin.getValue());
<ide> } catch (Exception e) {
<ide> log.error("Thread interruption into BLINK sequence", e);
<ide> public GPIOPin getPin() {
<ide> return pin;
<ide> }
<add>
<add> @Override
<add> public GPIOEndpoint getEndpoint() {
<add> return (GPIOEndpoint) super.getEndpoint();
<add> }
<add>
<ide> } |
|
Java | mit | 4906e9102bac087d262ad3a3d11cbe2dcb18882d | 0 | pearlqueen/java-simple-mvc | /**
* Copyright (c) 2010 Daniel Murphy
*
* 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.
*/
/**
* Created at 2:47:16 PM, Apr 5, 2010
*/
package com.dmurph.mvc.util;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import com.dmurph.mvc.ICloneable;
import com.dmurph.mvc.IDirtyable;
import com.dmurph.mvc.IModel;
import com.dmurph.mvc.IRevertable;
/**
* A full mvc implementation of an {@link ArrayList}. Supports all operations in {@link ICloneable}, {@link IDirtyable},
* and {@link IRevertable}. Also fires property change events for the size of the array ({@link #SIZE}) and the dirty value
* ({@link #DIRTY}), and if an element in the array changed ({@link #ELEMENT}).
*
* @author Daniel Murphy
*/
public class MVCArrayList<E extends Object> extends ArrayList<E> implements IModel, ICloneable, IDirtyable, IRevertable {
private static final long serialVersionUID = 4890270966369581329L;
/**
* Dirty property name for listening to property change events
* @see #addPropertyChangeListener(PropertyChangeListener)
*/
public static final String DIRTY = "ARRAY_LIST_DIRTY";
/**
* Array size property name for listening to property change events
* @see #addPropertyChangeListener(PropertyChangeListener)
*/
public static final String SIZE = "ARRAY_LIST_SIZE";
/**
* A value in the array was changed.
* @see #addPropertyChangeListener(PropertyChangeListener)
*/
public static final String ELEMENT = "ARRAY_LIST_ELEMENT_CHANGED";
private boolean dirty = false;
private final ArrayList<E> saved = new ArrayList<E>();
private final PropertyChangeSupport propertyChangeSupport;
public MVCArrayList(){
propertyChangeSupport = new PropertyChangeSupport(this);
}
@Override
public boolean add(E e) {
boolean ret = super.add(e);
firePropertyChange(SIZE, size() - 1, size());
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
@Override
public void clear() {
if(size() > 0){
int oldSize = size();
super.clear();
firePropertyChange(SIZE, oldSize, 0);
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
}
}
@Override
public E remove(int index) {
E ret = super.remove(index);
firePropertyChange(SIZE, size() - 1, size());
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
@Override
public boolean remove(Object o) {
boolean ret = super.remove(o);
firePropertyChange(SIZE, size() - 1, size());
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
@Override
public E set(int index, E element) {
E ret = super.set(index, element);
firePropertyChange(ELEMENT, ret, element);
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
/**
* Clones from another {@link ArrayList}, if the values are {@link ICloneable}, then
* they will be cloned to this one. Otherwise it's a shallow copy (just sets the same values).
* @param argOther an {@link ArrayList}
* @see com.dmurph.mvc.ICloneable#cloneFrom(com.dmurph.mvc.ICloneable)
*/
@SuppressWarnings("unchecked")
@Override
public void cloneFrom( ICloneable argOther) {
MVCArrayList<E> other = (MVCArrayList<E>) argOther;
clear();
for(E e : other){
if(e instanceof ICloneable){
add((E) ((ICloneable) e).clone());
}else{
add(e);
}
}
saved.clear();
for(E e : other.saved){
if(e instanceof ICloneable){
saved.add((E) ((ICloneable) e).clone());
}else{
saved.add(e);
}
}
this.dirty = other.dirty;
}
// do shallow clone, need to keep object references
private void setFromSaved(){
clear();
for(E e: saved){
add(e);
}
}
// do shallow clone, need to keep object references
private void setToSaved(){
saved.clear();
for(E e: this){
saved.add(e);
}
}
/**
* @see com.dmurph.mvc.IModel#addPropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(PropertyChangeListener argListener) {
propertyChangeSupport.addPropertyChangeListener(argListener);
}
/**
* @see com.dmurph.mvc.IModel#removePropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(PropertyChangeListener argListener) {
propertyChangeSupport.removePropertyChangeListener(argListener);
}
/**
* Fires a property change event. If the argOldValue == argNewValue
* or argOldValue.equals( argNewValue) then no event is thrown.
* @param argPropertyName property name, should match the get and set methods for property name
* @param argOldValue
* @param argNewValue
*/
private void firePropertyChange(String argPropertyName, Object argOldValue, Object argNewValue) {
propertyChangeSupport.firePropertyChange(argPropertyName, argOldValue, argNewValue);
}
/**
* Clones this object to another {@link MVCArrayList}. If the array values
* are also {@link ICloneable}, then they will be cloned as well. If not, the values
* are just set (shallow copy).
* @see java.util.ArrayList#clone()
*/
@Override
public ICloneable clone(){
MVCArrayList<E> other = new MVCArrayList<E>();
other.cloneFrom(this);
return other;
}
/**
* Also chacks to see if elements in this
* array are dirty, if any are {@link IDirtyable}.
* @see com.dmurph.mvc.IDirtyable#isDirty()
*/
@Override
public boolean isDirty() {
if(dirty){
return true;
}
for(E e : this){
if(e instanceof IDirtyable){
if(((IDirtyable) e).isDirty()){
return true;
}
}
}
return false;
}
/**
* Sets the dirty variable and, if argDirty is false,
* then will call {@link IDirtyable#setDirty(boolean)} on
* all {@link IDirtyable} objects in this array.
* @see com.dmurph.mvc.IDirtyable#setDirty(boolean)
*/
@Override
public boolean setDirty( boolean argDirty) {
boolean oldDirty = dirty;
dirty = argDirty;
if(!dirty){
for(E e: this){
if(e instanceof IDirtyable){
((IDirtyable) e).setDirty(dirty);
}
}
}
firePropertyChange(DIRTY, oldDirty, dirty);
return oldDirty;
}
/**
* Also calls {@link IRevertable#revertChanges()} on all
* objects in the reverted array that are {@link IRevertable}.
* @see com.dmurph.mvc.IRevertable#revertChanges()
*/
@Override
public boolean revertChanges() {
if(!isDirty()){
return false;
}
setFromSaved();
for(E e: this){
if(e instanceof IRevertable){
((IRevertable) e).revertChanges();
}
}
return true;
}
/**
* Also calls {@link IRevertable#saveChanges()()} on all
* objects in the reverted array that are {@link IRevertable}.
* @see com.dmurph.mvc.IRevertable#saveChanges()
*/
@Override
public boolean saveChanges() {
if(!isDirty()){
return false;
}
setToSaved();
for(E e: this){
if(e instanceof IRevertable){
((IRevertable) e).saveChanges();
}
}
return true;
}
}
| src/main/java/com/dmurph/mvc/util/MVCArrayList.java | /**
* Copyright (c) 2010 Daniel Murphy
*
* 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.
*/
/**
* Created at 2:47:16 PM, Apr 5, 2010
*/
package com.dmurph.mvc.util;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import com.dmurph.mvc.ICloneable;
import com.dmurph.mvc.IDirtyable;
import com.dmurph.mvc.IModel;
import com.dmurph.mvc.IRevertable;
/**
* A full mvc implementation of an arraylist. Supports all operations in {@link ICloneable}, {@link IDirtyable},
* and {@link IRevertable}. Also fires property change events when the dirty variable is changed.
*
* @author Daniel Murphy
*/
public class MVCArrayList<E extends Object> extends ArrayList<E> implements IModel, ICloneable, IDirtyable, IRevertable {
private static final long serialVersionUID = 4890270966369581329L;
/**
* Dirty property name.
*/
public static final String DIRTY = "ARRAY_LIST_DIRTY";
private boolean dirty = false;
private final ArrayList<E> orig = new ArrayList<E>();
private final PropertyChangeSupport propertyChangeSupport;
public MVCArrayList(){
propertyChangeSupport = new PropertyChangeSupport(this);
}
@Override
public boolean add(E e) {
boolean ret = super.add(e);
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
@Override
public void clear() {
if(size() > 0){
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
super.clear();
}
}
@Override
public E remove(int index) {
E ret = super.remove(index);
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
@Override
public boolean remove(Object o) {
boolean ret = super.remove(o);
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
@Override
public E set(int index, E element) {
E ret = super.set(index, element);
boolean old = dirty;
dirty = true;
firePropertyChange(DIRTY, old, dirty);
return ret;
}
/**
* Clones from another {@link ArrayList}, if the values are {@link ICloneable}, then
* they will be cloned to this one. Otherwise it's a shallow copy (just sets the same values).
* @param argOther an {@link ArrayList}
* @see com.dmurph.mvc.ICloneable#cloneFrom(com.dmurph.mvc.ICloneable)
*/
@SuppressWarnings("unchecked")
@Override
public void cloneFrom( ICloneable argOther) {
MVCArrayList<E> other = (MVCArrayList<E>) argOther;
clear();
for(E e : other){
if(e instanceof ICloneable){
add((E) ((ICloneable) e).clone());
}else{
add(e);
}
}
orig.clear();
for(E e : other.orig){
if(e instanceof ICloneable){
orig.add((E) ((ICloneable) e).clone());
}else{
orig.add(e);
}
}
}
// do shallow clone, need to keep object references
private void cloneFromOrig(){
clear();
for(E e: orig){
add(e);
}
}
// do shallow clone, need to keep object references
private void cloneToOrig(){
orig.clear();
for(E e: this){
orig.add(e);
}
}
/**
* @see com.dmurph.mvc.IModel#addPropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(PropertyChangeListener argListener) {
propertyChangeSupport.addPropertyChangeListener(argListener);
}
/**
* @see com.dmurph.mvc.IModel#removePropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(PropertyChangeListener argListener) {
propertyChangeSupport.removePropertyChangeListener(argListener);
}
/**
* Fires a property change event. If the argOldValue == argNewValue
* or argOldValue.equals( argNewValue) then no event is thrown.
* @param argPropertyName property name, should match the get and set methods for property name
* @param argOldValue
* @param argNewValue
*/
private void firePropertyChange(String argPropertyName, Object argOldValue, Object argNewValue) {
propertyChangeSupport.firePropertyChange(argPropertyName, argOldValue, argNewValue);
}
/**
* Clones this object to another {@link MVCArrayList}. If the array values
* are also {@link ICloneable}, then they will be cloned as well. If not, the values
* are just set (shallow copy).
* @see java.util.ArrayList#clone()
*/
@Override
public ICloneable clone(){
MVCArrayList<E> other = new MVCArrayList<E>();
other.cloneFrom(this);
return other;
}
/**
* @see com.dmurph.mvc.IDirtyable#isDirty()
*/
@Override
public boolean isDirty() {
if(dirty){
return true;
}
for(E e : this){
if(e instanceof IDirtyable){
if(((IDirtyable) e).isDirty()){
return true;
}
}
}
return false;
}
/**
* Just sets the dirty variable
* @see com.dmurph.mvc.IDirtyable#setDirty(boolean)
*/
@Override
public boolean setDirty( boolean argDirty) {
boolean oldDirty = dirty;
dirty = argDirty;
firePropertyChange(DIRTY, oldDirty, dirty);
return oldDirty;
}
/**
* @see com.dmurph.mvc.IRevertable#revertChanges()
*/
@Override
public boolean revertChanges() {
if(!isDirty()){
return false;
}
cloneFromOrig();
for(E e: this){
if(e instanceof IRevertable){
((IRevertable) e).revertChanges();
}
}
return true;
}
/**
* @see com.dmurph.mvc.IRevertable#saveChanges()
*/
@Override
public boolean saveChanges() {
if(!isDirty()){
return false;
}
cloneToOrig();
for(E e: this){
if(e instanceof IRevertable){
((IRevertable) e).saveChanges();
}
}
return true;
}
}
| updated MVCArrayList to send size changed and element changed properties | src/main/java/com/dmurph/mvc/util/MVCArrayList.java | updated MVCArrayList to send size changed and element changed properties | <ide><path>rc/main/java/com/dmurph/mvc/util/MVCArrayList.java
<ide> import com.dmurph.mvc.IRevertable;
<ide>
<ide> /**
<del> * A full mvc implementation of an arraylist. Supports all operations in {@link ICloneable}, {@link IDirtyable},
<del> * and {@link IRevertable}. Also fires property change events when the dirty variable is changed.
<add> * A full mvc implementation of an {@link ArrayList}. Supports all operations in {@link ICloneable}, {@link IDirtyable},
<add> * and {@link IRevertable}. Also fires property change events for the size of the array ({@link #SIZE}) and the dirty value
<add> * ({@link #DIRTY}), and if an element in the array changed ({@link #ELEMENT}).
<ide> *
<ide> * @author Daniel Murphy
<ide> */
<ide> private static final long serialVersionUID = 4890270966369581329L;
<ide>
<ide> /**
<del> * Dirty property name.
<add> * Dirty property name for listening to property change events
<add> * @see #addPropertyChangeListener(PropertyChangeListener)
<ide> */
<ide> public static final String DIRTY = "ARRAY_LIST_DIRTY";
<add> /**
<add> * Array size property name for listening to property change events
<add> * @see #addPropertyChangeListener(PropertyChangeListener)
<add> */
<add> public static final String SIZE = "ARRAY_LIST_SIZE";
<add> /**
<add> * A value in the array was changed.
<add> * @see #addPropertyChangeListener(PropertyChangeListener)
<add> */
<add> public static final String ELEMENT = "ARRAY_LIST_ELEMENT_CHANGED";
<add>
<ide> private boolean dirty = false;
<ide>
<del> private final ArrayList<E> orig = new ArrayList<E>();
<add> private final ArrayList<E> saved = new ArrayList<E>();
<ide> private final PropertyChangeSupport propertyChangeSupport;
<ide>
<ide> public MVCArrayList(){
<ide> @Override
<ide> public boolean add(E e) {
<ide> boolean ret = super.add(e);
<add> firePropertyChange(SIZE, size() - 1, size());
<ide> boolean old = dirty;
<ide> dirty = true;
<ide> firePropertyChange(DIRTY, old, dirty);
<ide> @Override
<ide> public void clear() {
<ide> if(size() > 0){
<add> int oldSize = size();
<add> super.clear();
<add> firePropertyChange(SIZE, oldSize, 0);
<ide> boolean old = dirty;
<ide> dirty = true;
<ide> firePropertyChange(DIRTY, old, dirty);
<del> super.clear();
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public E remove(int index) {
<ide> E ret = super.remove(index);
<add> firePropertyChange(SIZE, size() - 1, size());
<ide> boolean old = dirty;
<ide> dirty = true;
<ide> firePropertyChange(DIRTY, old, dirty);
<ide> @Override
<ide> public boolean remove(Object o) {
<ide> boolean ret = super.remove(o);
<add> firePropertyChange(SIZE, size() - 1, size());
<ide> boolean old = dirty;
<ide> dirty = true;
<ide> firePropertyChange(DIRTY, old, dirty);
<ide> @Override
<ide> public E set(int index, E element) {
<ide> E ret = super.set(index, element);
<add> firePropertyChange(ELEMENT, ret, element);
<ide> boolean old = dirty;
<ide> dirty = true;
<ide> firePropertyChange(DIRTY, old, dirty);
<ide> add(e);
<ide> }
<ide> }
<del> orig.clear();
<del> for(E e : other.orig){
<add> saved.clear();
<add> for(E e : other.saved){
<ide> if(e instanceof ICloneable){
<del> orig.add((E) ((ICloneable) e).clone());
<add> saved.add((E) ((ICloneable) e).clone());
<ide> }else{
<del> orig.add(e);
<del> }
<del> }
<add> saved.add(e);
<add> }
<add> }
<add> this.dirty = other.dirty;
<ide> }
<ide>
<ide> // do shallow clone, need to keep object references
<del> private void cloneFromOrig(){
<add> private void setFromSaved(){
<ide> clear();
<del> for(E e: orig){
<add> for(E e: saved){
<ide> add(e);
<ide> }
<ide> }
<ide>
<ide> // do shallow clone, need to keep object references
<del> private void cloneToOrig(){
<del> orig.clear();
<add> private void setToSaved(){
<add> saved.clear();
<ide> for(E e: this){
<del> orig.add(e);
<add> saved.add(e);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> /**
<add> * Also chacks to see if elements in this
<add> * array are dirty, if any are {@link IDirtyable}.
<ide> * @see com.dmurph.mvc.IDirtyable#isDirty()
<ide> */
<ide> @Override
<ide> }
<ide>
<ide> /**
<del> * Just sets the dirty variable
<add> * Sets the dirty variable and, if argDirty is false,
<add> * then will call {@link IDirtyable#setDirty(boolean)} on
<add> * all {@link IDirtyable} objects in this array.
<ide> * @see com.dmurph.mvc.IDirtyable#setDirty(boolean)
<ide> */
<ide> @Override
<ide> public boolean setDirty( boolean argDirty) {
<ide> boolean oldDirty = dirty;
<ide> dirty = argDirty;
<add> if(!dirty){
<add> for(E e: this){
<add> if(e instanceof IDirtyable){
<add> ((IDirtyable) e).setDirty(dirty);
<add> }
<add> }
<add> }
<ide> firePropertyChange(DIRTY, oldDirty, dirty);
<ide> return oldDirty;
<ide> }
<ide>
<ide> /**
<add> * Also calls {@link IRevertable#revertChanges()} on all
<add> * objects in the reverted array that are {@link IRevertable}.
<ide> * @see com.dmurph.mvc.IRevertable#revertChanges()
<ide> */
<ide> @Override
<ide> if(!isDirty()){
<ide> return false;
<ide> }
<del> cloneFromOrig();
<add> setFromSaved();
<ide> for(E e: this){
<ide> if(e instanceof IRevertable){
<ide> ((IRevertable) e).revertChanges();
<ide> }
<ide>
<ide> /**
<add> * Also calls {@link IRevertable#saveChanges()()} on all
<add> * objects in the reverted array that are {@link IRevertable}.
<ide> * @see com.dmurph.mvc.IRevertable#saveChanges()
<ide> */
<ide> @Override
<ide> if(!isDirty()){
<ide> return false;
<ide> }
<del> cloneToOrig();
<add> setToSaved();
<ide> for(E e: this){
<ide> if(e instanceof IRevertable){
<ide> ((IRevertable) e).saveChanges(); |
|
Java | apache-2.0 | 5bfef62ab07e34cdfe68c28574e0b078a2d727e2 | 0 | DaanHoogland/cloudstack,jcshen007/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,resmo/cloudstack | // 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.cloud.template;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
import org.apache.cloudstack.engine.subsystem.api.storage.Scope;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult;
import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
import org.apache.cloudstack.framework.async.AsyncRpcContext;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.PublishScope;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.org.Grouping;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.TemplateProfile;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.storage.download.DownloadMonitor;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.UriUtils;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
@Local(value = TemplateAdapter.class)
public class HypervisorTemplateAdapter extends TemplateAdapterBase {
private final static Logger s_logger = Logger.getLogger(HypervisorTemplateAdapter.class);
@Inject
DownloadMonitor _downloadMonitor;
@Inject
AgentManager _agentMgr;
@Inject
DataStoreManager storeMgr;
@Inject
TemplateService imageService;
@Inject
TemplateDataFactory imageFactory;
@Inject
TemplateManager templateMgr;
@Inject
AlertManager alertMgr;
@Inject
VMTemplateZoneDao templateZoneDao;
@Inject
EndPointSelector _epSelector;
@Inject
DataCenterDao _dcDao;
@Inject
MessageBus _messageBus;
@Override
public String getName() {
return TemplateAdapterType.Hypervisor.getName();
}
@Override
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
if ((!url.toLowerCase().endsWith("iso")) && (!url.toLowerCase().endsWith("iso.zip")) && (!url.toLowerCase().endsWith("iso.bz2")) &&
(!url.toLowerCase().endsWith("iso.gz"))) {
throw new InvalidParameterValueException("Please specify a valid iso");
}
UriUtils.validateUrl(url);
profile.setUrl(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
return profile;
}
@Override
public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
String path = null;
try {
URL str = new URL(url);
path = str.getPath();
} catch (MalformedURLException ex) {
throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is invalid");
}
try {
checkFormat(cmd.getFormat(), url);
} catch (InvalidParameterValueException ex) {
checkFormat(cmd.getFormat(), path);
}
UriUtils.validateUrl(url);
profile.setUrl(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
return profile;
}
private void checkFormat(String format, String url) {
if ((!url.toLowerCase().endsWith("vhd")) && (!url.toLowerCase().endsWith("vhd.zip")) && (!url.toLowerCase().endsWith("vhd.bz2")) &&
(!url.toLowerCase().endsWith("vhdx")) && (!url.toLowerCase().endsWith("vhdx.gz")) &&
(!url.toLowerCase().endsWith("vhdx.bz2")) && (!url.toLowerCase().endsWith("vhdx.zip")) &&
(!url.toLowerCase().endsWith("vhd.gz")) && (!url.toLowerCase().endsWith("qcow2")) && (!url.toLowerCase().endsWith("qcow2.zip")) &&
(!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) && (!url.toLowerCase().endsWith("ova")) &&
(!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) &&
(!url.toLowerCase().endsWith("tar")) && (!url.toLowerCase().endsWith("tar.zip")) && (!url.toLowerCase().endsWith("tar.bz2")) &&
(!url.toLowerCase().endsWith("tar.gz")) && (!url.toLowerCase().endsWith("vmdk")) && (!url.toLowerCase().endsWith("vmdk.gz")) &&
(!url.toLowerCase().endsWith("vmdk.zip")) && (!url.toLowerCase().endsWith("vmdk.bz2")) && (!url.toLowerCase().endsWith("img")) &&
(!url.toLowerCase().endsWith("img.gz")) && (!url.toLowerCase().endsWith("img.zip")) && (!url.toLowerCase().endsWith("img.bz2")) &&
(!url.toLowerCase().endsWith("raw")) && (!url.toLowerCase().endsWith("raw.gz")) && (!url.toLowerCase().endsWith("raw.bz2")) &&
(!url.toLowerCase().endsWith("raw.zip"))) {
throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase());
}
if ((format.equalsIgnoreCase("vhd")
&& (!url.toLowerCase().endsWith("vhd")
&& !url.toLowerCase().endsWith("vhd.zip")
&& !url.toLowerCase().endsWith("vhd.bz2")
&& !url.toLowerCase().endsWith("vhd.gz")))
|| (format.equalsIgnoreCase("vhdx")
&& (!url.toLowerCase().endsWith("vhdx")
&& !url.toLowerCase().endsWith("vhdx.zip")
&& !url.toLowerCase().endsWith("vhdx.bz2")
&& !url.toLowerCase().endsWith("vhdx.gz")))
|| (format.equalsIgnoreCase("qcow2")
&& (!url.toLowerCase().endsWith("qcow2")
&& !url.toLowerCase().endsWith("qcow2.zip")
&& !url.toLowerCase().endsWith("qcow2.bz2")
&& !url.toLowerCase().endsWith("qcow2.gz")))
|| (format.equalsIgnoreCase("ova")
&& (!url.toLowerCase().endsWith("ova")
&& !url.toLowerCase().endsWith("ova.zip")
&& !url.toLowerCase().endsWith("ova.bz2")
&& !url.toLowerCase().endsWith("ova.gz")))
|| (format.equalsIgnoreCase("tar")
&& (!url.toLowerCase().endsWith("tar")
&& !url.toLowerCase().endsWith("tar.zip")
&& !url.toLowerCase().endsWith("tar.bz2")
&& !url.toLowerCase().endsWith("tar.gz")))
|| (format.equalsIgnoreCase("raw")
&& (!url.toLowerCase().endsWith("img")
&& !url.toLowerCase().endsWith("img.zip")
&& !url.toLowerCase().endsWith("img.bz2")
&& !url.toLowerCase().endsWith("img.gz")
&& !url.toLowerCase().endsWith("raw")
&& !url.toLowerCase().endsWith("raw.bz2")
&& !url.toLowerCase().endsWith("raw.zip")
&& !url.toLowerCase().endsWith("raw.gz")))
|| (format.equalsIgnoreCase("vmdk")
&& (!url.toLowerCase().endsWith("vmdk")
&& !url.toLowerCase().endsWith("vmdk.zip")
&& !url.toLowerCase().endsWith("vmdk.bz2")
&& !url.toLowerCase().endsWith("vmdk.gz")))
) {
throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase());
}
}
@Override
public VMTemplateVO create(TemplateProfile profile) {
// persist entry in vm_template, vm_template_details and template_zone_ref tables, not that entry at template_store_ref is not created here, and created in createTemplateAsync.
VMTemplateVO template = persistTemplate(profile);
if (template == null) {
throw new CloudRuntimeException("Unable to persist the template " + profile.getTemplate());
}
// find all eligible image stores for this zone scope
List<DataStore> imageStores = storeMgr.getImageStoresByScope(new ZoneScope(profile.getZoneId()));
if (imageStores == null || imageStores.size() == 0) {
throw new CloudRuntimeException("Unable to find image store to download template " + profile.getTemplate());
}
Set<Long> zoneSet = new HashSet<Long>();
Collections.shuffle(imageStores); // For private templates choose a random store. TODO - Have a better algorithm based on size, no. of objects, load etc.
for (DataStore imageStore : imageStores) {
// skip data stores for a disabled zone
Long zoneId = imageStore.getScope().getScopeId();
if (zoneId != null) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
s_logger.warn("Unable to find zone by id " + zoneId + ", so skip downloading template to its image store " + imageStore.getId());
continue;
}
// Check if zone is disabled
if (Grouping.AllocationState.Disabled == zone.getAllocationState()) {
s_logger.info("Zone " + zoneId + " is disabled, so skip downloading template to its image store " + imageStore.getId());
continue;
}
// We want to download private template to one of the image store in a zone
if(isPrivateTemplate(template) && zoneSet.contains(zoneId)){
continue;
}else {
zoneSet.add(zoneId);
}
}
TemplateInfo tmpl = imageFactory.getTemplate(template.getId(), imageStore);
CreateTemplateContext<TemplateApiResult> context = new CreateTemplateContext<TemplateApiResult>(null, tmpl);
AsyncCallbackDispatcher<HypervisorTemplateAdapter, TemplateApiResult> caller = AsyncCallbackDispatcher.create(this);
caller.setCallback(caller.getTarget().createTemplateAsyncCallBack(null, null));
caller.setContext(context);
imageService.createTemplateAsync(tmpl, imageStore, caller);
}
_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
return template;
}
private boolean isPrivateTemplate(VMTemplateVO template){
// if public OR featured OR system template
if(template.isPublicTemplate() || template.isFeatured() || template.getTemplateType() == TemplateType.SYSTEM)
return false;
else
return true;
}
private class CreateTemplateContext<T> extends AsyncRpcContext<T> {
final TemplateInfo template;
public CreateTemplateContext(AsyncCompletionCallback<T> callback, TemplateInfo template) {
super(callback);
this.template = template;
}
}
protected Void createTemplateAsyncCallBack(AsyncCallbackDispatcher<HypervisorTemplateAdapter, TemplateApiResult> callback,
CreateTemplateContext<TemplateApiResult> context) {
TemplateApiResult result = callback.getResult();
TemplateInfo template = context.template;
if (result.isSuccess()) {
VMTemplateVO tmplt = _tmpltDao.findById(template.getId());
// need to grant permission for public templates
if (tmplt.isPublicTemplate()) {
_messageBus.publish(_name, TemplateManager.MESSAGE_REGISTER_PUBLIC_TEMPLATE_EVENT, PublishScope.LOCAL, tmplt.getId());
}
long accountId = tmplt.getAccountId();
if (template.getSize() != null) {
// publish usage event
String etype = EventTypes.EVENT_TEMPLATE_CREATE;
if (tmplt.getFormat() == ImageFormat.ISO) {
etype = EventTypes.EVENT_ISO_CREATE;
}
// get physical size from template_store_ref table
long physicalSize = 0;
DataStore ds = template.getDataStore();
TemplateDataStoreVO tmpltStore = _tmpltStoreDao.findByStoreTemplate(ds.getId(), template.getId());
if (tmpltStore != null) {
physicalSize = tmpltStore.getPhysicalSize();
} else {
s_logger.warn("No entry found in template_store_ref for template id: " + template.getId() + " and image store id: " + ds.getId() +
" at the end of registering template!");
}
Scope dsScope = ds.getScope();
if (dsScope.getScopeType() == ScopeType.ZONE) {
if (dsScope.getScopeId() != null) {
UsageEventUtils.publishUsageEvent(etype, template.getAccountId(), dsScope.getScopeId(), template.getId(), template.getName(), null, null,
physicalSize, template.getSize(), VirtualMachineTemplate.class.getName(), template.getUuid());
} else {
s_logger.warn("Zone scope image store " + ds.getId() + " has a null scope id");
}
} else if (dsScope.getScopeType() == ScopeType.REGION) {
// publish usage event for region-wide image store using a -1 zoneId for 4.2, need to revisit post-4.2
UsageEventUtils.publishUsageEvent(etype, template.getAccountId(), -1, template.getId(), template.getName(), null, null, physicalSize,
template.getSize(), VirtualMachineTemplate.class.getName(), template.getUuid());
}
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.secondary_storage, template.getSize());
}
}
return null;
}
@Override
@DB
public boolean delete(TemplateProfile profile) {
boolean success = true;
VMTemplateVO template = profile.getTemplate();
// find all eligible image stores for this template
List<DataStore> imageStores = templateMgr.getImageStoreByTemplate(template.getId(), profile.getZoneId());
if (imageStores == null || imageStores.size() == 0) {
// already destroyed on image stores
s_logger.info("Unable to find image store still having template: " + template.getName() + ", so just mark the template removed");
} else {
// Make sure the template is downloaded to all found image stores
for (DataStore store : imageStores) {
long storeId = store.getId();
List<TemplateDataStoreVO> templateStores = _tmpltStoreDao.listByTemplateStore(template.getId(), storeId);
for (TemplateDataStoreVO templateStore : templateStores) {
if (templateStore.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
String errorMsg = "Please specify a template that is not currently being downloaded.";
s_logger.debug("Template: " + template.getName() + " is currently being downloaded to secondary storage host: " + store.getName() +
"; cant' delete it.");
throw new CloudRuntimeException(errorMsg);
}
}
}
String eventType = "";
if (template.getFormat().equals(ImageFormat.ISO)) {
eventType = EventTypes.EVENT_ISO_DELETE;
} else {
eventType = EventTypes.EVENT_TEMPLATE_DELETE;
}
for (DataStore imageStore : imageStores) {
// publish zone-wide usage event
Long sZoneId = ((ImageStoreEntity)imageStore).getDataCenterId();
if (sZoneId != null) {
UsageEventUtils.publishUsageEvent(eventType, template.getAccountId(), sZoneId, template.getId(), null, null, null);
}
s_logger.info("Delete template from image store: " + imageStore.getName());
AsyncCallFuture<TemplateApiResult> future = imageService.deleteTemplateAsync(imageFactory.getTemplate(template.getId(), imageStore));
try {
TemplateApiResult result = future.get();
success = result.isSuccess();
if (!success) {
s_logger.warn("Failed to delete the template " + template + " from the image store: " + imageStore.getName() + " due to: " + result.getResult());
break;
}
// remove from template_zone_ref
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByZoneTemplate(sZoneId, template.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
} catch (InterruptedException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
} catch (ExecutionException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
}
}
}
if (success) {
if ((imageStores.size() > 1) && (profile.getZoneId() != null)) {
//if template is stored in more than one image stores, and the zone id is not null, then don't delete other templates.
return success;
}
// delete all cache entries for this template
List<TemplateInfo> cacheTmpls = imageFactory.listTemplateOnCache(template.getId());
for (TemplateInfo tmplOnCache : cacheTmpls) {
s_logger.info("Delete template from image cache store: " + tmplOnCache.getDataStore().getName());
tmplOnCache.delete();
}
// find all eligible image stores for this template
List<DataStore> iStores = templateMgr.getImageStoreByTemplate(template.getId(), null);
if (iStores == null || iStores.size() == 0) {
// Mark template as Inactive.
template.setState(VirtualMachineTemplate.State.Inactive);
_tmpltDao.update(template.getId(), template);
// Decrement the number of templates and total secondary storage
// space used by the account
Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
_resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
_resourceLimitMgr.recalculateResourceCount(template.getAccountId(), account.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// remove its related ACL permission
Pair<Class<?>, Long> tmplt = new Pair<Class<?>, Long>(VirtualMachineTemplate.class, template.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, tmplt);
}
return success;
}
@Override
public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
TemplateProfile profile = super.prepareDelete(cmd);
VMTemplateVO template = profile.getTemplate();
Long zoneId = profile.getZoneId();
if (template.getTemplateType() == TemplateType.SYSTEM) {
throw new InvalidParameterValueException("The DomR template cannot be deleted.");
}
if (zoneId != null && (storeMgr.getImageStore(zoneId) == null)) {
throw new InvalidParameterValueException("Failed to find a secondary storage in the specified zone.");
}
return profile;
}
@Override
public TemplateProfile prepareDelete(DeleteIsoCmd cmd) {
TemplateProfile profile = super.prepareDelete(cmd);
Long zoneId = profile.getZoneId();
if (zoneId != null && (storeMgr.getImageStore(zoneId) == null)) {
throw new InvalidParameterValueException("Failed to find a secondary storage in the specified zone.");
}
return profile;
}
}
| server/src/com/cloud/template/HypervisorTemplateAdapter.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.cloud.template;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd;
import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd;
import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd;
import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.EndPointSelector;
import org.apache.cloudstack.engine.subsystem.api.storage.Scope;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService;
import org.apache.cloudstack.engine.subsystem.api.storage.TemplateService.TemplateApiResult;
import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope;
import org.apache.cloudstack.framework.async.AsyncCallFuture;
import org.apache.cloudstack.framework.async.AsyncCallbackDispatcher;
import org.apache.cloudstack.framework.async.AsyncCompletionCallback;
import org.apache.cloudstack.framework.async.AsyncRpcContext;
import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.PublishScope;
import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO;
import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity;
import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.org.Grouping;
import com.cloud.storage.ScopeType;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.TemplateProfile;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.storage.download.DownloadMonitor;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.UriUtils;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.EntityManager;
import com.cloud.utils.exception.CloudRuntimeException;
@Local(value = TemplateAdapter.class)
public class HypervisorTemplateAdapter extends TemplateAdapterBase {
private final static Logger s_logger = Logger.getLogger(HypervisorTemplateAdapter.class);
@Inject
DownloadMonitor _downloadMonitor;
@Inject
AgentManager _agentMgr;
@Inject
DataStoreManager storeMgr;
@Inject
TemplateService imageService;
@Inject
TemplateDataFactory imageFactory;
@Inject
TemplateManager templateMgr;
@Inject
AlertManager alertMgr;
@Inject
VMTemplateZoneDao templateZoneDao;
@Inject
EndPointSelector _epSelector;
@Inject
DataCenterDao _dcDao;
@Inject
MessageBus _messageBus;
@Override
public String getName() {
return TemplateAdapterType.Hypervisor.getName();
}
@Override
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
if ((!url.toLowerCase().endsWith("iso")) && (!url.toLowerCase().endsWith("iso.zip")) && (!url.toLowerCase().endsWith("iso.bz2")) &&
(!url.toLowerCase().endsWith("iso.gz"))) {
throw new InvalidParameterValueException("Please specify a valid iso");
}
UriUtils.validateUrl(url);
profile.setUrl(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
return profile;
}
@Override
public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException {
TemplateProfile profile = super.prepare(cmd);
String url = profile.getUrl();
String path = null;
try {
URL str = new URL(url);
path = str.getPath();
} catch (MalformedURLException ex) {
throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is invalid");
}
try {
checkFormat(cmd.getFormat(), url);
} catch (InvalidParameterValueException ex) {
checkFormat(cmd.getFormat(), path);
}
UriUtils.validateUrl(url);
profile.setUrl(url);
// Check that the resource limit for secondary storage won't be exceeded
_resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(cmd.getEntityOwnerId()), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
return profile;
}
private void checkFormat(String format, String url) {
if ((!url.toLowerCase().endsWith("vhd")) && (!url.toLowerCase().endsWith("vhd.zip")) && (!url.toLowerCase().endsWith("vhd.bz2")) &&
(!url.toLowerCase().endsWith("vhdx")) && (!url.toLowerCase().endsWith("vhdx.gz")) &&
(!url.toLowerCase().endsWith("vhdx.bz2")) && (!url.toLowerCase().endsWith("vhdx.zip")) &&
(!url.toLowerCase().endsWith("vhd.gz")) && (!url.toLowerCase().endsWith("qcow2")) && (!url.toLowerCase().endsWith("qcow2.zip")) &&
(!url.toLowerCase().endsWith("qcow2.bz2")) && (!url.toLowerCase().endsWith("qcow2.gz")) && (!url.toLowerCase().endsWith("ova")) &&
(!url.toLowerCase().endsWith("ova.zip")) && (!url.toLowerCase().endsWith("ova.bz2")) && (!url.toLowerCase().endsWith("ova.gz")) &&
(!url.toLowerCase().endsWith("tar")) && (!url.toLowerCase().endsWith("tar.zip")) && (!url.toLowerCase().endsWith("tar.bz2")) &&
(!url.toLowerCase().endsWith("tar.gz")) && (!url.toLowerCase().endsWith("vmdk")) && (!url.toLowerCase().endsWith("vmdk.gz")) &&
(!url.toLowerCase().endsWith("vmdk.zip")) && (!url.toLowerCase().endsWith("vmdk.bz2")) && (!url.toLowerCase().endsWith("img")) &&
(!url.toLowerCase().endsWith("img.gz")) && (!url.toLowerCase().endsWith("img.zip")) && (!url.toLowerCase().endsWith("img.bz2")) &&
(!url.toLowerCase().endsWith("raw")) && (!url.toLowerCase().endsWith("raw.gz")) && (!url.toLowerCase().endsWith("raw.bz2")) &&
(!url.toLowerCase().endsWith("raw.zip"))) {
throw new InvalidParameterValueException("Please specify a valid " + format.toLowerCase());
}
if ((format.equalsIgnoreCase("vhd")
&& (!url.toLowerCase().endsWith("vhd")
&& !url.toLowerCase().endsWith("vhd.zip")
&& !url.toLowerCase().endsWith("vhd.bz2")
&& !url.toLowerCase().endsWith("vhd.gz")))
|| (format.equalsIgnoreCase("vhdx")
&& (!url.toLowerCase().endsWith("vhdx")
&& !url.toLowerCase().endsWith("vhdx.zip")
&& !url.toLowerCase().endsWith("vhdx.bz2")
&& !url.toLowerCase().endsWith("vhdx.gz")))
|| (format.equalsIgnoreCase("qcow2")
&& (!url.toLowerCase().endsWith("qcow2")
&& !url.toLowerCase().endsWith("qcow2.zip")
&& !url.toLowerCase().endsWith("qcow2.bz2")
&& !url.toLowerCase().endsWith("qcow2.gz")))
|| (format.equalsIgnoreCase("ova")
&& (!url.toLowerCase().endsWith("ova")
&& !url.toLowerCase().endsWith("ova.zip")
&& !url.toLowerCase().endsWith("ova.bz2")
&& !url.toLowerCase().endsWith("ova.gz")))
|| (format.equalsIgnoreCase("tar")
&& (!url.toLowerCase().endsWith("tar")
&& !url.toLowerCase().endsWith("tar.zip")
&& !url.toLowerCase().endsWith("tar.bz2")
&& !url.toLowerCase().endsWith("tar.gz")))
|| (format.equalsIgnoreCase("raw")
&& (!url.toLowerCase().endsWith("img")
&& !url.toLowerCase().endsWith("img.zip")
&& !url.toLowerCase().endsWith("img.bz2")
&& !url.toLowerCase().endsWith("img.gz")
&& !url.toLowerCase().endsWith("raw")
&& !url.toLowerCase().endsWith("raw.bz2")
&& !url.toLowerCase().endsWith("raw.zip")
&& !url.toLowerCase().endsWith("raw.gz")))
|| (format.equalsIgnoreCase("vmdk")
&& (!url.toLowerCase().endsWith("vmdk")
&& !url.toLowerCase().endsWith("vmdk.zip")
&& !url.toLowerCase().endsWith("vmdk.bz2")
&& !url.toLowerCase().endsWith("vmdk.gz")))
) {
throw new InvalidParameterValueException("Please specify a valid URL. URL:" + url + " is an invalid for the format " + format.toLowerCase());
}
}
@Override
public VMTemplateVO create(TemplateProfile profile) {
// persist entry in vm_template, vm_template_details and template_zone_ref tables, not that entry at template_store_ref is not created here, and created in createTemplateAsync.
VMTemplateVO template = persistTemplate(profile);
if (template == null) {
throw new CloudRuntimeException("Unable to persist the template " + profile.getTemplate());
}
// find all eligible image stores for this zone scope
List<DataStore> imageStores = storeMgr.getImageStoresByScope(new ZoneScope(profile.getZoneId()));
if (imageStores == null || imageStores.size() == 0) {
throw new CloudRuntimeException("Unable to find image store to download template " + profile.getTemplate());
}
Set<Long> zoneSet = new HashSet<Long>();
Collections.shuffle(imageStores); // For private templates choose a random store. TODO - Have a better algorithm based on size, no. of objects, load etc.
for (DataStore imageStore : imageStores) {
// skip data stores for a disabled zone
Long zoneId = imageStore.getScope().getScopeId();
if (zoneId != null) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
s_logger.warn("Unable to find zone by id " + zoneId + ", so skip downloading template to its image store " + imageStore.getId());
continue;
}
// Check if zone is disabled
if (Grouping.AllocationState.Disabled == zone.getAllocationState()) {
s_logger.info("Zone " + zoneId + " is disabled, so skip downloading template to its image store " + imageStore.getId());
continue;
}
// We want to download private template to one of the image store in a zone
if(isPrivateTemplate(template) && zoneSet.contains(zoneId)){
continue;
}else {
zoneSet.add(zoneId);
}
}
TemplateInfo tmpl = imageFactory.getTemplate(template.getId(), imageStore);
CreateTemplateContext<TemplateApiResult> context = new CreateTemplateContext<TemplateApiResult>(null, tmpl);
AsyncCallbackDispatcher<HypervisorTemplateAdapter, TemplateApiResult> caller = AsyncCallbackDispatcher.create(this);
caller.setCallback(caller.getTarget().createTemplateAsyncCallBack(null, null));
caller.setContext(context);
imageService.createTemplateAsync(tmpl, imageStore, caller);
}
_resourceLimitMgr.incrementResourceCount(profile.getAccountId(), ResourceType.template);
return template;
}
private boolean isPrivateTemplate(VMTemplateVO template){
// if public OR featured OR system template
if(template.isPublicTemplate() || template.isFeatured() || template.getTemplateType() == TemplateType.SYSTEM)
return false;
else
return true;
}
private class CreateTemplateContext<T> extends AsyncRpcContext<T> {
final TemplateInfo template;
public CreateTemplateContext(AsyncCompletionCallback<T> callback, TemplateInfo template) {
super(callback);
this.template = template;
}
}
protected Void createTemplateAsyncCallBack(AsyncCallbackDispatcher<HypervisorTemplateAdapter, TemplateApiResult> callback,
CreateTemplateContext<TemplateApiResult> context) {
TemplateApiResult result = callback.getResult();
TemplateInfo template = context.template;
if (result.isSuccess()) {
VMTemplateVO tmplt = _tmpltDao.findById(template.getId());
// need to grant permission for public templates
if (tmplt.isPublicTemplate()) {
_messageBus.publish(_name, TemplateManager.MESSAGE_REGISTER_PUBLIC_TEMPLATE_EVENT, PublishScope.LOCAL, tmplt.getId());
}
long accountId = tmplt.getAccountId();
if (template.getSize() != null) {
// publish usage event
String etype = EventTypes.EVENT_TEMPLATE_CREATE;
if (tmplt.getFormat() == ImageFormat.ISO) {
etype = EventTypes.EVENT_ISO_CREATE;
}
// get physical size from template_store_ref table
long physicalSize = 0;
DataStore ds = template.getDataStore();
TemplateDataStoreVO tmpltStore = _tmpltStoreDao.findByStoreTemplate(ds.getId(), template.getId());
if (tmpltStore != null) {
physicalSize = tmpltStore.getPhysicalSize();
} else {
s_logger.warn("No entry found in template_store_ref for template id: " + template.getId() + " and image store id: " + ds.getId() +
" at the end of registering template!");
}
Scope dsScope = ds.getScope();
if (dsScope.getScopeType() == ScopeType.ZONE) {
if (dsScope.getScopeId() != null) {
UsageEventUtils.publishUsageEvent(etype, template.getAccountId(), dsScope.getScopeId(), template.getId(), template.getName(), null, null,
physicalSize, template.getSize(), VirtualMachineTemplate.class.getName(), template.getUuid());
} else {
s_logger.warn("Zone scope image store " + ds.getId() + " has a null scope id");
}
} else if (dsScope.getScopeType() == ScopeType.REGION) {
// publish usage event for region-wide image store using a -1 zoneId for 4.2, need to revisit post-4.2
UsageEventUtils.publishUsageEvent(etype, template.getAccountId(), -1, template.getId(), template.getName(), null, null, physicalSize,
template.getSize(), VirtualMachineTemplate.class.getName(), template.getUuid());
}
_resourceLimitMgr.incrementResourceCount(accountId, ResourceType.secondary_storage, template.getSize());
}
}
return null;
}
@Override
@DB
public boolean delete(TemplateProfile profile) {
boolean success = true;
VMTemplateVO template = profile.getTemplate();
// find all eligible image stores for this template
List<DataStore> imageStores = templateMgr.getImageStoreByTemplate(template.getId(), profile.getZoneId());
if (imageStores == null || imageStores.size() == 0) {
// already destroyed on image stores
s_logger.info("Unable to find image store still having template: " + template.getName() + ", so just mark the template removed");
} else {
// Make sure the template is downloaded to all found image stores
for (DataStore store : imageStores) {
long storeId = store.getId();
List<TemplateDataStoreVO> templateStores = _tmpltStoreDao.listByTemplateStore(template.getId(), storeId);
for (TemplateDataStoreVO templateStore : templateStores) {
if (templateStore.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
String errorMsg = "Please specify a template that is not currently being downloaded.";
s_logger.debug("Template: " + template.getName() + " is currently being downloaded to secondary storage host: " + store.getName() +
"; cant' delete it.");
throw new CloudRuntimeException(errorMsg);
}
}
}
String eventType = "";
if (template.getFormat().equals(ImageFormat.ISO)) {
eventType = EventTypes.EVENT_ISO_DELETE;
} else {
eventType = EventTypes.EVENT_TEMPLATE_DELETE;
}
for (DataStore imageStore : imageStores) {
// publish zone-wide usage event
Long sZoneId = ((ImageStoreEntity)imageStore).getDataCenterId();
if (sZoneId != null) {
UsageEventUtils.publishUsageEvent(eventType, template.getAccountId(), sZoneId, template.getId(), null, null, null);
}
s_logger.info("Delete template from image store: " + imageStore.getName());
AsyncCallFuture<TemplateApiResult> future = imageService.deleteTemplateAsync(imageFactory.getTemplate(template.getId(), imageStore));
try {
TemplateApiResult result = future.get();
success = result.isSuccess();
if (!success) {
s_logger.warn("Failed to delete the template " + template + " from the image store: " + imageStore.getName() + " due to: " + result.getResult());
break;
}
// remove from template_zone_ref
List<VMTemplateZoneVO> templateZones = templateZoneDao.listByZoneTemplate(sZoneId, template.getId());
if (templateZones != null) {
for (VMTemplateZoneVO templateZone : templateZones) {
templateZoneDao.remove(templateZone.getId());
}
}
} catch (InterruptedException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
} catch (ExecutionException e) {
s_logger.debug("delete template Failed", e);
throw new CloudRuntimeException("delete template Failed", e);
}
}
}
if (success) {
// delete all cache entries for this template
List<TemplateInfo> cacheTmpls = imageFactory.listTemplateOnCache(template.getId());
for (TemplateInfo tmplOnCache : cacheTmpls) {
s_logger.info("Delete template from image cache store: " + tmplOnCache.getDataStore().getName());
tmplOnCache.delete();
}
// find all eligible image stores for this template
List<DataStore> iStores = templateMgr.getImageStoreByTemplate(template.getId(), null);
if (iStores == null || iStores.size() == 0) {
// Mark template as Inactive.
template.setState(VirtualMachineTemplate.State.Inactive);
_tmpltDao.update(template.getId(), template);
// Decrement the number of templates and total secondary storage
// space used by the account
Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
_resourceLimitMgr.decrementResourceCount(template.getAccountId(), ResourceType.template);
_resourceLimitMgr.recalculateResourceCount(template.getAccountId(), account.getDomainId(), ResourceType.secondary_storage.getOrdinal());
}
// remove its related ACL permission
Pair<Class<?>, Long> tmplt = new Pair<Class<?>, Long>(VirtualMachineTemplate.class, template.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, tmplt);
}
return success;
}
@Override
public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
TemplateProfile profile = super.prepareDelete(cmd);
VMTemplateVO template = profile.getTemplate();
Long zoneId = profile.getZoneId();
if (template.getTemplateType() == TemplateType.SYSTEM) {
throw new InvalidParameterValueException("The DomR template cannot be deleted.");
}
if (zoneId != null && (storeMgr.getImageStore(zoneId) == null)) {
throw new InvalidParameterValueException("Failed to find a secondary storage in the specified zone.");
}
return profile;
}
@Override
public TemplateProfile prepareDelete(DeleteIsoCmd cmd) {
TemplateProfile profile = super.prepareDelete(cmd);
Long zoneId = profile.getZoneId();
if (zoneId != null && (storeMgr.getImageStore(zoneId) == null)) {
throw new InvalidParameterValueException("Failed to find a secondary storage in the specified zone.");
}
return profile;
}
}
| CLOUDSTACK-5607: Don't delete the template if its stored in other zones.
| server/src/com/cloud/template/HypervisorTemplateAdapter.java | CLOUDSTACK-5607: Don't delete the template if its stored in other zones. | <ide><path>erver/src/com/cloud/template/HypervisorTemplateAdapter.java
<ide> }
<ide> }
<ide> if (success) {
<add> if ((imageStores.size() > 1) && (profile.getZoneId() != null)) {
<add> //if template is stored in more than one image stores, and the zone id is not null, then don't delete other templates.
<add> return success;
<add> }
<add>
<ide> // delete all cache entries for this template
<ide> List<TemplateInfo> cacheTmpls = imageFactory.listTemplateOnCache(template.getId());
<ide> for (TemplateInfo tmplOnCache : cacheTmpls) { |
|
JavaScript | mit | 629643063e02403de51d021cbca904b670d26a01 | 0 | dfahlander/typeson,dfahlander/typeson,brettz9/typeson,brettz9/typeson | /* globals assert */
/* eslint-disable no-console, no-restricted-syntax,
jsdoc/require-jsdoc, no-empty-function, no-shadow */
// import '../node_modules/core-js-bundle/minified.js';
import '../node_modules/regenerator-runtime/runtime.js';
import Typeson from '../typeson.js';
import * as B64 from
'../node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js';
const debug = false;
function log (...args) {
if (debug) {
console.log(...args);
}
}
const typeson = new Typeson().register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
Error: [
function (x) { return x instanceof Error; },
function (error) { return {name: error.name, message: error.message}; },
function (data) {
const e = new Error(data.message);
e.name = data.name;
return e;
}
],
SpecialNumber: [
function (x) {
return typeof x === 'number' &&
(isNaN(x) || x === Infinity || x === -Infinity);
},
function (n) {
return isNaN(n) ? 'NaN' : n > 0 ? 'Infinity' : '-Infinity';
},
function (s) {
return {NaN, Infinity, '-Infinity': -Infinity}[s];
}
],
ArrayBuffer: [
function test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },
function encapsulate (b) { return B64.encode(b); },
function revive (b64) { return B64.decode(b64); }
],
DataView: [
function (x) { return x instanceof DataView; },
function (dw) {
return {
buffer: dw.buffer,
byteOffset: dw.byteOffset,
byteLength: dw.byteLength
};
},
function (obj) {
return new DataView(obj.buffer, obj.byteOffset, obj.byteLength);
}
]
});
const globalTypeson = typeson;
function roundtrip (x) {
const tson = typeson.stringify(x, null, 2);
log(tson);
return typeson.parse(tson);
}
describe('Typeson', function () {
it('should support basic types', () => {
let res = roundtrip({});
assert(Object.keys(res).length === 0, 'Result should be empty');
const date = new Date();
const input = {
a: 'a', b: 2, c () {}, d: false, e: null,
f: Symbol('symbol'), g: [], h: date, i: /apa/gui
};
res = roundtrip(input);
assert(res !== input, 'Object is a clone, not a reference');
assert(res.a === 'a', 'String value');
assert(res.b === 2, 'Number value');
assert(!res.c, 'Functions should not follow by default');
assert(res.d === false, 'Boolean value');
assert(res.e === null, 'Null value');
assert(!res.f, 'Symbols should not follow by default');
assert(Array.isArray(res.g) && res.g.length === 0, 'Array value');
assert(
res.h instanceof Date && res.h.toString() === date.toString(),
'Date value'
);
assert(
Object.keys(res.i).length === 0,
'regex only treated as empty object by default'
);
});
it('should resolve nested objects', () => {
const input = {a: [{subA: 5}, [6, 7]], b: {subB: {c: 8}}};
const res = roundtrip(input);
assert(res.a[0].subA === 5, 'Object within array');
assert(res.a[1][0] === 6, 'Array within array');
assert(res.a[1][1] === 7, 'Array within array');
assert(res.b.subB.c === 8, 'Object within object');
});
it('should support object API', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const date = new Date();
const tson = typeson.stringify(date, null, 2);
log(tson);
const back = typeson.parse(tson);
assert(
back instanceof Date && back.toString() === date.toString(),
'Date value'
);
});
it('should support objects containing internally used properties', () => {
function test (data, cb) {
const tson = typeson.stringify(data, null, 2);
log(tson);
const result = typeson.parse(tson);
cb(result);
}
function valSwitch (val) {
test({$types: val}, function (result) {
assert(
result.$types === val &&
Object.keys(result).length === 1,
'Preserves $types on original object without additions'
);
});
test({$: val}, function (result) {
assert(
result.$ === val && Object.keys(result).length === 1,
'Preserves $ on original object without additions'
);
});
test({$: val, $types: val}, function (result) {
assert(
result.$ === val &&
result.$types === val &&
Object.keys(result).length === 2,
'Preserves $ and $types values on original ' +
'object without additions'
);
});
}
valSwitch(true);
valSwitch(false);
test(
{$: {}, $types: {$: {'': 'val', cyc: '#'}, '#': 'a1', '': 'b1'}},
function (result) {
assert(
typeof result.$ === 'object' &&
!Object.keys(result.$).length &&
result.$types.$[''] === 'val' &&
result.$types.$.cyc === '#' &&
result.$types['#'] === 'a1' &&
result.$types[''] === 'b1' &&
Object.keys(result.$types).length === 3,
'Preserves $ and $types subobjects on original ' +
'object without additions'
);
}
);
test({a: new Date(), $types: {}}, function (result) {
assert(
result.a instanceof Date &&
!('$' in result) &&
typeof result.$types === 'object' &&
!Object.keys(result.$types).length,
'Roundtrips type while preserving $types subobject ' +
'from original object without additions'
);
});
test({a: new Date(), $: {}}, function (result) {
assert(
result.a instanceof Date &&
!('$types' in result) &&
typeof result.$ === 'object' &&
!Object.keys(result.$).length,
'Roundtrips type while preserving $ subobject from ' +
'original object without additions'
);
});
test({a: new Date(), $types: {}, $: {}}, function (result) {
assert(
result.a instanceof Date &&
typeof result.$types === 'object' &&
!Object.keys(result.$types).length &&
typeof result.$ === 'object' &&
!Object.keys(result.$).length,
'Roundtrips type while preserving $ and $types subobjects ' +
'from original object without additions'
);
});
function valSwitch2 (val) {
test({a: new Date(), $types: val}, function (result) {
assert(
result.a instanceof Date &&
!('$' in result) &&
result.$types === val,
'Roundtrips type while preserving $types value ' +
'from original object'
);
});
test({a: new Date(), $: val}, function (result) {
assert(
result.a instanceof Date &&
!('$types' in result) &&
result.$ === val,
'Roundtrips type while preserving $ value ' +
'from original object'
);
});
test({a: new Date(), $types: val, $: val}, function (result) {
assert(
result.a instanceof Date &&
result.$types === val &&
result.$ === val,
'Roundtrips type while preserving $types and $ values ' +
'from original object'
);
});
}
valSwitch2(true);
valSwitch2(false);
test({a: new Date(), $: {}}, function (result) {
assert(
result.a instanceof Date &&
!('$types' in result) &&
typeof result.$ === 'object' &&
!Object.keys(result.$).length,
'Roundtrips type while preserving $ subojbect from original ' +
'object without additions'
);
});
});
it('should handle path separators in objects', () => {
const input = {
aaa: {
bbb: new Date(91000000000)
},
'aaa.bbb': 2,
lll: {
mmm: 3
},
'lll.mmm': new Date(92000000000),
'qqq.rrr': 4,
qqq: {
rrr: new Date(93000000000)
},
yyy: {
zzz: 5
},
'yyy.zzz': new Date(94000000000),
allNormal1: {
a: 100
},
'allNormal1.a': 200,
allTyped1: {
a: new Date(95000000000)
},
'allTyped1.a': new Date(96000000000),
'allNormal2.b': 400,
allNormal2: {
b: 500
},
allTyped2: {
b: new Date(97000000000)
},
'allTyped2.b': new Date(98000000000),
'A~': 'abc',
'A~1': 'ghi',
'A~0': 'def',
'A.': 'jkl',
'B~': new Date(99100000000),
'B~0': new Date(99200000000),
'B~1': new Date(99300000000),
'B.': new Date(99400000000)
};
const res = roundtrip(input);
assert(
res.aaa.bbb instanceof Date && res['aaa.bbb'] === 2 &&
res.aaa.bbb.getTime() === 91000000000,
'Properties with periods (with type) after normal ' +
'properties (without type)'
);
assert(
res['lll.mmm'] instanceof Date && res.lll.mmm === 3 &&
res['lll.mmm'].getTime() === 92000000000,
'Properties with periods (without type) after normal ' +
'properties (with type)'
);
assert(
res.qqq.rrr instanceof Date && res['qqq.rrr'] === 4 &&
res.qqq.rrr.getTime() === 93000000000,
'Properties with periods (without type) before normal ' +
'properties (with type)'
);
assert(
res['yyy.zzz'] instanceof Date && res.yyy.zzz === 5 &&
res['yyy.zzz'].getTime() === 94000000000,
'Properties with periods (with type) before normal ' +
'properties (without type)'
);
assert(
res.allNormal1.a === 100 && res['allNormal1.a'] === 200,
'Properties with periods (without type) after normal ' +
'properties (without type)'
);
assert(
res.allTyped1.a instanceof Date &&
res['allTyped1.a'] instanceof Date &&
res.allTyped1.a.getTime() === 95000000000 &&
res['allTyped1.a'].getTime() === 96000000000,
'Properties with periods (with type) after normal ' +
'properties (with type)'
);
assert(
res.allNormal2.b === 500 && res['allNormal2.b'] === 400,
'Properties with periods (without type) before normal ' +
'properties (without type)'
);
assert(
res.allTyped2.b instanceof Date &&
res['allTyped2.b'] instanceof Date &&
res.allTyped2.b.getTime() === 97000000000 &&
res['allTyped2.b'].getTime() === 98000000000,
'Properties with periods (with type) after normal ' +
'properties (with type)'
);
assert(
res['A~'] === 'abc' &&
res['A~0'] === 'def' &&
res['A~1'] === 'ghi' &&
res['A.'] === 'jkl' &&
res['B~'] instanceof Date &&
res['B~'].getTime() === 99100000000 &&
res['B~0'] instanceof Date &&
res['B~0'].getTime() === 99200000000 &&
res['B~1'] instanceof Date &&
res['B~1'].getTime() === 99300000000 &&
res['B.'] instanceof Date &&
res['B.'].getTime() === 99400000000,
'Find properties with escaped and unescaped characters'
);
});
it('should support arrays', () => {
const res = roundtrip([1, new Date(), 3]);
assert(Array.isArray(res), 'Result should be an array');
assert(res.length === 3, 'Should have length 3');
assert(res[2] === 3, 'Third item should be 3');
});
it('should support intermediate types', () => {
function CustomDate (date) {
this._date = date;
}
const typeson = new Typeson()
.register(globalTypeson.types)
.register({
CustomDate: [
(x) => x instanceof CustomDate,
(cd) => cd._date,
(date) => new CustomDate(date)
]
});
const date = new Date();
const input = new CustomDate(new Date());
const tson = typeson.stringify(input);
log(tson);
const back = typeson.parse(tson);
assert(back instanceof CustomDate, 'Should get CustomDate back');
assert(
back._date.getTime() === date.getTime(),
'Should have correct value'
);
});
it('should support intermediate types (async)', async () => {
function CustomDate (date) {
this._date = date;
}
const typeson = new Typeson()
.register({
date: {
test (x) { return x instanceof Date; },
replaceAsync (date) {
return new Typeson.Promise((resolve, reject) => {
setTimeout(() => {
resolve(date.getTime());
});
});
},
reviveAsync (time) {
return new Typeson.Promise((resolve, reject) => {
setTimeout(() => {
resolve(new Date(time));
});
});
}
}
})
.register({
CustomDate: {
test (x) {
return x instanceof CustomDate;
},
replaceAsync (cd) {
return cd._date;
},
reviveAsync (date) {
return new CustomDate(date);
}
}
});
const date = new Date();
const input = new CustomDate(new Date());
const tson = await typeson.stringifyAsync(input);
log(tson);
const back = await typeson.parseAsync(tson);
assert(back instanceof CustomDate, 'Should get CustomDate back');
assert(
back._date.getTime() === date.getTime(),
'Should have correct value'
);
});
it('should run replacers recursively', () => {
function CustomDate (date, name) {
this._date = date;
this.name = name;
this.year = date.getFullYear();
}
CustomDate.prototype.getRealDate = function () {
return this._date;
};
CustomDate.prototype.getName = function () {
return this.name;
};
const date = new Date();
const input = {
name: 'Karl',
date: new CustomDate(date, 'Otto')
};
const typeson = new Typeson()
.register(globalTypeson.types)
.register({
CustomDate: [
(x) => x instanceof CustomDate,
(cd) => ({_date: cd.getRealDate(), name: cd.name}),
(obj) => new CustomDate(obj._date, obj.name)
]
});
const tson = typeson.stringify(input, null, 2);
log(tson);
const result = typeson.parse(tson);
assert(result.name === 'Karl', 'Basic prop');
assert(
result.date instanceof CustomDate,
'Correct instance type of custom date'
);
assert(
result.date.getName() === 'Otto',
'prototype method works and properties seems to be in place'
);
assert(
result.date.getRealDate().getTime() === date.getTime(),
'The correct time is there'
);
});
it('should be able to stringify complex objects at root', () => {
const x = roundtrip(new Date(3));
assert(x instanceof Date, 'x should be a Date');
assert(x.getTime() === 3, 'Time should be 3');
const y = roundtrip([new Date(3)]);
assert(y[0] instanceof Date, 'y[0] should be a Date');
assert(y[0].getTime() === 3, 'Time should be 3');
function Custom () {
this.x = 'oops';
}
let TSON = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(s) => false,
(f) => new Custom()
]
});
let tson = TSON.stringify(new Custom());
log(tson);
let z = TSON.parse(tson);
assert(
z instanceof Custom && z.x === 'oops',
'Custom type encapsulated in bool should work'
);
TSON = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(s) => 42,
(f) => new Custom()
]
});
tson = TSON.stringify(new Custom());
log(tson);
z = TSON.parse(tson);
assert(
z instanceof Custom && z.x === 'oops',
'Custom type encapsulated in bool should work'
);
TSON = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(s) => 'foo',
(f) => new Custom()
]
});
tson = TSON.stringify(new Custom());
log(tson);
z = TSON.parse(tson);
assert(
z instanceof Custom && z.x === 'oops',
'Custom type encapsulated in bool should work'
);
});
it(
'should be possible to encapsulate object with reserved `$types` ' +
'property',
() => {
function Custom (val, $types) {
this.val = val;
this.$types = $types;
}
const typeson = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(c) => ({val: c.val, $types: c.$types}),
(o) => new Custom(o.val, o.$types)
]
});
const input = new Custom('bar', 'foo');
const tson = typeson.stringify(input);
log(tson);
const x = typeson.parse(tson);
assert(x instanceof Custom, 'Should get a Custom back');
assert(x.val === 'bar', 'Should have correct val value');
assert(x.$types === 'foo', 'Should have correct $types value');
}
);
/*
// Todo?
it('should leave left out type', () => {
// Uint8Buffer is not registered.
});
*/
it('executing toJSON', () => {
function A () {}
A.prototype.toJSON = function () { return 'abcd'; };
let typeson = new Typeson();
let a = new A(); // Encapsulated as is
let tson = typeson.stringify(a);
log(tson);
let back = typeson.parse(tson);
assert(back === 'abcd', 'Should have executed `toJSON`');
typeson = new Typeson();
// Plain object rebuilt during encapsulation including with `toJSON`
a = {
toJSON () { return 'abcd'; }
};
tson = typeson.stringify(a);
log(tson);
back = typeson.parse(tson);
assert(back === 'abcd', 'Should have executed `toJSON`');
});
it('should allow plain object replacements', () => {
const typeson = new Typeson().register({
plainObj: {
testPlainObjects: true,
test (x) {
return 'nonenum' in x;
},
replace (o) {
return {
b: o.b,
nonenum: o.nonenum
};
}
}
});
const a = {b: 5};
Object.defineProperty(a, 'nonenum', {
enumerable: false,
value: 100
});
let tson = typeson.stringify(a);
log(tson);
let back = typeson.parse(tson);
assert(back.b === 5, 'Should have kept property');
assert(
back.nonenum === 100,
'Should have kept non-enumerable property'
);
assert(
{}.propertyIsEnumerable.call(back, 'nonenum'),
'Non-enumerable property should now be enumerable'
);
const x = Object.create(null);
x.b = 7;
Object.defineProperty(x, 'nonenum', {
enumerable: false,
value: 50
});
tson = typeson.stringify(x);
log(tson);
back = typeson.parse(tson);
assert(back.b === 7, 'Should have kept property');
assert(back.nonenum === 50, 'Should have kept non-enumerable property');
assert(
{}.propertyIsEnumerable.call(back, 'nonenum'),
'Non-enumerable property should now be enumerable'
);
});
it('should allow forcing of async return', () => {
const typeson = new Typeson({sync: false, throwOnBadSyncType: false});
const x = 5;
return typeson.stringify(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back === 5,
'Should allow async to be forced even without ' +
'async return values'
);
return undefined;
});
});
it('should transmit state through replacers and revivers', () => {
function ReplaceReviver (obj) {
Object.defineProperty(this, 'obj', {
enumerable: false,
value: obj
});
}
ReplaceReviver.prototype[Symbol.toStringTag] = 'ReplaceReviver';
const typeson = new Typeson().register({
replaceReviveContainer: {
test (x) {
return Typeson.toStringTag(x) === 'ReplaceReviver';
},
replace (b, stateObj) {
if (!stateObj.objs) {
stateObj.objs = [];
}
const index = stateObj.objs.indexOf(b.obj);
if (index > -1) {
return {index};
}
stateObj.objs.push(b.obj);
return {
obj: b.obj
};
},
revive (o, stateObj) {
if (!stateObj.objs) {
stateObj.objs = [];
}
if ('index' in o) {
return stateObj.objs[o.index];
}
const rr = new ReplaceReviver(o.obj);
stateObj.objs.push(rr);
return rr;
}
}
});
const rrObj1 = {value: 10};
const rrObj2 = {value: 353};
const rrObjXYZ = {value: 10};
const rr1 = new ReplaceReviver(rrObj1);
const rr2 = new ReplaceReviver(rrObj2);
const rr3 = new ReplaceReviver(rrObj1);
const rrXYZ = new ReplaceReviver(rrObjXYZ);
const obj = {rr1, rr2, rr3, rrXYZ};
const tson = typeson.stringify(obj);
log(tson);
const back = typeson.parse(tson);
assert(back.rr1.obj.value === 10, 'Should preserve value (rr1)');
assert(back.rr2.obj.value === 353, 'Should preserve value (rr2)');
assert(back.rr3.obj.value === 10, 'Should preserve value (rr3)');
assert(back.rrXYZ.obj.value === 10, 'Should preserve value (rrXYZ)');
assert(back.rr1.obj === back.rr3.obj, 'Should preserve objects');
assert(
back.rr1.obj !== back.rrXYZ.obj,
'Should not confuse objects where only value is the same'
);
});
it('should allow serializing arrays to objects', () => {
let endIterateIn;
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateIn) {
endIterateIn = true;
}
}
}).register({
arraysToObjects: {
testPlainObjects: true,
test (x, stateObj) {
if (Array.isArray(x)) {
stateObj.iterateIn = 'object';
stateObj.addLength = true;
return true;
}
return false;
},
revive (o) {
const arr = [];
// No map here as may be a sparse array (including
// with `length` set)
Object.entries(o).forEach(([key, val]) => {
arr[key] = val;
});
return arr;
}
}
});
const arr = new Array(10);
arr[0] = 3;
arr[2] = {arr};
arr[2].f = [[arr]];
arr[3] = '4';
arr[4] = 5;
arr[6] = arr;
arr[7] = [arr];
arr[9] = {arr};
arr.b = 'ddd';
arr[-2] = 'eee';
arr[9].f = [[arr]];
const tson = typeson.stringify(arr, null, 2);
log('tson', tson);
assert(endIterateIn, 'Observes `endIterateIn` state');
const back = typeson.parse(tson);
log('back', back);
assert(
back[0] === 3 && back[3] === '4' && back[4] === 5,
'Preserves regular array indexes'
);
assert(
back.b === 'ddd' && back[-2] === 'eee',
'Preserves non-numeric and non-positive-integer indexes'
);
assert(
back[6] === back &&
back[7][0] === back &&
Array.isArray(back),
'Preserves circular array references'
);
assert(
Array.isArray(back[2].arr), 'Preserves cyclic array on object'
);
assert(
Array.isArray(back[9].arr), 'Preserves cyclic array on object'
);
assert(
back[2].f[0][0] === back, 'Preserves nested cyclic array'
);
assert(
back[9].f[0][0] === back, 'Preserves nested cyclic array'
);
});
it('should allow serializing arrays to objects', () => {
const typeson = new Typeson().register({
arraysToObjects: {
testPlainObjects: true,
test (x, stateObj) {
if (Array.isArray(x)) {
stateObj.iterateIn = 'object';
stateObj.addLength = true;
return true;
}
return false;
},
revive (o) {
const arr = [];
// No map here as may be a sparse array (including
// with `length` set)
Object.entries(o).forEach(([key, val]) => {
arr[key] = val;
});
return arr;
}
}
});
const arr = new Array(10);
arr[2] = {arr};
arr[2].f = [[arr]];
const tson = typeson.stringify(arr, null, 2);
log(tson);
const tsonStringifiedSomehowWithNestedTypesFirst = `
{
"2": {
"arr": "#",
"f": {
"0": {
"0": "#",
"length": 1
},
"length": 1
}
},
"length": 10,
"$types": {
"2.f.0.0": "#",
"": "arraysToObjects",
"2.arr": "#",
"2.f.0": "arraysToObjects",
"2.f": "arraysToObjects"
}
}
`;
const back = typeson.parse(tsonStringifiedSomehowWithNestedTypesFirst);
log('back', back);
assert(
Array.isArray(back[2].arr), 'Preserves cyclic array on object'
);
assert(
back[2].f[0][0] === back, 'Preserves nested cyclic array'
);
});
it('should allow unknown string tags', () => {
const map = {
map: {
test (x) { return Typeson.toStringTag(x) === 'Map'; },
replace (mp) { return [...mp.entries()]; },
revive (entries) { return new Map(entries); }
}
};
const typeson = new Typeson().register([map]);
const a = {
__raw_map: new Map(),
[Symbol.toStringTag]: 'a'
};
const tson = typeson.stringify(a, null, 2);
log('tson', tson);
const back = typeson.parse(tson);
assert(
back.__raw_map instanceof Map,
'Revives `Map` on class with Symbol.toStringTag'
);
// Todo: Need to implement Symbol iteration
// assert(
// back[Symbol.toStringTag] === 'a',
// 'Revives `Symbol.toStringTag`'
// );
});
it('should throw upon attempt to parse type that is not registered', () => {
const map = {
map: {
test (x) { return Typeson.toStringTag(x) === 'Map'; },
replace (mp) { return [...mp.entries()]; },
revive (entries) { return new Map(entries); }
}
};
const typeson = new Typeson().register([map]);
const a = {
someMap: new Map()
};
const tson = typeson.stringify(a, null, 2);
log('tson', tson);
const newTypeson = new Typeson();
assert.throws(
() => {
newTypeson.parse(tson);
},
Error,
'Unregistered type: map',
'Typeson instance without type'
);
});
it(
'should throw upon attempt to parse type that is not registered ' +
'(plain objects)',
() => {
const typeson = new Typeson().register([{
mySyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) { return o.prop; },
revive (data) { return {prop: data}; }
}
}]);
const obj = {prop: 52};
const tson = typeson.stringify(obj, null, 2);
log('tson', tson);
const newTypeson = new Typeson();
assert.throws(
() => {
newTypeson.parse(tson);
},
Error,
'Unregistered type: mySyncType',
'Typeson instance without type'
);
}
);
describe('Type error checking', () => {
it('disallows hash type', () => {
assert.throws(
() => {
new Typeson().register({'#': [
function () {}, function () {}, function () {}
]});
},
TypeError,
'# cannot be used as a type name as it is reserved ' +
'for cyclic objects',
'Should throw on attempting to register the ' +
"reserved 'type', '#'"
);
});
it('disallows JSON type names', () => {
const ok = [
'null', 'boolean', 'number', 'string', 'array', 'object'
].every((type) => {
let caught = false;
try {
new Typeson().register({
[type]: [function () {}, function () {}, function () {}]
});
} catch (err) {
caught = true;
}
return caught;
});
assert(
ok,
'Should throw on attempting to register the reserved JSON ' +
'object type names'
);
});
});
describe('Cyclics', () => {
it('should resolve cyclics', () => {
const data = {list: []};
for (let i = 0; i < 10; ++i) {
data.list.push({
name: 'name' + i,
parent: data.list,
root: data,
children: []
});
}
data.list[3].children = [data.list[0], data.list[1]];
const tson = typeson.stringify(data, null, 2);
log(tson);
const result = typeson.parse(tson);
assert(
result.list.length === 10,
'result.list.length should be 10'
);
assert(
result.list[3].children.length === 2,
'result.list[3] should have 2 children'
);
assert(
result.list[3].children[0] === result.list[0],
'First child of result.list[3] should be result.list[0]'
);
});
it('should resolve cyclics 2', () => {
const kalle = {name: 'Kalle', age: 33};
const input = [kalle, kalle, kalle];
const tson = typeson.stringify(input);
log(tson.match(/Kalle/gu).length);
log(tson);
assert(
tson.match(/Kalle/gu).length === 1,
"TSON should only contain one 'Kalle'. The others should " +
'just reference the first'
);
const result = typeson.parse(tson);
assert(
result[0] === result[1] && result[1] === result[2],
'The resulting object should also just have references ' +
'to the same object'
);
});
it('should resolve cyclic arrays', () => {
const recursive = [];
recursive.push(recursive);
let tson = typeson.stringify(recursive);
let result = typeson.parse(tson);
assert(result === result[0], 'array directly contains self');
const recursive2 = [];
recursive2.push([recursive2]);
tson = typeson.stringify(recursive2);
result = typeson.parse(tson);
assert(
result !== result[0] && result === result[0][0],
'array indirectly contains self'
);
const recursive3 = [recursive];
tson = typeson.stringify(recursive3);
log(tson);
result = typeson.parse(tson);
assert(
result !== result[0] && result !== result[0][0] &&
result[0] === result[0][0],
'array member contains self'
);
const recursive4 = [1, recursive];
tson = typeson.stringify(recursive4);
log(tson);
result = typeson.parse(tson);
assert(
result !== result[1] && result !== result[1][0] &&
result[1] === result[1][0],
'array member contains self'
);
});
it('should resolve cyclic object members', () => {
// eslint-disable-next-line sonarjs/prefer-object-literal
const recursive = {};
recursive.b = recursive;
const recursiveContainer = {a: recursive};
const tson = typeson.stringify(recursiveContainer);
log(tson);
const result = typeson.parse(tson);
assert(
result !== result.a && result !== result.b &&
result.a === result.a.b,
'Object property contains self'
);
});
it('should not resolve cyclics if not wanted', () => {
const kalle = {name: 'Kalle', age: 33};
const input = [kalle, kalle, kalle];
const typeson = new Typeson({cyclic: false});
const tson = typeson.stringify(input);
const json = JSON.stringify(input);
assert(
tson === json,
'TSON should be identical to JSON because the input is ' +
'simple and the cyclics of the input should be ignored'
);
});
it('should resolve cyclics in encapsulated objects', () => {
const buf = new ArrayBuffer(16);
const data = {
buf,
bar: {
data: new DataView(buf, 8, 8)
}
};
const tson = typeson.stringify(data, null, 2);
log(tson);
const back = typeson.parse(tson);
assert(
back.buf === back.bar.data.buffer,
'The buffers point to same object'
);
});
});
describe('Registration', () => {
it(
'should support registering a class without replacer or ' +
'reviver (by constructor/class)',
() => {
function MyClass () {}
const TSON = new Typeson().register({MyClass});
const x = new MyClass();
x.hello = 'world';
const tson = TSON.stringify(x);
log(tson);
const back = TSON.parse(tson);
assert(
back instanceof MyClass,
'Should revive to a MyClass instance.'
);
assert(
back.hello === 'world',
'Should have all properties there.'
);
}
);
it(
'should get observer event when registering a class ' +
'with only test',
() => {
let typeDetected;
const TSON = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected) {
typeDetected = true;
}
}
}).register([{
myType: {
testPlainObjects: true,
test (x) {
return 'prop' in x;
}
}
}]);
const x = {prop: 5};
const tson = TSON.stringify(x);
log(tson);
assert(typeDetected, 'Type was detected');
}
);
it('should execute replacers in proper order', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson().register([
{specificClassFinder: [
(x) => x instanceof Person, () => 'specific found'
]},
{genericClassFinder: [
(x) => x && typeof x === 'object', () => 'general found'
]}
]);
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'general found',
'Should execute replacers in proper order'
);
});
it('should execute replacers with `fallback` in proper order', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{specificClassFinder: [
(x) => x instanceof Person, () => 'specific found'
]}
]);
typeson.register([
{genericClassFinder: [
(x) => x && typeof x === 'object', () => 'general found'
]}
], {
fallback: 0
});
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'specific found',
'Should execute replacers in proper order'
);
});
it('should execute replacers with `fallback` in proper order', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{specificClassFinder: [
(x) => x instanceof Person, () => 'specific found'
]}
]);
typeson.register([
{genericClassFinder: [
(x) => x && typeof x === 'object', () => 'general found'
]}
], {
fallback: true
});
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'specific found',
'Should execute replacers in proper order'
);
});
it('should silently ignore nullish spec', () => {
function Person () {}
function Dog () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{
classFinder: [
(x) => x instanceof Person, () => 'person found'
],
badType: null
}
]);
typeson.register([
{
anotherBadType: null,
anotherClassFinder: [
(x) => x instanceof Dog, () => 'dog found'
]
}
]);
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'person found',
'Should find item despite nullish specs'
);
});
it('should allow replacing previously registered replacer', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{classFinder: [
(x) => x instanceof Person, () => 'found'
]}
]);
typeson.register(
[{classFinder: [
(x) => x instanceof Person, () => 'later found'
]}]
);
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'later found',
'Should replace previously registered replacer'
);
});
it('should allow removing previously registered replacer', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{classFinder: [
(x) => x instanceof Person, () => 'found'
]}
]);
typeson.register(
[{classFinder: null}]
);
const encapsulatedData = typeson.encapsulate(john);
assert(
!encapsulatedData.$types,
'Encapsulated should have no special type'
);
});
it(
'should allow removing previously registered replacer ' +
'(plain objects)',
() => {
const typeson = new Typeson();
typeson.register({
plainObj: {
testPlainObjects: true,
test (x) {
return 'nonenum' in x;
},
replace (o) {
return {
b: o.b,
nonenum: o.nonenum
};
}
}
});
typeson.register({plainObj: {
testPlainObjects: true
}});
const a = {b: 5};
Object.defineProperty(a, 'nonenum', {
enumerable: false,
value: 100
});
const encapsulatedData = typeson.encapsulate(a);
assert(
!encapsulatedData.$types,
'Encapsulated should have no special type'
);
}
);
});
describe('encapsulateObserver', () => {
it('should run encapsulateObserver sync', () => {
const expected = '{\n' +
' time: 959000000000\n' +
' vals: [\n' +
' 0: null\n' +
' 1: undefined\n' +
' 2: 5\n' +
' 3: str\n' +
' ]\n' +
' cyclicInput: #\n' +
'}\n';
let str = '';
let indentFactor = 0;
const indent = function () {
return new Array(indentFactor * 4 + 1).join(' ');
};
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected || o.replacing) {
return;
}
const isObject = o.value && typeof o.value === 'object';
const isArray = Array.isArray(o.value);
if (o.end) {
indentFactor--;
str += indent() + (isArray ? ']' : '}') + '\n';
return;
}
if (!('replaced' in o)) {
if (isArray) {
if (!('clone' in o)) {
return;
}
str += indent() +
(o.keypath ? o.keypath + ': ' : '') +
'[\n';
indentFactor++;
return;
}
if (isObject) {
if ('cyclicKeypath' in o) {
o.value = '#' + o.cyclicKeypath;
} else {
str += indent() + '{\n';
indentFactor++;
return;
}
}
} else if (isObject) {
// Special type that hasn't been finally resolved yet
return;
}
const idx = o.keypath.lastIndexOf('.') + 1;
str += indent() + o.keypath.slice(idx) + ': ' +
('replaced' in o ? o.replaced : o.value) + '\n';
}
})
.register(globalTypeson.types);
const input = {
time: new Date(959000000000),
vals: [null, undefined, 5, 'str']
};
input.cyclicInput = input;
/* const tson = */ typeson.encapsulate(input);
log(str);
log(expected);
assert(
str === expected,
'Observer able to reduce JSON to expected string'
);
});
it('encapsulateObserver should observe types', () => {
const actual = [];
const expected = [
'object', 'Date', 'array', 'null',
'undefined', 'number', 'string'
];
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected || o.replacing) {
return;
}
if (o.cyclic !== 'readonly' && !o.end) {
actual.push(o.type);
}
}
}).register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
]
});
const input = {
time: new Date(959000000000),
vals: [null, undefined, 5, 'str']
};
/* const tson = */ typeson.encapsulate(input);
assert(
actual.length === expected.length &&
actual.every((type, i) => type === expected[i]),
'Should report primitive and compound types'
);
});
it('should run encapsulateObserver async', () => {
let str = '';
const placeholderText = '(Please wait for the value...)';
function APromiseUser (a) { this.a = a; }
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected || o.replacing) {
return;
}
const isObject = o.value && typeof o.value === 'object';
const isArray = Array.isArray(o.value);
if (o.resolvingTypesonPromise) {
const idx = str.indexOf(placeholderText);
const start = str.slice(0, idx);
const end = str.slice(idx + placeholderText.length);
str = start + o.value + end;
} else if (o.awaitingTypesonPromise) {
str += '<span>' + placeholderText + '</span>';
} else if (!isObject && !isArray) {
str += '<span>' + o.value + '</span>';
}
}
}).register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
PromiseUser: [
function (x) { return x instanceof APromiseUser; },
function (o) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(o.a);
}, 300);
});
},
function (val) { return new APromiseUser(val); }
]
});
const input = ['aaa', new APromiseUser(5), 'bbb'];
const prom = typeson.encapsulateAsync(input).then(
function (encaps) {
const back = typeson.parse(JSON.stringify(encaps));
assert(
back[0] === input[0] &&
back[2] === input[2] &&
back[1] instanceof APromiseUser &&
back[1].a === 5,
'Should have resolved the one nested promise value'
);
log(str);
assert(
str === '<span>aaa</span><span>5</span>' +
'<span>bbb</span>',
'Should have allowed us to run the callback ' +
'asynchronously (where we can substitute a ' +
'placeholder)'
);
return undefined;
}
);
assert(
str === '<span>aaa</span><span>' + placeholderText +
'</span><span>bbb</span>',
'Should have allowed us to run the callback synchronously ' +
'(where we add a placeholder)'
);
return prom;
});
});
describe('Iteration', () => {
it('should allow `iterateIn`', () => {
function A (a) {
this.a = a;
}
function createExtendingClass (a) {
function B (b, isArr) {
this[3] = 4;
this.b = b;
this.isArr = isArr;
}
B.prototype = new A(a);
return B;
}
const typeson = new Typeson().register({
iterateIn: {
test (x, stateObj) {
if (x instanceof A) {
stateObj.iterateIn = x.isArr ? 'array' : 'object';
return true;
}
return false;
}
}
});
const B = createExtendingClass(5);
let b = new B(7);
let tson = typeson.stringify(b);
log(tson);
let back = typeson.parse(tson);
assert(!Array.isArray(back), 'Is not an array');
assert(back[3] === 4, 'Has numeric property');
assert(back.a === 5, "Got inherited 'a' property");
assert(back.b === 7, "Got own 'b' property");
b = new B(8, true);
tson = typeson.stringify(b);
log(tson);
back = typeson.parse(tson);
assert(Array.isArray(back), 'Is an array');
assert(back[3] === 4, 'Has numeric property');
assert(
!('a' in back),
"'a' property won't survive array stringification"
);
assert(
!('b' in back),
"'b' property won't survive array stringification"
);
});
it('should allow `iterateIn` (async)', async () => {
function A (a) {
this.a = a;
}
function createExtendingClass (a) {
function B (b, isArr) {
this[3] = 4;
this.b = b;
this.c = new MyAsync('abc');
this.e = new Typeson.Undefined();
this.isArr = isArr;
}
B.prototype = new A(a);
return B;
}
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register([{
undef: {
test (x) { return x instanceof Typeson.Undefined; },
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new Typeson.Undefined());
});
}
}
}, {
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new MyAsync(data));
});
}
}
}, {
iterateIn: {
test (x, stateObj) {
if (x instanceof A) {
stateObj.iterateIn = x.isArr ? 'array' : 'object';
return true;
}
return false;
},
replaceAsync (val) {
return new Typeson.Promise((resolve) => {
setTimeout(() => {
resolve(val);
});
});
},
reviveAsync (val) {
return new Typeson.Promise((resolve) => {
setTimeout(() => {
resolve(val);
});
});
}
}
}]);
const B = createExtendingClass(5);
let b = new B(7);
let tson = await typeson.stringifyAsync(b);
console.log(tson);
let back = await typeson.parseAsync(tson);
assert(!Array.isArray(back), 'Is not an array');
assert(back[3] === 4, 'Has numeric property');
assert(back.a === 5, "Got inherited 'a' property");
assert(back.b === 7, "Got own 'b' property");
assert(back.c instanceof MyAsync, "Got own 'c' property");
assert('e' in back && back.e === undefined, "Got own 'e' property");
b = new B(8, true);
tson = await typeson.stringifyAsync(b);
log(tson);
back = await typeson.parseAsync(tson);
assert(Array.isArray(back), 'Is an array');
assert(back[3] === 4, 'Has numeric property');
assert(
!('a' in back),
"'a' property won't survive array stringification"
);
assert(
!('b' in back),
"'b' property won't survive array stringification"
);
assert(
!('c' in back),
"'c' property won't survive array stringification"
);
assert(
!('e' in back),
"'e' property won't survive array stringification"
);
});
it('should allow `iterateUnsetNumeric`', () => {
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' &&
stateObj.ownKeys === false;
},
replace (n) { return 0; },
// Will avoid adding anything
revive (s) { return undefined; }
}
}
];
let endIterateUnsetNumeric;
let typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateUnsetNumeric) {
endIterateUnsetNumeric = true;
}
}
}).register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
let arr = [, 5, , , 6, ];
let tson = typeson.stringify(arr);
log(tson);
assert(
endIterateUnsetNumeric,
'Observer should get `endIterateUnsetNumeric`'
);
let back = typeson.parse(tson);
assert(!('0' in back), 'Undefined at index 0');
assert(back[1] === 5 && back[4] === 6, 'Set values restored');
assert(!('2' in back), 'Undefined at index 2');
assert(!('3' in back), 'Undefined at index 3');
assert(!('5' in back), 'Undefined at index 5');
// Once again for coverage of absent observer and
// nested keypath
typeson = new Typeson().register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
arr = {a: [, 5, , , 6, ]};
tson = typeson.stringify(arr);
log(tson);
back = typeson.parse(tson);
assert(!('0' in back.a), 'Undefined at index 0');
});
it('should allow `iterateUnsetNumeric` (storing `undefined`)', () => {
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' &&
stateObj.ownKeys === false;
},
replace (n) { return undefined; },
// Will avoid adding anything
revive (s) { return undefined; }
}
}
];
let endIterateUnsetNumeric;
let typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateUnsetNumeric) {
endIterateUnsetNumeric = true;
}
}
}).register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
let arr = [, 5, , , 6, ];
let tson = typeson.stringify(arr);
log(tson);
assert(
endIterateUnsetNumeric,
'Observer should get `endIterateUnsetNumeric`'
);
let back = typeson.parse(tson);
assert(!('0' in back), 'Undefined at index 0');
assert(back[1] === 5 && back[4] === 6, 'Set values restored');
assert(!('2' in back), 'Undefined at index 2');
assert(!('3' in back), 'Undefined at index 3');
assert(!('5' in back), 'Undefined at index 5');
// Once again for coverage of absent observer and
// nested keypath
typeson = new Typeson().register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
arr = {a: [, 5, , , 6, ]};
tson = typeson.stringify(arr);
log(tson);
back = typeson.parse(tson);
assert(!('0' in back.a), 'Undefined at index 0');
});
it('should allow `iterateUnsetNumeric` (async)', async () => {
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' &&
stateObj.ownKeys === false;
},
replaceAsync (n) {
return new Typeson.Promise((resolve) => {
setTimeout(() => {
resolve(0);
});
});
},
// Will avoid adding anything
revive (s) { return undefined; }
}
}
];
let endIterateUnsetNumeric;
let typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateUnsetNumeric) {
endIterateUnsetNumeric = true;
}
}
}).register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
let arr = [, 5, , , 6, ];
let tson = await typeson.stringifyAsync(arr);
log(tson);
assert(
endIterateUnsetNumeric,
'Observer should get `endIterateUnsetNumeric`'
);
let back = typeson.parse(tson);
assert(!('0' in back), 'Undefined at index 0');
assert(back[1] === 5 && back[4] === 6, 'Set values restored');
assert(!('2' in back), 'Undefined at index 2');
assert(!('3' in back), 'Undefined at index 3');
assert(!('5' in back), 'Undefined at index 5');
// Once again for coverage of absent observer and
// nested keypath
typeson = new Typeson().register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
arr = {a: [, 5, , , 6, ]};
tson = await typeson.stringifyAsync(arr);
log(tson);
back = typeson.parse(tson);
assert(!('0' in back.a), 'Undefined at index 0');
});
});
describe('Async vs. Sync', () => {
it('async README example', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson({sync: false}).register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
return typeson.stringify(mya).then(function (result) {
const back = typeson.parse(result, null, {sync: true});
assert(
back.prop === 500,
'Example of MyAsync should work'
);
return undefined;
});
});
it('should work with stringifyAsync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
return typeson.stringifyAsync(mya).then(function (result) {
const back = typeson.parse(result);
assert(
back.prop === 500,
'Example of MyAsync should work'
);
return typeson.stringifyAsync({prop: 5}, null, null, {
throwOnBadSyncType: false
});
}).then(function (result) {
const back = typeson.parse(result);
assert(
back.prop === 5,
'Example of synchronously-resolved simple object should ' +
'work with async API'
);
return undefined;
});
});
it('should work with encapsulateAsync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
return typeson.encapsulateAsync(mya).then(function (result) {
assert(
result.$ === 500 && result.$types.$[''] === 'myAsyncType',
'Example of MyAsync should work'
);
return typeson.encapsulateAsync({prop: 5}, null, {
throwOnBadSyncType: false
});
}).then(function (result) {
assert(
result.prop === 5,
'Example of synchronously-resolved simple object should ' +
'work with async API'
);
return undefined;
});
});
it('should throw with non-sync result to encapsulateSync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.encapsulateSync(mya);
}, TypeError, 'Sync method requested but async result obtained');
});
it('should throw with non-sync result to parseSync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return o.prop;
},
function (data) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(new MyAsync(data));
}, 800);
});
}
]
});
const mya = new MyAsync(500);
// eslint-disable-next-line no-sync
const smya = typeson.stringifySync(mya);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.parseSync(smya);
}, TypeError, 'Sync method requested but async result obtained');
});
it('should throw with sync result to encapsulateAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: [
function (x) { return x instanceof MySync; },
function (o) {
return o.prop;
},
function (data) {
return new MySync(data);
}
]
});
const mys = new MySync(500);
assert.throws(() => {
typeson.encapsulateAsync(mys);
}, TypeError, 'Async method requested but sync result obtained');
});
it('should throw with non-sync result to stringifySync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.stringifySync(mya);
}, TypeError, 'Sync method requested but async result obtained');
});
it('should throw with sync result to stringifyAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: [
function (x) { return x instanceof MySync; },
function (o) {
return o.prop;
},
function (data) {
return new MySync(data);
}
]
});
const mys = new MySync(500);
assert.throws(() => {
typeson.stringifyAsync(mys);
}, TypeError, 'Async method requested but sync result obtained');
});
it('should throw with non-sync result to reviveSync', async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
revive (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.reviveSync(encapsAsync);
}, TypeError, 'Sync method requested but async result obtained');
});
it(
'shouldn\'t run do revival with reviveAsync-only spec and ' +
'reviveSync method',
async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
// eslint-disable-next-line no-sync
const revivedAsync = typeson.reviveSync(encapsAsync);
assert(revivedAsync === 500);
}
);
it('should throw with sync result to reviveAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: {
test (x) { return x instanceof MySync; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return new MySync(data);
},
reviveAsync (data) {
// Do something more useful in real code
return new MySync(data);
}
}
});
const mys = new MySync(500);
// eslint-disable-next-line no-sync
const encapsSync = typeson.encapsulateSync(mys);
assert.throws(() => {
typeson.reviveAsync(encapsSync);
}, TypeError, 'Async method requested but sync result obtained');
});
it('should throw with sync result to parseAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: {
test (x) { return x instanceof MySync; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return new MySync(data);
},
reviveAsync (data) {
// Do something more useful in real code
return new MySync(data);
}
}
});
const mys = new MySync(500);
// eslint-disable-next-line no-sync
const stringSync = typeson.stringifySync(mys);
assert.throws(() => {
typeson.parseAsync(stringSync);
}, TypeError, 'Async method requested but sync result obtained');
});
/*
it(
'should throw with missing async method and reviveAsync ' +
'(plain objects)',
() => {
const typeson = new Typeson().register({
mySyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return {prop: data};
}
}
});
const mys = {prop: 500};
// eslint-disable-next-line no-sync
const encapsSync = typeson.encapsulateSync(mys);
assert.throws(
() => {
typeson.reviveAsync(encapsSync);
},
TypeError,
'Async method requested but no async reviver'
);
}
);
it('should throw with missing async method and reviveAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: {
test (x) { return x instanceof MySync; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return new MySync(data);
}
}
});
const mys = new MySync(500);
// eslint-disable-next-line no-sync
const encapsSync = typeson.encapsulateSync(mys);
assert.throws(() => {
typeson.reviveAsync(encapsSync);
}, TypeError, 'Async method requested but no async reviver');
});
*/
it('should revive with reviveAsync', async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
assert(back instanceof MyAsync, 'Returns instance of MyAsync');
assert(back.prop === 500, 'Has same property value');
});
it('should revive with reviveAsync (plain objects)', async () => {
const typeson = new Typeson().register({
myAsyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) { return o.prop; },
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve({prop: data});
});
}
}
});
const obj = {prop: 52};
const encapsAsync = await typeson.encapsulate(obj);
const back = await typeson.reviveAsync(encapsAsync);
assert(back.prop === 52, 'Has same property value');
});
it(
'should revive with nested async revive (plain with ' +
'non-plain object)',
async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register([{
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
revive (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
}, {
myPlainAsyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) {
return o.prop;
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
}]);
const obj = {prop: 52};
const encapsAsync = await typeson.encapsulate(obj);
// console.log('encapsAsync', encapsAsync);
const back = await typeson.reviveAsync(encapsAsync);
// console.log('back', back);
assert(back instanceof MyAsync, 'Is MyAsync instance');
assert(back.prop === 52, 'Has same property value');
}
);
it(
'should revive with nested async revive (plain with plain object)',
async () => {
const typeson = new Typeson().register([{
undef: {
testPlainObjects: true,
test (x) {
return 'undef' in x;
},
replace (o) {
return null;
},
reviveAsync () {
return new Typeson.Undefined();
}
}
}, {
myPlainAsyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) {
// console.log('replace', o);
return {
prop: o.prop,
x: o.x,
sth: {
undef: null
}
};
},
reviveAsync (data) {
// console.log('revive', data);
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve({
prop: data.prop,
x: data.x,
extra: {prop: 5},
sth: data.sth
});
});
}
}
}]);
const obj = {
prop: 52,
x: {prop: 500},
sth: {
undef: null
}
};
const encapsAsync = await typeson.encapsulate(obj);
log('encapsAsync', encapsAsync);
const back = await typeson.reviveAsync(encapsAsync);
log('back', back);
assert(back.prop === 52, 'Outer is `myPlainAsyncType`');
assert(
back.sth instanceof Typeson.Undefined,
'Outer has `Undefined`'
);
assert(back.extra.prop === 5, 'Outer has extra prop');
assert(back.x.prop === 500, 'Inner is `myPlainAsyncType`');
assert(back.x.extra.prop === 5, 'Inner has extra prop');
assert(
back.x.sth instanceof Typeson.Undefined,
'Inner has `Undefined`'
);
}
);
it(
'should revive with reviveAsync with only revive on spec',
async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
revive (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
assert(back instanceof MyAsync, 'Returns instance of MyAsync');
assert(back.prop === 500, 'Has same property value');
}
);
it('should revive with `Typeson.Undefined` `reviveAsync`', async () => {
const typeson = new Typeson().register({
undefinedType: {
test (x) {
return x === undefined;
},
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new Typeson.Undefined());
});
}
}
});
const mya = undefined;
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
assert(back === undefined, 'Returns `undefined`');
});
it(
'should revive with `Promise` returned by `reviveAsync`',
async () => {
const typeson = new Typeson().register({
undefinedType: {
test (x) {
return x === undefined;
},
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return Promise.resolve(5);
}
}
});
const mya = undefined;
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
log(typeof back);
assert(back === 5, 'Resolves to `5`');
}
);
it(
'should revive with non-`Promise` returned by `reviveAsync`',
async () => {
const typeson = new Typeson().register({
undefinedType: {
test (x) {
return x === undefined;
},
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return 5;
}
}
});
const mya = undefined;
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync, {
throwOnBadSyncType: false
});
log(typeof back);
assert(back === 5, 'Resolves to `5`');
}
);
});
});
describe('Typeson.isThenable', () => {
it('should detect `catch` upon second argument being `true`', () => {
const thenable = Typeson.isThenable(Promise.resolve(), true);
assert(thenable, 'Promise found to have catch');
});
it(
'should detect missing `catch` upon second argument being `true`',
() => {
const notThenable = Typeson.isThenable({then () {}}, true);
assert(!notThenable, 'Object not found with a catch');
}
);
});
describe('Typeson.isUserObject', () => {
it('should detect non-user objects', () => {
const a = null;
const b = [];
const c = /test/u;
assert(!Typeson.isUserObject(a), 'null is not a user object');
assert(!Typeson.isUserObject(b), 'Array is not a user object');
assert(!Typeson.isUserObject(c), 'RegExp is not a user object');
});
it('should detect user objects', () => {
class A {
}
class B extends A {}
const c = Object.create(null);
const d = {};
const e = new B();
assert(
Typeson.isUserObject(c),
'Object with null prototype is a user object'
);
assert(Typeson.isUserObject(d), 'Object literal is a user object');
assert(
Typeson.isUserObject(e),
'Instance of user class is a user object'
);
});
});
describe('Typeson.hasConstructorOf', () => {
it(
'should detect whether an object has a "null" constructor ' +
'(i.e., `null` prototype)',
() => {
function B () {}
const a = Object.create(null);
assert(
Typeson.hasConstructorOf(a, null),
'Object with null prototype has a "null" constructor'
);
B.prototype = a;
const c = new B();
assert(
Typeson.hasConstructorOf(c, null),
'Object with null prototype has a "null" ancestor constructor'
);
}
);
it('should detect whether an object is of a particular constructor', () => {
const d = function () { /* Twin */ };
const e = new function () { /* Twin */ }();
assert(
Typeson.hasConstructorOf(e, d),
'Object has constructor that is identical to ' +
'another when stringified'
);
class Undefined {}
Undefined.__typeson__type__ = 'TypesonUndefined';
const undef = new Undefined();
assert(
Typeson.hasConstructorOf(undef, Typeson.Undefined),
'Instance of Typeson.Undefined has constructor identical ' +
'to Typeson.Undefined despite inconsistent stringification'
);
});
});
describe('Typeson.specialTypeNames', () => {
it('should retrieve special type names', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const typeNames = typeson.specialTypeNames([
5, new Date(), 'str', new Date()
]);
assert(
typeNames.length === 1 && typeNames[0] === 'Date',
'Should only return (unique) special type names'
);
});
it('should return false if no special type names found', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const typeNames = typeson.specialTypeNames([
5
]);
assert(
typeNames === false,
'Should return `false` on failing to find any special type names'
);
});
});
describe('Typeson.rootTypeName', () => {
it('should retrieve root type name when JSON', () => {
let runCount = 0;
const typeson = new Typeson({
encapsulateObserver (o) {
runCount++;
}
}).register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const rootTypeName = typeson.rootTypeName([
5, new Date(), 'str', new Date()
]);
assert(
rootTypeName === 'array',
'Should return the single root type name'
);
assert(
runCount === 1,
'Should not iterate through the array structure'
);
});
it('should retrieve root type name for a special type at root', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const rootTypeName = typeson.rootTypeName(
new Date()
);
assert(
rootTypeName === 'Date',
'Should return the single root type name'
);
});
});
describe('Typeson.Promise', function () {
it('should allow single Promise resolution', () => {
const typeson = new Typeson();
const x = new Typeson.Promise(function (res) {
setTimeout(function () {
res(25);
}, 500);
});
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back === 25,
'Should have resolved the one promise value'
);
return undefined;
});
});
it('should allow single nested Promise resolution', () => {
function APromiseUser (a) { this.a = a; }
const typeson = new Typeson().register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
PromiseUser: [
function (x) { return x instanceof APromiseUser; },
function (o) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(o.a);
}, 300);
});
},
function (val) { return new APromiseUser(val); }
]
});
const x = new Typeson.Promise(function (res) {
setTimeout(function () {
res(new APromiseUser(555));
}, 1200);
});
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back instanceof APromiseUser &&
back.a === 555,
'Should have resolved the one nested promise value'
);
return undefined;
});
});
it('should allow multiple Promise resolution', () => {
const typeson = new Typeson();
const x = [
Typeson.Promise.resolve(5),
100,
new Typeson.Promise(function (res) {
setTimeout(function () {
res(25);
}, 500);
})
];
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back[0] === 5 && back[1] === 100 && back[2] === 25,
'Should have resolved multiple promise values (and ' +
'in the proper order)'
);
return undefined;
});
});
it('should allow nested Promise resolution', () => {
function APromiseUser (a) { this.a = a; }
const typeson = new Typeson().register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
PromiseUser: [
function (x) { return x instanceof APromiseUser; },
function (o) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(o.a);
}, 300);
});
},
function (val) { return new APromiseUser(val); }
]
});
const x = [
Typeson.Promise.resolve(5),
100,
new Typeson.Promise(function (res) {
setTimeout(function () {
res(25);
}, 500);
}),
new Typeson.Promise(function (res) {
setTimeout(function () {
res(Typeson.Promise.resolve(5));
});
}).then(function (r) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(r + 90);
}, 10);
});
}),
Typeson.Promise.resolve(new Date()),
new Typeson.Promise(function (res) {
setTimeout(function () {
res(new APromiseUser(555));
});
})
];
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back[0] === 5 &&
back[1] === 100 &&
back[2] === 25 &&
back[3] === 95 &&
back[4] instanceof Date &&
back[5] instanceof APromiseUser &&
back[5].a === 555,
'Should have resolved multiple nested promise ' +
'values (and in the proper order)'
);
return undefined;
});
});
it('should work with Promise utilities', () => {
function makePromises () {
const x = new Typeson.Promise(function (res) {
setTimeout(function () {
res(30);
}, 50);
});
const y = Typeson.Promise.resolve(400);
return [x, y];
}
// eslint-disable-next-line promise/avoid-new
return new Promise(function (resolve, reject) {
// eslint-disable-next-line promise/catch-or-return
Typeson.Promise.all(makePromises()).then(function (results) {
assert(
// eslint-disable-next-line promise/always-return
results[0] === 30 && results[1] === 400,
'Should work with Promise.all'
);
}).then(function () {
// eslint-disable-next-line promise/no-nesting
return Typeson.Promise.race(
makePromises()
// eslint-disable-next-line promise/always-return
).then(function (results) {
assert(
results === 400,
'Should work with Promise.race'
);
resolve();
});
});
});
});
it('should properly handle Promise rejections', () => {
function makeRejectedPromises () {
const x = new Typeson.Promise(function (res, rej) {
setTimeout(function () {
rej(30);
}, 50);
});
const y = new Typeson.Promise(function (res, rej) {
setTimeout(function () {
res(500);
}, 500);
});
return [x, y];
}
// eslint-disable-next-line promise/avoid-new
return new Promise(function (resolve, reject) {
makeRejectedPromises()[0].then(null, function (errCode) {
assert(
errCode === 30,
'`Typeson.Promise` should work with ' +
'`then(null, onRejected)`'
);
return Typeson.Promise.reject(400);
}).catch(function (errCode) {
assert(
errCode === 400,
'`Typeson.Promise` should work with `catch`'
);
return Typeson.Promise.all(makeRejectedPromises());
}).catch(function (errCode) {
assert(
errCode === 30,
'Promise.all should work with rejected promises'
);
return Typeson.Promise.race(makeRejectedPromises());
}).catch(function (errCode) {
assert(
errCode === 30,
'Promise.race should work with rejected promises'
);
return new Typeson.Promise(function () {
throw new Error('Sync throw');
});
}).catch(function (err) {
assert(
err.message === 'Sync throw',
'Typeson.Promise should work with synchronous throws'
);
return Typeson.Promise.resolve(55);
}).then(null, function () {
throw new Error('Should not reach here');
}).then(function (res) {
assert(
res === 55,
'Typeson.Promises should bypass `then` ' +
'without `onResolved`'
);
return Typeson.Promise.reject(33);
}).then(function () {
throw new Error('Should not reach here');
}).catch(function (errCode) {
assert(
errCode === 33,
'Typeson.Promises should bypass `then` when rejecting'
);
resolve();
});
});
});
});
| test/test.js | /* globals assert */
/* eslint-disable no-console, no-restricted-syntax,
jsdoc/require-jsdoc, no-empty-function, no-shadow */
// import '../node_modules/core-js-bundle/minified.js';
import '../node_modules/regenerator-runtime/runtime.js';
import Typeson from '../typeson.js';
import * as B64 from
'../node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js';
const debug = false;
function log (...args) {
if (debug) {
console.log(...args);
}
}
const typeson = new Typeson().register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
Error: [
function (x) { return x instanceof Error; },
function (error) { return {name: error.name, message: error.message}; },
function (data) {
const e = new Error(data.message);
e.name = data.name;
return e;
}
],
SpecialNumber: [
function (x) {
return typeof x === 'number' &&
(isNaN(x) || x === Infinity || x === -Infinity);
},
function (n) {
return isNaN(n) ? 'NaN' : n > 0 ? 'Infinity' : '-Infinity';
},
function (s) {
return {NaN, Infinity, '-Infinity': -Infinity}[s];
}
],
ArrayBuffer: [
function test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },
function encapsulate (b) { return B64.encode(b); },
function revive (b64) { return B64.decode(b64); }
],
DataView: [
function (x) { return x instanceof DataView; },
function (dw) {
return {
buffer: dw.buffer,
byteOffset: dw.byteOffset,
byteLength: dw.byteLength
};
},
function (obj) {
return new DataView(obj.buffer, obj.byteOffset, obj.byteLength);
}
]
});
const globalTypeson = typeson;
function roundtrip (x) {
const tson = typeson.stringify(x, null, 2);
log(tson);
return typeson.parse(tson);
}
describe('Typeson', function () {
it('should support basic types', () => {
let res = roundtrip({});
assert(Object.keys(res).length === 0, 'Result should be empty');
const date = new Date();
const input = {
a: 'a', b: 2, c () {}, d: false, e: null,
f: Symbol('symbol'), g: [], h: date, i: /apa/gui
};
res = roundtrip(input);
assert(res !== input, 'Object is a clone, not a reference');
assert(res.a === 'a', 'String value');
assert(res.b === 2, 'Number value');
assert(!res.c, 'Functions should not follow by default');
assert(res.d === false, 'Boolean value');
assert(res.e === null, 'Null value');
assert(!res.f, 'Symbols should not follow by default');
assert(Array.isArray(res.g) && res.g.length === 0, 'Array value');
assert(
res.h instanceof Date && res.h.toString() === date.toString(),
'Date value'
);
assert(
Object.keys(res.i).length === 0,
'regex only treated as empty object by default'
);
});
it('should resolve nested objects', () => {
const input = {a: [{subA: 5}, [6, 7]], b: {subB: {c: 8}}};
const res = roundtrip(input);
assert(res.a[0].subA === 5, 'Object within array');
assert(res.a[1][0] === 6, 'Array within array');
assert(res.a[1][1] === 7, 'Array within array');
assert(res.b.subB.c === 8, 'Object within object');
});
it('should support object API', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const date = new Date();
const tson = typeson.stringify(date, null, 2);
log(tson);
const back = typeson.parse(tson);
assert(
back instanceof Date && back.toString() === date.toString(),
'Date value'
);
});
it('should support objects containing internally used properties', () => {
function test (data, cb) {
const tson = typeson.stringify(data, null, 2);
log(tson);
const result = typeson.parse(tson);
cb(result);
}
function valSwitch (val) {
test({$types: val}, function (result) {
assert(
result.$types === val &&
Object.keys(result).length === 1,
'Preserves $types on original object without additions'
);
});
test({$: val}, function (result) {
assert(
result.$ === val && Object.keys(result).length === 1,
'Preserves $ on original object without additions'
);
});
test({$: val, $types: val}, function (result) {
assert(
result.$ === val &&
result.$types === val &&
Object.keys(result).length === 2,
'Preserves $ and $types values on original ' +
'object without additions'
);
});
}
valSwitch(true);
valSwitch(false);
test(
{$: {}, $types: {$: {'': 'val', cyc: '#'}, '#': 'a1', '': 'b1'}},
function (result) {
assert(
typeof result.$ === 'object' &&
!Object.keys(result.$).length &&
result.$types.$[''] === 'val' &&
result.$types.$.cyc === '#' &&
result.$types['#'] === 'a1' &&
result.$types[''] === 'b1' &&
Object.keys(result.$types).length === 3,
'Preserves $ and $types subobjects on original ' +
'object without additions'
);
}
);
test({a: new Date(), $types: {}}, function (result) {
assert(
result.a instanceof Date &&
!('$' in result) &&
typeof result.$types === 'object' &&
!Object.keys(result.$types).length,
'Roundtrips type while preserving $types subobject ' +
'from original object without additions'
);
});
test({a: new Date(), $: {}}, function (result) {
assert(
result.a instanceof Date &&
!('$types' in result) &&
typeof result.$ === 'object' &&
!Object.keys(result.$).length,
'Roundtrips type while preserving $ subobject from ' +
'original object without additions'
);
});
test({a: new Date(), $types: {}, $: {}}, function (result) {
assert(
result.a instanceof Date &&
typeof result.$types === 'object' &&
!Object.keys(result.$types).length &&
typeof result.$ === 'object' &&
!Object.keys(result.$).length,
'Roundtrips type while preserving $ and $types subobjects ' +
'from original object without additions'
);
});
function valSwitch2 (val) {
test({a: new Date(), $types: val}, function (result) {
assert(
result.a instanceof Date &&
!('$' in result) &&
result.$types === val,
'Roundtrips type while preserving $types value ' +
'from original object'
);
});
test({a: new Date(), $: val}, function (result) {
assert(
result.a instanceof Date &&
!('$types' in result) &&
result.$ === val,
'Roundtrips type while preserving $ value ' +
'from original object'
);
});
test({a: new Date(), $types: val, $: val}, function (result) {
assert(
result.a instanceof Date &&
result.$types === val &&
result.$ === val,
'Roundtrips type while preserving $types and $ values ' +
'from original object'
);
});
}
valSwitch2(true);
valSwitch2(false);
test({a: new Date(), $: {}}, function (result) {
assert(
result.a instanceof Date &&
!('$types' in result) &&
typeof result.$ === 'object' &&
!Object.keys(result.$).length,
'Roundtrips type while preserving $ subojbect from original ' +
'object without additions'
);
});
});
it('should handle path separators in objects', () => {
const input = {
aaa: {
bbb: new Date(91000000000)
},
'aaa.bbb': 2,
lll: {
mmm: 3
},
'lll.mmm': new Date(92000000000),
'qqq.rrr': 4,
qqq: {
rrr: new Date(93000000000)
},
yyy: {
zzz: 5
},
'yyy.zzz': new Date(94000000000),
allNormal1: {
a: 100
},
'allNormal1.a': 200,
allTyped1: {
a: new Date(95000000000)
},
'allTyped1.a': new Date(96000000000),
'allNormal2.b': 400,
allNormal2: {
b: 500
},
allTyped2: {
b: new Date(97000000000)
},
'allTyped2.b': new Date(98000000000),
'A~': 'abc',
'A~1': 'ghi',
'A~0': 'def',
'A.': 'jkl',
'B~': new Date(99100000000),
'B~0': new Date(99200000000),
'B~1': new Date(99300000000),
'B.': new Date(99400000000)
};
const res = roundtrip(input);
assert(
res.aaa.bbb instanceof Date && res['aaa.bbb'] === 2 &&
res.aaa.bbb.getTime() === 91000000000,
'Properties with periods (with type) after normal ' +
'properties (without type)'
);
assert(
res['lll.mmm'] instanceof Date && res.lll.mmm === 3 &&
res['lll.mmm'].getTime() === 92000000000,
'Properties with periods (without type) after normal ' +
'properties (with type)'
);
assert(
res.qqq.rrr instanceof Date && res['qqq.rrr'] === 4 &&
res.qqq.rrr.getTime() === 93000000000,
'Properties with periods (without type) before normal ' +
'properties (with type)'
);
assert(
res['yyy.zzz'] instanceof Date && res.yyy.zzz === 5 &&
res['yyy.zzz'].getTime() === 94000000000,
'Properties with periods (with type) before normal ' +
'properties (without type)'
);
assert(
res.allNormal1.a === 100 && res['allNormal1.a'] === 200,
'Properties with periods (without type) after normal ' +
'properties (without type)'
);
assert(
res.allTyped1.a instanceof Date &&
res['allTyped1.a'] instanceof Date &&
res.allTyped1.a.getTime() === 95000000000 &&
res['allTyped1.a'].getTime() === 96000000000,
'Properties with periods (with type) after normal ' +
'properties (with type)'
);
assert(
res.allNormal2.b === 500 && res['allNormal2.b'] === 400,
'Properties with periods (without type) before normal ' +
'properties (without type)'
);
assert(
res.allTyped2.b instanceof Date &&
res['allTyped2.b'] instanceof Date &&
res.allTyped2.b.getTime() === 97000000000 &&
res['allTyped2.b'].getTime() === 98000000000,
'Properties with periods (with type) after normal ' +
'properties (with type)'
);
assert(
res['A~'] === 'abc' &&
res['A~0'] === 'def' &&
res['A~1'] === 'ghi' &&
res['A.'] === 'jkl' &&
res['B~'] instanceof Date &&
res['B~'].getTime() === 99100000000 &&
res['B~0'] instanceof Date &&
res['B~0'].getTime() === 99200000000 &&
res['B~1'] instanceof Date &&
res['B~1'].getTime() === 99300000000 &&
res['B.'] instanceof Date &&
res['B.'].getTime() === 99400000000,
'Find properties with escaped and unescaped characters'
);
});
it('should support arrays', () => {
const res = roundtrip([1, new Date(), 3]);
assert(Array.isArray(res), 'Result should be an array');
assert(res.length === 3, 'Should have length 3');
assert(res[2] === 3, 'Third item should be 3');
});
it('should support intermediate types', () => {
function CustomDate (date) {
this._date = date;
}
const typeson = new Typeson()
.register(globalTypeson.types)
.register({
CustomDate: [
(x) => x instanceof CustomDate,
(cd) => cd._date,
(date) => new CustomDate(date)
]
});
const date = new Date();
const input = new CustomDate(new Date());
const tson = typeson.stringify(input);
log(tson);
const back = typeson.parse(tson);
assert(back instanceof CustomDate, 'Should get CustomDate back');
assert(
back._date.getTime() === date.getTime(),
'Should have correct value'
);
});
it('should support intermediate types (async)', async () => {
function CustomDate (date) {
this._date = date;
}
const typeson = new Typeson()
.register({
date: {
test (x) { return x instanceof Date; },
replaceAsync (date) {
return new Typeson.Promise((resolve, reject) => {
setTimeout(() => {
resolve(date.getTime());
});
});
},
reviveAsync (time) {
return new Typeson.Promise((resolve, reject) => {
setTimeout(() => {
resolve(new Date(time));
});
});
}
}
})
.register({
CustomDate: {
test (x) {
return x instanceof CustomDate;
},
replaceAsync (cd) {
return cd._date;
},
reviveAsync (date) {
return new CustomDate(date);
}
}
});
const date = new Date();
const input = new CustomDate(new Date());
const tson = await typeson.stringifyAsync(input);
log(tson);
const back = await typeson.parseAsync(tson);
assert(back instanceof CustomDate, 'Should get CustomDate back');
assert(
back._date.getTime() === date.getTime(),
'Should have correct value'
);
});
it('should run replacers recursively', () => {
function CustomDate (date, name) {
this._date = date;
this.name = name;
this.year = date.getFullYear();
}
CustomDate.prototype.getRealDate = function () {
return this._date;
};
CustomDate.prototype.getName = function () {
return this.name;
};
const date = new Date();
const input = {
name: 'Karl',
date: new CustomDate(date, 'Otto')
};
const typeson = new Typeson()
.register(globalTypeson.types)
.register({
CustomDate: [
(x) => x instanceof CustomDate,
(cd) => ({_date: cd.getRealDate(), name: cd.name}),
(obj) => new CustomDate(obj._date, obj.name)
]
});
const tson = typeson.stringify(input, null, 2);
log(tson);
const result = typeson.parse(tson);
assert(result.name === 'Karl', 'Basic prop');
assert(
result.date instanceof CustomDate,
'Correct instance type of custom date'
);
assert(
result.date.getName() === 'Otto',
'prototype method works and properties seems to be in place'
);
assert(
result.date.getRealDate().getTime() === date.getTime(),
'The correct time is there'
);
});
it('should be able to stringify complex objects at root', () => {
const x = roundtrip(new Date(3));
assert(x instanceof Date, 'x should be a Date');
assert(x.getTime() === 3, 'Time should be 3');
const y = roundtrip([new Date(3)]);
assert(y[0] instanceof Date, 'y[0] should be a Date');
assert(y[0].getTime() === 3, 'Time should be 3');
function Custom () {
this.x = 'oops';
}
let TSON = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(s) => false,
(f) => new Custom()
]
});
let tson = TSON.stringify(new Custom());
log(tson);
let z = TSON.parse(tson);
assert(
z instanceof Custom && z.x === 'oops',
'Custom type encapsulated in bool should work'
);
TSON = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(s) => 42,
(f) => new Custom()
]
});
tson = TSON.stringify(new Custom());
log(tson);
z = TSON.parse(tson);
assert(
z instanceof Custom && z.x === 'oops',
'Custom type encapsulated in bool should work'
);
TSON = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(s) => 'foo',
(f) => new Custom()
]
});
tson = TSON.stringify(new Custom());
log(tson);
z = TSON.parse(tson);
assert(
z instanceof Custom && z.x === 'oops',
'Custom type encapsulated in bool should work'
);
});
it(
'should be possible to encapsulate object with reserved `$types` ' +
'property',
() => {
function Custom (val, $types) {
this.val = val;
this.$types = $types;
}
const typeson = new Typeson().register({
Custom: [
(x) => x instanceof Custom,
(c) => ({val: c.val, $types: c.$types}),
(o) => new Custom(o.val, o.$types)
]
});
const input = new Custom('bar', 'foo');
const tson = typeson.stringify(input);
log(tson);
const x = typeson.parse(tson);
assert(x instanceof Custom, 'Should get a Custom back');
assert(x.val === 'bar', 'Should have correct val value');
assert(x.$types === 'foo', 'Should have correct $types value');
}
);
/*
// Todo?
it('should leave left out type', () => {
// Uint8Buffer is not registered.
});
*/
it('executing toJSON', () => {
function A () {}
A.prototype.toJSON = function () { return 'abcd'; };
let typeson = new Typeson();
let a = new A(); // Encapsulated as is
let tson = typeson.stringify(a);
log(tson);
let back = typeson.parse(tson);
assert(back === 'abcd', 'Should have executed `toJSON`');
typeson = new Typeson();
// Plain object rebuilt during encapsulation including with `toJSON`
a = {
toJSON () { return 'abcd'; }
};
tson = typeson.stringify(a);
log(tson);
back = typeson.parse(tson);
assert(back === 'abcd', 'Should have executed `toJSON`');
});
it('should allow plain object replacements', () => {
const typeson = new Typeson().register({
plainObj: {
testPlainObjects: true,
test (x) {
return 'nonenum' in x;
},
replace (o) {
return {
b: o.b,
nonenum: o.nonenum
};
}
}
});
const a = {b: 5};
Object.defineProperty(a, 'nonenum', {
enumerable: false,
value: 100
});
let tson = typeson.stringify(a);
log(tson);
let back = typeson.parse(tson);
assert(back.b === 5, 'Should have kept property');
assert(
back.nonenum === 100,
'Should have kept non-enumerable property'
);
assert(
{}.propertyIsEnumerable.call(back, 'nonenum'),
'Non-enumerable property should now be enumerable'
);
const x = Object.create(null);
x.b = 7;
Object.defineProperty(x, 'nonenum', {
enumerable: false,
value: 50
});
tson = typeson.stringify(x);
log(tson);
back = typeson.parse(tson);
assert(back.b === 7, 'Should have kept property');
assert(back.nonenum === 50, 'Should have kept non-enumerable property');
assert(
{}.propertyIsEnumerable.call(back, 'nonenum'),
'Non-enumerable property should now be enumerable'
);
});
it('should allow forcing of async return', () => {
const typeson = new Typeson({sync: false, throwOnBadSyncType: false});
const x = 5;
return typeson.stringify(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back === 5,
'Should allow async to be forced even without ' +
'async return values'
);
return undefined;
});
});
it('should transmit state through replacers and revivers', () => {
function ReplaceReviver (obj) {
Object.defineProperty(this, 'obj', {
enumerable: false,
value: obj
});
}
ReplaceReviver.prototype[Symbol.toStringTag] = 'ReplaceReviver';
const typeson = new Typeson().register({
replaceReviveContainer: {
test (x) {
return Typeson.toStringTag(x) === 'ReplaceReviver';
},
replace (b, stateObj) {
if (!stateObj.objs) {
stateObj.objs = [];
}
const index = stateObj.objs.indexOf(b.obj);
if (index > -1) {
return {index};
}
stateObj.objs.push(b.obj);
return {
obj: b.obj
};
},
revive (o, stateObj) {
if (!stateObj.objs) {
stateObj.objs = [];
}
if ('index' in o) {
return stateObj.objs[o.index];
}
const rr = new ReplaceReviver(o.obj);
stateObj.objs.push(rr);
return rr;
}
}
});
const rrObj1 = {value: 10};
const rrObj2 = {value: 353};
const rrObjXYZ = {value: 10};
const rr1 = new ReplaceReviver(rrObj1);
const rr2 = new ReplaceReviver(rrObj2);
const rr3 = new ReplaceReviver(rrObj1);
const rrXYZ = new ReplaceReviver(rrObjXYZ);
const obj = {rr1, rr2, rr3, rrXYZ};
const tson = typeson.stringify(obj);
log(tson);
const back = typeson.parse(tson);
assert(back.rr1.obj.value === 10, 'Should preserve value (rr1)');
assert(back.rr2.obj.value === 353, 'Should preserve value (rr2)');
assert(back.rr3.obj.value === 10, 'Should preserve value (rr3)');
assert(back.rrXYZ.obj.value === 10, 'Should preserve value (rrXYZ)');
assert(back.rr1.obj === back.rr3.obj, 'Should preserve objects');
assert(
back.rr1.obj !== back.rrXYZ.obj,
'Should not confuse objects where only value is the same'
);
});
it('should allow serializing arrays to objects', () => {
let endIterateIn;
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateIn) {
endIterateIn = true;
}
}
}).register({
arraysToObjects: {
testPlainObjects: true,
test (x, stateObj) {
if (Array.isArray(x)) {
stateObj.iterateIn = 'object';
stateObj.addLength = true;
return true;
}
return false;
},
revive (o) {
const arr = [];
// No map here as may be a sparse array (including
// with `length` set)
Object.entries(o).forEach(([key, val]) => {
arr[key] = val;
});
return arr;
}
}
});
const arr = new Array(10);
arr[0] = 3;
arr[2] = {arr};
arr[2].f = [[arr]];
arr[3] = '4';
arr[4] = 5;
arr[6] = arr;
arr[7] = [arr];
arr[9] = {arr};
arr.b = 'ddd';
arr[-2] = 'eee';
arr[9].f = [[arr]];
const tson = typeson.stringify(arr, null, 2);
log('tson', tson);
assert(endIterateIn, 'Observes `endIterateIn` state');
const back = typeson.parse(tson);
log('back', back);
assert(
back[0] === 3 && back[3] === '4' && back[4] === 5,
'Preserves regular array indexes'
);
assert(
back.b === 'ddd' && back[-2] === 'eee',
'Preserves non-numeric and non-positive-integer indexes'
);
assert(
back[6] === back &&
back[7][0] === back &&
Array.isArray(back),
'Preserves circular array references'
);
assert(
Array.isArray(back[2].arr), 'Preserves cyclic array on object'
);
assert(
Array.isArray(back[9].arr), 'Preserves cyclic array on object'
);
assert(
back[2].f[0][0] === back, 'Preserves nested cyclic array'
);
assert(
back[9].f[0][0] === back, 'Preserves nested cyclic array'
);
});
it('should allow serializing arrays to objects', () => {
const typeson = new Typeson().register({
arraysToObjects: {
testPlainObjects: true,
test (x, stateObj) {
if (Array.isArray(x)) {
stateObj.iterateIn = 'object';
stateObj.addLength = true;
return true;
}
return false;
},
revive (o) {
const arr = [];
// No map here as may be a sparse array (including
// with `length` set)
Object.entries(o).forEach(([key, val]) => {
arr[key] = val;
});
return arr;
}
}
});
const arr = new Array(10);
arr[2] = {arr};
arr[2].f = [[arr]];
const tson = typeson.stringify(arr, null, 2);
log(tson);
const tsonStringifiedSomehowWithNestedTypesFirst = `
{
"2": {
"arr": "#",
"f": {
"0": {
"0": "#",
"length": 1
},
"length": 1
}
},
"length": 10,
"$types": {
"2.f.0.0": "#",
"": "arraysToObjects",
"2.arr": "#",
"2.f.0": "arraysToObjects",
"2.f": "arraysToObjects"
}
}
`;
const back = typeson.parse(tsonStringifiedSomehowWithNestedTypesFirst);
log('back', back);
assert(
Array.isArray(back[2].arr), 'Preserves cyclic array on object'
);
assert(
back[2].f[0][0] === back, 'Preserves nested cyclic array'
);
});
it('should allow unknown string tags', () => {
const map = {
map: {
test (x) { return Typeson.toStringTag(x) === 'Map'; },
replace (mp) { return [...mp.entries()]; },
revive (entries) { return new Map(entries); }
}
};
const typeson = new Typeson().register([map]);
const a = {
__raw_map: new Map(),
[Symbol.toStringTag]: 'a'
};
const tson = typeson.stringify(a, null, 2);
log('tson', tson);
const back = typeson.parse(tson);
assert(
back.__raw_map instanceof Map,
'Revives `Map` on class with Symbol.toStringTag'
);
// Todo: Need to implement Symbol iteration
// assert(
// back[Symbol.toStringTag] === 'a',
// 'Revives `Symbol.toStringTag`'
// );
});
it('should throw upon attempt to parse type that is not registered', () => {
const map = {
map: {
test (x) { return Typeson.toStringTag(x) === 'Map'; },
replace (mp) { return [...mp.entries()]; },
revive (entries) { return new Map(entries); }
}
};
const typeson = new Typeson().register([map]);
const a = {
someMap: new Map()
};
const tson = typeson.stringify(a, null, 2);
log('tson', tson);
const newTypeson = new Typeson();
assert.throws(
() => {
newTypeson.parse(tson);
},
Error,
'Unregistered type: map',
'Typeson instance without type'
);
});
it(
'should throw upon attempt to parse type that is not registered ' +
'(plain objects)',
() => {
const typeson = new Typeson().register([{
mySyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) { return o.prop; },
revive (data) { return {prop: data}; }
}
}]);
const obj = {prop: 52};
const tson = typeson.stringify(obj, null, 2);
log('tson', tson);
const newTypeson = new Typeson();
assert.throws(
() => {
newTypeson.parse(tson);
},
Error,
'Unregistered type: mySyncType',
'Typeson instance without type'
);
}
);
describe('Type error checking', () => {
it('disallows hash type', () => {
assert.throws(
() => {
new Typeson().register({'#': [
function () {}, function () {}, function () {}
]});
},
TypeError,
'# cannot be used as a type name as it is reserved ' +
'for cyclic objects',
'Should throw on attempting to register the ' +
"reserved 'type', '#'"
);
});
it('disallows JSON type names', () => {
const ok = [
'null', 'boolean', 'number', 'string', 'array', 'object'
].every((type) => {
let caught = false;
try {
new Typeson().register({
[type]: [function () {}, function () {}, function () {}]
});
} catch (err) {
caught = true;
}
return caught;
});
assert(
ok,
'Should throw on attempting to register the reserved JSON ' +
'object type names'
);
});
});
describe('Cyclics', () => {
it('should resolve cyclics', () => {
const data = {list: []};
for (let i = 0; i < 10; ++i) {
data.list.push({
name: 'name' + i,
parent: data.list,
root: data,
children: []
});
}
data.list[3].children = [data.list[0], data.list[1]];
const tson = typeson.stringify(data, null, 2);
log(tson);
const result = typeson.parse(tson);
assert(
result.list.length === 10,
'result.list.length should be 10'
);
assert(
result.list[3].children.length === 2,
'result.list[3] should have 2 children'
);
assert(
result.list[3].children[0] === result.list[0],
'First child of result.list[3] should be result.list[0]'
);
});
it('should resolve cyclics 2', () => {
const kalle = {name: 'Kalle', age: 33};
const input = [kalle, kalle, kalle];
const tson = typeson.stringify(input);
log(tson.match(/Kalle/gu).length);
log(tson);
assert(
tson.match(/Kalle/gu).length === 1,
"TSON should only contain one 'Kalle'. The others should " +
'just reference the first'
);
const result = typeson.parse(tson);
assert(
result[0] === result[1] && result[1] === result[2],
'The resulting object should also just have references ' +
'to the same object'
);
});
it('should resolve cyclic arrays', () => {
const recursive = [];
recursive.push(recursive);
let tson = typeson.stringify(recursive);
let result = typeson.parse(tson);
assert(result === result[0], 'array directly contains self');
const recursive2 = [];
recursive2.push([recursive2]);
tson = typeson.stringify(recursive2);
result = typeson.parse(tson);
assert(
result !== result[0] && result === result[0][0],
'array indirectly contains self'
);
const recursive3 = [recursive];
tson = typeson.stringify(recursive3);
log(tson);
result = typeson.parse(tson);
assert(
result !== result[0] && result !== result[0][0] &&
result[0] === result[0][0],
'array member contains self'
);
const recursive4 = [1, recursive];
tson = typeson.stringify(recursive4);
log(tson);
result = typeson.parse(tson);
assert(
result !== result[1] && result !== result[1][0] &&
result[1] === result[1][0],
'array member contains self'
);
});
it('should resolve cyclic object members', () => {
// eslint-disable-next-line sonarjs/prefer-object-literal
const recursive = {};
recursive.b = recursive;
const recursiveContainer = {a: recursive};
const tson = typeson.stringify(recursiveContainer);
log(tson);
const result = typeson.parse(tson);
assert(
result !== result.a && result !== result.b &&
result.a === result.a.b,
'Object property contains self'
);
});
it('should not resolve cyclics if not wanted', () => {
const kalle = {name: 'Kalle', age: 33};
const input = [kalle, kalle, kalle];
const typeson = new Typeson({cyclic: false});
const tson = typeson.stringify(input);
const json = JSON.stringify(input);
assert(
tson === json,
'TSON should be identical to JSON because the input is ' +
'simple and the cyclics of the input should be ignored'
);
});
it('should resolve cyclics in encapsulated objects', () => {
const buf = new ArrayBuffer(16);
const data = {
buf,
bar: {
data: new DataView(buf, 8, 8)
}
};
const tson = typeson.stringify(data, null, 2);
log(tson);
const back = typeson.parse(tson);
assert(
back.buf === back.bar.data.buffer,
'The buffers point to same object'
);
});
});
describe('Registration', () => {
it(
'should support registering a class without replacer or ' +
'reviver (by constructor/class)',
() => {
function MyClass () {}
const TSON = new Typeson().register({MyClass});
const x = new MyClass();
x.hello = 'world';
const tson = TSON.stringify(x);
log(tson);
const back = TSON.parse(tson);
assert(
back instanceof MyClass,
'Should revive to a MyClass instance.'
);
assert(
back.hello === 'world',
'Should have all properties there.'
);
}
);
it(
'should get observer event when registering a class ' +
'with only test',
() => {
let typeDetected;
const TSON = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected) {
typeDetected = true;
}
}
}).register([{
myType: {
testPlainObjects: true,
test (x) {
return 'prop' in x;
}
}
}]);
const x = {prop: 5};
const tson = TSON.stringify(x);
log(tson);
assert(typeDetected, 'Type was detected');
}
);
it('should execute replacers in proper order', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson().register([
{specificClassFinder: [
(x) => x instanceof Person, () => 'specific found'
]},
{genericClassFinder: [
(x) => x && typeof x === 'object', () => 'general found'
]}
]);
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'general found',
'Should execute replacers in proper order'
);
});
it('should execute replacers with `fallback` in proper order', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{specificClassFinder: [
(x) => x instanceof Person, () => 'specific found'
]}
]);
typeson.register([
{genericClassFinder: [
(x) => x && typeof x === 'object', () => 'general found'
]}
], {
fallback: 0
});
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'specific found',
'Should execute replacers in proper order'
);
});
it('should execute replacers with `fallback` in proper order', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{specificClassFinder: [
(x) => x instanceof Person, () => 'specific found'
]}
]);
typeson.register([
{genericClassFinder: [
(x) => x && typeof x === 'object', () => 'general found'
]}
], {
fallback: true
});
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'specific found',
'Should execute replacers in proper order'
);
});
it('should silently ignore nullish spec', () => {
function Person () {}
function Dog () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{
classFinder: [
(x) => x instanceof Person, () => 'person found'
],
badType: null
}
]);
typeson.register([
{
anotherBadType: null,
anotherClassFinder: [
(x) => x instanceof Dog, () => 'dog found'
]
}
]);
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'person found',
'Should find item despite nullish specs'
);
});
it('should allow replacing previously registered replacer', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{classFinder: [
(x) => x instanceof Person, () => 'found'
]}
]);
typeson.register(
[{classFinder: [
(x) => x instanceof Person, () => 'later found'
]}]
);
const clonedData = typeson.parse(typeson.stringify(john));
assert(
clonedData === 'later found',
'Should replace previously registered replacer'
);
});
it('should allow removing previously registered replacer', () => {
function Person () {}
const john = new Person();
const typeson = new Typeson();
typeson.register([
{classFinder: [
(x) => x instanceof Person, () => 'found'
]}
]);
typeson.register(
[{classFinder: null}]
);
const encapsulatedData = typeson.encapsulate(john);
assert(
!encapsulatedData.$types,
'Encapsulated should have no special type'
);
});
it(
'should allow removing previously registered replacer ' +
'(plain objects)',
() => {
const typeson = new Typeson();
typeson.register({
plainObj: {
testPlainObjects: true,
test (x) {
return 'nonenum' in x;
},
replace (o) {
return {
b: o.b,
nonenum: o.nonenum
};
}
}
});
typeson.register({plainObj: {
testPlainObjects: true
}});
const a = {b: 5};
Object.defineProperty(a, 'nonenum', {
enumerable: false,
value: 100
});
const encapsulatedData = typeson.encapsulate(a);
assert(
!encapsulatedData.$types,
'Encapsulated should have no special type'
);
}
);
});
describe('encapsulateObserver', () => {
it('should run encapsulateObserver sync', () => {
const expected = '{\n' +
' time: 959000000000\n' +
' vals: [\n' +
' 0: null\n' +
' 1: undefined\n' +
' 2: 5\n' +
' 3: str\n' +
' ]\n' +
' cyclicInput: #\n' +
'}\n';
let str = '';
let indentFactor = 0;
const indent = function () {
return new Array(indentFactor * 4 + 1).join(' ');
};
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected || o.replacing) {
return;
}
const isObject = o.value && typeof o.value === 'object';
const isArray = Array.isArray(o.value);
if (o.end) {
indentFactor--;
str += indent() + (isArray ? ']' : '}') + '\n';
return;
}
if (!('replaced' in o)) {
if (isArray) {
if (!('clone' in o)) {
return;
}
str += indent() +
(o.keypath ? o.keypath + ': ' : '') +
'[\n';
indentFactor++;
return;
}
if (isObject) {
if ('cyclicKeypath' in o) {
o.value = '#' + o.cyclicKeypath;
} else {
str += indent() + '{\n';
indentFactor++;
return;
}
}
} else if (isObject) {
// Special type that hasn't been finally resolved yet
return;
}
const idx = o.keypath.lastIndexOf('.') + 1;
str += indent() + o.keypath.slice(idx) + ': ' +
('replaced' in o ? o.replaced : o.value) + '\n';
}
})
.register(globalTypeson.types);
const input = {
time: new Date(959000000000),
vals: [null, undefined, 5, 'str']
};
input.cyclicInput = input;
/* const tson = */ typeson.encapsulate(input);
log(str);
log(expected);
assert(
str === expected,
'Observer able to reduce JSON to expected string'
);
});
it('encapsulateObserver should observe types', () => {
const actual = [];
const expected = [
'object', 'Date', 'array', 'null',
'undefined', 'number', 'string'
];
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected || o.replacing) {
return;
}
if (o.cyclic !== 'readonly' && !o.end) {
actual.push(o.type);
}
}
}).register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
]
});
const input = {
time: new Date(959000000000),
vals: [null, undefined, 5, 'str']
};
/* const tson = */ typeson.encapsulate(input);
assert(
actual.length === expected.length &&
actual.every((type, i) => type === expected[i]),
'Should report primitive and compound types'
);
});
it('should run encapsulateObserver async', () => {
let str = '';
const placeholderText = '(Please wait for the value...)';
function APromiseUser (a) { this.a = a; }
const typeson = new Typeson({
encapsulateObserver (o) {
if (o.typeDetected || o.replacing) {
return;
}
const isObject = o.value && typeof o.value === 'object';
const isArray = Array.isArray(o.value);
if (o.resolvingTypesonPromise) {
const idx = str.indexOf(placeholderText);
const start = str.slice(0, idx);
const end = str.slice(idx + placeholderText.length);
str = start + o.value + end;
} else if (o.awaitingTypesonPromise) {
str += '<span>' + placeholderText + '</span>';
} else if (!isObject && !isArray) {
str += '<span>' + o.value + '</span>';
}
}
}).register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
PromiseUser: [
function (x) { return x instanceof APromiseUser; },
function (o) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(o.a);
}, 300);
});
},
function (val) { return new APromiseUser(val); }
]
});
const input = ['aaa', new APromiseUser(5), 'bbb'];
const prom = typeson.encapsulateAsync(input).then(
function (encaps) {
const back = typeson.parse(JSON.stringify(encaps));
assert(
back[0] === input[0] &&
back[2] === input[2] &&
back[1] instanceof APromiseUser &&
back[1].a === 5,
'Should have resolved the one nested promise value'
);
log(str);
assert(
str === '<span>aaa</span><span>5</span>' +
'<span>bbb</span>',
'Should have allowed us to run the callback ' +
'asynchronously (where we can substitute a ' +
'placeholder)'
);
return undefined;
}
);
assert(
str === '<span>aaa</span><span>' + placeholderText +
'</span><span>bbb</span>',
'Should have allowed us to run the callback synchronously ' +
'(where we add a placeholder)'
);
return prom;
});
});
describe('Iteration', () => {
it('should allow `iterateIn`', () => {
function A (a) {
this.a = a;
}
function createExtendingClass (a) {
function B (b, isArr) {
this[3] = 4;
this.b = b;
this.isArr = isArr;
}
B.prototype = new A(a);
return B;
}
const typeson = new Typeson().register({
iterateIn: {
test (x, stateObj) {
if (x instanceof A) {
stateObj.iterateIn = x.isArr ? 'array' : 'object';
return true;
}
return false;
}
}
});
const B = createExtendingClass(5);
let b = new B(7);
let tson = typeson.stringify(b);
log(tson);
let back = typeson.parse(tson);
assert(!Array.isArray(back), 'Is not an array');
assert(back[3] === 4, 'Has numeric property');
assert(back.a === 5, "Got inherited 'a' property");
assert(back.b === 7, "Got own 'b' property");
b = new B(8, true);
tson = typeson.stringify(b);
log(tson);
back = typeson.parse(tson);
assert(Array.isArray(back), 'Is an array');
assert(back[3] === 4, 'Has numeric property');
assert(
!('a' in back),
"'a' property won't survive array stringification"
);
assert(
!('b' in back),
"'b' property won't survive array stringification"
);
});
it('should allow `iterateIn` (async)', async () => {
function A (a) {
this.a = a;
}
function createExtendingClass (a) {
function B (b, isArr) {
this[3] = 4;
this.b = b;
this.c = new MyAsync('abc');
this.isArr = isArr;
}
B.prototype = new A(a);
return B;
}
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register([{
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new MyAsync(data));
});
}
}
}, {
iterateIn: {
test (x, stateObj) {
if (x instanceof A) {
stateObj.iterateIn = x.isArr ? 'array' : 'object';
return true;
}
return false;
},
replaceAsync (val) {
return new Typeson.Promise((resolve) => {
setTimeout(() => {
resolve(val);
});
});
},
reviveAsync (val) {
return new Typeson.Promise((resolve) => {
setTimeout(() => {
resolve(val);
});
});
}
}
}]);
const B = createExtendingClass(5);
let b = new B(7);
let tson = await typeson.stringifyAsync(b);
log(tson);
let back = await typeson.parseAsync(tson);
assert(!Array.isArray(back), 'Is not an array');
assert(back[3] === 4, 'Has numeric property');
assert(back.a === 5, "Got inherited 'a' property");
assert(back.b === 7, "Got own 'b' property");
assert(back.c instanceof MyAsync, "Got own 'c' property");
b = new B(8, true);
tson = await typeson.stringifyAsync(b);
log(tson);
back = await typeson.parseAsync(tson);
assert(Array.isArray(back), 'Is an array');
assert(back[3] === 4, 'Has numeric property');
assert(
!('a' in back),
"'a' property won't survive array stringification"
);
assert(
!('b' in back),
"'b' property won't survive array stringification"
);
assert(
!('c' in back),
"'c' property won't survive array stringification"
);
});
it('should allow `iterateUnsetNumeric`', () => {
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' &&
stateObj.ownKeys === false;
},
replace (n) { return 0; },
// Will avoid adding anything
revive (s) { return undefined; }
}
}
];
let endIterateUnsetNumeric;
let typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateUnsetNumeric) {
endIterateUnsetNumeric = true;
}
}
}).register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
let arr = [, 5, , , 6, ];
let tson = typeson.stringify(arr);
log(tson);
assert(
endIterateUnsetNumeric,
'Observer should get `endIterateUnsetNumeric`'
);
let back = typeson.parse(tson);
assert(!('0' in back), 'Undefined at index 0');
assert(back[1] === 5 && back[4] === 6, 'Set values restored');
assert(!('2' in back), 'Undefined at index 2');
assert(!('3' in back), 'Undefined at index 3');
assert(!('5' in back), 'Undefined at index 5');
// Once again for coverage of absent observer and
// nested keypath
typeson = new Typeson().register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
arr = {a: [, 5, , , 6, ]};
tson = typeson.stringify(arr);
log(tson);
back = typeson.parse(tson);
assert(!('0' in back.a), 'Undefined at index 0');
});
it('should allow `iterateUnsetNumeric` (storing `undefined`)', () => {
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' &&
stateObj.ownKeys === false;
},
replace (n) { return undefined; },
// Will avoid adding anything
revive (s) { return undefined; }
}
}
];
let endIterateUnsetNumeric;
let typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateUnsetNumeric) {
endIterateUnsetNumeric = true;
}
}
}).register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
let arr = [, 5, , , 6, ];
let tson = typeson.stringify(arr);
log(tson);
assert(
endIterateUnsetNumeric,
'Observer should get `endIterateUnsetNumeric`'
);
let back = typeson.parse(tson);
assert(!('0' in back), 'Undefined at index 0');
assert(back[1] === 5 && back[4] === 6, 'Set values restored');
assert(!('2' in back), 'Undefined at index 2');
assert(!('3' in back), 'Undefined at index 3');
assert(!('5' in back), 'Undefined at index 5');
// Once again for coverage of absent observer and
// nested keypath
typeson = new Typeson().register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
arr = {a: [, 5, , , 6, ]};
tson = typeson.stringify(arr);
log(tson);
back = typeson.parse(tson);
assert(!('0' in back.a), 'Undefined at index 0');
});
it('should allow `iterateUnsetNumeric` (async)', async () => {
const sparseUndefined = [
{
sparseArrays: {
testPlainObjects: true,
test (x) { return Array.isArray(x); },
replace (a, stateObj) {
stateObj.iterateUnsetNumeric = true;
return a;
}
}
},
{
sparseUndefined: {
test (x, stateObj) {
return typeof x === 'undefined' &&
stateObj.ownKeys === false;
},
replaceAsync (n) {
return new Typeson.Promise((resolve) => {
setTimeout(() => {
resolve(0);
});
});
},
// Will avoid adding anything
revive (s) { return undefined; }
}
}
];
let endIterateUnsetNumeric;
let typeson = new Typeson({
encapsulateObserver (o) {
if (o.endIterateUnsetNumeric) {
endIterateUnsetNumeric = true;
}
}
}).register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
let arr = [, 5, , , 6, ];
let tson = await typeson.stringifyAsync(arr);
log(tson);
assert(
endIterateUnsetNumeric,
'Observer should get `endIterateUnsetNumeric`'
);
let back = typeson.parse(tson);
assert(!('0' in back), 'Undefined at index 0');
assert(back[1] === 5 && back[4] === 6, 'Set values restored');
assert(!('2' in back), 'Undefined at index 2');
assert(!('3' in back), 'Undefined at index 3');
assert(!('5' in back), 'Undefined at index 5');
// Once again for coverage of absent observer and
// nested keypath
typeson = new Typeson().register([sparseUndefined]);
// eslint-disable-next-line max-len
// eslint-disable-next-line no-sparse-arrays, comma-dangle, array-bracket-spacing
arr = {a: [, 5, , , 6, ]};
tson = await typeson.stringifyAsync(arr);
log(tson);
back = typeson.parse(tson);
assert(!('0' in back.a), 'Undefined at index 0');
});
});
describe('Async vs. Sync', () => {
it('async README example', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson({sync: false}).register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
return typeson.stringify(mya).then(function (result) {
const back = typeson.parse(result, null, {sync: true});
assert(
back.prop === 500,
'Example of MyAsync should work'
);
return undefined;
});
});
it('should work with stringifyAsync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
return typeson.stringifyAsync(mya).then(function (result) {
const back = typeson.parse(result);
assert(
back.prop === 500,
'Example of MyAsync should work'
);
return typeson.stringifyAsync({prop: 5}, null, null, {
throwOnBadSyncType: false
});
}).then(function (result) {
const back = typeson.parse(result);
assert(
back.prop === 5,
'Example of synchronously-resolved simple object should ' +
'work with async API'
);
return undefined;
});
});
it('should work with encapsulateAsync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
return typeson.encapsulateAsync(mya).then(function (result) {
assert(
result.$ === 500 && result.$types.$[''] === 'myAsyncType',
'Example of MyAsync should work'
);
return typeson.encapsulateAsync({prop: 5}, null, {
throwOnBadSyncType: false
});
}).then(function (result) {
assert(
result.prop === 5,
'Example of synchronously-resolved simple object should ' +
'work with async API'
);
return undefined;
});
});
it('should throw with non-sync result to encapsulateSync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.encapsulateSync(mya);
}, TypeError, 'Sync method requested but async result obtained');
});
it('should throw with non-sync result to parseSync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return o.prop;
},
function (data) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(new MyAsync(data));
}, 800);
});
}
]
});
const mya = new MyAsync(500);
// eslint-disable-next-line no-sync
const smya = typeson.stringifySync(mya);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.parseSync(smya);
}, TypeError, 'Sync method requested but async result obtained');
});
it('should throw with sync result to encapsulateAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: [
function (x) { return x instanceof MySync; },
function (o) {
return o.prop;
},
function (data) {
return new MySync(data);
}
]
});
const mys = new MySync(500);
assert.throws(() => {
typeson.encapsulateAsync(mys);
}, TypeError, 'Async method requested but sync result obtained');
});
it('should throw with non-sync result to stringifySync', () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: [
function (x) { return x instanceof MyAsync; },
function (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
function (data) {
return new MyAsync(data);
}
]
});
const mya = new MyAsync(500);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.stringifySync(mya);
}, TypeError, 'Sync method requested but async result obtained');
});
it('should throw with sync result to stringifyAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: [
function (x) { return x instanceof MySync; },
function (o) {
return o.prop;
},
function (data) {
return new MySync(data);
}
]
});
const mys = new MySync(500);
assert.throws(() => {
typeson.stringifyAsync(mys);
}, TypeError, 'Async method requested but sync result obtained');
});
it('should throw with non-sync result to reviveSync', async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(o.prop);
}, 800);
});
},
revive (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
assert.throws(() => {
// eslint-disable-next-line no-sync
typeson.reviveSync(encapsAsync);
}, TypeError, 'Sync method requested but async result obtained');
});
it(
'shouldn\'t run do revival with reviveAsync-only spec and ' +
'reviveSync method',
async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
// eslint-disable-next-line no-sync
const revivedAsync = typeson.reviveSync(encapsAsync);
assert(revivedAsync === 500);
}
);
it('should throw with sync result to reviveAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: {
test (x) { return x instanceof MySync; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return new MySync(data);
},
reviveAsync (data) {
// Do something more useful in real code
return new MySync(data);
}
}
});
const mys = new MySync(500);
// eslint-disable-next-line no-sync
const encapsSync = typeson.encapsulateSync(mys);
assert.throws(() => {
typeson.reviveAsync(encapsSync);
}, TypeError, 'Async method requested but sync result obtained');
});
it('should throw with sync result to parseAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: {
test (x) { return x instanceof MySync; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return new MySync(data);
},
reviveAsync (data) {
// Do something more useful in real code
return new MySync(data);
}
}
});
const mys = new MySync(500);
// eslint-disable-next-line no-sync
const stringSync = typeson.stringifySync(mys);
assert.throws(() => {
typeson.parseAsync(stringSync);
}, TypeError, 'Async method requested but sync result obtained');
});
/*
it(
'should throw with missing async method and reviveAsync ' +
'(plain objects)',
() => {
const typeson = new Typeson().register({
mySyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return {prop: data};
}
}
});
const mys = {prop: 500};
// eslint-disable-next-line no-sync
const encapsSync = typeson.encapsulateSync(mys);
assert.throws(
() => {
typeson.reviveAsync(encapsSync);
},
TypeError,
'Async method requested but no async reviver'
);
}
);
it('should throw with missing async method and reviveAsync', () => {
function MySync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
mySyncType: {
test (x) { return x instanceof MySync; },
replace (o) {
return o.prop;
},
revive (data) {
// Do something more useful in real code
return new MySync(data);
}
}
});
const mys = new MySync(500);
// eslint-disable-next-line no-sync
const encapsSync = typeson.encapsulateSync(mys);
assert.throws(() => {
typeson.reviveAsync(encapsSync);
}, TypeError, 'Async method requested but no async reviver');
});
*/
it('should revive with reviveAsync', async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
assert(back instanceof MyAsync, 'Returns instance of MyAsync');
assert(back.prop === 500, 'Has same property value');
});
it('should revive with reviveAsync (plain objects)', async () => {
const typeson = new Typeson().register({
myAsyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) { return o.prop; },
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve({prop: data});
});
}
}
});
const obj = {prop: 52};
const encapsAsync = await typeson.encapsulate(obj);
const back = await typeson.reviveAsync(encapsAsync);
assert(back.prop === 52, 'Has same property value');
});
it(
'should revive with nested async revive (plain with ' +
'non-plain object)',
async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register([{
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
revive (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
}, {
myPlainAsyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) {
return o.prop;
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
}]);
const obj = {prop: 52};
const encapsAsync = await typeson.encapsulate(obj);
// console.log('encapsAsync', encapsAsync);
const back = await typeson.reviveAsync(encapsAsync);
// console.log('back', back);
assert(back instanceof MyAsync, 'Is MyAsync instance');
assert(back.prop === 52, 'Has same property value');
}
);
it(
'should revive with nested async revive (plain with plain object)',
async () => {
const typeson = new Typeson().register([{
undef: {
testPlainObjects: true,
test (x) {
return 'undef' in x;
},
replace (o) {
return null;
},
reviveAsync () {
return new Typeson.Undefined();
}
}
}, {
myPlainAsyncType: {
testPlainObjects: true,
test (x) { return 'prop' in x; },
replace (o) {
// console.log('replace', o);
return {
prop: o.prop,
x: o.x,
sth: {
undef: null
}
};
},
reviveAsync (data) {
// console.log('revive', data);
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve({
prop: data.prop,
x: data.x,
extra: {prop: 5},
sth: data.sth
});
});
}
}
}]);
const obj = {
prop: 52,
x: {prop: 500},
sth: {
undef: null
}
};
const encapsAsync = await typeson.encapsulate(obj);
log('encapsAsync', encapsAsync);
const back = await typeson.reviveAsync(encapsAsync);
log('back', back);
assert(back.prop === 52, 'Outer is `myPlainAsyncType`');
assert(
back.sth instanceof Typeson.Undefined,
'Outer has `Undefined`'
);
assert(back.extra.prop === 5, 'Outer has extra prop');
assert(back.x.prop === 500, 'Inner is `myPlainAsyncType`');
assert(back.x.extra.prop === 5, 'Inner has extra prop');
assert(
back.x.sth instanceof Typeson.Undefined,
'Inner has `Undefined`'
);
}
);
it(
'should revive with reviveAsync with only revive on spec',
async () => {
function MyAsync (prop) {
this.prop = prop;
}
const typeson = new Typeson().register({
myAsyncType: {
test (x) { return x instanceof MyAsync; },
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(() => {
resolve(o.prop);
}, 800);
});
},
revive (data) {
// Do something more useful in real code
return new Typeson.Promise((resolve, reject) => {
resolve(new MyAsync(data));
});
}
}
});
const mya = new MyAsync(500);
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
assert(back instanceof MyAsync, 'Returns instance of MyAsync');
assert(back.prop === 500, 'Has same property value');
}
);
it('should revive with `Typeson.Undefined` `reviveAsync`', async () => {
const typeson = new Typeson().register({
undefinedType: {
test (x) {
return x === undefined;
},
replaceAsync (o) {
return new Typeson.Promise(function (resolve, reject) {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return new Typeson.Promise(function (resolve, reject) {
resolve(new Typeson.Undefined());
});
}
}
});
const mya = undefined;
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
assert(back === undefined, 'Returns `undefined`');
});
it(
'should revive with `Promise` returned by `reviveAsync`',
async () => {
const typeson = new Typeson().register({
undefinedType: {
test (x) {
return x === undefined;
},
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return Promise.resolve(5);
}
}
});
const mya = undefined;
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync);
log(typeof back);
assert(back === 5, 'Resolves to `5`');
}
);
it(
'should revive with non-`Promise` returned by `reviveAsync`',
async () => {
const typeson = new Typeson().register({
undefinedType: {
test (x) {
return x === undefined;
},
replaceAsync (o) {
return new Typeson.Promise((resolve, reject) => {
// Do something more useful in real code
setTimeout(function () {
resolve(null);
}, 800);
});
},
reviveAsync (data) {
// Do something more useful in real code
return 5;
}
}
});
const mya = undefined;
const encapsAsync = await typeson.encapsulateAsync(mya);
const back = await typeson.reviveAsync(encapsAsync, {
throwOnBadSyncType: false
});
log(typeof back);
assert(back === 5, 'Resolves to `5`');
}
);
});
});
describe('Typeson.isThenable', () => {
it('should detect `catch` upon second argument being `true`', () => {
const thenable = Typeson.isThenable(Promise.resolve(), true);
assert(thenable, 'Promise found to have catch');
});
it(
'should detect missing `catch` upon second argument being `true`',
() => {
const notThenable = Typeson.isThenable({then () {}}, true);
assert(!notThenable, 'Object not found with a catch');
}
);
});
describe('Typeson.isUserObject', () => {
it('should detect non-user objects', () => {
const a = null;
const b = [];
const c = /test/u;
assert(!Typeson.isUserObject(a), 'null is not a user object');
assert(!Typeson.isUserObject(b), 'Array is not a user object');
assert(!Typeson.isUserObject(c), 'RegExp is not a user object');
});
it('should detect user objects', () => {
class A {
}
class B extends A {}
const c = Object.create(null);
const d = {};
const e = new B();
assert(
Typeson.isUserObject(c),
'Object with null prototype is a user object'
);
assert(Typeson.isUserObject(d), 'Object literal is a user object');
assert(
Typeson.isUserObject(e),
'Instance of user class is a user object'
);
});
});
describe('Typeson.hasConstructorOf', () => {
it(
'should detect whether an object has a "null" constructor ' +
'(i.e., `null` prototype)',
() => {
function B () {}
const a = Object.create(null);
assert(
Typeson.hasConstructorOf(a, null),
'Object with null prototype has a "null" constructor'
);
B.prototype = a;
const c = new B();
assert(
Typeson.hasConstructorOf(c, null),
'Object with null prototype has a "null" ancestor constructor'
);
}
);
it('should detect whether an object is of a particular constructor', () => {
const d = function () { /* Twin */ };
const e = new function () { /* Twin */ }();
assert(
Typeson.hasConstructorOf(e, d),
'Object has constructor that is identical to ' +
'another when stringified'
);
class Undefined {}
Undefined.__typeson__type__ = 'TypesonUndefined';
const undef = new Undefined();
assert(
Typeson.hasConstructorOf(undef, Typeson.Undefined),
'Instance of Typeson.Undefined has constructor identical ' +
'to Typeson.Undefined despite inconsistent stringification'
);
});
});
describe('Typeson.specialTypeNames', () => {
it('should retrieve special type names', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const typeNames = typeson.specialTypeNames([
5, new Date(), 'str', new Date()
]);
assert(
typeNames.length === 1 && typeNames[0] === 'Date',
'Should only return (unique) special type names'
);
});
it('should return false if no special type names found', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const typeNames = typeson.specialTypeNames([
5
]);
assert(
typeNames === false,
'Should return `false` on failing to find any special type names'
);
});
});
describe('Typeson.rootTypeName', () => {
it('should retrieve root type name when JSON', () => {
let runCount = 0;
const typeson = new Typeson({
encapsulateObserver (o) {
runCount++;
}
}).register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const rootTypeName = typeson.rootTypeName([
5, new Date(), 'str', new Date()
]);
assert(
rootTypeName === 'array',
'Should return the single root type name'
);
assert(
runCount === 1,
'Should not iterate through the array structure'
);
});
it('should retrieve root type name for a special type at root', () => {
const typeson = new Typeson().register({
Date: {
test (x) { return x instanceof Date; },
replace (date) { return date.getTime(); },
revive (time) { return new Date(time); }
}
});
const rootTypeName = typeson.rootTypeName(
new Date()
);
assert(
rootTypeName === 'Date',
'Should return the single root type name'
);
});
});
describe('Typeson.Promise', function () {
it('should allow single Promise resolution', () => {
const typeson = new Typeson();
const x = new Typeson.Promise(function (res) {
setTimeout(function () {
res(25);
}, 500);
});
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back === 25,
'Should have resolved the one promise value'
);
return undefined;
});
});
it('should allow single nested Promise resolution', () => {
function APromiseUser (a) { this.a = a; }
const typeson = new Typeson().register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
PromiseUser: [
function (x) { return x instanceof APromiseUser; },
function (o) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(o.a);
}, 300);
});
},
function (val) { return new APromiseUser(val); }
]
});
const x = new Typeson.Promise(function (res) {
setTimeout(function () {
res(new APromiseUser(555));
}, 1200);
});
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back instanceof APromiseUser &&
back.a === 555,
'Should have resolved the one nested promise value'
);
return undefined;
});
});
it('should allow multiple Promise resolution', () => {
const typeson = new Typeson();
const x = [
Typeson.Promise.resolve(5),
100,
new Typeson.Promise(function (res) {
setTimeout(function () {
res(25);
}, 500);
})
];
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back[0] === 5 && back[1] === 100 && back[2] === 25,
'Should have resolved multiple promise values (and ' +
'in the proper order)'
);
return undefined;
});
});
it('should allow nested Promise resolution', () => {
function APromiseUser (a) { this.a = a; }
const typeson = new Typeson().register({
Date: [
function (x) { return x instanceof Date; },
function (date) { return date.getTime(); },
function (time) { return new Date(time); }
],
PromiseUser: [
function (x) { return x instanceof APromiseUser; },
function (o) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(o.a);
}, 300);
});
},
function (val) { return new APromiseUser(val); }
]
});
const x = [
Typeson.Promise.resolve(5),
100,
new Typeson.Promise(function (res) {
setTimeout(function () {
res(25);
}, 500);
}),
new Typeson.Promise(function (res) {
setTimeout(function () {
res(Typeson.Promise.resolve(5));
});
}).then(function (r) {
return new Typeson.Promise(function (res) {
setTimeout(function () {
res(r + 90);
}, 10);
});
}),
Typeson.Promise.resolve(new Date()),
new Typeson.Promise(function (res) {
setTimeout(function () {
res(new APromiseUser(555));
});
})
];
return typeson.stringifyAsync(x).then(function (tson) {
log(tson);
const back = typeson.parse(tson);
assert(
back[0] === 5 &&
back[1] === 100 &&
back[2] === 25 &&
back[3] === 95 &&
back[4] instanceof Date &&
back[5] instanceof APromiseUser &&
back[5].a === 555,
'Should have resolved multiple nested promise ' +
'values (and in the proper order)'
);
return undefined;
});
});
it('should work with Promise utilities', () => {
function makePromises () {
const x = new Typeson.Promise(function (res) {
setTimeout(function () {
res(30);
}, 50);
});
const y = Typeson.Promise.resolve(400);
return [x, y];
}
// eslint-disable-next-line promise/avoid-new
return new Promise(function (resolve, reject) {
// eslint-disable-next-line promise/catch-or-return
Typeson.Promise.all(makePromises()).then(function (results) {
assert(
// eslint-disable-next-line promise/always-return
results[0] === 30 && results[1] === 400,
'Should work with Promise.all'
);
}).then(function () {
// eslint-disable-next-line promise/no-nesting
return Typeson.Promise.race(
makePromises()
// eslint-disable-next-line promise/always-return
).then(function (results) {
assert(
results === 400,
'Should work with Promise.race'
);
resolve();
});
});
});
});
it('should properly handle Promise rejections', () => {
function makeRejectedPromises () {
const x = new Typeson.Promise(function (res, rej) {
setTimeout(function () {
rej(30);
}, 50);
});
const y = new Typeson.Promise(function (res, rej) {
setTimeout(function () {
res(500);
}, 500);
});
return [x, y];
}
// eslint-disable-next-line promise/avoid-new
return new Promise(function (resolve, reject) {
makeRejectedPromises()[0].then(null, function (errCode) {
assert(
errCode === 30,
'`Typeson.Promise` should work with ' +
'`then(null, onRejected)`'
);
return Typeson.Promise.reject(400);
}).catch(function (errCode) {
assert(
errCode === 400,
'`Typeson.Promise` should work with `catch`'
);
return Typeson.Promise.all(makeRejectedPromises());
}).catch(function (errCode) {
assert(
errCode === 30,
'Promise.all should work with rejected promises'
);
return Typeson.Promise.race(makeRejectedPromises());
}).catch(function (errCode) {
assert(
errCode === 30,
'Promise.race should work with rejected promises'
);
return new Typeson.Promise(function () {
throw new Error('Sync throw');
});
}).catch(function (err) {
assert(
err.message === 'Sync throw',
'Typeson.Promise should work with synchronous throws'
);
return Typeson.Promise.resolve(55);
}).then(null, function () {
throw new Error('Should not reach here');
}).then(function (res) {
assert(
res === 55,
'Typeson.Promises should bypass `then` ' +
'without `onResolved`'
);
return Typeson.Promise.reject(33);
}).then(function () {
throw new Error('Should not reach here');
}).catch(function (errCode) {
assert(
errCode === 33,
'Typeson.Promises should bypass `then` when rejecting'
);
resolve();
});
});
});
});
| - Testing: `Undefined` coverage
| test/test.js | - Testing: `Undefined` coverage | <ide><path>est/test.js
<ide> this[3] = 4;
<ide> this.b = b;
<ide> this.c = new MyAsync('abc');
<add> this.e = new Typeson.Undefined();
<ide> this.isArr = isArr;
<ide> }
<ide> B.prototype = new A(a);
<ide> this.prop = prop;
<ide> }
<ide> const typeson = new Typeson().register([{
<add> undef: {
<add> test (x) { return x instanceof Typeson.Undefined; },
<add> replaceAsync (o) {
<add> return new Typeson.Promise(function (resolve, reject) {
<add> // Do something more useful in real code
<add> setTimeout(function () {
<add> resolve(null);
<add> }, 800);
<add> });
<add> },
<add> reviveAsync (data) {
<add> // Do something more useful in real code
<add> return new Typeson.Promise(function (resolve, reject) {
<add> resolve(new Typeson.Undefined());
<add> });
<add> }
<add> }
<add> }, {
<ide> myAsyncType: {
<ide> test (x) { return x instanceof MyAsync; },
<ide> replaceAsync (o) {
<ide>
<ide> let b = new B(7);
<ide> let tson = await typeson.stringifyAsync(b);
<del> log(tson);
<add> console.log(tson);
<ide> let back = await typeson.parseAsync(tson);
<ide> assert(!Array.isArray(back), 'Is not an array');
<ide> assert(back[3] === 4, 'Has numeric property');
<ide> assert(back.a === 5, "Got inherited 'a' property");
<ide> assert(back.b === 7, "Got own 'b' property");
<ide> assert(back.c instanceof MyAsync, "Got own 'c' property");
<add> assert('e' in back && back.e === undefined, "Got own 'e' property");
<ide>
<ide> b = new B(8, true);
<ide> tson = await typeson.stringifyAsync(b);
<ide> assert(
<ide> !('c' in back),
<ide> "'c' property won't survive array stringification"
<add> );
<add> assert(
<add> !('e' in back),
<add> "'e' property won't survive array stringification"
<ide> );
<ide> });
<ide> |
|
Java | apache-2.0 | b65f57f6caab70ebc3d26741fde433b28239eea6 | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.sandwell.JavaSimulation;
import java.util.ArrayList;
import com.jaamsim.events.ProcessTarget;
import com.jaamsim.ui.FrameBox;
import com.sandwell.JavaSimulation3D.GUIFrame;
/**
* Class EventManager - Sandwell Discrete Event Simulation
* <p>
* The EventManager is responsible for scheduling future events, controlling
* conditional event evaluation, and advancing the simulation time. Events are
* scheduled in based on:
* <ul>
* <li>1 - The execution time scheduled for the event
* <li>2 - The priority of the event (if scheduled to occur at the same time)
* <li>3 - If both 1) and 2) are equal, the order in which the event was
* scheduled (FILO - Stack ordering)
* </ul>
* <p>
* The event time is scheduled using a backing long value. Double valued time is
* taken in by the scheduleWait function and scaled to the nearest long value
* using the simTimeFactor.
* <p>
* The EventManager thread is always the bottom thread on the threadStack, so
* that after each event has finished, along with any spawned events, the
* program control will pass back to the EventManager.
* <p>
* The runnable interface is implemented so that the eventManager runs as a
* separate thread.
* <p>
* EventManager is held as a static member of class entity, this ensures that
* all entities will schedule themselves with the same event manager.
*/
public final class EventManager implements Runnable {
boolean traceEvents = false;
private static int eventState;
static final int EVENTS_STOPPED = 0;
static final int EVENTS_RUNNING = 1;
static final int EVENTS_RUNONE = 2;
static final int EVENTS_TIMESTEP = 3;
static final int EVENTS_UNTILTIME = 4;
final String name;
private final Object lockObject; // Object used as global lock for synchronization
private final ArrayList<Event> eventStack;
/*
* eventStack is a list of all future events for this eventManager in order
* of execution. The next event to be executed is found at position 0.
*/
private final ArrayList<Process> conditionalList; // List of all conditionally waiting processes
private final Thread eventManagerThread;
private long currentTick; // Master simulation time (long)
private long targetTick; // The time a child eventManager will run to before waking the parent eventManager
// Real time execution state
private boolean executeRealTime; // TRUE if the simulation is to be executed in Real Time mode
private boolean rebaseRealTime; // TRUE if the time keeping for Real Time model needs re-basing
private int realTimeFactor; // target ratio of elapsed simulation time to elapsed wall clock time
private double baseSimTime; // simulation time at which Real Time mode was commenced
private long baseTimeMillis; // wall clock time in milliseconds at which Real Time model was commenced
private EventTraceRecord traceRecord;
private long debuggingTime;
/*
* event time to debug, implements the run to time functionality
*/
static final int PRIO_DEFAULT = 5;
static final int PRIO_LASTLIFO = 11;
static final int PRIO_LASTFIFO = 12;
static final int STATE_WAITING = 0;
static final int STATE_EXITED = 1;
static final int STATE_INTERRUPTED = 2;
static final int STATE_TERMINATED = 3;
/*
* Used to communicate with the eventViewer about the status of a given event
*/
static {
eventState = EVENTS_STOPPED;
}
/**
* Allocates a new EventManager with the given parent and name
*
* @param parent the connection point for this EventManager in the tree
* @param name the name this EventManager should use
*/
private EventManager(String name) {
// Basic initialization
this.name = name;
lockObject = new Object();
// Initialize the thread which processes events from this EventManager
eventManagerThread = new Thread(this, "evt-" + name);
traceRecord = new EventTraceRecord();
// Initialize and event lists and timekeeping variables
currentTick = 0;
targetTick = 0;
eventStack = new ArrayList<Event>();
conditionalList = new ArrayList<Process>();
executeRealTime = false;
realTimeFactor = 1;
rebaseRealTime = true;
}
public static EventManager initEventManager(String name) {
EventManager evtman = new EventManager(name);
evtman.eventManagerThread.start();
return evtman;
}
void clear() {
basicInit();
}
// Initialize the eventManager. This method is needed only for re-initialization.
// It is not used when the eventManager is first created.
private void basicInit() {
targetTick = Long.MAX_VALUE;
currentTick = 0;
rebaseRealTime = true;
traceRecord.clearTrace();
EventTracer.init();
traceEvents = false;
synchronized (lockObject) {
// Kill threads on the event stack
for (Event each : eventStack) {
if (each.process == null)
continue;
if (each.process.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot terminate an active thread" );
}
each.process.setFlag(Process.TERMINATE);
each.process.interrupt();
}
eventStack.clear();
// Kill conditional threads
for (Process each : conditionalList) {
if (each.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot terminate an active thread" );
}
each.setFlag(Process.TERMINATE);
each.interrupt();
}
conditionalList.clear();
}
}
private void evaluateConditionals() {
// All conditional events if time advanced
synchronized (lockObject) {
if (conditionalList.size() == 0) {
return;
}
// Loop through the conditions in reverse order and add to the linked
// list of active threads
for (int i = 0; i < conditionalList.size() - 1; i++) {
conditionalList.get(i).setNextProcess(conditionalList.get(i + 1));
}
conditionalList.get(conditionalList.size() - 1).setNextProcess(null);
// Wake up the first conditional thread to be tested
// at this point, nextThread == conditionalList.get(0)
switchThread(conditionalList.get(0));
}
}
private boolean checkStopConditions() {
switch (EventManager.getEventState()) {
case EVENTS_RUNNING:
case EVENTS_STOPPED:
return false;
case EVENTS_RUNONE:
return true;
case EVENTS_TIMESTEP:
if (eventStack.get(0).schedTick != debuggingTime)
return true;
else
return false;
case EVENTS_UNTILTIME:
if (eventStack.get(0).schedTick >= debuggingTime)
return true;
else
return false;
default:
return false;
}
}
// Notify the parent eventManager than this eventManager has completed all its
// events up to some specified simulation time.
private void wakeParent() {
synchronized (lockObject) {
// For the top level eventManager, notify the simulation object
// Stop the eventManager's thread
threadWait();
}
}
/**
* Main event processing loop for the eventManager.
*
* Each eventManager runs its loop continuous throughout the simulation run
* with its own thread. The loop for each eventManager is never terminated.
* It is only paused and restarted as required. The run method is called by
* eventManager.start().
*/
@Override
public void run() {
// Loop continuously
while (true) {
// 1) Check whether the model has been paused
if (EventManager.getEventState() == EventManager.EVENTS_STOPPED) {
synchronized (lockObject) {
this.threadWait();
}
continue;
}
// 2) Execute the next event at the present simulation time
// Is there another event at this simulation time?
if (eventStack.size() > 0 &&
eventStack.get(0).schedTick == currentTick) {
// Remove the event from the future events
Event nextEvent = eventStack.remove(0);
this.retireEvent(nextEvent, STATE_EXITED);
Process p = nextEvent.process;
if (p == null)
p = Process.allocate(this, nextEvent.target);
// Pass control to this event's thread
p.setNextProcess(null);
switchThread(p);
continue;
}
// 3) Check to see if the target simulation time has been reached
if (currentTick == targetTick) {
// Notify the parent eventManager that this child has finished
this.wakeParent();
continue;
}
// 4) Advance to the next event time
// (at this point, there are no more events at the present event time)
// Check all the conditional events
this.evaluateConditionals();
// Determine the next event time
long nextTick;
if (eventStack.size() > 0) {
nextTick = Math.min(eventStack.get(0).schedTick, targetTick);
}
else {
nextTick = targetTick;
}
// Only the top-level eventManager should update the master simulation time
// Advance simulation time smoothly between events
if (executeRealTime) {
this.doRealTime(nextTick);
// Has the simulation been stopped and restarted
if( eventStack.get(0).schedTick == 0 )
continue;
}
// Update the displayed simulation time
FrameBox.timeUpdate( Process.ticksToSeconds(nextTick) );
// Set the present time for this eventManager to the next event time
if (eventStack.size() > 0 && eventStack.get(0).schedTick < nextTick) {
System.out.format("Big trouble:%s %d %d\n", name, nextTick, eventStack.get(0).schedTick);
nextTick = eventStack.get(0).schedTick;
}
currentTick = nextTick;
if (checkStopConditions()) {
synchronized (lockObject) {
EventManager.setEventState(EventManager.EVENTS_STOPPED);
}
GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_PAUSED);
}
}
}
/**
* Advance simulation time smoothly between events.
* @param nextTick = internal simulation time for the next event
*/
private void doRealTime(long nextTick) {
double nextSimTime = Process.ticksToSeconds(nextTick);
// Loop until the next event time is reached
double simTime = this.calcSimTime(Process.ticksToSeconds(currentTick));
while( simTime < nextSimTime && executeRealTime ) {
// Update the displayed simulation time
FrameBox.timeUpdate(simTime);
// Wait for 20 milliseconds
this.threadPause(20);
// Has the simulation set to the paused state during the wait?
if( EventManager.getEventState() == EventManager.EVENTS_STOPPED ) {
synchronized (lockObject) {
this.threadWait();
}
// Has the simulation been stopped and restarted?
if( eventStack.get(0).schedTick == 0 )
return;
}
// Calculate the simulation time corresponding to the present wall clock time
simTime = this.calcSimTime(simTime);
}
}
/**
* Return the simulation time corresponding the given wall clock time
* @param simTime = the current simulation time used when setting a real-time basis
* @return simulation time in seconds
*/
private double calcSimTime(double simTime) {
long curMS = System.currentTimeMillis();
if (rebaseRealTime) {
baseSimTime = simTime;
baseTimeMillis = curMS;
rebaseRealTime = false;
}
double simSeconds = ((curMS - baseTimeMillis) * realTimeFactor) / 1000.0d;
return baseSimTime + simSeconds;
}
/**
* Called when a process has finished invoking a model method and unwinds
* the threadStack one level.
*/
void releaseProcess() {
traceProcessEnd();
synchronized (lockObject) {
assertNotWaitUntil();
Process next = Process.current().getNextProcess();
if (next != null) {
next.interrupt();
} else {
// TODO: check for the switching of eventmanagers
Process.current().getEventManager().eventManagerThread.interrupt();
}
}
}
// Pause the current active thread and restart the next thread on the
// active thread list. For this case, a future event or conditional event
// has been created for the current thread. Called by
// eventManager.scheduleWait() and related methods, and by
// eventManager.waitUntil().
// restorePreviousActiveThread()
private void popThread() {
synchronized (lockObject) {
Process next = Process.current().getNextProcess();
Process.current().clearFlag(Process.ACTIVE);
if (next != null) {
Process.current().setNextProcess(null);
switchThread(next);
} else {
// TODO: check for the switching of eventmanagers
switchThread(Process.current().getEventManager().eventManagerThread);
}
Process.current().wake(this);
}
}
void switchThread(Thread next) {
synchronized (lockObject) {
next.interrupt();
threadWait();
}
}
/**
* Calculate the time for an event taking into account numeric overflow.
*/
private long calculateEventTime(long base, long waitLength) {
// Check for numeric overflow of internal time
long nextEventTime = base + waitLength;
if (nextEventTime < 0)
nextEventTime = Long.MAX_VALUE;
return nextEventTime;
}
void scheduleSingleProcess(long waitLength, int eventPriority, ProcessTarget t) {
assertNotWaitUntil();
long eventTime = calculateEventTime(Process.currentTick(), waitLength);
synchronized (lockObject) {
for (int i = 0; i < eventStack.size(); i++) {
Event each = eventStack.get(i);
// We passed where any duplicate could be, break out to the
// insertion part
if (each.schedTick > eventTime)
break;
// if we have an exact match, do not schedule another event
if (each.schedTick == eventTime &&
each.priority == eventPriority &&
each.target == t) {
//System.out.println("Suppressed duplicate event:" +Process.currentTick() + " " + each.target.getDescription());
Process.current().getEventManager().traceSchedProcess(each);
return;
}
}
// Create an event for the new process at the present time, and place it on the event stack
Event newEvent = new Event(this.currentTick(), eventTime, eventPriority, null, t);
Process.current().getEventManager().traceSchedProcess(newEvent);
addEventToStack(newEvent);
}
}
/**
* Schedules a future event to occur with a given priority. Lower priority
* events will be executed preferentially over higher priority. This is
* by lower priority events being placed higher on the event stack.
* @param ticks the number of discrete ticks from now to schedule the event.
* @param priority the priority of the scheduled event: 1 is the highest priority (default is priority 5)
*/
void waitTicks(long ticks, int priority) {
// Test for negative duration schedule wait length
if(ticks < 0)
throw new ErrorException("Negative duration wait is invalid (wait length specified to be %d )", ticks);
assertNotWaitUntil();
long nextEventTime = calculateEventTime(Process.currentTick(), ticks);
Event temp = new Event(currentTick(), nextEventTime, priority, Process.current(), null);
Process.current().getEventManager().traceEvent(temp, STATE_WAITING);
addEventToStack(temp);
popThread();
}
/**
* Schedules a future event to occur with a given priority. Lower priority
* events will be executed preferentially over higher priority. This is
* by lower priority events being placed higher on the event stack.
* @param waitLength the length of time from now to schedule the event.
* @param eventPriority the priority of the scheduled event: 1 is the highest priority (default is priority 5)
*/
void scheduleWait(long waitLength, int eventPriority) {
// Test for zero duration scheduled wait length
if (waitLength == 0)
return;
waitTicks(waitLength, eventPriority);
}
/**
* Adds a new event to the event stack. This method will add an event to
* the event stack based on its scheduled time, priority, and in stack
* order otherwise. Called from scheduleWait in order to abstract the
* underlying data structure and event scheduling routines if necessary.
* This implementation utilizes a stack structure, but his could be
* replaced with a heap or other basic structure.
* @param waitLength is the length of time in the future to schedule the
* event.
* @param eventPriority is the priority of the event, default 0
*/
private void addEventToStack(Event newEvent) {
synchronized (lockObject) {
if (newEvent.schedTick < currentTick) {
throw new ErrorException("Going back in time");
}
int i;
// skip all event that happen before the new event
for (i = 0; i < eventStack.size(); i++) {
if (eventStack.get(i).schedTick < newEvent.schedTick) {
continue;
} else {
break;
}
}
// skip all events at an equal time that have higher priority
for (; i < eventStack.size(); i++) {
// next stack event happens at a later time, i is the insertion index
if (eventStack.get(i).schedTick > newEvent.schedTick) {
break;
}
// skip the higher priority events at the same time
if (eventStack.get(i).priority < newEvent.priority) {
continue;
}
// scheduleLastFIFO is special because it adds in queue, rather
// than stack ordering, so keep going until we find an event that
// happens at a later time without regard to priority
if (newEvent.priority != PRIO_LASTFIFO) {
break;
}
}
// Insert the event in the stack
eventStack.add(i, newEvent);
}
}
/**
* Debugging aid to test that we are not executing a conditional event, useful
* to try and catch places where a waitUntil was missing a waitUntilEnded.
* While not fatal, it will print out a stack dump to try and find where the
* waitUntilEnded was missed.
*/
private void assertNotWaitUntil() {
Process process = Process.current();
if (process.testFlag(Process.COND_WAIT)) {
System.out.println("AUDIT - waitUntil without waitUntilEnded " + process);
for (StackTraceElement elem : process.getStackTrace()) {
System.out.println(elem.toString());
}
}
}
/**
* Used to achieve conditional waits in the simulation. Adds the calling
* thread to the conditional stack, then wakes the next waiting thread on
* the thread stack.
*/
void waitUntil() {
synchronized (lockObject) {
if (!conditionalList.contains(Process.current())) {
Process.current().getEventManager().traceWaitUntil(0);
Process.current().setFlag(Process.COND_WAIT);
conditionalList.add(Process.current());
}
}
popThread();
}
void waitUntilEnded() {
synchronized (lockObject) {
if (!conditionalList.remove(Process.current())) {
// Do not wait at all if we never actually were on the waitUntilStack
// ie. we never called waitUntil
return;
} else {
traceWaitUntil(1);
Process.current().clearFlag(Process.COND_WAIT);
waitTicks(0, PRIO_LASTFIFO);
}
}
}
/**
* Removes the thread from the pending list and executes it immediately
*/
void interrupt( Process intThread ) {
synchronized (lockObject) {
if (intThread.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot interrupt an active thread" );
}
assertNotWaitUntil();
for (int i = 0; i < eventStack.size(); i++) {
if (eventStack.get(i).process == intThread) {
Event interruptEvent = eventStack.remove(i);
retireEvent(interruptEvent, STATE_INTERRUPTED);
interruptEvent.process.setNextProcess(Process.current());
switchThread(interruptEvent.process);
return;
}
}
throw new ErrorException("Tried to interrupt a thread in %s that couldn't be found", name);
}
}
void terminateThread( Process killThread ) {
synchronized (lockObject) {
if (killThread.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot terminate an active thread" );
}
assertNotWaitUntil();
if (conditionalList.remove(killThread)) {
killThread.setFlag(Process.TERMINATE);
killThread.interrupt();
return;
}
for( int i = 0; i < eventStack.size(); i++ ) {
if (eventStack.get(i).process == killThread) {
Event temp = eventStack.remove(i);
retireEvent(temp, STATE_TERMINATED);
killThread.setFlag(Process.TERMINATE);
killThread.interrupt();
return;
}
}
}
throw new ErrorException("Tried to terminate a thread in %s that couldn't be found", name);
}
private void retireEvent(Event retired, int reason) {
traceEvent(retired, reason);
}
long currentTick() {
return currentTick;
}
void setExecuteRealTime(boolean useRealTime, int factor) {
executeRealTime = useRealTime;
realTimeFactor = factor;
if (useRealTime)
rebaseRealTime = true;
}
/**
* Locks the calling thread in an inactive state to the global lock.
* When a new thread is created, and the current thread has been pushed
* onto the inactive thread stack it must be put to sleep to preserve
* program ordering.
* <p>
* The function takes no parameters, it puts the calling thread to sleep.
* This method is NOT static as it requires the use of wait() which cannot
* be called from a static context
* <p>
* There is a synchronized block of code that will acquire the global lock
* and then wait() the current thread.
*/
private void threadWait() {
// Ensure that the thread owns the global thread lock
synchronized( lockObject ) {
try {
/*
* Halt the thread and only wake up by being interrupted.
*
* The infinite loop is _absolutely_ necessary to prevent
* spurious wakeups from waking us early....which causes the
* model to get into an inconsistent state causing crashes.
*/
while (true) { lockObject.wait(); }
}
// Catch the exception when the thread is interrupted
catch( InterruptedException e ) {}
}
}
private void threadPause(long millisToWait) {
// Ensure that the thread owns the global thread lock
synchronized( lockObject ) {
try {
/*
* Halt the thread and allow timeouts to wake us.
*/
lockObject.wait(millisToWait);
}
// Catch the exception when the thread is interrupted
catch( InterruptedException e ) {}
}
}
void scheduleProcess(long waitLength, int eventPriority, ProcessTarget t) {
long schedTick = currentTick + waitLength;
Event e = new Event(currentTick, schedTick, eventPriority, null, t);
this.traceSchedProcess(e);
addEventToStack(e);
}
private static synchronized int getEventState() {
return eventState;
}
private static synchronized void setEventState(int state) {
eventState = state;
}
/**
* Sets the value that is tested in the doProcess loop to determine if the
* next event should be executed. If set to false, the eventManager will
* execute a threadWait() and wait until an interrupt is generated. It is
* guaranteed in this state that there is an empty thread stack and the
* thread referenced in activeThread is the eventManager thread.
*/
void pause() {
EventManager.setEventState(EventManager.EVENTS_STOPPED);
}
/**
* Sets the value that is tested in the doProcess loop to determine if the
* next event should be executed. Generates an interrupt of activeThread
* in case the eventManager thread has already been paused and needs to
* resume the event execution loop. This prevents the model being resumed
* from an inconsistent state.
*/
void resume() {
rebaseRealTime = true;
if (EventManager.getEventState() != EventManager.EVENTS_STOPPED)
return;
synchronized( lockObject ) {
EventManager.setEventState(EventManager.EVENTS_RUNNING);
eventManagerThread.interrupt();
}
}
public void nextOneEvent() {
EventManager.setEventState(EventManager.EVENTS_RUNONE);
startDebugging();
}
public void nextEventTime() {
debuggingTime = eventStack.get(0).schedTick;
EventManager.setEventState(EventManager.EVENTS_TIMESTEP);
startDebugging();
}
void runToTime(double stopTime) {
debuggingTime = ((long)(stopTime * Process.getSimTimeFactor()));
EventManager.setEventState(EventManager.EVENTS_UNTILTIME);
GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_RUNNING);
startDebugging();
}
public void startDebugging() {
synchronized( lockObject ) {
if (eventStack.size() == 0)
return;
eventManagerThread.interrupt();
}
}
private void traceEvent(Event evt, int reason) {
if (traceEvents) traceRecord.formatEventTrace(name, evt, reason);
}
void traceProcessStart(ProcessTarget t) {
if (traceEvents) traceRecord.formatBegin(name, currentTick, t);
}
void traceProcessEnd() {
if (traceEvents) traceRecord.formatExit(name, currentTick);
}
private void traceSchedProcess(Event target) {
if (traceEvents) traceRecord.formatSchedProcessTrace(name, currentTick, target);
}
private void traceWaitUntil(int reason) {
if (traceEvents) traceRecord.formatWaitUntilTrace(name, currentTick, reason);
}
/**
* Holder class for event data used by the event monitor to schedule future
* events.
*/
static class Event {
final long addedTick; // The tick at which this event was queued to execute
final long schedTick; // The tick at which this event will execute
final int priority; // The schedule priority of this event
final ProcessTarget target;
final Process process;
/**
* Constructs a new event object.
* @param currentTick the current simulation tick
* @param scheduleTick the simulation tick the event is schedule for
* @param prio the event priority for scheduling purposes
* @param caller
* @param process
*/
Event(long currentTick, long scheduleTick, int prio, Process process, ProcessTarget target) {
addedTick = currentTick;
schedTick = scheduleTick;
priority = prio;
this.target = target;
this.process = process;
}
String getDesc() {
if (target != null)
return target.getDescription();
StackTraceElement[] callStack = process.getStackTrace();
boolean seenEntity = false;
for (int i = 0; i < callStack.length; i++) {
if (callStack[i].getClassName().equals("com.sandwell.JavaSimulation.Entity")) {
seenEntity = true;
continue;
}
if (seenEntity)
return String.format("%s:%s", callStack[i].getClassName(), callStack[i].getMethodName());
}
// Possible the process hasn't started running yet, check the Process target
// state
return "Unknown Method State";
}
}
@Override
public String toString() {
return name;
}
}
| src/main/java/com/sandwell/JavaSimulation/EventManager.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.sandwell.JavaSimulation;
import java.util.ArrayList;
import com.jaamsim.events.ProcessTarget;
import com.jaamsim.ui.FrameBox;
import com.sandwell.JavaSimulation3D.GUIFrame;
/**
* Class EventManager - Sandwell Discrete Event Simulation
* <p>
* The EventManager is responsible for scheduling future events, controlling
* conditional event evaluation, and advancing the simulation time. Events are
* scheduled in based on:
* <ul>
* <li>1 - The execution time scheduled for the event
* <li>2 - The priority of the event (if scheduled to occur at the same time)
* <li>3 - If both 1) and 2) are equal, the order in which the event was
* scheduled (FILO - Stack ordering)
* </ul>
* <p>
* The event time is scheduled using a backing long value. Double valued time is
* taken in by the scheduleWait function and scaled to the nearest long value
* using the simTimeFactor.
* <p>
* The EventManager thread is always the bottom thread on the threadStack, so
* that after each event has finished, along with any spawned events, the
* program control will pass back to the EventManager.
* <p>
* The runnable interface is implemented so that the eventManager runs as a
* separate thread.
* <p>
* EventManager is held as a static member of class entity, this ensures that
* all entities will schedule themselves with the same event manager.
*/
public final class EventManager implements Runnable {
boolean traceEvents = false;
private static int eventState;
static final int EVENTS_STOPPED = 0;
static final int EVENTS_RUNNING = 1;
static final int EVENTS_RUNONE = 2;
static final int EVENTS_TIMESTEP = 3;
static final int EVENTS_UNTILTIME = 4;
final String name;
private final Object lockObject; // Object used as global lock for synchronization
private final ArrayList<Event> eventStack;
/*
* eventStack is a list of all future events for this eventManager in order
* of execution. The next event to be executed is found at position 0.
*/
private final ArrayList<Process> conditionalList; // List of all conditionally waiting processes
private final Thread eventManagerThread;
private long currentTick; // Master simulation time (long)
private long targetTick; // The time a child eventManager will run to before waking the parent eventManager
// Real time execution state
private boolean executeRealTime; // TRUE if the simulation is to be executed in Real Time mode
private boolean rebaseRealTime; // TRUE if the time keeping for Real Time model needs re-basing
private int realTimeFactor; // target ratio of elapsed simulation time to elapsed wall clock time
private double baseSimTime; // simulation time at which Real Time mode was commenced
private long baseTimeMillis; // wall clock time in milliseconds at which Real Time model was commenced
private EventTraceRecord traceRecord;
private long debuggingTime;
/*
* event time to debug, implements the run to time functionality
*/
static final int PRIO_DEFAULT = 5;
static final int PRIO_LASTLIFO = 11;
static final int PRIO_LASTFIFO = 12;
static final int STATE_WAITING = 0;
static final int STATE_EXITED = 1;
static final int STATE_INTERRUPTED = 2;
static final int STATE_TERMINATED = 3;
/*
* Used to communicate with the eventViewer about the status of a given event
*/
static {
eventState = EVENTS_STOPPED;
}
/**
* Allocates a new EventManager with the given parent and name
*
* @param parent the connection point for this EventManager in the tree
* @param name the name this EventManager should use
*/
private EventManager(String name) {
// Basic initialization
this.name = name;
lockObject = new Object();
// Initialize the thread which processes events from this EventManager
eventManagerThread = new Thread(this, "evt-" + name);
traceRecord = new EventTraceRecord();
// Initialize and event lists and timekeeping variables
currentTick = 0;
targetTick = 0;
eventStack = new ArrayList<Event>();
conditionalList = new ArrayList<Process>();
executeRealTime = false;
realTimeFactor = 1;
rebaseRealTime = true;
}
public static EventManager initEventManager(String name) {
EventManager evtman = new EventManager(name);
evtman.eventManagerThread.start();
return evtman;
}
void clear() {
basicInit();
}
// Initialize the eventManager. This method is needed only for re-initialization.
// It is not used when the eventManager is first created.
private void basicInit() {
targetTick = Long.MAX_VALUE;
currentTick = 0;
rebaseRealTime = true;
traceRecord.clearTrace();
EventTracer.init();
traceEvents = false;
synchronized (lockObject) {
// Kill threads on the event stack
for (Event each : eventStack) {
if (each.process == null)
continue;
if (each.process.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot terminate an active thread" );
}
each.process.setFlag(Process.TERMINATE);
each.process.interrupt();
}
eventStack.clear();
// Kill conditional threads
for (Process each : conditionalList) {
if (each.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot terminate an active thread" );
}
each.setFlag(Process.TERMINATE);
each.interrupt();
}
conditionalList.clear();
}
}
private void evaluateConditionals() {
// All conditional events if time advanced
synchronized (lockObject) {
if (conditionalList.size() == 0) {
return;
}
// Loop through the conditions in reverse order and add to the linked
// list of active threads
for (int i = 0; i < conditionalList.size() - 1; i++) {
conditionalList.get(i).setNextProcess(conditionalList.get(i + 1));
}
conditionalList.get(conditionalList.size() - 1).setNextProcess(null);
// Wake up the first conditional thread to be tested
// at this point, nextThread == conditionalList.get(0)
switchThread(conditionalList.get(0));
}
}
private boolean checkStopConditions() {
switch (EventManager.getEventState()) {
case EVENTS_RUNNING:
case EVENTS_STOPPED:
return false;
case EVENTS_RUNONE:
return true;
case EVENTS_TIMESTEP:
if (eventStack.get(0).schedTick != debuggingTime)
return true;
else
return false;
case EVENTS_UNTILTIME:
if (eventStack.get(0).schedTick >= debuggingTime)
return true;
else
return false;
default:
return false;
}
}
// Notify the parent eventManager than this eventManager has completed all its
// events up to some specified simulation time.
private void wakeParent() {
synchronized (lockObject) {
// For the top level eventManager, notify the simulation object
// Stop the eventManager's thread
threadWait();
}
}
/**
* Main event processing loop for the eventManager.
*
* Each eventManager runs its loop continuous throughout the simulation run
* with its own thread. The loop for each eventManager is never terminated.
* It is only paused and restarted as required. The run method is called by
* eventManager.start().
*/
@Override
public void run() {
// Loop continuously
while (true) {
// 1) Check whether the model has been paused
if (EventManager.getEventState() == EventManager.EVENTS_STOPPED) {
synchronized (lockObject) {
this.threadWait();
}
continue;
}
// 2) Execute the next event at the present simulation time
// Is there another event at this simulation time?
if (eventStack.size() > 0 &&
eventStack.get(0).schedTick == currentTick) {
// Remove the event from the future events
Event nextEvent = eventStack.remove(0);
this.retireEvent(nextEvent, STATE_EXITED);
Process p = nextEvent.process;
if (p == null)
p = Process.allocate(this, nextEvent.target);
// Pass control to this event's thread
p.setNextProcess(null);
switchThread(p);
continue;
}
// 3) Check to see if the target simulation time has been reached
if (currentTick == targetTick) {
// Notify the parent eventManager that this child has finished
this.wakeParent();
continue;
}
// 4) Advance to the next event time
// (at this point, there are no more events at the present event time)
// Check all the conditional events
this.evaluateConditionals();
// Determine the next event time
long nextTick;
if (eventStack.size() > 0) {
nextTick = Math.min(eventStack.get(0).schedTick, targetTick);
}
else {
nextTick = targetTick;
}
// Only the top-level eventManager should update the master simulation time
// Advance simulation time smoothly between events
if (executeRealTime) {
this.doRealTime(nextTick);
// Has the simulation been stopped and restarted
if( eventStack.get(0).schedTick == 0 )
continue;
}
// Update the displayed simulation time
FrameBox.timeUpdate( Process.ticksToSeconds(nextTick) );
// Set the present time for this eventManager to the next event time
if (eventStack.size() > 0 && eventStack.get(0).schedTick < nextTick) {
System.out.format("Big trouble:%s %d %d\n", name, nextTick, eventStack.get(0).schedTick);
nextTick = eventStack.get(0).schedTick;
}
currentTick = nextTick;
if (checkStopConditions()) {
synchronized (lockObject) {
EventManager.setEventState(EventManager.EVENTS_STOPPED);
}
GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_PAUSED);
}
}
}
/**
* Advance simulation time smoothly between events.
* @param nextTick = internal simulation time for the next event
*/
private void doRealTime(long nextTick) {
double nextSimTime = Process.ticksToSeconds(nextTick);
// Loop until the next event time is reached
double simTime = this.calcSimTime(Process.ticksToSeconds(currentTick));
while( simTime < nextSimTime && executeRealTime ) {
// Update the displayed simulation time
FrameBox.timeUpdate(simTime);
// Wait for 20 milliseconds
this.threadPause(20);
// Has the simulation set to the paused state during the wait?
if( EventManager.getEventState() == EventManager.EVENTS_STOPPED ) {
synchronized (lockObject) {
this.threadWait();
}
// Has the simulation been stopped and restarted?
if( eventStack.get(0).schedTick == 0 )
return;
}
// Calculate the simulation time corresponding to the present wall clock time
simTime = this.calcSimTime(simTime);
}
}
/**
* Return the simulation time corresponding the given wall clock time
* @param simTime = the current simulation time used when setting a real-time basis
* @return simulation time in seconds
*/
private double calcSimTime(double simTime) {
long curMS = System.currentTimeMillis();
if (rebaseRealTime) {
baseSimTime = simTime;
baseTimeMillis = curMS;
rebaseRealTime = false;
}
double simSeconds = ((curMS - baseTimeMillis) * realTimeFactor) / 1000.0d;
return baseSimTime + simSeconds;
}
/**
* Called when a process has finished invoking a model method and unwinds
* the threadStack one level.
*/
void releaseProcess() {
traceProcessEnd();
synchronized (lockObject) {
assertNotWaitUntil();
Process next = Process.current().getNextProcess();
if (next != null) {
next.interrupt();
} else {
// TODO: check for the switching of eventmanagers
Process.current().getEventManager().eventManagerThread.interrupt();
}
}
}
// Pause the current active thread and restart the next thread on the
// active thread list. For this case, a future event or conditional event
// has been created for the current thread. Called by
// eventManager.scheduleWait() and related methods, and by
// eventManager.waitUntil().
// restorePreviousActiveThread()
private void popThread() {
synchronized (lockObject) {
Process next = Process.current().getNextProcess();
Process.current().clearFlag(Process.ACTIVE);
if (next != null) {
Process.current().setNextProcess(null);
switchThread(next);
} else {
// TODO: check for the switching of eventmanagers
switchThread(Process.current().getEventManager().eventManagerThread);
}
Process.current().wake(this);
}
}
void switchThread(Thread next) {
synchronized (lockObject) {
next.interrupt();
threadWait();
}
}
/**
* Calculate the time for an event taking into account numeric overflow.
*/
private long calculateEventTime(long base, long waitLength) {
// Check for numeric overflow of internal time
long nextEventTime = base + waitLength;
if (nextEventTime < 0)
nextEventTime = Long.MAX_VALUE;
return nextEventTime;
}
void scheduleSingleProcess(long waitLength, int eventPriority, ProcessTarget t) {
assertNotWaitUntil();
long eventTime = calculateEventTime(Process.currentTick(), waitLength);
synchronized (lockObject) {
for (int i = 0; i < eventStack.size(); i++) {
Event each = eventStack.get(i);
// We passed where any duplicate could be, break out to the
// insertion part
if (each.schedTick > eventTime)
break;
// if we have an exact match, do not schedule another event
if (each.schedTick == eventTime &&
each.priority == eventPriority &&
each.target == t) {
//System.out.println("Suppressed duplicate event:" +Process.currentTick() + " " + each.target.getDescription());
Process.current().getEventManager().traceSchedProcess(each);
return;
}
}
// Create an event for the new process at the present time, and place it on the event stack
Event newEvent = new Event(this.currentTick(), eventTime, eventPriority, null, t);
Process.current().getEventManager().traceSchedProcess(newEvent);
addEventToStack(newEvent);
}
}
/**
* Schedules a future event to occur with a given priority. Lower priority
* events will be executed preferentially over higher priority. This is
* by lower priority events being placed higher on the event stack.
* @param ticks the number of discrete ticks from now to schedule the event.
* @param priority the priority of the scheduled event: 1 is the highest priority (default is priority 5)
*/
void waitTicks(long ticks, int priority) {
// Test for negative duration schedule wait length
if(ticks < 0)
throw new ErrorException("Negative duration wait is invalid (wait length specified to be %d )", ticks);
assertNotWaitUntil();
long nextEventTime = calculateEventTime(Process.currentTick(), ticks);
Event temp = new Event(currentTick(), nextEventTime, priority, Process.current(), null);
Process.current().getEventManager().traceEvent(temp, STATE_WAITING);
addEventToStack(temp);
popThread();
}
/**
* Schedules a future event to occur with a given priority. Lower priority
* events will be executed preferentially over higher priority. This is
* by lower priority events being placed higher on the event stack.
* @param waitLength the length of time from now to schedule the event.
* @param eventPriority the priority of the scheduled event: 1 is the highest priority (default is priority 5)
*/
void scheduleWait(long waitLength, int eventPriority) {
// Test for zero duration scheduled wait length
if (waitLength == 0)
return;
waitTicks(waitLength, eventPriority);
}
/**
* Adds a new event to the event stack. This method will add an event to
* the event stack based on its scheduled time, priority, and in stack
* order otherwise. Called from scheduleWait in order to abstract the
* underlying data structure and event scheduling routines if necessary.
* This implementation utilizes a stack structure, but his could be
* replaced with a heap or other basic structure.
* @param waitLength is the length of time in the future to schedule the
* event.
* @param eventPriority is the priority of the event, default 0
*/
private void addEventToStack(Event newEvent) {
synchronized (lockObject) {
if (newEvent.schedTick < currentTick) {
System.out.println("Time travel detected - whoops");
throw new ErrorException("Going back in time");
}
int i;
// skip all event that happen before the new event
for (i = 0; i < eventStack.size(); i++) {
if (eventStack.get(i).schedTick < newEvent.schedTick) {
continue;
} else {
break;
}
}
// skip all events at an equal time that have higher priority
for (; i < eventStack.size(); i++) {
// next stack event happens at a later time, i is the insertion index
if (eventStack.get(i).schedTick > newEvent.schedTick) {
break;
}
// skip the higher priority events at the same time
if (eventStack.get(i).priority < newEvent.priority) {
continue;
}
// scheduleLastFIFO is special because it adds in queue, rather
// than stack ordering, so keep going until we find an event that
// happens at a later time without regard to priority
if (newEvent.priority != PRIO_LASTFIFO) {
break;
}
}
// Insert the event in the stack
eventStack.add(i, newEvent);
}
}
/**
* Debugging aid to test that we are not executing a conditional event, useful
* to try and catch places where a waitUntil was missing a waitUntilEnded.
* While not fatal, it will print out a stack dump to try and find where the
* waitUntilEnded was missed.
*/
private void assertNotWaitUntil() {
Process process = Process.current();
if (process.testFlag(Process.COND_WAIT)) {
System.out.println("AUDIT - waitUntil without waitUntilEnded " + process);
for (StackTraceElement elem : process.getStackTrace()) {
System.out.println(elem.toString());
}
}
}
/**
* Used to achieve conditional waits in the simulation. Adds the calling
* thread to the conditional stack, then wakes the next waiting thread on
* the thread stack.
*/
void waitUntil() {
synchronized (lockObject) {
if (!conditionalList.contains(Process.current())) {
Process.current().getEventManager().traceWaitUntil(0);
Process.current().setFlag(Process.COND_WAIT);
conditionalList.add(Process.current());
}
}
popThread();
}
void waitUntilEnded() {
synchronized (lockObject) {
if (!conditionalList.remove(Process.current())) {
// Do not wait at all if we never actually were on the waitUntilStack
// ie. we never called waitUntil
return;
} else {
traceWaitUntil(1);
Process.current().clearFlag(Process.COND_WAIT);
waitTicks(0, PRIO_LASTFIFO);
}
}
}
/**
* Removes the thread from the pending list and executes it immediately
*/
void interrupt( Process intThread ) {
synchronized (lockObject) {
if (intThread.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot interrupt an active thread" );
}
assertNotWaitUntil();
for (int i = 0; i < eventStack.size(); i++) {
if (eventStack.get(i).process == intThread) {
Event interruptEvent = eventStack.remove(i);
retireEvent(interruptEvent, STATE_INTERRUPTED);
interruptEvent.process.setNextProcess(Process.current());
switchThread(interruptEvent.process);
return;
}
}
throw new ErrorException("Tried to interrupt a thread in %s that couldn't be found", name);
}
}
void terminateThread( Process killThread ) {
synchronized (lockObject) {
if (killThread.testFlag(Process.ACTIVE)) {
throw new ErrorException( "Cannot terminate an active thread" );
}
assertNotWaitUntil();
if (conditionalList.remove(killThread)) {
killThread.setFlag(Process.TERMINATE);
killThread.interrupt();
return;
}
for( int i = 0; i < eventStack.size(); i++ ) {
if (eventStack.get(i).process == killThread) {
Event temp = eventStack.remove(i);
retireEvent(temp, STATE_TERMINATED);
killThread.setFlag(Process.TERMINATE);
killThread.interrupt();
return;
}
}
//if (parent != null) {
// parent.terminateThread(killThread);
// return;
//}
}
System.out.format("Threadevt:%s", killThread.getEventManager().name);
throw new ErrorException("Tried to terminate a thread in %s that couldn't be found", name);
}
private void retireEvent(Event retired, int reason) {
traceEvent(retired, reason);
}
long currentTick() {
return currentTick;
}
void setExecuteRealTime(boolean useRealTime, int factor) {
executeRealTime = useRealTime;
realTimeFactor = factor;
if (useRealTime)
rebaseRealTime = true;
}
/**
* Locks the calling thread in an inactive state to the global lock.
* When a new thread is created, and the current thread has been pushed
* onto the inactive thread stack it must be put to sleep to preserve
* program ordering.
* <p>
* The function takes no parameters, it puts the calling thread to sleep.
* This method is NOT static as it requires the use of wait() which cannot
* be called from a static context
* <p>
* There is a synchronized block of code that will acquire the global lock
* and then wait() the current thread.
*/
private void threadWait() {
// Ensure that the thread owns the global thread lock
synchronized( lockObject ) {
try {
/*
* Halt the thread and only wake up by being interrupted.
*
* The infinite loop is _absolutely_ necessary to prevent
* spurious wakeups from waking us early....which causes the
* model to get into an inconsistent state causing crashes.
*/
while (true) { lockObject.wait(); }
}
// Catch the exception when the thread is interrupted
catch( InterruptedException e ) {}
}
}
private void threadPause(long millisToWait) {
// Ensure that the thread owns the global thread lock
synchronized( lockObject ) {
try {
/*
* Halt the thread and allow timeouts to wake us.
*/
lockObject.wait(millisToWait);
}
// Catch the exception when the thread is interrupted
catch( InterruptedException e ) {}
}
}
void scheduleProcess(long waitLength, int eventPriority, ProcessTarget t) {
long schedTick = currentTick + waitLength;
Event e = new Event(currentTick, schedTick, eventPriority, null, t);
this.traceSchedProcess(e);
addEventToStack(e);
}
private static synchronized int getEventState() {
return eventState;
}
private static synchronized void setEventState(int state) {
eventState = state;
}
/**
* Sets the value that is tested in the doProcess loop to determine if the
* next event should be executed. If set to false, the eventManager will
* execute a threadWait() and wait until an interrupt is generated. It is
* guaranteed in this state that there is an empty thread stack and the
* thread referenced in activeThread is the eventManager thread.
*/
void pause() {
EventManager.setEventState(EventManager.EVENTS_STOPPED);
}
/**
* Sets the value that is tested in the doProcess loop to determine if the
* next event should be executed. Generates an interrupt of activeThread
* in case the eventManager thread has already been paused and needs to
* resume the event execution loop. This prevents the model being resumed
* from an inconsistent state.
*/
void resume() {
rebaseRealTime = true;
if (EventManager.getEventState() != EventManager.EVENTS_STOPPED)
return;
synchronized( lockObject ) {
EventManager.setEventState(EventManager.EVENTS_RUNNING);
eventManagerThread.interrupt();
}
}
public void nextOneEvent() {
EventManager.setEventState(EventManager.EVENTS_RUNONE);
startDebugging();
}
public void nextEventTime() {
debuggingTime = eventStack.get(0).schedTick;
EventManager.setEventState(EventManager.EVENTS_TIMESTEP);
startDebugging();
}
void runToTime(double stopTime) {
debuggingTime = ((long)(stopTime * Process.getSimTimeFactor()));
EventManager.setEventState(EventManager.EVENTS_UNTILTIME);
GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_RUNNING);
startDebugging();
}
public void startDebugging() {
synchronized( lockObject ) {
if (eventStack.size() == 0)
return;
eventManagerThread.interrupt();
}
}
private void traceEvent(Event evt, int reason) {
if (traceEvents) traceRecord.formatEventTrace(name, evt, reason);
}
void traceProcessStart(ProcessTarget t) {
if (traceEvents) traceRecord.formatBegin(name, currentTick, t);
}
void traceProcessEnd() {
if (traceEvents) traceRecord.formatExit(name, currentTick);
}
private void traceSchedProcess(Event target) {
if (traceEvents) traceRecord.formatSchedProcessTrace(name, currentTick, target);
}
private void traceWaitUntil(int reason) {
if (traceEvents) traceRecord.formatWaitUntilTrace(name, currentTick, reason);
}
/**
* Holder class for event data used by the event monitor to schedule future
* events.
*/
static class Event {
final long addedTick; // The tick at which this event was queued to execute
final long schedTick; // The tick at which this event will execute
final int priority; // The schedule priority of this event
final ProcessTarget target;
final Process process;
/**
* Constructs a new event object.
* @param currentTick the current simulation tick
* @param scheduleTick the simulation tick the event is schedule for
* @param prio the event priority for scheduling purposes
* @param caller
* @param process
*/
Event(long currentTick, long scheduleTick, int prio, Process process, ProcessTarget target) {
addedTick = currentTick;
schedTick = scheduleTick;
priority = prio;
this.target = target;
this.process = process;
}
String getDesc() {
if (target != null)
return target.getDescription();
StackTraceElement[] callStack = process.getStackTrace();
boolean seenEntity = false;
for (int i = 0; i < callStack.length; i++) {
if (callStack[i].getClassName().equals("com.sandwell.JavaSimulation.Entity")) {
seenEntity = true;
continue;
}
if (seenEntity)
return String.format("%s:%s", callStack[i].getClassName(), callStack[i].getMethodName());
}
// Possible the process hasn't started running yet, check the Process target
// state
return "Unknown Method State";
}
}
@Override
public String toString() {
return name;
}
}
| JS: remove some output that was throwing an ErrorException anyway
The exception is good enough to report what is wrong.
Signed-off-by: Harvey Harrison <[email protected]>
| src/main/java/com/sandwell/JavaSimulation/EventManager.java | JS: remove some output that was throwing an ErrorException anyway | <ide><path>rc/main/java/com/sandwell/JavaSimulation/EventManager.java
<ide> private void addEventToStack(Event newEvent) {
<ide> synchronized (lockObject) {
<ide> if (newEvent.schedTick < currentTick) {
<del> System.out.println("Time travel detected - whoops");
<ide> throw new ErrorException("Going back in time");
<ide> }
<ide>
<ide> return;
<ide> }
<ide> }
<del> //if (parent != null) {
<del> // parent.terminateThread(killThread);
<del> // return;
<del> //}
<del> }
<del> System.out.format("Threadevt:%s", killThread.getEventManager().name);
<add> }
<ide> throw new ErrorException("Tried to terminate a thread in %s that couldn't be found", name);
<ide> }
<ide> |
|
JavaScript | mit | 3a8bc3d2f5199da46f95258837f58e917bd3e12e | 0 | silverbux/rsjs | f731f4c5-2e9c-11e5-9a50-a45e60cdfd11 | helloWorld.js | f7251a91-2e9c-11e5-b546-a45e60cdfd11 | f731f4c5-2e9c-11e5-9a50-a45e60cdfd11 | helloWorld.js | f731f4c5-2e9c-11e5-9a50-a45e60cdfd11 | <ide><path>elloWorld.js
<del>f7251a91-2e9c-11e5-b546-a45e60cdfd11
<add>f731f4c5-2e9c-11e5-9a50-a45e60cdfd11 |
|
JavaScript | mit | 16c86d6acec376a43f713d5dbea84661bdd997e6 | 0 | caspervonb/node-rdbg,bradparks/node-rdbg | const http = require('http');
const ws = require('ws');
const path = require('path');
const events = require('events');
const util = require('util');
const async = require('async');
const url = require('url');
const stream = require('stream');
function Client() {
events.EventEmitter.call(this);
this._socket = null;
this._callbacks = {};
this._commands = {};
this._counter = 0;
this._scripts = [];
this._console = new stream.Readable({ objectMode: true });
this._console._read = function() { };
}
util.inherits(Client, events.EventEmitter);
Object.defineProperty(Client.prototype, 'socket', {
get: function() {
return this._socket;
},
});
Object.defineProperty(Client.prototype, 'console', {
get: function() {
return this._console;
},
});
Client.prototype.sendCommand = function(method, params, callback) {
try {
var id = this._counter++;
var request = {
id: id,
method: method,
params: params
};
this.emit('request', request);
this._socket.send(JSON.stringify(request));
this._callbacks[id] = callback;
this._commands[id] = request;
} catch (error) {
return callback(error);
}
};
Client.prototype.attach = function attach(target) {
if (typeof target === 'object') {
target = target.webSocketDebuggerUrl;
}
var socket = ws.connect(target);
socket.on('open', function() {
this.emit('attach');
}.bind(this));
socket.on('close', function() {
self.emit('detatch');
}.bind(this));
socket.on('error', function(error) {
self.emit('error', error);
}.bind(this));
socket.on('message', function(data) {
try {
var message = JSON.parse(data);
if (message.id) {
var command = this._commands[message.id];
var callback = this._callbacks[message.id];
this.emit('response', command, message);
if (callback) {
if (message.error) {
callback(message.error);
} else if (message.result) {
callback(null, message.result);
} else if (message.params) {
callback(null, message.params);
}
delete this._callbacks[message.id];
}
delete this._commands[message.id];
if (Object.keys(this._commands).length === 0) {
this.emit('ready');
}
} else {
this.emit('message', message);
if (message.method === 'Console.messageAdded') {
this._console.push(message.params.message);
}
if (message.method === 'Debugger.scriptParsed') {
this._scripts = this._scripts.filter(function(script) {
return message.params.url !== script.url;
});
this._scripts.push(message.params);
this.emit('scriptParse', message.params);
}
}
} catch (error) {
this.emit('error', error);
}
}.bind(this));
this._socket = socket;
};
Client.prototype.detatch = function() {
if (this._socket) {
this._socket.close();
}
};
Client.prototype.evaluate = function evaluate(expression, callback) {
this.sendCommand('Runtime.evaluate', {
expression: expression,
}, callback);
};
Client.prototype.getScripts = function scripts(callback) {
callback(this._scripts);
};
Client.prototype.getScriptSource = function(script, callback) {
this.sendCommand('Debugger.getScriptSource', {
scriptId: script.scriptId,
}, callback);
};
Client.prototype.setScriptSource = function source(script, contents, callback) {
this.sendCommand('Debugger.setScriptSource', {
scriptId: script.scriptId,
scriptSource: contents
}, callback);
};
module.exports.Client = Client;
function createClient() {
var client = new Client();
return client;
}
module.exports.createClient = createClient;
function get(port, host, callback) {
var request = http.get({
port: port,
host: host,
path: '/json'
});
request.on('response', function(response) {
var body = '';
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
try {
var targets = JSON.parse(body);
return callback(null, targets);
} catch (error) {
return callback(error);
}
});
});
request.on('error', function(error) {
return callback(error);
});
};
module.exports.get = get;
| lib/index.js | const http = require('http');
const ws = require('ws');
const path = require('path');
const events = require('events');
const util = require('util');
const async = require('async');
const url = require('url');
const stream = require('stream');
function Client() {
events.EventEmitter.call(this);
this._socket = null;
this._callbacks = {};
this._commands = {};
this._counter = 0;
this._scripts = [];
this._console = new stream.Readable({ objectMode: true });
this._console._read = function() { };
}
util.inherits(Client, events.EventEmitter);
Object.defineProperty(Client.prototype, 'socket', {
get: function() {
return this._socket;
},
});
Object.defineProperty(Client.prototype, 'console', {
get: function() {
return this._console;
},
});
Client.prototype.sendCommand = function(method, params, callback) {
try {
var id = this._counter++;
var request = {
id: id,
method: method,
params: params
};
this.emit('request', request);
this._socket.send(JSON.stringify(request));
this._callbacks[id] = callback;
this._commands[id] = request;
} catch (error) {
return callback(error);
}
};
Client.prototype.attach = function attach(target) {
if (typeof target === 'object') {
target = target.webSocketDebuggerUrl;
}
var socket = ws.connect(target);
socket.on('open', function() {
this.emit('attach');
}.bind(this));
socket.on('close', function() {
self.emit('detatch');
}.bind(this));
socket.on('error', function(error) {
self.emit('error', error);
}.bind(this));
socket.on('message', function(data) {
try {
var message = JSON.parse(data);
if (message.id) {
var command = this._commands[message.id];
var callback = this._callbacks[message.id];
this.emit('response', command, message);
if (callback) {
if (message.error) {
callback(message.error);
} else if (message.result) {
callback(null, message.result);
} else if (message.params) {
callback(null, message.params);
}
delete this._callbacks[message.id];
}
delete this._commands[message.id];
} else {
this.emit('message', message);
if (message.method === 'Console.messageAdded') {
this._console.push(message.params.message);
}
if (message.method === 'Debugger.scriptParsed') {
this._scripts = this._scripts.filter(function(script) {
return message.params.url !== script.url;
});
this._scripts.push(message.params);
this.emit('scriptParse', message.params);
}
}
} catch (error) {
this.emit('error', error);
}
}.bind(this));
this._socket = socket;
};
Client.prototype.detatch = function() {
if (this._socket) {
this._socket.close();
}
};
Client.prototype.evaluate = function evaluate(expression, callback) {
this.sendCommand('Runtime.evaluate', {
expression: expression,
}, callback);
};
Client.prototype.getScripts = function scripts(callback) {
callback(this._scripts);
};
Client.prototype.getScriptSource = function(script, callback) {
this.sendCommand('Debugger.getScriptSource', {
scriptId: script.scriptId,
}, callback);
};
Client.prototype.setScriptSource = function source(script, contents, callback) {
this.sendCommand('Debugger.setScriptSource', {
scriptId: script.scriptId,
scriptSource: contents
}, callback);
};
module.exports.Client = Client;
function createClient() {
var client = new Client();
return client;
}
module.exports.createClient = createClient;
function get(port, host, callback) {
var request = http.get({
port: port,
host: host,
path: '/json'
});
request.on('response', function(response) {
var body = '';
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
try {
var targets = JSON.parse(body);
return callback(null, targets);
} catch (error) {
return callback(error);
}
});
});
request.on('error', function(error) {
return callback(error);
});
};
module.exports.get = get;
| Emit 'ready' event from Client when there are no more commands to process
| lib/index.js | Emit 'ready' event from Client when there are no more commands to process | <ide><path>ib/index.js
<ide> }
<ide>
<ide> delete this._commands[message.id];
<add>
<add> if (Object.keys(this._commands).length === 0) {
<add> this.emit('ready');
<add> }
<ide> } else {
<ide> this.emit('message', message);
<ide> if (message.method === 'Console.messageAdded') { |
|
Java | agpl-3.0 | abeafd82e102d89f1684a7b4000e0b2428ff8317 | 0 | Audiveris/audiveris,Audiveris/audiveris | //----------------------------------------------------------------------------//
// //
// S c o r e M a n a g e r //
// //
// Copyright (C) Herve Bitteur 2000-2006. All rights reserved. //
// This software is released under the terms of the GNU General Public //
// License. Please contact the author at [email protected] //
// to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.score;
import omr.Main;
import omr.score.export.ScoreExporter;
import omr.util.FileUtil;
import omr.util.Logger;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
/**
* Class <code>ScoreManager</code> handles a collection of score instances.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class ScoreManager
{
//~ Static fields/initializers ---------------------------------------------
private static final Logger logger = Logger.getLogger(ScoreManager.class);
/** The single instance of this class */
private static ScoreManager INSTANCE;
//~ Instance fields --------------------------------------------------------
/** Slot for one potential change listener */
private ChangeListener changeListener;
/** Unique change event */
private final ChangeEvent changeEvent;
/** Instances of score */
private List<Score> instances = new ArrayList<Score>();
//~ Constructors -----------------------------------------------------------
//--------------//
// ScoreManager //
//--------------//
/**
* Creates a Score Manager.
*/
private ScoreManager ()
{
changeEvent = new ChangeEvent(this);
}
//~ Methods ----------------------------------------------------------------
//-------------------//
// setChangeListener //
//-------------------//
/**
* Register one change listener
*
* @param changeListener the entity to be notified of any change
*/
public void setChangeListener (ChangeListener changeListener)
{
this.changeListener = changeListener;
}
//-------------//
// getInstance //
//-------------//
/**
* Report the single instance of this class,
*
* @return the single instance
*/
public static ScoreManager getInstance ()
{
if (INSTANCE == null) {
INSTANCE = new ScoreManager();
}
return INSTANCE;
}
//-----------//
// getScores //
//-----------//
/**
* Get the collection of scores currently handled by OMR
*
* @return The collection
*/
public List<Score> getScores ()
{
return instances;
}
//---------------//
// checkInserted //
//---------------//
/**
* Register score in score instances if not yet done
*/
public void checkInserted (Score score)
{
if (!instances.contains(score)) {
insertInstance(score);
}
}
//-------//
// close //
//-------//
/**
* Close a score instance
*/
public void close (Score score)
{
if (logger.isFineEnabled()) {
logger.fine("close " + score);
}
// Remove from list of instance
if (instances.contains(score)) {
instances.remove(score);
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
//----------//
// closeAll //
//----------//
/**
* Close all score instances
*/
public void closeAll ()
{
if (logger.isFineEnabled()) {
logger.fine("closeAll");
}
for (Iterator<Score> it = instances.iterator(); it.hasNext();) {
Score score = it.next();
it.remove(); // Done here to avoid concurrent modification
score.close();
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
//-------------//
// deserialize //
//-------------//
/**
* Deserialize the provided binary file to allocate the corresponding Score
* hierarchy
*
* @param file the file that contains the Score data in binary format
*
* @return the allocated Score (and its related classes such as Page, etc),
* or null if load has failed.
*/
public Score deserialize (File file)
{
logger.info("Deserializing score from " + file + " ...");
try {
long s0 = java.lang.System.currentTimeMillis();
ObjectInputStream s = new ObjectInputStream(
new FileInputStream(file));
Score score = (Score) s.readObject();
s.close();
long s1 = java.lang.System.currentTimeMillis();
logger.info("Score deserialized in " + (s1 - s0) + " ms");
return score;
} catch (Exception ex) {
logger.warning("Could not deserialize score from " + file);
logger.warning(ex.toString());
return null;
}
}
//---------------//
// dumpAllScores //
//---------------//
/**
* Dump all score instances
*/
public void dumpAllScores ()
{
java.lang.System.out.println("\n");
java.lang.System.out.println("* All Scores *");
for (Score score : instances) {
java.lang.System.out.println("------------------------------");
if (score.dumpNode()) {
score.dumpChildren(1);
}
}
java.lang.System.out.println("------------------------------");
logger.info(instances.size() + " score(s) dumped");
}
//--------//
// export //
//--------//
/**
* Export a score using the partwise structure of MusicXML, using the
* default file for the provided score
*
* @param score the score to export
*/
public void export (Score score)
{
export(score, null);
}
//--------//
// export //
//--------//
/**
* Export a score using the partwise structure of MusicXML to the provided
* file
*
* @param score the score to export
* @param xmlFile the xml file to write, or null
*/
public void export (Score score,
File xmlFile)
{
new ScoreExporter(score, xmlFile);
}
//-----------//
// exportAll //
//-----------//
/**
* Export all score instances
*/
public void exportAll ()
{
if (logger.isFineEnabled()) {
logger.fine("exportAll");
}
for (Score score : instances) {
score.export();
}
}
//---------------//
// linkAllScores //
//---------------//
/**
* Make an attempt to link every score to proper sheet entity
*/
public void linkAllScores ()
{
if (logger.isFineEnabled()) {
logger.fine("linkAllScores");
}
for (Score score : instances) {
score.linkWithSheet();
}
}
//------//
// load //
//------//
/**
* Load a score from its file
*
* @param file the file from which score has to be retrieved. Depending on
* the precise extension of the file, the score will be
* unmarshalled (by an XML binder) or de-serialized (by plain
* Java).
*
* @return the score, or null if load has failed
*/
public Score load (File file)
{
// Make file canonical
try {
file = new File(file.getCanonicalPath());
} catch (IOException ex) {
logger.warning(
"Cannot get canonical form of file " + file.getPath(),
ex);
return null;
}
Score score = null;
String ext = FileUtil.getExtension(file);
if (ext.equals(ScoreFormat.XML.extension)) {
// try {
// // This may take a while, and even fail ...
// score = (Score) getXmlMapper()
// .load(file);
// ////
// score.dump();
// omr.util.Dumper.dump(score.getSheet());
//
// ////
// } catch (Exception ex) {
// }
} else if (ext.equals(ScoreFormat.BINARY.extension)) {
// This may take a while, and even fail ...
score = deserialize(file);
} else {
logger.warning("Unrecognized score extension on " + file);
}
if (score != null) {
// Some adjustments
score.setRadix(FileUtil.getNameSansExtension(file));
// Fix the container relationships
score.setChildrenContainer();
// Insert in list of instances
insertInstance(score);
// Link with sheet side ?
score.linkWithSheet();
}
return score;
}
//-----------//
// serialize //
//-----------//
/**
* Serialize the score to its binary file, and remember the actual file
* used
*/
public void serialize (Score score)
throws Exception
{
// Make sure the destination directory exists
File dir = new File(Main.getOutputFolder());
if (!dir.exists()) {
logger.info("Creating directory " + dir);
dir.mkdirs();
}
File file = new File(
dir,
score.getRadix() + ScoreFormat.BINARY.extension);
logger.info("Serializing score to " + file + " ...");
long s0 = java.lang.System.currentTimeMillis();
ObjectOutput s = new ObjectOutputStream(new FileOutputStream(file));
s.writeObject(score);
s.close();
long s1 = java.lang.System.currentTimeMillis();
logger.info("Score serialized in " + (s1 - s0) + " ms");
}
//--------------//
// serializeAll //
//--------------//
/**
* Serialize all score instances
*/
public void serializeAll ()
{
if (logger.isFineEnabled()) {
logger.fine("serializeAll");
}
for (Score score : instances) {
try {
score.serialize();
} catch (Exception ex) {
logger.warning("Could not serialize " + score);
}
}
}
//--------//
// remove //
//--------//
/**
* Remove a given score from memory
*
* @param score the score instance to remove
*/
void remove (Score score)
{
// Remove from list of instance
if (instances.contains(score)) {
instances.remove(score);
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
//----------------//
// insertInstance //
//----------------//
private void insertInstance (Score score)
{
if (logger.isFineEnabled()) {
logger.fine("insertInstance " + score);
}
if (score.getRadix() != null) {
// Remove duplicate if any
for (Iterator<Score> it = instances.iterator(); it.hasNext();) {
Score s = it.next();
if (logger.isFineEnabled()) {
logger.fine("checking with " + s.getRadix());
}
if (s.getRadix()
.equals(score.getRadix())) {
if (logger.isFineEnabled()) {
logger.fine("Removing duplicate " + s);
}
it.remove();
s.close();
break;
}
}
// Insert new score instances
instances.add(score);
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
}
| src/main/omr/score/ScoreManager.java | //----------------------------------------------------------------------------//
// //
// S c o r e M a n a g e r //
// //
// Copyright (C) Herve Bitteur 2000-2006. All rights reserved. //
// This software is released under the terms of the GNU General Public //
// License. Please contact the author at [email protected] //
// to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.score;
import omr.Main;
import omr.score.export.ScoreExporter;
import omr.util.FileUtil;
import omr.util.Logger;
import omr.util.XmlMapper;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
/**
* Class <code>ScoreManager</code> handles a collection of score instances.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class ScoreManager
{
//~ Static fields/initializers ---------------------------------------------
private static final Logger logger = Logger.getLogger(ScoreManager.class);
/** Specific glyph XML mapper */
private static XmlMapper xmlMapper;
/** The single instance of this class */
private static ScoreManager INSTANCE;
//~ Instance fields --------------------------------------------------------
/** Slot for one potential change listener */
private ChangeListener changeListener;
/** Unique change event */
private final ChangeEvent changeEvent;
/** Instances of score */
private List<Score> instances = new ArrayList<Score>();
//~ Constructors -----------------------------------------------------------
//--------------//
// ScoreManager //
//--------------//
/**
* Creates a Score Manager.
*/
private ScoreManager ()
{
changeEvent = new ChangeEvent(this);
}
//~ Methods ----------------------------------------------------------------
//-------------------//
// setChangeListener //
//-------------------//
/**
* Register one change listener
*
* @param changeListener the entity to be notified of any change
*/
public void setChangeListener (ChangeListener changeListener)
{
this.changeListener = changeListener;
}
//-------------//
// getInstance //
//-------------//
/**
* Report the single instance of this class,
*
* @return the single instance
*/
public static ScoreManager getInstance ()
{
if (INSTANCE == null) {
INSTANCE = new ScoreManager();
}
return INSTANCE;
}
//-----------//
// getScores //
//-----------//
/**
* Get the collection of scores currently handled by OMR
*
* @return The collection
*/
public List<Score> getScores ()
{
return instances;
}
//---------------//
// checkInserted //
//---------------//
/**
* Register score in score instances if not yet done
*/
public void checkInserted (Score score)
{
if (!instances.contains(score)) {
insertInstance(score);
}
}
//-------//
// close //
//-------//
/**
* Close a score instance
*/
public void close (Score score)
{
if (logger.isFineEnabled()) {
logger.fine("close " + score);
}
// Remove from list of instance
if (instances.contains(score)) {
instances.remove(score);
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
//----------//
// closeAll //
//----------//
/**
* Close all score instances
*/
public void closeAll ()
{
if (logger.isFineEnabled()) {
logger.fine("closeAll");
}
for (Iterator<Score> it = instances.iterator(); it.hasNext();) {
Score score = it.next();
it.remove(); // Done here to avoid concurrent modification
score.close();
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
//-------------//
// deserialize //
//-------------//
/**
* Deserialize the provided binary file to allocate the corresponding Score
* hierarchy
*
* @param file the file that contains the Score data in binary format
*
* @return the allocated Score (and its related classes such as Page, etc),
* or null if load has failed.
*/
public Score deserialize (File file)
{
logger.info("Deserializing score from " + file + " ...");
try {
long s0 = java.lang.System.currentTimeMillis();
ObjectInputStream s = new ObjectInputStream(
new FileInputStream(file));
Score score = (Score) s.readObject();
s.close();
long s1 = java.lang.System.currentTimeMillis();
logger.info("Score deserialized in " + (s1 - s0) + " ms");
return score;
} catch (Exception ex) {
logger.warning("Could not deserialize score from " + file);
logger.warning(ex.toString());
return null;
}
}
//---------------//
// dumpAllScores //
//---------------//
/**
* Dump all score instances
*/
public void dumpAllScores ()
{
java.lang.System.out.println("\n");
java.lang.System.out.println("* All Scores *");
for (Score score : instances) {
java.lang.System.out.println("------------------------------");
if (score.dumpNode()) {
score.dumpChildren(1);
}
}
java.lang.System.out.println("------------------------------");
logger.info(instances.size() + " score(s) dumped");
}
//--------//
// export //
//--------//
/**
* Export a score using the partwise structure of MusicXML, using the
* default file for the provided score
*
* @param score the score to export
*/
public void export (Score score)
{
export(score, null);
}
//--------//
// export //
//--------//
/**
* Export a score using the partwise structure of MusicXML to the provided
* file
*
* @param score the score to export
* @param xmlFile the xml file to write, or null
*/
public void export (Score score,
File xmlFile)
{
new ScoreExporter(score, xmlFile);
}
//-----------//
// exportAll //
//-----------//
/**
* Export all score instances
*/
public void exportAll ()
{
if (logger.isFineEnabled()) {
logger.fine("exportAll");
}
for (Score score : instances) {
score.export();
}
}
//---------------//
// linkAllScores //
//---------------//
/**
* Make an attempt to link every score to proper sheet entity
*/
public void linkAllScores ()
{
if (logger.isFineEnabled()) {
logger.fine("linkAllScores");
}
for (Score score : instances) {
score.linkWithSheet();
}
}
//------//
// load //
//------//
/**
* Load a score from its file
*
* @param file the file from which score has to be retrieved. Depending on
* the precise extension of the file, the score will be
* unmarshalled (by an XML binder) or de-serialized (by plain
* Java).
*
* @return the score, or null if load has failed
*/
public Score load (File file)
{
// Make file canonical
try {
file = new File(file.getCanonicalPath());
} catch (IOException ex) {
logger.warning(
"Cannot get canonical form of file " + file.getPath(),
ex);
return null;
}
Score score = null;
String ext = FileUtil.getExtension(file);
if (ext.equals(ScoreFormat.XML.extension)) {
try {
// This may take a while, and even fail ...
score = (Score) getXmlMapper()
.load(file);
////
score.dump();
omr.util.Dumper.dump(score.getSheet());
////
} catch (Exception ex) {
}
} else if (ext.equals(ScoreFormat.BINARY.extension)) {
// This may take a while, and even fail ...
score = deserialize(file);
} else {
logger.warning("Unrecognized score extension on " + file);
}
if (score != null) {
// Some adjustments
score.setRadix(FileUtil.getNameSansExtension(file));
// Fix the container relationships
score.setChildrenContainer();
// Insert in list of instances
insertInstance(score);
// Link with sheet side ?
score.linkWithSheet();
}
return score;
}
//-----------//
// serialize //
//-----------//
/**
* Serialize the score to its binary file, and remember the actual file
* used
*/
public void serialize (Score score)
throws Exception
{
// Make sure the destination directory exists
File dir = new File(Main.getOutputFolder());
if (!dir.exists()) {
logger.info("Creating directory " + dir);
dir.mkdirs();
}
File file = new File(
dir,
score.getRadix() + ScoreFormat.BINARY.extension);
logger.info("Serializing score to " + file + " ...");
long s0 = java.lang.System.currentTimeMillis();
ObjectOutput s = new ObjectOutputStream(new FileOutputStream(file));
s.writeObject(score);
s.close();
long s1 = java.lang.System.currentTimeMillis();
logger.info("Score serialized in " + (s1 - s0) + " ms");
}
//--------------//
// serializeAll //
//--------------//
/**
* Serialize all score instances
*/
public void serializeAll ()
{
if (logger.isFineEnabled()) {
logger.fine("serializeAll");
}
for (Score score : instances) {
try {
score.serialize();
} catch (Exception ex) {
logger.warning("Could not serialize " + score);
}
}
}
//-------//
// store //
//-------//
/**
* Marshal a score to its XML file
*/
public void store (Score score)
{
store(score, null);
}
//-------//
// store //
//-------//
/**
* Marshal a score to its XML file
*/
public void store (Score score,
File xmlFile)
{
// Where do we write the score xml file?
if (xmlFile == null) {
xmlFile = new File(
Main.getOutputFolder(),
score.getRadix() + ScoreFormat.XML.extension);
}
// Make sure the folder exists
File folder = new File(xmlFile.getParent());
if (!folder.exists()) {
logger.info("Creating folder " + folder);
folder.mkdirs();
}
try {
// Store to disk
getXmlMapper()
.store(score, xmlFile);
logger.info("Score stored to " + xmlFile);
} catch (Exception ignored) {
// Exception already signaled to the user
}
}
//----------//
// storeAll //
//----------//
/**
* Store all score instances
*/
public void storeAll ()
{
if (logger.isFineEnabled()) {
logger.fine("storeAll");
}
for (Score score : instances) {
score.store();
}
}
//--------//
// remove //
//--------//
/**
* Remove a given score from memory
*
* @param score the score instance to remove
*/
void remove (Score score)
{
// Remove from list of instance
if (instances.contains(score)) {
instances.remove(score);
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
//--------------//
// getXmlMapper //
//--------------//
private XmlMapper getXmlMapper ()
{
if (xmlMapper == null) {
xmlMapper = new XmlMapper(Score.class);
}
return xmlMapper;
}
//----------------//
// insertInstance //
//----------------//
private void insertInstance (Score score)
{
if (logger.isFineEnabled()) {
logger.fine("insertInstance " + score);
}
if (score.getRadix() != null) {
// Remove duplicate if any
for (Iterator<Score> it = instances.iterator(); it.hasNext();) {
Score s = it.next();
if (logger.isFineEnabled()) {
logger.fine("checking with " + s.getRadix());
}
if (s.getRadix()
.equals(score.getRadix())) {
if (logger.isFineEnabled()) {
logger.fine("Removing duplicate " + s);
}
it.remove();
s.close();
break;
}
}
// Insert new score instances
instances.add(score);
if (changeListener != null) {
changeListener.stateChanged(changeEvent);
}
}
}
}
| No more XmlMapper
| src/main/omr/score/ScoreManager.java | No more XmlMapper | <ide><path>rc/main/omr/score/ScoreManager.java
<ide>
<ide> import omr.util.FileUtil;
<ide> import omr.util.Logger;
<del>import omr.util.XmlMapper;
<ide>
<ide> import java.io.*;
<ide> import java.util.*;
<ide>
<ide> private static final Logger logger = Logger.getLogger(ScoreManager.class);
<ide>
<del> /** Specific glyph XML mapper */
<del> private static XmlMapper xmlMapper;
<del>
<ide> /** The single instance of this class */
<ide> private static ScoreManager INSTANCE;
<ide>
<ide> String ext = FileUtil.getExtension(file);
<ide>
<ide> if (ext.equals(ScoreFormat.XML.extension)) {
<del> try {
<del> // This may take a while, and even fail ...
<del> score = (Score) getXmlMapper()
<del> .load(file);
<del> ////
<del> score.dump();
<del> omr.util.Dumper.dump(score.getSheet());
<del>
<del> ////
<del> } catch (Exception ex) {
<del> }
<add>// try {
<add>// // This may take a while, and even fail ...
<add>// score = (Score) getXmlMapper()
<add>// .load(file);
<add>// ////
<add>// score.dump();
<add>// omr.util.Dumper.dump(score.getSheet());
<add>//
<add>// ////
<add>// } catch (Exception ex) {
<add>// }
<ide> } else if (ext.equals(ScoreFormat.BINARY.extension)) {
<ide> // This may take a while, and even fail ...
<ide> score = deserialize(file);
<ide> }
<ide> }
<ide>
<del> //-------//
<del> // store //
<del> //-------//
<del> /**
<del> * Marshal a score to its XML file
<del> */
<del> public void store (Score score)
<del> {
<del> store(score, null);
<del> }
<del>
<del> //-------//
<del> // store //
<del> //-------//
<del> /**
<del> * Marshal a score to its XML file
<del> */
<del> public void store (Score score,
<del> File xmlFile)
<del> {
<del> // Where do we write the score xml file?
<del> if (xmlFile == null) {
<del> xmlFile = new File(
<del> Main.getOutputFolder(),
<del> score.getRadix() + ScoreFormat.XML.extension);
<del> }
<del>
<del> // Make sure the folder exists
<del> File folder = new File(xmlFile.getParent());
<del>
<del> if (!folder.exists()) {
<del> logger.info("Creating folder " + folder);
<del> folder.mkdirs();
<del> }
<del>
<del> try {
<del> // Store to disk
<del> getXmlMapper()
<del> .store(score, xmlFile);
<del> logger.info("Score stored to " + xmlFile);
<del> } catch (Exception ignored) {
<del> // Exception already signaled to the user
<del> }
<del> }
<del>
<del> //----------//
<del> // storeAll //
<del> //----------//
<del> /**
<del> * Store all score instances
<del> */
<del> public void storeAll ()
<del> {
<del> if (logger.isFineEnabled()) {
<del> logger.fine("storeAll");
<del> }
<del>
<del> for (Score score : instances) {
<del> score.store();
<del> }
<del> }
<del>
<ide> //--------//
<ide> // remove //
<ide> //--------//
<ide> changeListener.stateChanged(changeEvent);
<ide> }
<ide> }
<del> }
<del>
<del> //--------------//
<del> // getXmlMapper //
<del> //--------------//
<del> private XmlMapper getXmlMapper ()
<del> {
<del> if (xmlMapper == null) {
<del> xmlMapper = new XmlMapper(Score.class);
<del> }
<del>
<del> return xmlMapper;
<ide> }
<ide>
<ide> //----------------// |
|
Java | apache-2.0 | e4b7ab0e61a9866345dbe30ea7911c4ddacf960a | 0 | streamingpool/streamingpool-ext-tensorics | /**
* Copyright (c) 2016 European Organisation for Nuclear Research (CERN), All Rights Reserved.
*/
package cern.streaming.pool.ext.tensorics.service;
import static cern.streaming.pool.core.service.util.ReactiveStreams.fromRx;
import static cern.streaming.pool.core.service.util.ReactiveStreams.rxFrom;
import static rx.Observable.combineLatest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.tensorics.core.resolve.domain.DetailedResolved;
import org.tensorics.core.resolve.engine.ResolvingEngine;
import org.tensorics.core.tree.domain.Contexts;
import org.tensorics.core.tree.domain.EditableResolvingContext;
import org.tensorics.core.tree.domain.Expression;
import org.tensorics.core.tree.domain.Node;
import org.tensorics.core.tree.domain.ResolvingContext;
import org.tensorics.core.tree.walking.Trees;
import cern.streaming.pool.core.service.DiscoveryService;
import cern.streaming.pool.core.service.ReactiveStream;
import cern.streaming.pool.core.service.StreamFactory;
import cern.streaming.pool.core.service.StreamId;
import cern.streaming.pool.ext.tensorics.domain.DetailedExpressionStreamId;
import cern.streaming.pool.ext.tensorics.domain.StreamIdBasedExpression;
import rx.Observable;
import rx.functions.FuncN;
/**
* @author kfuchsbe, caguiler
*/
public class DetailedTensoricsExpressionStreamFactory implements StreamFactory {
private static final FuncN<ResolvingContext> CONTEXT_COMBINER = (Object... entriesToCombine) -> {
EditableResolvingContext context = Contexts.newResolvingContext();
for (Object entry : entriesToCombine) {
ExpToValue castedEntry = (ExpToValue) entry;
context.put(castedEntry.node, castedEntry.value);
}
return context;
};
private final ResolvingEngine engine;
public DetailedTensoricsExpressionStreamFactory(ResolvingEngine engine) {
this.engine = engine;
}
@SuppressWarnings("unchecked")
@Override
public <T> ReactiveStream<T> create(StreamId<T> id, DiscoveryService discoveryService) {
if (!(id instanceof DetailedExpressionStreamId)) {
return null;
}
return (ReactiveStream<T>) fromRx(resolvedStream((DetailedExpressionStreamId<?, ?>) id, discoveryService));
}
private <T, E extends Expression<T>> Observable<DetailedResolved<T, E>> resolvedStream(
DetailedExpressionStreamId<T, E> id, DiscoveryService discoveryService) {
E expression = id.getExpression();
Collection<Node> leaves = Trees.findBottomNodes(expression);
System.out.println("leaves:" + leaves);
@SuppressWarnings("unchecked")
Map<StreamIdBasedExpression<Object>, StreamId<Object>> streamIds = leaves.stream()
.filter(node -> node instanceof StreamIdBasedExpression)
.map(node -> ((StreamIdBasedExpression<Object>) node))
.collect(Collectors.toMap(exp -> exp, exp -> exp.streamId()));
List<Observable<ExpToValue>> observableEntries = new ArrayList<>();
for (Entry<StreamIdBasedExpression<Object>, StreamId<Object>> entry : streamIds.entrySet()) {
Observable<?> plainObservable = rxFrom(discoveryService.discover(entry.getValue()));
plainObservable.doOnNext((a) -> System.out.println(a));
Observable<ExpToValue> mappedObservable = plainObservable.map(obj -> (new ExpToValue(entry.getKey(), obj)));
observableEntries.add(mappedObservable);
}
return combineLatest(observableEntries, CONTEXT_COMBINER).map(ctx -> engine.resolveDetailed(expression, ctx));
}
private static final class ExpToValue {
public ExpToValue(StreamIdBasedExpression<Object> node, Object value) {
super();
this.node = node;
this.value = value;
}
private final StreamIdBasedExpression<Object> node;
private final Object value;
}
}
| src/java/cern/streaming/pool/ext/tensorics/service/DetailedTensoricsExpressionStreamFactory.java | /**
* Copyright (c) 2016 European Organisation for Nuclear Research (CERN), All Rights Reserved.
*/
package cern.streaming.pool.ext.tensorics.service;
import static cern.streaming.pool.core.service.util.ReactiveStreams.fromRx;
import static cern.streaming.pool.core.service.util.ReactiveStreams.rxFrom;
import static rx.Observable.combineLatest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.tensorics.core.resolve.domain.DetailedResolved;
import org.tensorics.core.resolve.engine.ResolvingEngine;
import org.tensorics.core.tree.domain.Contexts;
import org.tensorics.core.tree.domain.EditableResolvingContext;
import org.tensorics.core.tree.domain.Expression;
import org.tensorics.core.tree.domain.Node;
import org.tensorics.core.tree.domain.ResolvingContext;
import org.tensorics.core.tree.walking.Trees;
import cern.streaming.pool.core.service.DiscoveryService;
import cern.streaming.pool.core.service.ReactiveStream;
import cern.streaming.pool.core.service.StreamFactory;
import cern.streaming.pool.core.service.StreamId;
import cern.streaming.pool.ext.tensorics.domain.DetailedExpressionStreamId;
import cern.streaming.pool.ext.tensorics.domain.StreamIdBasedExpression;
import rx.Observable;
import rx.functions.FuncN;
/**
* @author kfuchsbe, caguiler
*/
public class DetailedTensoricsExpressionStreamFactory implements StreamFactory {
private static final FuncN<ResolvingContext> CONTEXT_COMBINER = (Object... entriesToCombine) -> {
EditableResolvingContext context = Contexts.newResolvingContext();
for (Object entry : entriesToCombine) {
ExpToValue castedEntry = (ExpToValue) entry;
context.put(castedEntry.node, castedEntry.value);
}
return context;
};
private final ResolvingEngine engine;
public DetailedTensoricsExpressionStreamFactory(ResolvingEngine engine) {
this.engine = engine;
}
@SuppressWarnings("unchecked")
@Override
public <T> ReactiveStream<T> create(StreamId<T> id, DiscoveryService discoveryService) {
if (!(id instanceof DetailedExpressionStreamId)) {
return null;
}
return (ReactiveStream<T>) fromRx(resolvedStream((DetailedExpressionStreamId<?, ?>) id, discoveryService));
}
private <T, E extends Expression<T>> Observable<DetailedResolved<T, E>> resolvedStream(
DetailedExpressionStreamId<T, E> id, DiscoveryService discoveryService) {
E expression = id.getExpression();
Collection<Node> leaves = Trees.findBottomNodes(expression);
@SuppressWarnings("unchecked")
Map<StreamIdBasedExpression<Object>, StreamId<Object>> streamIds = leaves.stream()
.filter(node -> node instanceof StreamIdBasedExpression)
.map(node -> ((StreamIdBasedExpression<Object>) node))
.collect(Collectors.toMap(exp -> exp, exp -> exp.streamId()));
List<Observable<ExpToValue>> observableEntries = new ArrayList<>();
for (Entry<StreamIdBasedExpression<Object>, StreamId<Object>> entry : streamIds.entrySet()) {
Observable<?> plainObservable = rxFrom(discoveryService.discover(entry.getValue()));
Observable<ExpToValue> mappedObservable = plainObservable.map(obj -> (new ExpToValue(entry.getKey(), obj)));
observableEntries.add(mappedObservable);
}
return combineLatest(observableEntries, CONTEXT_COMBINER).map(ctx -> engine.resolveDetailed(expression, ctx));
}
private static final class ExpToValue {
public ExpToValue(StreamIdBasedExpression<Object> node, Object value) {
super();
this.node = node;
this.value = value;
}
private final StreamIdBasedExpression<Object> node;
private final Object value;
}
}
| filling gui work (debug output) | src/java/cern/streaming/pool/ext/tensorics/service/DetailedTensoricsExpressionStreamFactory.java | filling gui work (debug output) | <ide><path>rc/java/cern/streaming/pool/ext/tensorics/service/DetailedTensoricsExpressionStreamFactory.java
<ide>
<ide> Collection<Node> leaves = Trees.findBottomNodes(expression);
<ide>
<add> System.out.println("leaves:" + leaves);
<add>
<ide> @SuppressWarnings("unchecked")
<ide> Map<StreamIdBasedExpression<Object>, StreamId<Object>> streamIds = leaves.stream()
<ide> .filter(node -> node instanceof StreamIdBasedExpression)
<ide>
<ide> for (Entry<StreamIdBasedExpression<Object>, StreamId<Object>> entry : streamIds.entrySet()) {
<ide> Observable<?> plainObservable = rxFrom(discoveryService.discover(entry.getValue()));
<add> plainObservable.doOnNext((a) -> System.out.println(a));
<ide> Observable<ExpToValue> mappedObservable = plainObservable.map(obj -> (new ExpToValue(entry.getKey(), obj)));
<ide> observableEntries.add(mappedObservable);
<ide> } |
|
JavaScript | mit | 155f0a04b9cea902ee52cf715c7f4408a1558165 | 0 | yishn/Sabaki,yishn/Goban,yishn/Goban,yishn/Sabaki | var remote = require('electron').remote
var ipcRenderer = require('electron').ipcRenderer
var fs = require('fs')
var shell = require('shell')
var sgf = require('../modules/sgf')
var fuzzyfinder = require('../modules/fuzzyfinder')
var gametree = require('../modules/gametree')
var sound = require('../modules/sound')
var helper = require('../modules/helper')
var process = remote.require('process')
var app = remote.app
var dialog = remote.dialog
var gtp = remote.require('./modules/gtp')
var setting = remote.require('./modules/setting')
var GeminiScrollbar = require('gemini-scrollbar')
var Board = require('../modules/board')
var Menu = remote.Menu
var MenuItem = remote.MenuItem
/**
* Getter & setter
*/
function getRootTree() {
if (!getCurrentTreePosition()) return null
return gametree.getRoot(getCurrentTreePosition()[0])
}
function setRootTree(tree, updateHash) {
if (tree.nodes.length == 0) return
tree.parent = null
if (updateHash) document.body.store('treehash', gametree.getHash(tree))
setCurrentTreePosition(sgf.addBoard(tree), 0, true)
setPlayerName(1, 'PB' in tree.nodes[0] ? tree.nodes[0].PB[0] : 'Black')
setPlayerName(-1, 'PW' in tree.nodes[0] ? tree.nodes[0].PW[0] : 'White')
}
function getGraphMatrixDict() {
return $('graph').retrieve('graphmatrixdict')
}
function setGraphMatrixDict(matrixdict) {
if (!getShowSidebar()) return
var s, graph
try {
s = $('graph').retrieve('sigma')
graph = gametree.matrixdict2graph(matrixdict)
} catch(e) { }
try {
if (s && graph) {
s.graph.clear()
s.graph.read(graph)
}
} catch(e) {
setGraphMatrixDict(matrixdict)
}
$('graph').store('graphmatrixdict', matrixdict)
}
function getCurrentTreePosition() {
return $('goban').retrieve('position')
}
function setCurrentTreePosition(tree, index, now) {
if (!tree || getScoringMode()) return
// Remove old graph node color
var oldNode = getCurrentGraphNode()
var oldPos = getCurrentTreePosition()
var node = getGraphNode(tree, index)
if (oldNode && oldNode != node)
oldNode.color = oldNode.originalColor
// Store new position
$('goban').store('position', [tree, index])
var redraw = !node
|| !gametree.onCurrentTrack(tree)
|| tree.collapsed && index == tree.nodes.length - 1
var t = tree
t.collapsed = false
while (t.parent && t.parent.collapsed) {
redraw = true
t.parent.collapsed = false
t = t.parent
}
// Update graph, slider and comment text
updateSidebar(redraw, now)
sgf.addBoard(tree, index)
if (tree.nodes[index].board) setBoard(tree.nodes[index].board)
// Determine current player
var currentplayer = 1
if ('B' in tree.nodes[index]
|| 'PL' in tree.nodes[index] && tree.nodes[index].PL[0] == 'W'
|| 'HA' in tree.nodes[index] && tree.nodes[index].HA[0].toInt() >= 1)
currentplayer = -1
setCurrentPlayer(currentplayer)
}
function getCurrentGraphNode() {
var pos = getCurrentTreePosition()
if (!pos) return null
return getGraphNode(pos[0], pos[1])
}
function getGraphNode(tree, index) {
var id = typeof tree === 'object' ? tree.id + '-' + index : tree
var s = $('graph').retrieve('sigma')
return s.graph.nodes(id)
}
function getSelectedTool() {
var li = $$('#edit .selected')[0]
var tool = li.get('class').replace('selected', '').replace('-tool', '').trim()
if (tool == 'stone') {
return li.getElement('img').get('src').indexOf('_1') != -1 ? 'stone_1' : 'stone_-1'
} else {
return tool
}
}
function setSelectedTool(tool) {
if (!getEditMode()) {
setEditMode(true)
if (getSelectedTool().indexOf(tool) != -1) return
}
$$('#edit .' + tool + '-tool a').fireEvent('click')
}
function getBoard() {
return $('goban').retrieve('board')
}
function setBoard(board) {
if (!getBoard() || getBoard().size != board.size) {
$('goban').store('board', board)
buildBoard()
}
$('goban').store('board', board)
setCaptures(board.captures)
for (var x = 0; x < board.size; x++) {
for (var y = 0; y < board.size; y++) {
var li = $('goban').getElement('.pos_' + x + '-' + y)
var sign = board.arrangement[li.retrieve('tuple')]
var types = ['ghost_1', 'ghost_-1', 'circle', 'triangle',
'cross', 'square', 'label', 'point']
types.forEach(function(x) {
if (li.hasClass(x)) li.removeClass(x)
})
li.set('title', '')
if (li.retrieve('tuple') in board.overlays) {
var overlay = board.overlays[li.retrieve('tuple')]
var type = overlay[0], ghost = overlay[1], label = overlay[2]
if (type != '') li.addClass(type)
if (ghost != 0) li.addClass('ghost_' + ghost)
if (label != '') li.set('title', label)
}
if (li.hasClass('sign_' + sign)) continue
for (var i = -1; i <= 1; i++) {
if (li.hasClass('sign_' + i)) li.removeClass('sign_' + i)
}
li.addClass('sign_' + sign)
.getElement('img').set('src', '../img/goban/stone_' + sign + '.png')
}
}
}
function getScoringMethod() {
return $$('#score .tabs .territory')[0].hasClass('current') ? 'territory' : 'area'
}
function setScoringMethod(method) {
$$('#score .tabs li').removeClass('current')
$$('#score .tabs .' + method).addClass('current')
$$('#score tr > *').addClass('disabled')
$$('#score table .' + method).removeClass('disabled')
setting.set('scoring.method', method)
// Update UI
for (var sign = -1; sign <= 1; sign += 2) {
var tr = $$('#score tbody tr' + (sign < 0 ? ':last-child' : ''))[0]
var tds = tr.getElements('td')
tds[4].set('text', 0)
for (var i = 0; i <= 3; i++) {
if (tds[i].hasClass('disabled') || isNaN(tds[i].get('text').toFloat())) continue
tds[4].set('text', tds[4].get('text').toFloat() + tds[i].get('text').toFloat())
}
}
}
function getKomi() {
var rootNode = getRootTree().nodes[0]
return 'KM' in rootNode ? rootNode.KM[0].toFloat() : 0
}
function getEngineName() {
return $('console').retrieve('enginename')
}
function getEngineController() {
return $('console').retrieve('controller')
}
function getEngineCommands() {
return $('console').retrieve('commands')
}
function setUndoable(undoable) {
if (undoable) {
var rootTree = gametree.clone(getRootTree())
var position = gametree.getLevel.apply(null, getCurrentTreePosition())
document.body
.addClass('undoable')
.store('undodata-root', rootTree)
.store('undodata-pos', position)
} else {
document.body
.removeClass('undoable')
.store('undodata-root', null)
.store('undodata-pos', null)
}
}
function getBookmark() {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
return 'SBKBM' in node
}
function setBookmark(bookmark) {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
if (bookmark) node.SBKBM = [1]
else delete node.SBKBM
updateGraph()
}
/**
* Methods
*/
function loadSettings() {
if (setting.get('view.fuzzy_stone_placement'))
$('goban').addClass('fuzzy')
if (setting.get('view.show_coordinates'))
$('goban').addClass('coordinates')
if (setting.get('view.show_variations'))
$('goban').addClass('variations')
if (setting.get('view.show_leftsidebar')) {
document.body.addClass('leftsidebar')
setLeftSidebarWidth(setting.get('view.leftsidebar_width'))
}
if (setting.get('view.show_graph') || setting.get('view.show_comments')) {
document.body.addClass('sidebar')
setSidebarArrangement(setting.get('view.show_graph'), setting.get('view.show_comments'))
}
setSidebarWidth(setting.get('view.sidebar_width'))
}
function prepareEditTools() {
$$('#edit ul a').addEvent('click', function() {
if (!this.getParent().hasClass('selected')) {
$$('#edit .selected').removeClass('selected')
this.getParent().addClass('selected')
} else if (this.getParent().hasClass('stone-tool')) {
var img = this.getElement('img')
var black = img.get('src') == '../img/edit/stone_1.svg'
img.set('src', black ? '../img/edit/stone_-1.svg' : '../img/edit/stone_1.svg')
}
})
}
function prepareGameGraph() {
var container = $('graph')
var s = new sigma(container)
s.settings({
defaultNodeColor: setting.get('graph.node_inactive_color'),
defaultEdgeColor: setting.get('graph.node_color'),
defaultNodeBorderColor: 'rgba(255,255,255,.2)',
edgeColor: 'default',
borderSize: 2,
zoomMax: 1,
zoomMin: 1,
autoResize: false,
autoRescale: false
})
var getTreePos = function(e) { return [e.data.node.data[0], e.data.node.data[1]] }
s.bind('clickNode', function(e) {
setCurrentTreePosition.apply(null, getTreePos(e).concat([true]))
}).bind('rightClickNode', function(e) {
openNodeMenu.apply(null, getTreePos(e))
})
container.store('sigma', s)
}
function prepareSlider() {
var slider = $$('#sidebar .slider .inner')[0]
Element.NativeEvents.touchstart = 2
Element.NativeEvents.touchmove = 2
Element.NativeEvents.touchend = 2
var changeSlider = function(percentage) {
percentage = Math.min(1, Math.max(0, percentage))
var height = Math.round((gametree.getHeight(getRootTree()) - 1) * percentage)
var pos = gametree.navigate(getRootTree(), 0, height)
if (helper.equals(pos, getCurrentTreePosition())) return
setCurrentTreePosition.apply(null, pos)
updateSlider()
}
slider.addEvent('mousedown', function(e) {
if (e.event.buttons != 1) return
this.store('mousedown', true).addClass('active')
document.body.fireEvent('mousemove', e)
}).addEvent('touchstart', function() {
this.addClass('active')
}).addEvent('touchmove', function(e) {
var percentage = (e.client.y - slider.getPosition().y) / slider.getSize().y
changeSlider(percentage)
}).addEvent('touchend', function() {
this.removeClass('active')
})
document.body.addEvent('mouseup', function() {
slider.store('mousedown', false)
.removeClass('active')
}).addEvent('mousemove', function(e) {
if (e.event.buttons != 1 || !slider.retrieve('mousedown'))
return
var percentage = (e.event.clientY - slider.getPosition().y) / slider.getSize().y
changeSlider(percentage)
})
// Prepare previous/next buttons
$$('#sidebar .slider a').addEvent('mousedown', function() {
this.store('mousedown', true)
startAutoScroll(this.hasClass('next') ? 1 : -1)
})
document.body.addEvent('mouseup', function() {
$$('#sidebar .slider a').store('mousedown', false)
})
}
function prepareDragDropFiles() {
Element.NativeEvents.dragover = 2
Element.NativeEvents.drop = 2
document.body.addEvent('dragover', function() {
return false
}).addEvent('drop', function(e) {
e.preventDefault()
if (e.event.dataTransfer.files.length == 0) return
loadGame(e.event.dataTransfer.files[0].path)
})
}
function prepareConsole() {
$$('#console form').addEvent('submit', function(e) {
e.preventDefault()
var input = this.getElement('input')
if (input.value.trim() == '') return
input.blur()
var command = gtp.parseCommand(input.value)
sendGTPCommand(command)
})
$$('#console form input').addEvent('keydown', function(e) {
if ([40, 38, 9].indexOf(e.code) != -1) e.preventDefault()
var inputs = $$('#console form input')
if (this.retrieve('index') == null) this.store('index', inputs.indexOf(this))
var i = this.retrieve('index')
var length = inputs.length
if ([38, 40].indexOf(e.code) != -1) {
if (e.code == 38) {
// Up
i = Math.max(i - 1, 0)
} else if (e.code == 40) {
// Down
i = Math.min(i + 1, length - 1)
}
this.value = i == length - 1 ? '' : inputs[i].value
this.store('index', i)
} else if (e.code == 9) {
// Tab
var tokens = this.value.split(' ')
var commands = getEngineCommands()
if (!commands) return
var i = 0
var selection = this.selectionStart
while (selection > tokens[i].length && selection.length != 0 && i < tokens.length - 1)
selection -= tokens[i++].length + 1
var result = fuzzyfinder.find(tokens[i], getEngineCommands())
if (!result) return
tokens[i] = result
this.value = tokens.join(' ')
this.selectionStart = this.selectionEnd = (function() {
var sum = 0
while (i >= 0) sum += tokens[i--].length + 1
return sum - 1
})()
}
})
}
function loadEngines() {
// Load menu items
ipcRenderer.send('build-menu')
// Load engines list
var ul = $$('#preferences .engines-list ul')[0]
ul.empty()
setting.getEngines().forEach(function(engine) {
addEngineItem(engine.name, engine.path, engine.args)
})
}
function attachEngine(exec, args) {
detachEngine()
setIsBusy(true)
setTimeout(function() {
var split = require('argv-split')
var controller = new gtp.Controller(exec, split(args))
if (controller.error) {
showMessageBox('There was an error attaching the engine.', 'error')
setIsBusy(false)
return
}
controller.on('quit', function() { $('console').store('controller', null) })
$('console').store('controller', controller)
sendGTPCommand(new gtp.Command(null, 'name'), true, function(response) {
$('console').store('enginename', response.content)
})
sendGTPCommand(new gtp.Command(null, 'version'))
sendGTPCommand(new gtp.Command(null, 'protocol_version'))
sendGTPCommand(new gtp.Command(null, 'list_commands'), true, function(response) {
$('console').store('commands', response.content.split('\n'))
})
syncEngine()
setIsBusy(false)
}, setting.get('gtp.attach_delay'))
}
function detachEngine() {
sendGTPCommand(new gtp.Command(null, 'quit'), true)
clearConsole()
$('console').store('controller', null)
.store('boardhash', null)
}
function syncEngine() {
var board = getBoard()
if (!getEngineController()
|| $('console').retrieve('boardhash') == board.getHash()) return
if (!board.isValid()) {
showMessageBox('GTP engines don’t support invalid board positions.', 'warning')
return
}
setIsBusy(true)
sendGTPCommand(new gtp.Command(null, 'clear_board'), true)
sendGTPCommand(new gtp.Command(null, 'boardsize', [board.size]), true)
sendGTPCommand(new gtp.Command(null, 'komi', [getKomi()]), true)
// Replay
for (var i = 0; i < board.size; i++) {
for (var j = 0; j < board.size; j++) {
var v = [i, j]
var sign = board.arrangement[v]
if (sign == 0) continue
var color = sign > 0 ? 'B' : 'W'
var point = gtp.vertex2point(v, board.size)
sendGTPCommand(new gtp.Command(null, 'play', [color, point]), true)
}
}
$('console').store('boardhash', board.getHash())
setIsBusy(false)
}
function checkForUpdates(callback) {
if (!callback) callback = function(hasUpdates) {}
var url = 'https://github.com/yishn/' + app.getName() + '/releases/latest'
// Check internet connection first
remote.require('dns').lookup('github.com', function(err) {
if (err) return
remote.require('https').get(url, function(response) {
response.once('data', function(chunk) {
chunk = '' + chunk
var hasUpdates = chunk.indexOf('v' + app.getVersion()) == -1
if (hasUpdates && showMessageBox(
'There is a new version of ' + app.getName() + ' available.',
'info',
['Download Update', 'Not Now'], 1
) == 0) shell.openExternal(url)
callback(hasUpdates)
})
}).on('error', function(e) {})
})
}
function makeMove(vertex, sendCommand) {
if (sendCommand == null) sendCommand = getEngineController() != null
var pass = !getBoard().hasVertex(vertex)
if (!pass && getBoard().arrangement[vertex] != 0) return
var position = getCurrentTreePosition()
var tree = position[0], index = position[1]
var sign = getCurrentPlayer()
var color = sign > 0 ? 'B' : 'W'
var capture = false, suicide = false
var createNode = true
if (sendCommand) syncEngine()
if (!pass) {
// Check for ko
if (setting.get('game.show_ko_warning')) {
var tp = gametree.navigate(tree, index, -1)
var prevTree = tp[0], prevIndex = tp[1]
var ko = false
if (prevTree) {
var hash = getBoard().makeMove(sign, vertex).getHash()
ko = prevTree.nodes[prevIndex].board.getHash() == hash
}
if (ko && showMessageBox(
['You are about to play a move which repeats a previous board position.',
'This is invalid in some rulesets.'].join('\n'),
'info',
['Play Anyway', 'Don’t Play'], 1
) != 0) return
}
// Check for suicide
capture = getBoard().getNeighborhood(vertex).some(function(v) {
return getBoard().arrangement[v] == -sign && getBoard().getLiberties(v).length == 1
})
suicide = !capture && getBoard().getNeighborhood(vertex).filter(function(v) {
return getBoard().arrangement[v] == sign
}).every(function(v) {
return getBoard().getLiberties(v).length == 1
}) && getBoard().getNeighborhood(vertex).filter(function(v) {
return getBoard().arrangement[v] == 0
}).length == 0
if (suicide && setting.get('game.show_suicide_warning')) {
if (showMessageBox(
['You are about to play a suicide move.',
'This is invalid in some rulesets.'].join('\n'),
'info',
['Play Anyway', 'Don’t Play'], 1
) != 0) return
}
// Randomize shift and readjust
var li = $$('#goban .pos_' + vertex[0] + '-' + vertex[1])
var direction = Math.floor(Math.random() * 9)
for (var i = 0; i < 9; i++) li.removeClass('shift_' + i)
li.addClass('shift_' + direction)
readjustShifts(vertex)
}
if (tree.current == null && tree.nodes.length - 1 == index) {
// Append move
var node = {}
node[color] = [sgf.vertex2point(vertex)]
tree.nodes.push(node)
setCurrentTreePosition(tree, tree.nodes.length - 1)
} else {
if (index != tree.nodes.length - 1) {
// Search for next move
var nextNode = tree.nodes[index + 1]
var moveExists = color in nextNode
&& helper.equals(sgf.point2vertex(nextNode[color][0]), vertex)
if (moveExists) {
setCurrentTreePosition(tree, index + 1)
createNode = false
}
} else {
// Search for variation
var variations = tree.subtrees.filter(function(subtree) {
return subtree.nodes.length > 0
&& color in subtree.nodes[0]
&& helper.equals(sgf.point2vertex(subtree.nodes[0][color][0]), vertex)
})
if (variations.length > 0) {
setCurrentTreePosition(sgf.addBoard(variations[0]), 0)
createNode = false
}
}
if (createNode) {
// Create variation
var splitted = gametree.splitTree(tree, index)
var node = {}; node[color] = [sgf.vertex2point(vertex)]
var newtree = gametree.new()
newtree.nodes = [node]
newtree.parent = splitted
splitted.subtrees.push(newtree)
splitted.current = splitted.subtrees.length - 1
sgf.addBoard(newtree, newtree.nodes.length - 1)
setCurrentTreePosition(newtree, 0)
}
}
// Play sounds
if (!pass) {
var delay = setting.get('sound.captureDelayMin')
delay += Math.floor(Math.random() * (setting.get('sound.captureDelayMax') - delay))
if (capture || suicide) setTimeout(function() {
sound.playCapture()
}, delay)
sound.playPachi()
} else {
sound.playPass()
}
// Remove undo information
setUndoable(false)
// Enter scoring mode when two consecutive passes
var enterScoring = false
if (pass && createNode) {
var prevNode = tree.nodes[index]
var prevColor = sign > 0 ? 'W' : 'B'
var prevPass = prevColor in prevNode && prevNode[prevColor][0] == ''
if (prevPass) {
enterScoring = true
setScoringMode(true)
}
}
// Handle GTP engine
if (sendCommand && !enterScoring) {
sendGTPCommand(
new gtp.Command(null, 'play', [color, gtp.vertex2point(vertex, getBoard().size)]),
true
)
$('console').store('boardhash', getBoard().getHash())
setIsBusy(true)
setTimeout(function() {
generateMove(true)
}, setting.get('gtp.move_delay'))
}
}
function useTool(vertex, event) {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
var node = tree.nodes[index]
var tool = getSelectedTool()
var board = getBoard()
var dictionary = {
cross: 'MA',
triangle: 'TR',
circle: 'CR',
square: 'SQ',
number: 'LB',
label: 'LB'
}
if (tool.indexOf('stone') != -1) {
if ('B' in node || 'W' in node) {
// New variation needed
var splitted = gametree.splitTree(tree, index)
if (splitted != tree || splitted.subtrees.length != 0) {
tree = gametree.new()
tree.parent = splitted
splitted.subtrees.push(tree)
}
node = { PL: getCurrentPlayer() > 0 ? ['B'] : ['W'] }
index = tree.nodes.length
tree.nodes.push(node)
}
var sign = tool.indexOf('_1') != -1 ? 1 : -1
if (event.button == 2) sign = -sign
var oldSign = board.arrangement[vertex]
var ids = ['AW', 'AE', 'AB']
var id = ids[sign + 1]
var point = sgf.vertex2point(vertex)
for (var i = -1; i <= 1; i++) {
if (!(ids[i + 1] in node)) continue
k = node[ids[i + 1]].indexOf(point)
if (k >= 0) {
node[ids[i + 1]].splice(k, 1)
if (node[ids[i + 1]].length == 0) {
delete node[ids[i + 1]]
}
}
}
if (oldSign != sign) {
if (id in node) node[id].push(point)
else node[id] = [point]
} else if (oldSign == sign) {
if ('AE' in node) node.AE.push(point)
else node.AE = [point]
}
} else {
if (event.button != 0) return
if (tool != 'label' && tool != 'number') {
if (vertex in board.overlays && board.overlays[vertex][0] == tool) {
delete board.overlays[vertex]
} else {
board.overlays[vertex] = [tool, 0, '']
}
} else if (tool == 'number') {
if (vertex in board.overlays && board.overlays[vertex][0] == 'label') {
delete board.overlays[vertex]
} else {
var number = 1
if ('LB' in node) {
var list = node.LB.map(function(x) {
return x.substr(3).toInt()
}).filter(function(x) {
return !isNaN(x)
})
list.sort(function(a, b) { return a - b })
for (var i = 0; i <= list.length; i++) {
if (i < list.length && i + 1 == list[i]) continue
number = i + 1
break
}
}
board.overlays[vertex] = [tool, 0, number.toString()]
}
} else if (tool == 'label') {
if (vertex in board.overlays && board.overlays[vertex][0] == 'label') {
delete board.overlays[vertex]
} else {
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var k = 0
if ('LB' in node) {
var list = node.LB.filter(function(x) {
return x.length == 4
}).map(function(x) {
return alpha.indexOf(x[3])
}).filter(function(x) { return x >= 0 })
list.sort(function(a, b) { return a - b })
for (var i = 0; i <= list.length; i++) {
if (i < list.length && i == list[i]) continue
k = Math.min(i, alpha.length - 1)
break
}
}
board.overlays[vertex] = [tool, 0, alpha[k]]
}
}
for (var id in dictionary) delete node[dictionary[id]]
// Update SGF
$$('#goban .row li').forEach(function(li) {
var v = li.retrieve('tuple')
if (!(v in board.overlays)) return
var id = dictionary[board.overlays[v][0]]
var pt = sgf.vertex2point(v)
if (id == 'LB') pt += ':' + board.overlays[v][2]
if (id in node) node[id].push(pt)
else node[id] = [pt]
})
}
setUndoable(false)
setCurrentTreePosition(tree, index)
}
function findPosition(step, condition) {
if (isNaN(step)) step = 1
else step = step >= 0 ? 1 : -1
setIsBusy(true)
setTimeout(function() {
var pos = getCurrentTreePosition()
var iterator = gametree.makeNodeIterator.apply(null, pos)
while (true) {
pos = step >= 0 ? iterator.next() : iterator.prev()
if (!pos) {
var root = getRootTree()
if (step == 1) {
pos = [root, 0]
} else {
var sections = gametree.getSection(root, gametree.getHeight(root) - 1)
pos = sections[sections.length - 1]
}
iterator = gametree.makeNodeIterator.apply(null, pos)
}
if (helper.equals(pos, getCurrentTreePosition()) || condition.apply(null, pos)) break
}
setCurrentTreePosition.apply(null, pos)
setIsBusy(false)
}, setting.get('find.delay'))
}
function findBookmark(step) {
findPosition(step, function(tree, index) {
var node = tree.nodes[index]
return 'SBKBM' in node
})
}
function findMove(vertex, text, step) {
if (vertex == null && text.trim() == '') return
var point = vertex ? sgf.vertex2point(vertex) : null
findPosition(step, function(tree, index) {
var node = tree.nodes[index]
var cond = function(prop, value) {
return prop in node && node[prop][0].toLowerCase().indexOf(value.toLowerCase()) >= 0
}
return (!point || ['B', 'W'].some(function(x) { return cond(x, point) }))
&& (!text || cond('C', text))
})
}
function vertexClicked(vertex, event) {
closeGameInfo()
if (getScoringMode()) {
if (event.button != 0) return
if (getBoard().arrangement[vertex] == 0) return
getBoard().getRelatedChains(vertex).forEach(function(v) {
$$('#goban .pos_' + v[0] + '-' + v[1]).toggleClass('dead')
})
updateAreaMap()
} else if (getEditMode()) {
useTool(vertex, event)
} else if (getFindMode()) {
if (event.button != 0) return
setIndicatorVertex(vertex)
findMove(getIndicatorVertex(), getFindText(), 1)
} else {
// Playing mode
if (event.button != 0) return
var board = getBoard()
if (board.arrangement[vertex] == 0) {
makeMove(vertex)
} else if (vertex in board.overlays
&& board.overlays[vertex][0] == 'point'
&& setting.get('edit.click_currentvertex_to_remove')) {
removeNode.apply(null, getCurrentTreePosition())
}
closeDrawers()
}
}
function updateSidebar(redraw, now) {
clearTimeout($('sidebar').retrieve('updatesidebarid'))
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
$('sidebar').store('updatesidebarid', setTimeout(function() {
if (!helper.equals(getCurrentTreePosition(), [tree, index]))
return
// Set current path
var t = tree
while (t.parent) {
t.parent.current = t.parent.subtrees.indexOf(t)
t = t.parent
}
// Update
updateSlider()
updateCommentText()
updateSgfProperties()
if (redraw) updateGraph()
centerGraphCameraAt(getCurrentGraphNode())
}, now ? 0 : setting.get('graph.delay')))
}
function updateGraph() {
if (!getShowSidebar() || !getCurrentTreePosition()) return
setGraphMatrixDict(gametree.tree2matrixdict(getRootTree()))
centerGraphCameraAt(getCurrentGraphNode())
}
function updateSlider() {
if (!getShowSidebar()) return
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
var total = gametree.getHeight(getRootTree()) - 1
var relative = gametree.getLevel(tree, index)
setSliderValue(total == 0 ? 0 : relative * 100 / total, relative)
}
function updateCommentText() {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
setCommentText('C' in node ? node.C[0] : '')
}
function updateSgfProperties() {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
// TODO
}
function updateAreaMap() {
var board = getBoard().clone()
$$('#goban .row li.dead').forEach(function(li) {
if (li.hasClass('sign_1')) board.captures['-1']++
else if (li.hasClass('sign_-1')) board.captures['1']++
board.arrangement[li.retrieve('tuple')] = 0
})
var map = board.getAreaMap()
$$('#goban .row li').forEach(function(li) {
li.removeClass('area_-1').removeClass('area_0').removeClass('area_1')
.addClass('area_' + map[li.retrieve('tuple')])
})
var falsedead = $$('#goban .row li.area_-1.sign_-1.dead, #goban .row li.area_1.sign_1.dead')
if (falsedead.length > 0) {
falsedead.removeClass('dead')
return updateAreaMap()
}
$('goban').store('areamap', map)
.store('finalboard', board)
}
function commitCommentText() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
var comment = $$('#properties textarea').get('value')[0]
if (comment != '') tree.nodes[index].C = [comment]
else delete tree.nodes[index].C
updateCommentText()
updateSidebar(true)
setUndoable(false)
}
function commitGameInfo() {
var rootNode = getRootTree().nodes[0]
var info = $('info')
rootNode.BR = [info.getElement('input[name="rank_1"]').get('value').trim()]
rootNode.WR = [info.getElement('input[name="rank_-1"]').get('value').trim()]
rootNode.PB = [info.getElement('input[name="name_1"]').get('value').trim()]
rootNode.PW = [info.getElement('input[name="name_-1"]').get('value').trim()]
setPlayerName(1, rootNode.PB[0])
setPlayerName(-1, rootNode.PW[0])
var result = info.getElement('input[name="result"]').get('value').trim()
rootNode.RE = [result]
if (result == '') delete rootNode.RE
var komi = info.getElement('input[name="komi"]').get('value').toFloat()
rootNode.KM = [String.from(komi)]
if (isNaN(komi)) rootNode.KM = ['0']
var handicap = info.getElement('select[name="handicap"]').selectedIndex
if (handicap == 0) delete rootNode.HA
else rootNode.HA = [String.from(handicap + 1)]
var size = info.getElement('input[name="size"]').get('value').toInt()
rootNode.SZ = [String.from(Math.max(Math.min(size, 26), 9))]
if (isNaN(size)) rootNode.SZ = ['' + setting.get('game.default_board_size')]
if (!info.getElement('select[name="handicap"]').disabled) {
setCurrentTreePosition(getRootTree(), 0)
if (!('HA' in rootNode)) {
delete rootNode.AB
} else {
var board = getBoard()
var stones = board.getHandicapPlacement(rootNode.HA[0].toInt())
rootNode.AB = []
for (var i = 0; i < stones.length; i++) {
rootNode.AB.push(sgf.vertex2point(stones[i]))
}
}
setCurrentTreePosition(getRootTree(), 0)
}
setUndoable(false)
}
function commitScore() {
var rootNode = getRootTree().nodes[0]
var results = $$('#score tbody td:last-child').get('text')
var diff = results[0].toFloat() - results[1].toFloat()
var result = diff > 0 ? 'B+' : (diff < 0 ? 'W+' : 'Draw')
if (diff != 0) result = result + Math.abs(diff)
rootNode.RE = [result]
showGameInfo()
setUndoable(false)
}
function commitPreferences() {
// Save general preferences
$$('#preferences input[type="checkbox"]').forEach(function(el) {
setting.set(el.name, el.checked)
})
remote.getCurrentWindow().webContents.setAudioMuted(!setting.get('sound.enable'))
setFuzzyStonePlacement(setting.get('view.fuzzy_stone_placement'))
// Save engines
setting.clearEngines()
$$('#preferences .engines-list li').forEach(function(li) {
var nameinput = li.getElement('h3 input')
setting.addEngine(
nameinput.value.trim() == '' ? nameinput.placeholder : nameinput.value,
li.getElement('h3 + p input').value,
li.getElement('h3 + p + p input').value
)
})
setting.save()
loadEngines()
}
function sendGTPCommand(command, ignoreBlocked, callback) {
if (!getEngineController()) {
$$('#console form:last-child input')[0].value = ''
return
}
var controller = getEngineController()
var container = $$('#console .inner')[0]
var oldform = container.getElement('form:last-child')
var form = oldform.clone().cloneEvents(oldform)
var pre = new Element('pre', { text: ' ' })
form.getElement('input').set('value', '').cloneEvents(oldform.getElement('input'))
oldform.addClass('waiting').getElement('input').value = command.toString()
container.grab(pre).grab(form)
if (getShowLeftSidebar()) form.getElement('input').focus()
// Cleanup
var forms = $$('#console .inner form')
if (forms.length > setting.get('console.max_history_count')) {
forms[0].getNext('pre').dispose()
forms[0].dispose()
}
var listener = function(response, c) {
pre.set('html', response.toHtml())
helper.wireLinks(pre)
oldform.removeClass('waiting')
if (callback) callback(response)
// Update scrollbars
var view = $$('#console .gm-scroll-view')[0]
var scrollbar = $('console').retrieve('scrollbar')
view.scrollTo(0, view.getScrollSize().y)
if (scrollbar) scrollbar.update()
}
if (!ignoreBlocked && setting.get('console.blocked_commands').indexOf(command.name) != -1) {
listener(new gtp.Response(null, 'blocked command', true, true), command)
} else {
controller.once('response-' + command.internalId, listener)
controller.sendCommand(command)
}
}
function generateMove(ignoreBusy) {
if (!getEngineController() || !ignoreBusy && getIsBusy()) return
closeDrawers()
syncEngine()
setIsBusy(true)
var color = getCurrentPlayer() > 0 ? 'B' : 'W'
var opponent = getCurrentPlayer() > 0 ? 'W' : 'B'
sendGTPCommand(new gtp.Command(null, 'genmove', [color]), true, function(r) {
setIsBusy(false)
if (r.content.toLowerCase() == 'resign') {
showMessageBox(getEngineName() + ' has resigned.')
getRootTree().nodes[0].RE = [opponent + '+Resign']
return
}
var v = [-1, -1]
if (r.content.toLowerCase() != 'pass')
v = gtp.point2vertex(r.content, getBoard().size)
$('console').store('boardhash', getBoard().makeMove(getCurrentPlayer(), v).getHash())
makeMove(v, false)
})
}
function centerGraphCameraAt(node) {
if (!getShowSidebar() || !node) return
var s = $('graph').retrieve('sigma')
s.renderers[0].resize().render()
var matrixdict = getGraphMatrixDict()
var y = matrixdict[1][node.id][1]
var wp = gametree.getWidth(y, matrixdict[0])
var width = wp[0], padding = wp[1]
var x = matrixdict[1][node.id][0] - padding
var relX = width == 1 ? 0 : x / (width - 1)
var diff = (width - 1) * setting.get('graph.grid_size') / 2
diff = Math.min(diff, s.renderers[0].width / 2 - setting.get('graph.grid_size'))
node.color = setting.get('graph.node_active_color')
s.refresh()
sigma.misc.animation.camera(
s.camera,
{
x: node[s.camera.readPrefix + 'x'] + (1 - 2 * relX) * diff,
y: node[s.camera.readPrefix + 'y']
},
{ duration: setting.get('graph.delay') }
)
}
function askForSave() {
if (!getRootTree()) return true
var hash = gametree.getHash(getRootTree())
if (hash != document.body.retrieve('treehash')) {
var answer = showMessageBox(
'Your changes will be lost if you close this game without saving.',
'warning',
['Save', 'Don’t Save', 'Cancel'], 2
)
if (answer == 0) saveGame()
else if (answer == 2) return false
}
return true
}
function startAutoScroll(direction, delay) {
if (direction > 0 && !$$('#sidebar .slider a.next')[0].retrieve('mousedown')
|| direction < 0 && !$$('#sidebar .slider a.prev')[0].retrieve('mousedown')) return
if (delay == null) delay = setting.get('autoscroll.max_interval')
delay = Math.max(setting.get('autoscroll.min_interval'), delay)
var slider = $$('#sidebar .slider')[0]
clearTimeout(slider.retrieve('autoscrollid'))
if (direction > 0) goForward()
else goBack()
updateSlider()
slider.store('autoscrollid', setTimeout(function() {
startAutoScroll(direction, delay - setting.get('autoscroll.diff'))
}, delay))
}
/**
* Menu
*/
function newGame(playSound) {
if (getIsBusy() || !askForSave()) return
var buffer = ';GM[1]AP[' + app.getName() + ':' + app.getVersion() + ']'
buffer += 'CA[UTF-8]PB[Black]PW[White]KM[' + setting.get('game.default_komi')
+ ']SZ[' + setting.get('game.default_board_size') + ']'
closeDrawers()
var tree = sgf.parse(sgf.tokenize(buffer))
setRootTree(tree, true)
setUndoable(false)
remote.getCurrentWindow().setRepresentedFilename('')
if (arguments.length >= 1 && playSound) {
sound.playNewGame()
showGameInfo()
}
}
function loadGame(filename) {
if (getIsBusy() || !askForSave()) return
setIsBusy(true)
if (!filename) {
var result = dialog.showOpenDialog(remote.getCurrentWindow(), {
filters: [sgf.meta, { name: 'All Files', extensions: ['*'] }]
})
if (result) filename = result[0]
}
if (filename) {
setTimeout(function() {
var win = remote.getCurrentWindow()
try {
var tree = sgf.parseFile(filename, function(progress) {
setProgressIndicator(progress, win)
}).subtrees[0]
closeDrawers()
setRootTree(tree, true)
setUndoable(false)
} catch(e) {
showMessageBox('This file is unreadable.', 'warning')
}
setProgressIndicator(-1, win)
remote.getCurrentWindow().setRepresentedFilename(filename)
if (setting.get('game.goto_end_after_loading')) goToEnd()
setIsBusy(false)
}, setting.get('app.loadgame_delay'))
} else {
setIsBusy(false)
}
}
function saveGame() {
if (getIsBusy()) return
setIsBusy(true)
var result = dialog.showSaveDialog(remote.getCurrentWindow(), {
filters: [sgf.meta, { name: 'All Files', extensions: ['*'] }]
})
if (result) {
var tree = getRootTree()
var text = sgf.tree2string(tree)
fs.writeFile(result, '(' + text + ')')
document.body.store('treehash', gametree.getHash(tree))
remote.getCurrentWindow().setRepresentedFilename(result)
}
setIsBusy(false)
}
function clearAllOverlays() {
closeDrawers()
var overlayIds = ['MA', 'TR', 'CR', 'SQ', 'LB', 'AR', 'LN']
// Save undo information
setUndoable(true)
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
overlayIds.forEach(function(id) {
delete tree.nodes[index][id]
})
setCurrentTreePosition(tree, index)
}
function goBack() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
setCurrentTreePosition.apply(null, gametree.navigate(tree, index, -1))
}
function goForward() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
setCurrentTreePosition.apply(null, gametree.navigate(tree, index, 1))
}
function goToNextFork() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (index != tree.nodes.length - 1)
setCurrentTreePosition(tree, tree.nodes.length - 1)
else if (tree.current != null) {
var subtree = tree.subtrees[tree.current]
setCurrentTreePosition(subtree, subtree.nodes.length - 1)
}
}
function goToPreviousFork() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (tree.parent == null || tree.parent.nodes.length == 0)
setCurrentTreePosition(tree, 0)
else setCurrentTreePosition(tree.parent, tree.parent.nodes.length - 1)
}
function goToBeginning() {
var tree = getRootTree()
if (tree.nodes.length == 0) return
setCurrentTreePosition(tree, 0)
}
function goToEnd() {
var tree = getCurrentTreePosition()[0]
setCurrentTreePosition.apply(null, gametree.navigate(tree, 0, gametree.getCurrentHeight(tree) - 1))
}
function goToNextVariation() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (!tree.parent) return
var mod = tree.parent.subtrees.length
var i = (tree.parent.current + 1) % mod
setCurrentTreePosition(tree.parent.subtrees[i], 0)
}
function goToPreviousVariation() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (!tree.parent) return
var mod = tree.parent.subtrees.length
var i = (tree.parent.current + mod - 1) % mod
setCurrentTreePosition(tree.parent.subtrees[i], 0)
}
function removeNode(tree, index) {
if (!tree.parent && index == 0) {
showMessageBox('The root node cannot be removed.', 'warning')
return
}
if (setting.get('edit.show_removenode_warning') && showMessageBox(
'Do you really want to remove this node permanently?',
'warning',
['Remove Node', 'Cancel'], 1
) == 1) return
// Save undo information
setUndoable(true)
// Remove node
closeDrawers()
var prev = gametree.navigate(tree, index, -1)
if (index != 0) {
tree.nodes.splice(index, tree.nodes.length)
tree.current = null
tree.subtrees.length = 0
} else {
var parent = tree.parent
var i = parent.subtrees.indexOf(tree)
parent.subtrees.splice(i, 1)
if (parent.current >= i) parent.current--
gametree.reduceTree(parent)
}
setGraphMatrixDict(gametree.tree2matrixdict(getRootTree()))
if (getCurrentGraphNode()) prev = getCurrentTreePosition()
setCurrentTreePosition(prev[0], prev[1])
}
function undoBoard() {
if (document.body.retrieve('undodata-root') == null
|| document.body.retrieve('undodata-pos') == null)
return
setIsBusy(true)
setTimeout(function() {
setRootTree(document.body.retrieve('undodata-root'))
var pos = gametree.navigate(getRootTree(), 0, document.body.retrieve('undodata-pos'))
setCurrentTreePosition.apply(null, pos)
updateSidebar(true, true)
setUndoable(false)
setIsBusy(false)
}, setting.get('edit.undo_delay'))
}
/**
* Main events
*/
document.addEvent('keydown', function(e) {
if (e.code == 27) {
// Escape key
closeDrawers()
}
}).addEvent('domready', function() {
loadSettings()
loadEngines()
prepareDragDropFiles()
prepareEditTools()
prepareGameGraph()
prepareSlider()
prepareConsole()
$$('#goban, #graph canvas:last-child, #graph .slider').addEvent('mousewheel', function(e) {
if (e.wheel < 0) goForward()
else if (e.wheel > 0) goBack()
})
})
window.addEvent('load', function() {
newGame()
if (!setting.get('app.startup_check_updates')) return
setTimeout(function() {
checkForUpdates()
}, setting.get('app.startup_check_updates_delay'))
}).addEvent('resize', function() {
resizeBoard()
}).addEvent('beforeunload', function(e) {
if (!askForSave()) {
e.event.returnValue = 'false'
return
}
detachEngine()
var win = remote.getCurrentWindow()
if (win.isMaximized() || win.isMinimized() || win.isFullScreen()) return
var size = document.body.getSize()
setting.set('window.width', size.x).set('window.height', size.y)
})
| view/index.js | var remote = require('electron').remote
var ipcRenderer = require('electron').ipcRenderer
var fs = require('fs')
var shell = require('shell')
var sgf = require('../modules/sgf')
var fuzzyfinder = require('../modules/fuzzyfinder')
var gametree = require('../modules/gametree')
var sound = require('../modules/sound')
var helper = require('../modules/helper')
var process = remote.require('process')
var app = remote.app
var dialog = remote.dialog
var gtp = remote.require('./modules/gtp')
var setting = remote.require('./modules/setting')
var GeminiScrollbar = require('gemini-scrollbar')
var Board = require('../modules/board')
var Menu = remote.Menu
var MenuItem = remote.MenuItem
/**
* Getter & setter
*/
function getRootTree() {
if (!getCurrentTreePosition()) return null
return gametree.getRoot(getCurrentTreePosition()[0])
}
function setRootTree(tree, updateHash) {
if (tree.nodes.length == 0) return
tree.parent = null
if (updateHash) document.body.store('treehash', gametree.getHash(tree))
setCurrentTreePosition(sgf.addBoard(tree), 0, true)
setPlayerName(1, 'PB' in tree.nodes[0] ? tree.nodes[0].PB[0] : 'Black')
setPlayerName(-1, 'PW' in tree.nodes[0] ? tree.nodes[0].PW[0] : 'White')
}
function getGraphMatrixDict() {
return $('graph').retrieve('graphmatrixdict')
}
function setGraphMatrixDict(matrixdict) {
if (!getShowSidebar()) return
var s, graph
try {
s = $('graph').retrieve('sigma')
graph = gametree.matrixdict2graph(matrixdict)
} catch(e) { }
try {
if (s && graph) {
s.graph.clear()
s.graph.read(graph)
}
} catch(e) {
setGraphMatrixDict(matrixdict)
}
$('graph').store('graphmatrixdict', matrixdict)
}
function getCurrentTreePosition() {
return $('goban').retrieve('position')
}
function setCurrentTreePosition(tree, index, now) {
if (!tree || getScoringMode()) return
// Remove old graph node color
var oldNode = getCurrentGraphNode()
var oldPos = getCurrentTreePosition()
var node = getGraphNode(tree, index)
if (oldNode && oldNode != node)
oldNode.color = oldNode.originalColor
// Store new position
$('goban').store('position', [tree, index])
var redraw = !node
|| !gametree.onCurrentTrack(tree)
|| tree.collapsed && index == tree.nodes.length - 1
var t = tree
t.collapsed = false
while (t.parent && t.parent.collapsed) {
redraw = true
t.parent.collapsed = false
t = t.parent
}
// Update graph, slider and comment text
updateSidebar(redraw, now)
sgf.addBoard(tree, index)
if (tree.nodes[index].board) setBoard(tree.nodes[index].board)
// Determine current player
var currentplayer = 1
if ('B' in tree.nodes[index]
|| 'PL' in tree.nodes[index] && tree.nodes[index].PL[0] == 'W'
|| 'HA' in tree.nodes[index] && tree.nodes[index].HA[0].toInt() >= 1)
currentplayer = -1
setCurrentPlayer(currentplayer)
}
function getCurrentGraphNode() {
var pos = getCurrentTreePosition()
if (!pos) return null
return getGraphNode(pos[0], pos[1])
}
function getGraphNode(tree, index) {
var id = typeof tree === 'object' ? tree.id + '-' + index : tree
var s = $('graph').retrieve('sigma')
return s.graph.nodes(id)
}
function getSelectedTool() {
var li = $$('#edit .selected')[0]
var tool = li.get('class').replace('selected', '').replace('-tool', '').trim()
if (tool == 'stone') {
return li.getElement('img').get('src').indexOf('_1') != -1 ? 'stone_1' : 'stone_-1'
} else {
return tool
}
}
function setSelectedTool(tool) {
if (!getEditMode()) {
setEditMode(true)
if (getSelectedTool().indexOf(tool) != -1) return
}
$$('#edit .' + tool + '-tool a').fireEvent('click')
}
function getBoard() {
return $('goban').retrieve('board')
}
function setBoard(board) {
if (!getBoard() || getBoard().size != board.size) {
$('goban').store('board', board)
buildBoard()
}
$('goban').store('board', board)
setCaptures(board.captures)
for (var x = 0; x < board.size; x++) {
for (var y = 0; y < board.size; y++) {
var li = $('goban').getElement('.pos_' + x + '-' + y)
var sign = board.arrangement[li.retrieve('tuple')]
var types = ['ghost_1', 'ghost_-1', 'circle', 'triangle',
'cross', 'square', 'label', 'point']
types.forEach(function(x) {
if (li.hasClass(x)) li.removeClass(x)
})
li.set('title', '')
if (li.retrieve('tuple') in board.overlays) {
var overlay = board.overlays[li.retrieve('tuple')]
var type = overlay[0], ghost = overlay[1], label = overlay[2]
if (type != '') li.addClass(type)
if (ghost != 0) li.addClass('ghost_' + ghost)
if (label != '') li.set('title', label)
}
if (li.hasClass('sign_' + sign)) continue
for (var i = -1; i <= 1; i++) {
if (li.hasClass('sign_' + i)) li.removeClass('sign_' + i)
}
li.addClass('sign_' + sign)
.getElement('img').set('src', '../img/goban/stone_' + sign + '.png')
}
}
}
function getScoringMethod() {
return $$('#score .tabs .territory')[0].hasClass('current') ? 'territory' : 'area'
}
function setScoringMethod(method) {
$$('#score .tabs li').removeClass('current')
$$('#score .tabs .' + method).addClass('current')
$$('#score tr > *').addClass('disabled')
$$('#score table .' + method).removeClass('disabled')
setting.set('scoring.method', method)
// Update UI
for (var sign = -1; sign <= 1; sign += 2) {
var tr = $$('#score tbody tr' + (sign < 0 ? ':last-child' : ''))[0]
var tds = tr.getElements('td')
tds[4].set('text', 0)
for (var i = 0; i <= 3; i++) {
if (tds[i].hasClass('disabled') || isNaN(tds[i].get('text').toFloat())) continue
tds[4].set('text', tds[4].get('text').toFloat() + tds[i].get('text').toFloat())
}
}
}
function getKomi() {
var rootNode = getRootTree().nodes[0]
return 'KM' in rootNode ? rootNode.KM[0].toFloat() : 0
}
function getEngineName() {
return $('console').retrieve('enginename')
}
function getEngineController() {
return $('console').retrieve('controller')
}
function getEngineCommands() {
return $('console').retrieve('commands')
}
function setUndoable(undoable) {
if (undoable) {
var rootTree = gametree.clone(getRootTree())
var position = gametree.getLevel.apply(null, getCurrentTreePosition())
document.body
.addClass('undoable')
.store('undodata-root', rootTree)
.store('undodata-pos', position)
} else {
document.body
.removeClass('undoable')
.store('undodata-root', null)
.store('undodata-pos', null)
}
}
function getBookmark() {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
return 'SBKBM' in node
}
function setBookmark(bookmark) {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
if (bookmark) node.SBKBM = [1]
else delete node.SBKBM
updateGraph()
}
/**
* Methods
*/
function loadSettings() {
if (setting.get('view.fuzzy_stone_placement'))
$('goban').addClass('fuzzy')
if (setting.get('view.show_coordinates'))
$('goban').addClass('coordinates')
if (setting.get('view.show_variations'))
$('goban').addClass('variations')
if (setting.get('view.show_leftsidebar')) {
document.body.addClass('leftsidebar')
setLeftSidebarWidth(setting.get('view.leftsidebar_width'))
}
if (setting.get('view.show_graph') || setting.get('view.show_comments')) {
document.body.addClass('sidebar')
setSidebarArrangement(setting.get('view.show_graph'), setting.get('view.show_comments'))
}
setSidebarWidth(setting.get('view.sidebar_width'))
}
function prepareEditTools() {
$$('#edit ul a').addEvent('click', function() {
if (!this.getParent().hasClass('selected')) {
$$('#edit .selected').removeClass('selected')
this.getParent().addClass('selected')
} else if (this.getParent().hasClass('stone-tool')) {
var img = this.getElement('img')
var black = img.get('src') == '../img/edit/stone_1.svg'
img.set('src', black ? '../img/edit/stone_-1.svg' : '../img/edit/stone_1.svg')
}
})
}
function prepareGameGraph() {
var container = $('graph')
var s = new sigma(container)
s.settings({
defaultNodeColor: setting.get('graph.node_inactive_color'),
defaultEdgeColor: setting.get('graph.node_color'),
defaultNodeBorderColor: 'rgba(255,255,255,.2)',
edgeColor: 'default',
borderSize: 2,
zoomMax: 1,
zoomMin: 1,
autoResize: false,
autoRescale: false
})
var getTreePos = function(e) { return [e.data.node.data[0], e.data.node.data[1]] }
s.bind('clickNode', function(e) {
setCurrentTreePosition.apply(null, getTreePos(e).concat([true]))
}).bind('rightClickNode', function(e) {
openNodeMenu.apply(null, getTreePos(e))
})
container.store('sigma', s)
}
function prepareSlider() {
var slider = $$('#sidebar .slider .inner')[0]
Element.NativeEvents.touchstart = 2
Element.NativeEvents.touchmove = 2
Element.NativeEvents.touchend = 2
var changeSlider = function(percentage) {
percentage = Math.min(1, Math.max(0, percentage))
var height = Math.round((gametree.getHeight(getRootTree()) - 1) * percentage)
var pos = gametree.navigate(getRootTree(), 0, height)
if (helper.equals(pos, getCurrentTreePosition())) return
setCurrentTreePosition.apply(null, pos)
updateSlider()
}
slider.addEvent('mousedown', function(e) {
if (e.event.buttons != 1) return
this.store('mousedown', true).addClass('active')
document.body.fireEvent('mousemove', e)
}).addEvent('touchstart', function() {
this.addClass('active')
}).addEvent('touchmove', function(e) {
var percentage = (e.client.y - slider.getPosition().y) / slider.getSize().y
changeSlider(percentage)
}).addEvent('touchend', function() {
this.removeClass('active')
})
document.body.addEvent('mouseup', function() {
slider.store('mousedown', false)
.removeClass('active')
}).addEvent('mousemove', function(e) {
if (e.event.buttons != 1 || !slider.retrieve('mousedown'))
return
var percentage = (e.event.clientY - slider.getPosition().y) / slider.getSize().y
changeSlider(percentage)
})
// Prepare previous/next buttons
$$('#sidebar .slider a').addEvent('mousedown', function() {
this.store('mousedown', true)
startAutoScroll(this.hasClass('next') ? 1 : -1)
})
document.body.addEvent('mouseup', function() {
$$('#sidebar .slider a').store('mousedown', false)
})
}
function prepareDragDropFiles() {
Element.NativeEvents.dragover = 2
Element.NativeEvents.drop = 2
document.body.addEvent('dragover', function() {
return false
}).addEvent('drop', function(e) {
e.preventDefault()
if (e.event.dataTransfer.files.length == 0) return
loadGame(e.event.dataTransfer.files[0].path)
})
}
function prepareConsole() {
$$('#console form').addEvent('submit', function(e) {
e.preventDefault()
var input = this.getElement('input')
if (input.value.trim() == '') return
input.blur()
var command = gtp.parseCommand(input.value)
sendGTPCommand(command)
})
$$('#console form input').addEvent('keydown', function(e) {
if ([40, 38, 9].indexOf(e.code) != -1) e.preventDefault()
var inputs = $$('#console form input')
if (this.retrieve('index') == null) this.store('index', inputs.indexOf(this))
var i = this.retrieve('index')
var length = inputs.length
if ([38, 40].indexOf(e.code) != -1) {
if (e.code == 38) {
// Up
i = Math.max(i - 1, 0)
} else if (e.code == 40) {
// Down
i = Math.min(i + 1, length - 1)
}
this.value = i == length - 1 ? '' : inputs[i].value
this.store('index', i)
} else if (e.code == 9) {
// Tab
var tokens = this.value.split(' ')
var commands = getEngineCommands()
if (!commands) return
var i = 0
var selection = this.selectionStart
while (selection > tokens[i].length && selection.length != 0 && i < tokens.length - 1)
selection -= tokens[i++].length + 1
var result = fuzzyfinder.find(tokens[i], getEngineCommands())
if (!result) return
tokens[i] = result
this.value = tokens.join(' ')
this.selectionStart = this.selectionEnd = (function() {
var sum = 0
while (i >= 0) sum += tokens[i--].length + 1
return sum - 1
})()
}
})
}
function loadEngines() {
// Load menu items
ipcRenderer.send('build-menu')
// Load engines list
var ul = $$('#preferences .engines-list ul')[0]
ul.empty()
setting.getEngines().forEach(function(engine) {
addEngineItem(engine.name, engine.path, engine.args)
})
}
function attachEngine(exec, args) {
detachEngine()
setIsBusy(true)
setTimeout(function() {
var split = require('argv-split')
var controller = new gtp.Controller(exec, split(args))
if (controller.error) {
showMessageBox('There was an error attaching the engine.', 'error')
setIsBusy(false)
return
}
controller.on('quit', function() { $('console').store('controller', null) })
$('console').store('controller', controller)
sendGTPCommand(new gtp.Command(null, 'name'), true, function(response) {
$('console').store('enginename', response.content)
})
sendGTPCommand(new gtp.Command(null, 'version'))
sendGTPCommand(new gtp.Command(null, 'protocol_version'))
sendGTPCommand(new gtp.Command(null, 'list_commands'), true, function(response) {
$('console').store('commands', response.content.split('\n'))
})
syncEngine()
setIsBusy(false)
}, setting.get('gtp.attach_delay'))
}
function detachEngine() {
sendGTPCommand(new gtp.Command(null, 'quit'), true)
clearConsole()
$('console').store('controller', null)
.store('boardhash', null)
}
function syncEngine() {
var board = getBoard()
if (!getEngineController()
|| $('console').retrieve('boardhash') == board.getHash()) return
if (!board.isValid()) {
showMessageBox('GTP engines don’t support invalid board positions.', 'warning')
return
}
setIsBusy(true)
sendGTPCommand(new gtp.Command(null, 'clear_board'), true)
sendGTPCommand(new gtp.Command(null, 'boardsize', [board.size]), true)
sendGTPCommand(new gtp.Command(null, 'komi', [getKomi()]), true)
// Replay
for (var i = 0; i < board.size; i++) {
for (var j = 0; j < board.size; j++) {
var v = [i, j]
var sign = board.arrangement[v]
if (sign == 0) continue
var color = sign > 0 ? 'B' : 'W'
var point = gtp.vertex2point(v, board.size)
sendGTPCommand(new gtp.Command(null, 'play', [color, point]), true)
}
}
$('console').store('boardhash', board.getHash())
setIsBusy(false)
}
function checkForUpdates(callback) {
if (!callback) callback = function(hasUpdates) {}
var url = 'https://github.com/yishn/' + app.getName() + '/releases/latest'
// Check internet connection first
remote.require('dns').lookup('github.com', function(err) {
if (err) return
remote.require('https').get(url, function(response) {
response.once('data', function(chunk) {
chunk = '' + chunk
var hasUpdates = chunk.indexOf('v' + app.getVersion()) == -1
if (hasUpdates && showMessageBox(
'There is a new version of ' + app.getName() + ' available.',
'info',
['Download Update', 'Not Now'], 1
) == 0) shell.openExternal(url)
callback(hasUpdates)
})
}).on('error', function(e) {})
})
}
function makeMove(vertex, sendCommand) {
if (sendCommand == null) sendCommand = getEngineController() != null
var pass = !getBoard().hasVertex(vertex)
if (!pass && getBoard().arrangement[vertex] != 0) return
var position = getCurrentTreePosition()
var tree = position[0], index = position[1]
var sign = getCurrentPlayer()
var color = sign > 0 ? 'B' : 'W'
var capture = false, suicide = false
var createNode = true
if (sendCommand) syncEngine()
if (!pass) {
// Check for ko
if (setting.get('game.show_ko_warning')) {
var tp = gametree.navigate(tree, index, -1)
var prevTree = tp[0], prevIndex = tp[1]
var ko = false
if (prevTree) {
var hash = getBoard().makeMove(sign, vertex).getHash()
ko = prevTree.nodes[prevIndex].board.getHash() == hash
}
if (ko && showMessageBox(
['You are about to play a move which repeats a previous board position.',
'This is invalid in some rulesets.'].join('\n'),
'info',
['Play Anyway', 'Don’t Play'], 1
) != 0) return
}
// Check for suicide
capture = getBoard().getNeighborhood(vertex).some(function(v) {
return getBoard().arrangement[v] == -sign && getBoard().getLiberties(v).length == 1
})
suicide = !capture && getBoard().getNeighborhood(vertex).filter(function(v) {
return getBoard().arrangement[v] == sign
}).every(function(v) {
return getBoard().getLiberties(v).length == 1
}) && getBoard().getNeighborhood(vertex).filter(function(v) {
return getBoard().arrangement[v] == 0
}).length == 0
if (suicide && setting.get('game.show_suicide_warning')) {
if (showMessageBox(
['You are about to play a suicide move.',
'This is invalid in some rulesets.'].join('\n'),
'info',
['Play Anyway', 'Don’t Play'], 1
) != 0) return
}
// Randomize shift and readjust
var li = $$('#goban .pos_' + vertex[0] + '-' + vertex[1])
var direction = Math.floor(Math.random() * 9)
for (var i = 0; i < 9; i++) li.removeClass('shift_' + i)
li.addClass('shift_' + direction)
readjustShifts(vertex)
}
if (tree.current == null && tree.nodes.length - 1 == index) {
// Append move
var node = {}
node[color] = [sgf.vertex2point(vertex)]
tree.nodes.push(node)
setCurrentTreePosition(tree, tree.nodes.length - 1)
} else {
if (index != tree.nodes.length - 1) {
// Search for next move
var nextNode = tree.nodes[index + 1]
var moveExists = color in nextNode
&& helper.equals(sgf.point2vertex(nextNode[color][0]), vertex)
if (moveExists) {
setCurrentTreePosition(tree, index + 1)
createNode = false
}
} else {
// Search for variation
var variations = tree.subtrees.filter(function(subtree) {
return subtree.nodes.length > 0
&& color in subtree.nodes[0]
&& helper.equals(sgf.point2vertex(subtree.nodes[0][color][0]), vertex)
})
if (variations.length > 0) {
setCurrentTreePosition(sgf.addBoard(variations[0]), 0)
createNode = false
}
}
if (createNode) {
// Create variation
var splitted = gametree.splitTree(tree, index)
var node = {}; node[color] = [sgf.vertex2point(vertex)]
var newtree = gametree.new()
newtree.nodes = [node]
newtree.parent = splitted
splitted.subtrees.push(newtree)
splitted.current = splitted.subtrees.length - 1
sgf.addBoard(newtree, newtree.nodes.length - 1)
setCurrentTreePosition(newtree, 0)
}
}
// Play sounds
if (!pass) {
var delay = setting.get('sound.captureDelayMin')
delay += Math.floor(Math.random() * (setting.get('sound.captureDelayMax') - delay))
if (capture || suicide) setTimeout(function() {
sound.playCapture()
}, delay)
sound.playPachi()
} else {
sound.playPass()
}
// Remove undo information
setUndoable(false)
// Enter scoring mode when two consecutive passes
var enterScoring = false
if (pass && createNode) {
var prevNode = tree.nodes[index]
var prevColor = sign > 0 ? 'W' : 'B'
var prevPass = prevColor in prevNode && prevNode[prevColor][0] == ''
if (prevPass) {
enterScoring = true
setScoringMode(true)
}
}
// Handle GTP engine
if (sendCommand && !enterScoring) {
sendGTPCommand(
new gtp.Command(null, 'play', [color, gtp.vertex2point(vertex, getBoard().size)]),
true
)
$('console').store('boardhash', getBoard().getHash())
setIsBusy(true)
setTimeout(function() {
generateMove(true)
}, setting.get('gtp.move_delay'))
}
}
function useTool(vertex, event) {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
var node = tree.nodes[index]
var tool = getSelectedTool()
var board = getBoard()
var dictionary = {
cross: 'MA',
triangle: 'TR',
circle: 'CR',
square: 'SQ',
number: 'LB',
label: 'LB'
}
if (tool.indexOf('stone') != -1) {
if ('B' in node || 'W' in node) {
// New variation needed
var splitted = gametree.splitTree(tree, index)
if (splitted != tree || splitted.subtrees.length != 0) {
tree = gametree.new()
tree.parent = splitted
splitted.subtrees.push(tree)
}
node = { PL: getCurrentPlayer() > 0 ? ['B'] : ['W'] }
index = tree.nodes.length
tree.nodes.push(node)
}
var sign = tool.indexOf('_1') != -1 ? 1 : -1
if (event.button == 2) sign = -sign
var oldSign = board.arrangement[vertex]
var ids = ['AW', 'AE', 'AB']
var id = ids[sign + 1]
var point = sgf.vertex2point(vertex)
for (var i = -1; i <= 1; i++) {
if (!(ids[i + 1] in node)) continue
k = node[ids[i + 1]].indexOf(point)
if (k >= 0) {
node[ids[i + 1]].splice(k, 1)
if (node[ids[i + 1]].length == 0) {
delete node[ids[i + 1]]
}
}
}
if (oldSign != sign) {
if (id in node) node[id].push(point)
else node[id] = [point]
} else if (oldSign == sign) {
if ('AE' in node) node.AE.push(point)
else node.AE = [point]
}
} else {
if (event.button != 0) return
if (tool != 'label' && tool != 'number') {
if (vertex in board.overlays && board.overlays[vertex][0] == tool) {
delete board.overlays[vertex]
} else {
board.overlays[vertex] = [tool, 0, '']
}
} else if (tool == 'number') {
if (vertex in board.overlays && board.overlays[vertex][0] == 'label') {
delete board.overlays[vertex]
} else {
var number = 1
if ('LB' in node) {
var list = node.LB.map(function(x) {
return x.substr(3).toInt()
}).filter(function(x) {
return !isNaN(x)
})
list.sort(function(a, b) { return a - b })
for (var i = 0; i <= list.length; i++) {
if (i < list.length && i + 1 == list[i]) continue
number = i + 1
break
}
}
board.overlays[vertex] = [tool, 0, number.toString()]
}
} else if (tool == 'label') {
if (vertex in board.overlays && board.overlays[vertex][0] == 'label') {
delete board.overlays[vertex]
} else {
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
var k = 0
if ('LB' in node) {
var list = node.LB.filter(function(x) {
return x.length == 4
}).map(function(x) {
return alpha.indexOf(x[3])
}).filter(function(x) { return x >= 0 })
list.sort(function(a, b) { return a - b })
for (var i = 0; i <= list.length; i++) {
if (i < list.length && i == list[i]) continue
k = Math.min(i, alpha.length - 1)
break
}
}
board.overlays[vertex] = [tool, 0, alpha[k]]
}
}
for (var id in dictionary) delete node[dictionary[id]]
// Update SGF
$$('#goban .row li').forEach(function(li) {
var v = li.retrieve('tuple')
if (!(v in board.overlays)) return
var id = dictionary[board.overlays[v][0]]
var pt = sgf.vertex2point(v)
if (id == 'LB') pt += ':' + board.overlays[v][2]
if (id in node) node[id].push(pt)
else node[id] = [pt]
})
}
setUndoable(false)
setCurrentTreePosition(tree, index)
}
function findPosition(step, condition) {
if (isNaN(step)) step = 1
else step = step >= 0 ? 1 : -1
setIsBusy(true)
setTimeout(function() {
var pos = getCurrentTreePosition()
var iterator = gametree.makeNodeIterator.apply(null, pos)
while (true) {
pos = step >= 0 ? iterator.next() : iterator.prev()
if (!pos) {
var root = getRootTree()
if (step == 1) {
pos = [root, 0]
} else {
var sections = gametree.getSection(root, gametree.getHeight(root) - 1)
pos = sections[sections.length - 1]
}
iterator = gametree.makeNodeIterator.apply(null, pos)
}
if (helper.equals(pos, getCurrentTreePosition()) || condition.apply(null, pos)) break
}
setCurrentTreePosition.apply(null, pos)
setIsBusy(false)
}, setting.get('find.delay'))
}
function findBookmark(step) {
findPosition(step, function(tree, index) {
var node = tree.nodes[index]
return 'SBKBM' in node
})
}
function findMove(vertex, text, step) {
if (vertex == null && text.trim() == '') return
var point = vertex ? sgf.vertex2point(vertex) : null
findPosition(step, function(tree, index) {
var node = tree.nodes[index]
var cond = function(prop, value) {
return prop in node && node[prop][0].toLowerCase().indexOf(value.toLowerCase()) >= 0
}
return (!point || ['B', 'W'].some(function(x) { return cond(x, point) }))
&& (!text || cond('C', text))
})
}
function vertexClicked(vertex, event) {
closeGameInfo()
if (getScoringMode()) {
if (event.button != 0) return
if (getBoard().arrangement[vertex] == 0) return
getBoard().getRelatedChains(vertex).forEach(function(v) {
$$('#goban .pos_' + v[0] + '-' + v[1]).toggleClass('dead')
})
updateAreaMap()
} else if (getEditMode()) {
useTool(vertex, event)
} else if (getFindMode()) {
if (event.button != 0) return
setIndicatorVertex(vertex)
findMove(getIndicatorVertex(), getFindText(), 1)
} else {
// Playing mode
if (event.button != 0) return
var board = getBoard()
if (board.arrangement[vertex] == 0) {
makeMove(vertex)
} else if (vertex in board.overlays
&& board.overlays[vertex][0] == 'point'
&& setting.get('edit.click_currentvertex_to_remove')) {
removeNode.apply(null, getCurrentTreePosition())
}
closeDrawers()
}
}
function updateSidebar(redraw, now) {
clearTimeout($('sidebar').retrieve('updatesidebarid'))
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
$('sidebar').store('updatesidebarid', setTimeout(function() {
if (!helper.equals(getCurrentTreePosition(), [tree, index]))
return
// Set current path
var t = tree
while (t.parent) {
t.parent.current = t.parent.subtrees.indexOf(t)
t = t.parent
}
// Update
updateSlider()
updateCommentText()
updateSgfProperties()
if (redraw) updateGraph()
centerGraphCameraAt(getCurrentGraphNode())
}, now ? 0 : setting.get('graph.delay')))
}
function updateGraph() {
if (!getShowSidebar() || !getCurrentTreePosition()) return
setGraphMatrixDict(gametree.tree2matrixdict(getRootTree()))
centerGraphCameraAt(getCurrentGraphNode())
}
function updateSlider() {
if (!getShowSidebar()) return
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
var total = gametree.getHeight(getRootTree()) - 1
var relative = gametree.getLevel(tree, index)
setSliderValue(total == 0 ? 0 : relative * 100 / total, relative)
}
function updateCommentText() {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
setCommentText('C' in node ? node.C[0] : '')
}
function updateSgfProperties() {
var tp = getCurrentTreePosition()
var node = tp[0].nodes[tp[1]]
// TODO
}
function updateAreaMap() {
var board = getBoard().clone()
$$('#goban .row li.dead').forEach(function(li) {
if (li.hasClass('sign_1')) board.captures['-1']++
else if (li.hasClass('sign_-1')) board.captures['1']++
board.arrangement[li.retrieve('tuple')] = 0
})
var map = board.getAreaMap()
$$('#goban .row li').forEach(function(li) {
li.removeClass('area_-1').removeClass('area_0').removeClass('area_1')
.addClass('area_' + map[li.retrieve('tuple')])
})
var falsedead = $$('#goban .row li.area_-1.sign_-1.dead, #goban .row li.area_1.sign_1.dead')
if (falsedead.length > 0) {
falsedead.removeClass('dead')
return updateAreaMap()
}
$('goban').store('areamap', map)
.store('finalboard', board)
}
function commitCommentText() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
var comment = $$('#properties textarea').get('value')[0]
if (comment != '') tree.nodes[index].C = [comment]
else delete tree.nodes[index].C
updateCommentText()
updateSidebar(true)
setUndoable(false)
}
function commitGameInfo() {
var rootNode = getRootTree().nodes[0]
var info = $('info')
rootNode.BR = [info.getElement('input[name="rank_1"]').get('value').trim()]
rootNode.WR = [info.getElement('input[name="rank_-1"]').get('value').trim()]
rootNode.PB = [info.getElement('input[name="name_1"]').get('value').trim()]
rootNode.PW = [info.getElement('input[name="name_-1"]').get('value').trim()]
setPlayerName(1, rootNode.PB[0])
setPlayerName(-1, rootNode.PW[0])
var result = info.getElement('input[name="result"]').get('value').trim()
rootNode.RE = [result]
if (result == '') delete rootNode.RE
var komi = info.getElement('input[name="komi"]').get('value').toFloat()
rootNode.KM = [String.from(komi)]
if (isNaN(komi)) rootNode.KM = ['0']
var handicap = info.getElement('select[name="handicap"]').selectedIndex
if (handicap == 0) delete rootNode.HA
else rootNode.HA = [String.from(handicap + 1)]
var size = info.getElement('input[name="size"]').get('value').toInt()
rootNode.SZ = [String.from(Math.max(Math.min(size, 26), 9))]
if (isNaN(size)) rootNode.SZ = ['' + setting.get('game.default_board_size')]
if (!info.getElement('select[name="handicap"]').disabled) {
setCurrentTreePosition(getRootTree(), 0)
if (!('HA' in rootNode)) {
delete rootNode.AB
} else {
var board = getBoard()
var stones = board.getHandicapPlacement(rootNode.HA[0].toInt())
rootNode.AB = []
for (var i = 0; i < stones.length; i++) {
rootNode.AB.push(sgf.vertex2point(stones[i]))
}
}
setCurrentTreePosition(getRootTree(), 0)
}
setUndoable(false)
}
function commitScore() {
var rootNode = getRootTree().nodes[0]
var results = $$('#score tbody td:last-child').get('text')
var diff = results[0].toFloat() - results[1].toFloat()
var result = diff > 0 ? 'B+' : (diff < 0 ? 'W+' : 'Draw')
if (diff != 0) result = result + Math.abs(diff)
rootNode.RE = [result]
showGameInfo()
setUndoable(false)
}
function commitPreferences() {
// Save general preferences
$$('#preferences input[type="checkbox"]').forEach(function(el) {
setting.set(el.name, el.checked)
})
remote.getCurrentWindow().webContents.setAudioMuted(!setting.get('sound.enable'))
setFuzzyStonePlacement(setting.get('view.fuzzy_stone_placement'))
// Save engines
setting.clearEngines()
$$('#preferences .engines-list li').forEach(function(li) {
var nameinput = li.getElement('h3 input')
setting.addEngine(
nameinput.value.trim() == '' ? nameinput.placeholder : nameinput.value,
li.getElement('h3 + p input').value,
li.getElement('h3 + p + p input').value
)
})
setting.save()
loadEngines()
}
function sendGTPCommand(command, ignoreBlocked, callback) {
if (!getEngineController()) {
$$('#console form:last-child input')[0].value = ''
return
}
var controller = getEngineController()
var container = $$('#console .inner')[0]
var oldform = container.getElement('form:last-child')
var form = oldform.clone().cloneEvents(oldform)
var pre = new Element('pre', { text: ' ' })
form.getElement('input').set('value', '').cloneEvents(oldform.getElement('input'))
oldform.addClass('waiting').getElement('input').value = command.toString()
container.grab(pre).grab(form)
if (getShowLeftSidebar()) form.getElement('input').focus()
// Cleanup
var forms = $$('#console .inner form')
if (forms.length > setting.get('console.max_history_count')) {
forms[0].getNext('pre').dispose()
forms[0].dispose()
}
var listener = function(response, c) {
pre.set('html', response.toHtml())
helper.wireLinks(pre)
oldform.removeClass('waiting')
if (callback) callback(response)
// Update scrollbars
var view = $$('#console .gm-scroll-view')[0]
var scrollbar = $('console').retrieve('scrollbar')
view.scrollTo(0, view.getScrollSize().y)
if (scrollbar) scrollbar.update()
}
if (!ignoreBlocked && setting.get('console.blocked_commands').indexOf(command.name) != -1) {
listener(new gtp.Response(null, 'blocked command', true, true), command)
} else {
controller.once('response-' + command.internalId, listener)
controller.sendCommand(command)
}
}
function generateMove(ignoreBusy) {
if (!getEngineController() || !ignoreBusy && getIsBusy()) return
closeDrawers()
syncEngine()
setIsBusy(true)
var color = getCurrentPlayer() > 0 ? 'B' : 'W'
var opponent = getCurrentPlayer() > 0 ? 'W' : 'B'
sendGTPCommand(new gtp.Command(null, 'genmove', [color]), true, function(r) {
setIsBusy(false)
if (r.content.toLowerCase() == 'resign') {
showMessageBox(getEngineName() + ' has resigned.')
getRootTree().nodes[0].RE = [opponent + '+Resign']
return
}
var v = [-1, -1]
if (r.content.toLowerCase() != 'pass')
v = gtp.point2vertex(r.content, getBoard().size)
$('console').store('boardhash', getBoard().makeMove(getCurrentPlayer(), v).getHash())
makeMove(v, false)
})
}
function centerGraphCameraAt(node) {
if (!getShowSidebar() || !node) return
var s = $('graph').retrieve('sigma')
s.renderers[0].resize().render()
var matrixdict = getGraphMatrixDict()
var y = matrixdict[1][node.id][1]
var wp = gametree.getWidth(y, matrixdict[0])
var width = wp[0], padding = wp[1]
var x = matrixdict[1][node.id][0] - padding
var relX = width == 1 ? 0 : x / (width - 1)
var diff = (width - 1) * setting.get('graph.grid_size') / 2
diff = Math.min(diff, s.renderers[0].width / 2 - setting.get('graph.grid_size'))
node.color = setting.get('graph.node_active_color')
s.refresh()
sigma.misc.animation.camera(
s.camera,
{
x: node[s.camera.readPrefix + 'x'] + (1 - 2 * relX) * diff,
y: node[s.camera.readPrefix + 'y']
},
{ duration: setting.get('graph.delay') }
)
}
function askForSave() {
if (!getRootTree()) return true
var hash = gametree.getHash(getRootTree())
if (hash != document.body.retrieve('treehash')) {
var answer = showMessageBox(
'Your changes will be lost if you close this game without saving.',
'warning',
['Save', 'Don’t Save', 'Cancel'], 2
)
if (answer == 0) saveGame()
else if (answer == 2) return false
}
return true
}
function startAutoScroll(direction, delay) {
if (direction > 0 && !$$('#sidebar .slider a.next')[0].retrieve('mousedown')
|| direction < 0 && !$$('#sidebar .slider a.prev')[0].retrieve('mousedown')) return
if (delay == null) delay = setting.get('autoscroll.max_interval')
delay = Math.max(setting.get('autoscroll.min_interval'), delay)
var slider = $$('#sidebar .slider')[0]
clearTimeout(slider.retrieve('autoscrollid'))
if (direction > 0) goForward()
else goBack()
updateSlider()
slider.store('autoscrollid', setTimeout(function() {
startAutoScroll(direction, delay - setting.get('autoscroll.diff'))
}, delay))
}
/**
* Menu
*/
function newGame(playSound) {
if (getIsBusy() || !askForSave()) return
var buffer = ';GM[1]AP[' + app.getName() + ':' + app.getVersion() + ']'
buffer += 'CA[UTF-8]PB[Black]PW[White]KM[' + setting.get('game.default_komi')
+ ']SZ[' + setting.get('game.default_board_size') + ']'
closeDrawers()
var tree = sgf.parse(sgf.tokenize(buffer))
setRootTree(tree, true)
setUndoable(false)
if (arguments.length >= 1 && playSound) {
sound.playNewGame()
showGameInfo()
}
}
function loadGame(filename) {
if (getIsBusy() || !askForSave()) return
setIsBusy(true)
if (!filename) {
var result = dialog.showOpenDialog(remote.getCurrentWindow(), {
filters: [sgf.meta, { name: 'All Files', extensions: ['*'] }]
})
if (result) filename = result[0]
}
if (filename) {
setTimeout(function() {
var win = remote.getCurrentWindow()
try {
var tree = sgf.parseFile(filename, function(progress) {
setProgressIndicator(progress, win)
}).subtrees[0]
closeDrawers()
setRootTree(tree, true)
setUndoable(false)
} catch(e) {
showMessageBox('This file is unreadable.', 'warning')
}
setProgressIndicator(-1, win)
if (setting.get('game.goto_end_after_loading')) goToEnd()
setIsBusy(false)
}, setting.get('app.loadgame_delay'))
} else {
setIsBusy(false)
}
}
function saveGame() {
if (getIsBusy()) return
setIsBusy(true)
var result = dialog.showSaveDialog(remote.getCurrentWindow(), {
filters: [sgf.meta, { name: 'All Files', extensions: ['*'] }]
})
if (result) {
var tree = getRootTree()
var text = sgf.tree2string(tree)
fs.writeFile(result, '(' + text + ')')
document.body.store('treehash', gametree.getHash(tree))
}
setIsBusy(false)
}
function clearAllOverlays() {
closeDrawers()
var overlayIds = ['MA', 'TR', 'CR', 'SQ', 'LB', 'AR', 'LN']
// Save undo information
setUndoable(true)
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
overlayIds.forEach(function(id) {
delete tree.nodes[index][id]
})
setCurrentTreePosition(tree, index)
}
function goBack() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
setCurrentTreePosition.apply(null, gametree.navigate(tree, index, -1))
}
function goForward() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
setCurrentTreePosition.apply(null, gametree.navigate(tree, index, 1))
}
function goToNextFork() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (index != tree.nodes.length - 1)
setCurrentTreePosition(tree, tree.nodes.length - 1)
else if (tree.current != null) {
var subtree = tree.subtrees[tree.current]
setCurrentTreePosition(subtree, subtree.nodes.length - 1)
}
}
function goToPreviousFork() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (tree.parent == null || tree.parent.nodes.length == 0)
setCurrentTreePosition(tree, 0)
else setCurrentTreePosition(tree.parent, tree.parent.nodes.length - 1)
}
function goToBeginning() {
var tree = getRootTree()
if (tree.nodes.length == 0) return
setCurrentTreePosition(tree, 0)
}
function goToEnd() {
var tree = getCurrentTreePosition()[0]
setCurrentTreePosition.apply(null, gametree.navigate(tree, 0, gametree.getCurrentHeight(tree) - 1))
}
function goToNextVariation() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (!tree.parent) return
var mod = tree.parent.subtrees.length
var i = (tree.parent.current + 1) % mod
setCurrentTreePosition(tree.parent.subtrees[i], 0)
}
function goToPreviousVariation() {
var tp = getCurrentTreePosition()
var tree = tp[0], index = tp[1]
if (!tree.parent) return
var mod = tree.parent.subtrees.length
var i = (tree.parent.current + mod - 1) % mod
setCurrentTreePosition(tree.parent.subtrees[i], 0)
}
function removeNode(tree, index) {
if (!tree.parent && index == 0) {
showMessageBox('The root node cannot be removed.', 'warning')
return
}
if (setting.get('edit.show_removenode_warning') && showMessageBox(
'Do you really want to remove this node permanently?',
'warning',
['Remove Node', 'Cancel'], 1
) == 1) return
// Save undo information
setUndoable(true)
// Remove node
closeDrawers()
var prev = gametree.navigate(tree, index, -1)
if (index != 0) {
tree.nodes.splice(index, tree.nodes.length)
tree.current = null
tree.subtrees.length = 0
} else {
var parent = tree.parent
var i = parent.subtrees.indexOf(tree)
parent.subtrees.splice(i, 1)
if (parent.current >= i) parent.current--
gametree.reduceTree(parent)
}
setGraphMatrixDict(gametree.tree2matrixdict(getRootTree()))
if (getCurrentGraphNode()) prev = getCurrentTreePosition()
setCurrentTreePosition(prev[0], prev[1])
}
function undoBoard() {
if (document.body.retrieve('undodata-root') == null
|| document.body.retrieve('undodata-pos') == null)
return
setIsBusy(true)
setTimeout(function() {
setRootTree(document.body.retrieve('undodata-root'))
var pos = gametree.navigate(getRootTree(), 0, document.body.retrieve('undodata-pos'))
setCurrentTreePosition.apply(null, pos)
updateSidebar(true, true)
setUndoable(false)
setIsBusy(false)
}, setting.get('edit.undo_delay'))
}
/**
* Main events
*/
document.addEvent('keydown', function(e) {
if (e.code == 27) {
// Escape key
closeDrawers()
}
}).addEvent('domready', function() {
loadSettings()
loadEngines()
prepareDragDropFiles()
prepareEditTools()
prepareGameGraph()
prepareSlider()
prepareConsole()
$$('#goban, #graph canvas:last-child, #graph .slider').addEvent('mousewheel', function(e) {
if (e.wheel < 0) goForward()
else if (e.wheel > 0) goBack()
})
})
window.addEvent('load', function() {
newGame()
if (!setting.get('app.startup_check_updates')) return
setTimeout(function() {
checkForUpdates()
}, setting.get('app.startup_check_updates_delay'))
}).addEvent('resize', function() {
resizeBoard()
}).addEvent('beforeunload', function(e) {
if (!askForSave()) {
e.event.returnValue = 'false'
return
}
detachEngine()
var win = remote.getCurrentWindow()
if (win.isMaximized() || win.isMinimized() || win.isFullScreen()) return
var size = document.body.getSize()
setting.set('window.width', size.x).set('window.height', size.y)
})
| Set represented filename
| view/index.js | Set represented filename | <ide><path>iew/index.js
<ide> var tree = sgf.parse(sgf.tokenize(buffer))
<ide> setRootTree(tree, true)
<ide> setUndoable(false)
<add> remote.getCurrentWindow().setRepresentedFilename('')
<ide>
<ide> if (arguments.length >= 1 && playSound) {
<ide> sound.playNewGame()
<ide> }
<ide>
<ide> setProgressIndicator(-1, win)
<add> remote.getCurrentWindow().setRepresentedFilename(filename)
<ide>
<ide> if (setting.get('game.goto_end_after_loading')) goToEnd()
<ide> setIsBusy(false)
<ide>
<ide> fs.writeFile(result, '(' + text + ')')
<ide> document.body.store('treehash', gametree.getHash(tree))
<add> remote.getCurrentWindow().setRepresentedFilename(result)
<ide> }
<ide>
<ide> setIsBusy(false) |
|
Java | apache-2.0 | ba1c75bcda598f6a095acf88c643523147e92c00 | 0 | hedyn/wsonrpc | package net.apexes.wsonrpc.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.websocket.Session;
import net.apexes.wsonrpc.BinaryWrapper;
import net.apexes.wsonrpc.ExceptionProcessor;
import net.apexes.wsonrpc.WsonrpcConfig;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.googlecode.jsonrpc4j.DefaultExceptionResolver;
import com.googlecode.jsonrpc4j.ExceptionResolver;
import com.googlecode.jsonrpc4j.JsonRpcClient;
import com.googlecode.jsonrpc4j.JsonRpcClientException;
import com.googlecode.jsonrpc4j.JsonRpcMultiServer;
import com.googlecode.jsonrpc4j.NoCloseInputStream;
/**
*
* @author <a href=mailto:[email protected]>HeDYn</a>
*
*/
class WsonrpcDispatcher implements Caller {
private final ExecutorService execService;
private final ObjectMapper mapper;
private final BinaryWrapper binaryProcessor;
private final long timeout;
private final JsonRpcClient jsonRpcClient;
private final JsonRpcMultiServer jsonRpcServer;
private ExceptionResolver exceptionResolver = DefaultExceptionResolver.INSTANCE;
private ExceptionProcessor exceptionProcessor;
public WsonrpcDispatcher(WsonrpcConfig config) {
this.execService = config.getExecutorService();
this.mapper = config.getObjectMapper();
this.binaryProcessor = config.getBinaryWrapper();
this.timeout = config.getTimeout();
jsonRpcClient = new JsonRpcClient(mapper);
jsonRpcServer = new JsonRpcMultiServer(mapper);
}
public void setExceptionResolver(ExceptionResolver exceptionResolver) {
this.exceptionResolver = exceptionResolver;
}
public void setExceptionProcessor(ExceptionProcessor processor) {
this.exceptionProcessor = processor;
}
public ExceptionProcessor getExceptionProcessor() {
return exceptionProcessor;
}
public void addService(String name, Object handler) {
jsonRpcServer.addService(name, handler);
}
@Override
public long getTimeout() {
return timeout;
}
@Override
public void notify(Session session, String serviceName, String methodName, Object argument)
throws Exception {
invoke(session, serviceName, methodName, argument, null);
}
@Override
public Future<Object> request(Session session, String serviceName, String methodName, Object argument,
Type returnType) throws Exception {
String id = UUID.randomUUID().toString().replace("-", "");
WosonrpcFuture<Object> future = new WosonrpcFuture<>(id, returnType);
WsonrpcContext.Futures.put(future);
try {
invoke(session, serviceName, methodName, argument, id);
return future;
} catch (Exception ex) {
WsonrpcContext.Futures.out(id);
throw ex;
}
}
private void invoke(Session session, String serviceName, String methodName, Object argument, String id)
throws Exception {
ByteArrayOutputStream ops = new ByteArrayOutputStream();
jsonRpcClient.invoke(serviceName + "." + methodName, argument, binaryProcessor.wrap(ops), id);
session.getBasicRemote().sendBinary(ByteBuffer.wrap(ops.toByteArray()));
}
public void handle(Session session, ByteBuffer buffer) throws Exception {
InputStream ips = binaryProcessor.wrap(new ByteArrayInputStream(buffer.array()));
JsonNode data = mapper.readTree(new NoCloseInputStream(ips));
// bail on invalid response
if (!data.isObject()) {
throw new JsonRpcClientException(0, "Invalid WSON-RPC data", data);
}
ObjectNode jsonObject = ObjectNode.class.cast(data);
if (jsonObject.has("method")) {
response(session, jsonObject);
} else {
accept(jsonObject);
}
}
private void accept(ObjectNode jsonObject) throws Exception {
JsonNode idNode = jsonObject.get("id");
if (idNode == null || !idNode.isTextual()) {
return;
}
String id = idNode.textValue();
WosonrpcFuture<Object> future = WsonrpcContext.Futures.out(id);
if (future == null) {
return;
}
// detect errors
JsonNode exceptionNode = jsonObject.get("error");
if (exceptionNode != null && !exceptionNode.isNull()) {
// resolve and throw the exception
Throwable throwable;
if (exceptionResolver == null) {
throwable = DefaultExceptionResolver.INSTANCE.resolveException(jsonObject);
} else {
throwable = exceptionResolver.resolveException(jsonObject);
}
future.setException(throwable);
}
// convert it to a return object
JsonNode resultNode = jsonObject.get("result");
if (resultNode != null && !resultNode.isNull()) {
Type returnType = future.returnType;
if (returnType == null) {
return;
}
JsonParser returnJsonParser = mapper.treeAsTokens(resultNode);
JavaType returnJavaType = TypeFactory.defaultInstance().constructType(returnType);
Object value = mapper.readValue(returnJsonParser, returnJavaType);
future.set(value);
} else {
Throwable throwable;
if (exceptionResolver == null) {
throwable = DefaultExceptionResolver.INSTANCE.resolveException(jsonObject);
} else {
throwable = exceptionResolver.resolveException(jsonObject);
}
future.setException(throwable);
}
}
private void response(final Session session, final ObjectNode jsonObject) {
execService.execute(new Runnable() {
@Override
public void run() {
WsonrpcContext.Sessions.begin(session);
try {
ByteArrayOutputStream ops = new ByteArrayOutputStream();
jsonRpcServer.handleNode(jsonObject, binaryProcessor.wrap(ops));
session.getBasicRemote().sendBinary(ByteBuffer.wrap(ops.toByteArray()));
} catch (Exception ex) {
if (exceptionProcessor != null) {
exceptionProcessor.onError(ex, jsonObject);
}
} finally {
WsonrpcContext.Sessions.end();
}
}
});
}
}
| src/main/java/net/apexes/wsonrpc/internal/WsonrpcDispatcher.java | package net.apexes.wsonrpc.internal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.websocket.Session;
import net.apexes.wsonrpc.BinaryWrapper;
import net.apexes.wsonrpc.ExceptionProcessor;
import net.apexes.wsonrpc.WsonrpcConfig;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.googlecode.jsonrpc4j.DefaultExceptionResolver;
import com.googlecode.jsonrpc4j.ExceptionResolver;
import com.googlecode.jsonrpc4j.JsonRpcClient;
import com.googlecode.jsonrpc4j.JsonRpcClientException;
import com.googlecode.jsonrpc4j.JsonRpcMultiServer;
import com.googlecode.jsonrpc4j.NoCloseInputStream;
/**
*
* @author <a href=mailto:[email protected]>HeDYn</a>
*
*/
class WsonrpcDispatcher implements Caller {
private final ExecutorService execService;
private final ObjectMapper mapper;
private final BinaryWrapper binaryProcessor;
private final long timeout;
private final JsonRpcClient jsonRpcClient;
private final JsonRpcMultiServer jsonRpcServer;
private ExceptionResolver exceptionResolver = DefaultExceptionResolver.INSTANCE;
private ExceptionProcessor exceptionProcessor;
public WsonrpcDispatcher(WsonrpcConfig config) {
this.execService = config.getExecutorService();
this.mapper = config.getObjectMapper();
this.binaryProcessor = config.getBinaryWrapper();
this.timeout = config.getTimeout();
jsonRpcClient = new JsonRpcClient(mapper);
jsonRpcServer = new JsonRpcMultiServer(mapper);
}
public void setExceptionResolver(ExceptionResolver exceptionResolver) {
this.exceptionResolver = exceptionResolver;
}
public void setExceptionProcessor(ExceptionProcessor processor) {
this.exceptionProcessor = processor;
}
public ExceptionProcessor getExceptionProcessor() {
return exceptionProcessor;
}
public void addService(String name, Object handler) {
jsonRpcServer.addService(name, handler);
}
@Override
public long getTimeout() {
return timeout;
}
@Override
public void notify(Session session, String serviceName, String methodName, Object argument)
throws Exception {
String id = UUID.randomUUID().toString().replace("-", "");
invoke(session, serviceName, methodName, argument, id);
}
@Override
public Future<Object> request(Session session, String serviceName, String methodName, Object argument,
Type returnType) throws Exception {
String id = UUID.randomUUID().toString().replace("-", "");
WosonrpcFuture<Object> future = new WosonrpcFuture<>(id, returnType);
WsonrpcContext.Futures.put(future);
try {
invoke(session, serviceName, methodName, argument, id);
return future;
} catch (Exception ex) {
WsonrpcContext.Futures.out(id);
throw ex;
}
}
private void invoke(Session session, String serviceName, String methodName, Object argument, String id)
throws Exception {
ByteArrayOutputStream ops = new ByteArrayOutputStream();
jsonRpcClient.invoke(serviceName + "." + methodName, argument, binaryProcessor.wrap(ops), id);
session.getBasicRemote().sendBinary(ByteBuffer.wrap(ops.toByteArray()));
}
public void handle(Session session, ByteBuffer buffer) throws Exception {
InputStream ips = binaryProcessor.wrap(new ByteArrayInputStream(buffer.array()));
JsonNode data = mapper.readTree(new NoCloseInputStream(ips));
// bail on invalid response
if (!data.isObject()) {
throw new JsonRpcClientException(0, "Invalid WSON-RPC data", data);
}
ObjectNode jsonObject = ObjectNode.class.cast(data);
if (jsonObject.has("method")) {
response(session, jsonObject);
} else {
accept(jsonObject);
}
}
private void accept(ObjectNode jsonObject) throws Exception {
JsonNode idNode = jsonObject.get("id");
if (idNode == null || !idNode.isTextual()) {
return;
}
String id = idNode.textValue();
WosonrpcFuture<Object> future = WsonrpcContext.Futures.out(id);
if (future == null) {
return;
}
// detect errors
JsonNode exceptionNode = jsonObject.get("error");
if (exceptionNode != null && !exceptionNode.isNull()) {
// resolve and throw the exception
Throwable throwable;
if (exceptionResolver == null) {
throwable = DefaultExceptionResolver.INSTANCE.resolveException(jsonObject);
} else {
throwable = exceptionResolver.resolveException(jsonObject);
}
future.setException(throwable);
}
// convert it to a return object
JsonNode resultNode = jsonObject.get("result");
if (resultNode != null && !resultNode.isNull()) {
Type returnType = future.returnType;
if (returnType == null) {
return;
}
JsonParser returnJsonParser = mapper.treeAsTokens(resultNode);
JavaType returnJavaType = TypeFactory.defaultInstance().constructType(returnType);
Object value = mapper.readValue(returnJsonParser, returnJavaType);
future.set(value);
} else {
Throwable throwable;
if (exceptionResolver == null) {
throwable = DefaultExceptionResolver.INSTANCE.resolveException(jsonObject);
} else {
throwable = exceptionResolver.resolveException(jsonObject);
}
future.setException(throwable);
}
}
private void response(final Session session, final ObjectNode jsonObject) {
execService.execute(new Runnable() {
@Override
public void run() {
WsonrpcContext.Sessions.begin(session);
try {
ByteArrayOutputStream ops = new ByteArrayOutputStream();
jsonRpcServer.handleNode(jsonObject, binaryProcessor.wrap(ops));
session.getBasicRemote().sendBinary(ByteBuffer.wrap(ops.toByteArray()));
} catch (Exception ex) {
if (exceptionProcessor != null) {
exceptionProcessor.onError(ex, jsonObject);
}
} finally {
WsonrpcContext.Sessions.end();
}
}
});
}
}
| 按jsonrpc定义notify不带id | src/main/java/net/apexes/wsonrpc/internal/WsonrpcDispatcher.java | 按jsonrpc定义notify不带id | <ide><path>rc/main/java/net/apexes/wsonrpc/internal/WsonrpcDispatcher.java
<ide> @Override
<ide> public void notify(Session session, String serviceName, String methodName, Object argument)
<ide> throws Exception {
<del> String id = UUID.randomUUID().toString().replace("-", "");
<del> invoke(session, serviceName, methodName, argument, id);
<add> invoke(session, serviceName, methodName, argument, null);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 2cf6e14737ab7118f61cd8ac94b94541b429401f | 0 | Samsung/GearVRf,Samsung/GearVRf,Samsung/GearVRf,Samsung/GearVRf,Samsung/GearVRf,Samsung/GearVRf,Samsung/GearVRf | /* Copyright 2016 Samsung Electronics Co., LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gearvrf;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.opengl.EGL14;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.EGLConfigChooser;
import android.opengl.GLSurfaceView.EGLContextFactory;
import android.opengl.GLSurfaceView.EGLWindowSurfaceFactory;
import android.opengl.GLSurfaceView.Renderer;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.SurfaceHolder;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.VrAppSettings;
import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;
/**
* Keep Oculus-specifics here
*/
final class OvrVrapiActivityHandler implements OvrActivityHandler {
private final GVRApplication mApplication;
private long mPtr;
private GLSurfaceView mSurfaceView;
private EGLSurface mPixelBuffer;
// warning: writable static state; used to determine when vrapi can be safely uninitialized
private static WeakReference<OvrVrapiActivityHandler> sVrapiOwner = new WeakReference<>(null);
private OvrViewManager mViewManager;
private int mCurrentSurfaceWidth, mCurrentSurfaceHeight;
OvrVrapiActivityHandler(final GVRApplication application, final OvrActivityNative activityNative) throws VrapiNotAvailableException {
if (null == application) {
throw new IllegalArgumentException();
}
try {
application.getActivity().getPackageManager().getPackageInfo("com.oculus.systemdriver", PackageManager.GET_SIGNATURES);
} catch (final PackageManager.NameNotFoundException e) {
try {
application.getActivity().getPackageManager().getPackageInfo("com.oculus.systemactivities", PackageManager.GET_SIGNATURES);
} catch (PackageManager.NameNotFoundException e1) {
Log.e(TAG, "oculus packages missing, assuming vrapi will not work");
throw new VrapiNotAvailableException();
}
}
mApplication = application;
mPtr = activityNative.getNative();
if (null != sVrapiOwner.get()) {
nativeUninitializeVrApi();
}
if (VRAPI_INITIALIZE_UNKNOWN_ERROR == nativeInitializeVrApi(mPtr)) {
throw new VrapiNotAvailableException();
}
sVrapiOwner = new WeakReference<>(this);
}
@Override
public void onPause() {
if (null != mSurfaceView) {
final CountDownLatch cdl = new CountDownLatch(1);
mSurfaceView.onPause();
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
//these two must happen on the gl thread
nativeLeaveVrMode(mPtr);
destroySurfaceForTimeWarp();
cdl.countDown();
}
});
try {
cdl.await();
} catch (final InterruptedException e) {
}
}
mCurrentSurfaceWidth = mCurrentSurfaceHeight = 0;
}
@Override
public void onResume() {
final OvrVrapiActivityHandler currentOwner = sVrapiOwner.get();
if (this != currentOwner) {
nativeUninitializeVrApi();
nativeInitializeVrApi(mPtr);
sVrapiOwner = new WeakReference<>(this);
}
if (null != mSurfaceView) {
mSurfaceView.onResume();
}
}
@Override
public boolean onBack() {
if (null != mSurfaceView) {
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
nativeShowConfirmQuit(mPtr);
}
});
}
return true;
}
@Override
public void onDestroy() {
if (this == sVrapiOwner.get()) {
nativeUninitializeVrApi();
sVrapiOwner.clear();
}
}
@Override
public void setViewManager(GVRViewManager viewManager) {
mViewManager = (OvrViewManager)viewManager;
}
@Override
public void onSetScript() {
mSurfaceView = new GLSurfaceView(mApplication.getActivity());
mSurfaceView.setZOrderOnTop(true);
final DisplayMetrics metrics = new DisplayMetrics();
mApplication.getActivity().getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
final VrAppSettings appSettings = mApplication.getAppSettings();
int defaultWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);
int defaultHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);
final int frameBufferWidth = appSettings.getFramebufferPixelsWide();
final int frameBufferHeight = appSettings.getFramebufferPixelsHigh();
final SurfaceHolder holder = mSurfaceView.getHolder();
holder.setFormat(PixelFormat.TRANSLUCENT);
if ((-1 != frameBufferHeight) && (-1 != frameBufferWidth)) {
if ((defaultWidthPixels != frameBufferWidth) && (defaultHeightPixels != frameBufferHeight)) {
Log.v(TAG, "--- window configuration ---");
Log.v(TAG, "--- width: %d", frameBufferWidth);
Log.v(TAG, "--- height: %d", frameBufferHeight);
//a different resolution of the native window requested
defaultWidthPixels = frameBufferWidth;
defaultHeightPixels = frameBufferHeight;
Log.v(TAG, "----------------------------");
}
}
holder.setFixedSize(defaultWidthPixels, defaultHeightPixels);
mSurfaceView.setPreserveEGLContextOnPause(true);
mSurfaceView.setEGLContextClientVersion(3);
mSurfaceView.setEGLContextFactory(mContextFactory);
mSurfaceView.setEGLConfigChooser(mConfigChooser);
mSurfaceView.setEGLWindowSurfaceFactory(mWindowSurfaceFactory);
mSurfaceView.setRenderer(mRenderer);
mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
mApplication.getActivity().setContentView(mSurfaceView);
}
private final EGLContextFactory mContextFactory = new EGLContextFactory() {
@Override
public void destroyContext(final EGL10 egl, final EGLDisplay display, final EGLContext context) {
Log.v(TAG, "EGLContextFactory.destroyContext 0x%X", context.hashCode());
egl.eglDestroyContext(display, context);
}
@Override
public EGLContext createContext(final EGL10 egl, final EGLDisplay display, final EGLConfig eglConfig) {
final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
final int[] contextAttribs = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL10.EGL_NONE
};
final EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, contextAttribs);
if (context == EGL10.EGL_NO_CONTEXT) {
throw new IllegalStateException("eglCreateContext failed; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
Log.v(TAG, "EGLContextFactory.createContext 0x%X", context.hashCode());
return context;
}
};
private final EGLWindowSurfaceFactory mWindowSurfaceFactory = new EGLWindowSurfaceFactory() {
@Override
public void destroySurface(final EGL10 egl, final EGLDisplay display, final EGLSurface surface) {
Log.v(TAG, "EGLWindowSurfaceFactory.destroySurface 0x%X, mPixelBuffer 0x%X", surface.hashCode(), mPixelBuffer.hashCode());
boolean result = egl.eglDestroySurface(display, mPixelBuffer);
Log.v(TAG, "EGLWindowSurfaceFactory.destroySurface successful %b, egl error 0x%x", result, egl.eglGetError());
mPixelBuffer = null;
}
@Override
public EGLSurface createWindowSurface(final EGL10 egl, final EGLDisplay display, final EGLConfig config,
final Object ignoredNativeWindow) {
final int[] surfaceAttribs = {
EGL10.EGL_WIDTH, 16,
EGL10.EGL_HEIGHT, 16,
EGL10.EGL_NONE
};
mPixelBuffer = egl.eglCreatePbufferSurface(display, config, surfaceAttribs);
if (EGL10.EGL_NO_SURFACE == mPixelBuffer) {
throw new IllegalStateException("Pixel buffer surface not created; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
Log.v(TAG, "EGLWindowSurfaceFactory.eglCreatePbufferSurface 0x%X", mPixelBuffer.hashCode());
return mPixelBuffer;
}
};
private final EGLConfigChooser mConfigChooser = new EGLConfigChooser() {
@Override
public EGLConfig chooseConfig(final EGL10 egl, final EGLDisplay display) {
final int[] numberConfigs = new int[1];
if (!egl.eglGetConfigs(display, null, 0, numberConfigs)) {
throw new IllegalStateException("Unable to retrieve number of egl configs available.");
}
final EGLConfig[] configs = new EGLConfig[numberConfigs[0]];
if (!egl.eglGetConfigs(display, configs, configs.length, numberConfigs)) {
throw new IllegalStateException("Unable to retrieve egl configs available.");
}
final int[] configAttribs = new int[16];
int counter = 0;
configAttribs[counter++] = EGL10.EGL_ALPHA_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_BLUE_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_GREEN_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_RED_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_DEPTH_SIZE;
configAttribs[counter++] = 0;
configAttribs[counter++] = EGL10.EGL_SAMPLES;
configAttribs[counter++] = 0;
Log.v(TAG, "--- window surface configuration ---");
final VrAppSettings appSettings = mApplication.getAppSettings();
if (appSettings.useSrgbFramebuffer) {
final int EGL_GL_COLORSPACE_KHR = 0x309D;
final int EGL_GL_COLORSPACE_SRGB_KHR = 0x3089;
configAttribs[counter++] = EGL_GL_COLORSPACE_KHR;
configAttribs[counter++] = EGL_GL_COLORSPACE_SRGB_KHR;
}
Log.v(TAG, "--- srgb framebuffer: %b", appSettings.useSrgbFramebuffer);
if (appSettings.useProtectedFramebuffer) {
final int EGL_PROTECTED_CONTENT_EXT = 0x32c0;
configAttribs[counter++] = EGL_PROTECTED_CONTENT_EXT;
configAttribs[counter++] = EGL14.EGL_TRUE;
}
Log.v(TAG, "--- protected framebuffer: %b", appSettings.useProtectedFramebuffer);
configAttribs[counter++] = EGL10.EGL_NONE;
Log.v(TAG, "------------------------------------");
EGLConfig config = null;
for (int i = 0; i < numberConfigs[0]; ++i) {
final int[] value = new int[1];
final int EGL_OPENGL_ES3_BIT_KHR = 0x0040;
if (!egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_RENDERABLE_TYPE,
value)) {
Log.v(TAG, "eglGetConfigAttrib for EGL_RENDERABLE_TYPE failed");
continue;
}
if ((value[0] & EGL_OPENGL_ES3_BIT_KHR) != EGL_OPENGL_ES3_BIT_KHR) {
continue;
}
if (!egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_SURFACE_TYPE, value)) {
Log.v(TAG, "eglGetConfigAttrib for EGL_SURFACE_TYPE failed");
continue;
}
if ((value[0]
& (EGL10.EGL_WINDOW_BIT | EGL10.EGL_PBUFFER_BIT)) != (EGL10.EGL_WINDOW_BIT
| EGL10.EGL_PBUFFER_BIT)) {
continue;
}
int j = 0;
for (; configAttribs[j] != EGL10.EGL_NONE; j += 2) {
if (!egl.eglGetConfigAttrib(display, configs[i], configAttribs[j], value)) {
Log.v(TAG, "eglGetConfigAttrib for " + configAttribs[j] + " failed");
continue;
}
if (value[0] != configAttribs[j + 1]) {
break;
}
}
if (configAttribs[j] == EGL10.EGL_NONE) {
config = configs[i];
break;
}
}
return config;
}
};
private void destroySurfaceForTimeWarp() {
final EGL10 egl = (EGL10) EGLContext.getEGL();
final EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
final EGLContext context = egl.eglGetCurrentContext();
if (!egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, context)) {
Log.v(TAG, "destroySurfaceForTimeWarp makeCurrent NO_SURFACE failed, egl error 0x%x", egl.eglGetError());
}
}
private final Renderer mRenderer = new Renderer() {
@Override
public void onSurfaceCreated(final GL10 gl, final EGLConfig config) {
Log.i(TAG, "onSurfaceCreated");
nativeOnSurfaceCreated(mPtr);
mViewManager.onSurfaceCreated();
}
@Override
public void onSurfaceChanged(final GL10 gl, final int width, final int height) {
Log.i(TAG, "onSurfaceChanged; %d x %d", width, height);
if (width < height) {
Log.v(TAG, "short-circuiting onSurfaceChanged; surface in portrait");
return;
}
if (mCurrentSurfaceWidth == width && mCurrentSurfaceHeight == height) {
return;
}
mCurrentSurfaceWidth = width; mCurrentSurfaceHeight = height;
nativeLeaveVrMode(mPtr);
destroySurfaceForTimeWarp();
final EGL10 egl = (EGL10) EGLContext.getEGL();
final EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
final EGLContext context = egl.eglGetCurrentContext();
// necessary to explicitly make the pbuffer current for the rendering thread;
// TimeWarp took over the window surface
if (!egl.eglMakeCurrent(display, mPixelBuffer, mPixelBuffer, context)) {
throw new IllegalStateException("Failed to make context current ; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
nativeOnSurfaceChanged(mPtr, mSurfaceView.getHolder().getSurface());
mViewManager.onSurfaceChanged(width, height);
mViewManager.createSwapChain();
}
@Override
public void onDrawFrame(final GL10 gl) {
mViewManager.onDrawFrame();
}
};
@SuppressWarnings("serial")
static final class VrapiNotAvailableException extends RuntimeException {
}
private static native void nativeOnSurfaceCreated(long ptr);
private static native void nativeOnSurfaceChanged(long ptr, Surface surface);
private static native void nativeLeaveVrMode(long ptr);
private static native void nativeShowConfirmQuit(long appPtr);
private static native int nativeInitializeVrApi(long ptr);
static native int nativeUninitializeVrApi();
private static final int VRAPI_INITIALIZE_UNKNOWN_ERROR = -1;
private static final String TAG = "OvrVrapiActivityHandler";
}
| GVRf/Framework/backend_oculus/src/main/java/org/gearvrf/OvrVrapiActivityHandler.java | /* Copyright 2016 Samsung Electronics Co., LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gearvrf;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.opengl.EGL14;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.EGLConfigChooser;
import android.opengl.GLSurfaceView.EGLContextFactory;
import android.opengl.GLSurfaceView.EGLWindowSurfaceFactory;
import android.opengl.GLSurfaceView.Renderer;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.SurfaceHolder;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.VrAppSettings;
import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;
/**
* Keep Oculus-specifics here
*/
final class OvrVrapiActivityHandler implements OvrActivityHandler {
private final GVRApplication mApplication;
private long mPtr;
private GLSurfaceView mSurfaceView;
private EGLSurface mPixelBuffer;
// warning: writable static state; used to determine when vrapi can be safely uninitialized
private static WeakReference<OvrVrapiActivityHandler> sVrapiOwner = new WeakReference<>(null);
private OvrViewManager mViewManager;
private int mCurrentSurfaceWidth, mCurrentSurfaceHeight;
OvrVrapiActivityHandler(final GVRApplication application, final OvrActivityNative activityNative) throws VrapiNotAvailableException {
if (null == application) {
throw new IllegalArgumentException();
}
try {
application.getActivity().getPackageManager().getPackageInfo("com.oculus.systemdriver", PackageManager.GET_SIGNATURES);
} catch (final PackageManager.NameNotFoundException e) {
try {
application.getActivity().getPackageManager().getPackageInfo("com.oculus.systemactivities", PackageManager.GET_SIGNATURES);
} catch (PackageManager.NameNotFoundException e1) {
Log.e(TAG, "oculus packages missing, assuming vrapi will not work");
throw new VrapiNotAvailableException();
}
}
mApplication = application;
mPtr = activityNative.getNative();
if (null != sVrapiOwner.get()) {
nativeUninitializeVrApi();
}
if (VRAPI_INITIALIZE_UNKNOWN_ERROR == nativeInitializeVrApi(mPtr)) {
throw new VrapiNotAvailableException();
}
sVrapiOwner = new WeakReference<>(this);
}
@Override
public void onPause() {
if (null != mSurfaceView) {
final CountDownLatch cdl = new CountDownLatch(1);
mSurfaceView.onPause();
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
//these two must happen on the gl thread
nativeLeaveVrMode(mPtr);
destroySurfaceForTimeWarp();
cdl.countDown();
}
});
try {
cdl.await();
} catch (final InterruptedException e) {
}
}
mCurrentSurfaceWidth = mCurrentSurfaceHeight = 0;
}
@Override
public void onResume() {
final OvrVrapiActivityHandler currentOwner = sVrapiOwner.get();
if (this != currentOwner) {
nativeUninitializeVrApi();
nativeInitializeVrApi(mPtr);
sVrapiOwner = new WeakReference<>(this);
}
if (null != mSurfaceView) {
mSurfaceView.onResume();
}
}
@Override
public boolean onBack() {
if (null != mSurfaceView) {
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
nativeShowConfirmQuit(mPtr);
}
});
}
return true;
}
@Override
public void onDestroy() {
if (this == sVrapiOwner.get()) {
nativeUninitializeVrApi();
sVrapiOwner.clear();
}
}
@Override
public void setViewManager(GVRViewManager viewManager) {
mViewManager = (OvrViewManager)viewManager;
}
@Override
public void onSetScript() {
mSurfaceView = new GLSurfaceView(mApplication.getActivity());
mSurfaceView.setZOrderOnTop(true);
final DisplayMetrics metrics = new DisplayMetrics();
mApplication.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
final VrAppSettings appSettings = mApplication.getAppSettings();
int defaultWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);
int defaultHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);
final int frameBufferWidth = appSettings.getFramebufferPixelsWide();
final int frameBufferHeight = appSettings.getFramebufferPixelsHigh();
final SurfaceHolder holder = mSurfaceView.getHolder();
holder.setFormat(PixelFormat.TRANSLUCENT);
if ((-1 != frameBufferHeight) && (-1 != frameBufferWidth)) {
if ((defaultWidthPixels != frameBufferWidth) && (defaultHeightPixels != frameBufferHeight)) {
Log.v(TAG, "--- window configuration ---");
Log.v(TAG, "--- width: %d", frameBufferWidth);
Log.v(TAG, "--- height: %d", frameBufferHeight);
//a different resolution of the native window requested
defaultWidthPixels = frameBufferWidth;
defaultHeightPixels = frameBufferHeight;
Log.v(TAG, "----------------------------");
}
}
holder.setFixedSize(defaultWidthPixels, defaultHeightPixels);
mSurfaceView.setPreserveEGLContextOnPause(true);
mSurfaceView.setEGLContextClientVersion(3);
mSurfaceView.setEGLContextFactory(mContextFactory);
mSurfaceView.setEGLConfigChooser(mConfigChooser);
mSurfaceView.setEGLWindowSurfaceFactory(mWindowSurfaceFactory);
mSurfaceView.setRenderer(mRenderer);
mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
mApplication.getActivity().setContentView(mSurfaceView);
}
private final EGLContextFactory mContextFactory = new EGLContextFactory() {
@Override
public void destroyContext(final EGL10 egl, final EGLDisplay display, final EGLContext context) {
Log.v(TAG, "EGLContextFactory.destroyContext 0x%X", context.hashCode());
egl.eglDestroyContext(display, context);
}
@Override
public EGLContext createContext(final EGL10 egl, final EGLDisplay display, final EGLConfig eglConfig) {
final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
final int[] contextAttribs = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL10.EGL_NONE
};
final EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, contextAttribs);
if (context == EGL10.EGL_NO_CONTEXT) {
throw new IllegalStateException("eglCreateContext failed; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
Log.v(TAG, "EGLContextFactory.createContext 0x%X", context.hashCode());
return context;
}
};
private final EGLWindowSurfaceFactory mWindowSurfaceFactory = new EGLWindowSurfaceFactory() {
@Override
public void destroySurface(final EGL10 egl, final EGLDisplay display, final EGLSurface surface) {
Log.v(TAG, "EGLWindowSurfaceFactory.destroySurface 0x%X, mPixelBuffer 0x%X", surface.hashCode(), mPixelBuffer.hashCode());
boolean result = egl.eglDestroySurface(display, mPixelBuffer);
Log.v(TAG, "EGLWindowSurfaceFactory.destroySurface successful %b, egl error 0x%x", result, egl.eglGetError());
mPixelBuffer = null;
}
@Override
public EGLSurface createWindowSurface(final EGL10 egl, final EGLDisplay display, final EGLConfig config,
final Object ignoredNativeWindow) {
final int[] surfaceAttribs = {
EGL10.EGL_WIDTH, 16,
EGL10.EGL_HEIGHT, 16,
EGL10.EGL_NONE
};
mPixelBuffer = egl.eglCreatePbufferSurface(display, config, surfaceAttribs);
if (EGL10.EGL_NO_SURFACE == mPixelBuffer) {
throw new IllegalStateException("Pixel buffer surface not created; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
Log.v(TAG, "EGLWindowSurfaceFactory.eglCreatePbufferSurface 0x%X", mPixelBuffer.hashCode());
return mPixelBuffer;
}
};
private final EGLConfigChooser mConfigChooser = new EGLConfigChooser() {
@Override
public EGLConfig chooseConfig(final EGL10 egl, final EGLDisplay display) {
final int[] numberConfigs = new int[1];
if (!egl.eglGetConfigs(display, null, 0, numberConfigs)) {
throw new IllegalStateException("Unable to retrieve number of egl configs available.");
}
final EGLConfig[] configs = new EGLConfig[numberConfigs[0]];
if (!egl.eglGetConfigs(display, configs, configs.length, numberConfigs)) {
throw new IllegalStateException("Unable to retrieve egl configs available.");
}
final int[] configAttribs = new int[16];
int counter = 0;
configAttribs[counter++] = EGL10.EGL_ALPHA_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_BLUE_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_GREEN_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_RED_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_DEPTH_SIZE;
configAttribs[counter++] = 0;
configAttribs[counter++] = EGL10.EGL_SAMPLES;
configAttribs[counter++] = 0;
Log.v(TAG, "--- window surface configuration ---");
final VrAppSettings appSettings = mApplication.getAppSettings();
if (appSettings.useSrgbFramebuffer) {
final int EGL_GL_COLORSPACE_KHR = 0x309D;
final int EGL_GL_COLORSPACE_SRGB_KHR = 0x3089;
configAttribs[counter++] = EGL_GL_COLORSPACE_KHR;
configAttribs[counter++] = EGL_GL_COLORSPACE_SRGB_KHR;
}
Log.v(TAG, "--- srgb framebuffer: %b", appSettings.useSrgbFramebuffer);
if (appSettings.useProtectedFramebuffer) {
final int EGL_PROTECTED_CONTENT_EXT = 0x32c0;
configAttribs[counter++] = EGL_PROTECTED_CONTENT_EXT;
configAttribs[counter++] = EGL14.EGL_TRUE;
}
Log.v(TAG, "--- protected framebuffer: %b", appSettings.useProtectedFramebuffer);
configAttribs[counter++] = EGL10.EGL_NONE;
Log.v(TAG, "------------------------------------");
EGLConfig config = null;
for (int i = 0; i < numberConfigs[0]; ++i) {
final int[] value = new int[1];
final int EGL_OPENGL_ES3_BIT_KHR = 0x0040;
if (!egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_RENDERABLE_TYPE,
value)) {
Log.v(TAG, "eglGetConfigAttrib for EGL_RENDERABLE_TYPE failed");
continue;
}
if ((value[0] & EGL_OPENGL_ES3_BIT_KHR) != EGL_OPENGL_ES3_BIT_KHR) {
continue;
}
if (!egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_SURFACE_TYPE, value)) {
Log.v(TAG, "eglGetConfigAttrib for EGL_SURFACE_TYPE failed");
continue;
}
if ((value[0]
& (EGL10.EGL_WINDOW_BIT | EGL10.EGL_PBUFFER_BIT)) != (EGL10.EGL_WINDOW_BIT
| EGL10.EGL_PBUFFER_BIT)) {
continue;
}
int j = 0;
for (; configAttribs[j] != EGL10.EGL_NONE; j += 2) {
if (!egl.eglGetConfigAttrib(display, configs[i], configAttribs[j], value)) {
Log.v(TAG, "eglGetConfigAttrib for " + configAttribs[j] + " failed");
continue;
}
if (value[0] != configAttribs[j + 1]) {
break;
}
}
if (configAttribs[j] == EGL10.EGL_NONE) {
config = configs[i];
break;
}
}
return config;
}
};
private void destroySurfaceForTimeWarp() {
final EGL10 egl = (EGL10) EGLContext.getEGL();
final EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
final EGLContext context = egl.eglGetCurrentContext();
if (!egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, context)) {
Log.v(TAG, "destroySurfaceForTimeWarp makeCurrent NO_SURFACE failed, egl error 0x%x", egl.eglGetError());
}
}
private final Renderer mRenderer = new Renderer() {
@Override
public void onSurfaceCreated(final GL10 gl, final EGLConfig config) {
Log.i(TAG, "onSurfaceCreated");
nativeOnSurfaceCreated(mPtr);
mViewManager.onSurfaceCreated();
}
@Override
public void onSurfaceChanged(final GL10 gl, final int width, final int height) {
Log.i(TAG, "onSurfaceChanged; %d x %d", width, height);
if (width < height) {
Log.v(TAG, "short-circuiting onSurfaceChanged; surface in portrait");
return;
}
if (mCurrentSurfaceWidth == width && mCurrentSurfaceHeight == height) {
return;
}
mCurrentSurfaceWidth = width; mCurrentSurfaceHeight = height;
nativeLeaveVrMode(mPtr);
destroySurfaceForTimeWarp();
final EGL10 egl = (EGL10) EGLContext.getEGL();
final EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
final EGLContext context = egl.eglGetCurrentContext();
// necessary to explicitly make the pbuffer current for the rendering thread;
// TimeWarp took over the window surface
if (!egl.eglMakeCurrent(display, mPixelBuffer, mPixelBuffer, context)) {
throw new IllegalStateException("Failed to make context current ; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
nativeOnSurfaceChanged(mPtr, mSurfaceView.getHolder().getSurface());
mViewManager.onSurfaceChanged(width, height);
mViewManager.createSwapChain();
}
@Override
public void onDrawFrame(final GL10 gl) {
mViewManager.onDrawFrame();
}
};
@SuppressWarnings("serial")
static final class VrapiNotAvailableException extends RuntimeException {
}
private static native void nativeOnSurfaceCreated(long ptr);
private static native void nativeOnSurfaceChanged(long ptr, Surface surface);
private static native void nativeLeaveVrMode(long ptr);
private static native void nativeShowConfirmQuit(long appPtr);
private static native int nativeInitializeVrApi(long ptr);
static native int nativeUninitializeVrApi();
private static final int VRAPI_INITIALIZE_UNKNOWN_ERROR = -1;
private static final String TAG = "OvrVrapiActivityHandler";
}
| backend_oculus: fix for Android 9
| GVRf/Framework/backend_oculus/src/main/java/org/gearvrf/OvrVrapiActivityHandler.java | backend_oculus: fix for Android 9 | <ide><path>VRf/Framework/backend_oculus/src/main/java/org/gearvrf/OvrVrapiActivityHandler.java
<ide> mSurfaceView.setZOrderOnTop(true);
<ide>
<ide> final DisplayMetrics metrics = new DisplayMetrics();
<del> mApplication.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
<add> mApplication.getActivity().getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
<ide> final VrAppSettings appSettings = mApplication.getAppSettings();
<ide> int defaultWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);
<ide> int defaultHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels); |
|
JavaScript | mit | c896c9510b2529159ebd7f9d34809417f372980d | 0 | Orange-OpenSource/Orange-Boosted-Bootstrap,Orange-OpenSource/Orange-Boosted-Bootstrap | /**
* --------------------------------------------------------------------------
* Bootstrap (v4.3.1): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
import $ from 'jquery'
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
const NAME = 'button'
const VERSION = '4.3.1'
const DATA_KEY = 'bs.button'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const JQUERY_NO_CONFLICT = $.fn[NAME]
const ClassName = {
ACTIVE : 'active',
BUTTON : 'btn',
FOCUS : 'focus'
}
const Selector = {
DATA_TOGGLE_CARROT : '[data-toggle^="button"]',
DATA_TOGGLE : '[data-toggle="buttons"]',
INPUT : 'input:not([type="hidden"])',
ACTIVE : '.active',
BUTTON : '.btn'
}
const Event = {
CLICK_DATA_API : `click${EVENT_KEY}${DATA_API_KEY}`,
FOCUS_BLUR_DATA_API : `focus${EVENT_KEY}${DATA_API_KEY} ` +
`blur${EVENT_KEY}${DATA_API_KEY}`
}
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
class Button {
constructor(element) {
this._element = element
}
// Getters
static get VERSION() {
return VERSION
}
// Public
toggle() {
const rootElement = $(this._element).closest(
Selector.DATA_TOGGLE
)[0]
const input = this._element.querySelector(Selector.INPUT)
if (rootElement) {
const activeElement = rootElement.querySelector(Selector.ACTIVE)
if (activeElement) {
activeElement.classList.remove(ClassName.ACTIVE)
}
}
if (input) {
if (input.checked) {
this._element.classList.add(ClassName.ACTIVE)
} else {
this._element.classList.remove(ClassName.ACTIVE)
}
} else {
this._element.classList.toggle(ClassName.ACTIVE)
this._element.setAttribute('aria-pressed',
this._element.classList.contains(ClassName.ACTIVE))
}
}
dispose() {
$.removeData(this._element, DATA_KEY)
this._element = null
}
// Static
static _jQueryInterface(config) {
return this.each(function () {
let data = $(this).data(DATA_KEY)
if (!data) {
data = new Button(this)
$(this).data(DATA_KEY, data)
}
if (config === 'toggle') {
data[config]()
}
})
}
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document)
.on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, (event) => {
let button = event.target
if (!$(button).hasClass(ClassName.BUTTON)) {
button = $(button).closest(Selector.BUTTON)
}
Button._jQueryInterface.call($(button), 'toggle')
})
.on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, (event) => {
const button = $(event.target).closest(Selector.BUTTON)[0]
if (button) {
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type))
}
})
.on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT > Selector.INPUT, (event) => {
const button = $(event.target).closest(Selector.BUTTON)[0]
if (button) {
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type))
}
})
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Button._jQueryInterface
$.fn[NAME].Constructor = Button
$.fn[NAME].noConflict = () => {
$.fn[NAME] = JQUERY_NO_CONFLICT
return Button._jQueryInterface
}
export default Button
| js/src/button.js | /**
* --------------------------------------------------------------------------
* Bootstrap (v4.3.1): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
import $ from 'jquery'
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
const NAME = 'button'
const VERSION = '4.3.1'
const DATA_KEY = 'bs.button'
const EVENT_KEY = `.${DATA_KEY}`
const DATA_API_KEY = '.data-api'
const JQUERY_NO_CONFLICT = $.fn[NAME]
const ClassName = {
ACTIVE : 'active',
BUTTON : 'btn',
FOCUS : 'focus'
}
const Selector = {
DATA_TOGGLE_CARROT : '[data-toggle^="button"]',
DATA_TOGGLE : '[data-toggle="buttons"]',
INPUT : 'input:not([type="hidden"])',
ACTIVE : '.active',
BUTTON : '.btn'
}
const Event = {
CLICK_DATA_API : `click${EVENT_KEY}${DATA_API_KEY}`,
FOCUS_BLUR_DATA_API : `focus${EVENT_KEY}${DATA_API_KEY} ` +
`blur${EVENT_KEY}${DATA_API_KEY}`
}
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
class Button {
constructor(element) {
this._element = element
}
// Getters
static get VERSION() {
return VERSION
}
// Public
toggle() {
const rootElement = $(this._element).closest(
Selector.DATA_TOGGLE
)[0]
const input = this._element.querySelector(Selector.INPUT)
if (rootElement) {
const activeElement = rootElement.querySelector(Selector.ACTIVE)
if (activeElement) {
activeElement.classList.remove(ClassName.ACTIVE)
}
}
if (input) {
if (input.checked) {
this._element.classList.add(ClassName.ACTIVE)
} else {
this._element.classList.remove(ClassName.ACTIVE)
}
} else {
this._element.classList.toggle(ClassName.ACTIVE)
this._element.setAttribute('aria-pressed',
this._element.classList.contains(ClassName.ACTIVE))
}
}
dispose() {
$.removeData(this._element, DATA_KEY)
this._element = null
}
// Static
static _jQueryInterface(config) {
return this.each(function () {
let data = $(this).data(DATA_KEY)
if (!data) {
data = new Button(this)
$(this).data(DATA_KEY, data)
}
if (config === 'toggle') {
data[config]()
}
})
}
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
$(document)
.on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, (event) => {
let button = event.target
if (!$(button).hasClass(ClassName.BUTTON)) {
button = $(button).closest(Selector.BUTTON)
}
Button._jQueryInterface.call($(button), 'toggle')
})
.on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, (event) => {
const button = $(event.target).closest(Selector.BUTTON)[0]
if (button) {
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type))
}
})
.on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT.querySelector(Selector.INPUT), (event) => {
const button = $(event.target).closest(Selector.BUTTON)[0]
if (button) {
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type))
}
})
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Button._jQueryInterface
$.fn[NAME].Constructor = Button
$.fn[NAME].noConflict = () => {
$.fn[NAME] = JQUERY_NO_CONFLICT
return Button._jQueryInterface
}
export default Button
| fix(button): fix js error when linting
| js/src/button.js | fix(button): fix js error when linting | <ide><path>s/src/button.js
<ide> $(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type))
<ide> }
<ide> })
<del> .on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT.querySelector(Selector.INPUT), (event) => {
<add> .on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT > Selector.INPUT, (event) => {
<ide> const button = $(event.target).closest(Selector.BUTTON)[0]
<ide> if (button) {
<ide> $(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type)) |
|
Java | apache-2.0 | 0a783ded977dc48f56abd0e38c7eeb49dacb9db4 | 0 | lemire/javaewah,wang19742008/javaewah | package com.googlecode.javaewah.benchmark;
/*
* Copyright 2009-2013, Daniel Lemire, Cliff Moon, David McIntosh, Robert Becho, Google Inc. and Veronika Zenz
* Licensed under APL 2.0.
*/
/**
* This class will generate lists of random integers with a "clustered" distribution.
* Reference:
* Anh VN, Moffat A. Index compression using 64-bit words. Software: Practice and Experience 2010; 40(2):131-147.
*
* @author Daniel Lemire
*/
class ClusteredDataGenerator {
public ClusteredDataGenerator() {
}
/**
* generates randomly N distinct integers from 0 to Max.
* @param N number of integers
* @param Max maximum integer value
* @return a randomly generated array
*/
public int[] generateClustered(int N, int Max) {
int[] array = new int[N];
fillClustered(array, 0, N, 0, Max);
return array;
}
void fillClustered(int[] array, int offset, int length, int Min, int Max) {
final int range = Max - Min;
if ((range == length) || (length <= 10)) {
fillUniform(array, offset, length, Min, Max);
return;
}
final int cut = length / 2
+ ((range - length - 1 > 0) ? this.unidg.rand.nextInt(range - length - 1) : 0);
final double p = this.unidg.rand.nextDouble();
if (p < 0.25) {
fillUniform(array, offset, length / 2, Min, Min + cut);
fillClustered(array, offset + length / 2, length - length / 2, Min + cut,
Max);
} else if (p < 0.5) {
fillClustered(array, offset, length / 2, Min, Min + cut);
fillUniform(array, offset + length / 2, length - length / 2, Min + cut,
Max);
} else {
fillClustered(array, offset, length / 2, Min, Min + cut);
fillClustered(array, offset + length / 2, length - length / 2, Min + cut,
Max);
}
}
void fillUniform(int[] array, int offset, int length, int Min, int Max) {
int[] v = this.unidg.generateUniform(length, Max - Min);
for (int k = 0; k < v.length; ++k)
array[k + offset] = Min + v[k];
}
public static void main(String[] args) {
int[] example = (new ClusteredDataGenerator()).generateClustered(20, 1000);
for (int k = 0; k < example.length; ++k)
System.out.println(example[k]);
}
UniformDataGenerator unidg = new UniformDataGenerator();
}
| src/main/java/com/googlecode/javaewah/benchmark/ClusteredDataGenerator.java | package com.googlecode.javaewah.benchmark;
/*
* Copyright 2009-2013, Daniel Lemire, Cliff Moon, David McIntosh, Robert Becho, Google Inc. and Veronika Zenz
* Licensed under APL 2.0.
*/
/**
* This class will generate uniformly distributed lists of random integers.
*
* @author Daniel Lemire
*/
class ClusteredDataGenerator {
public ClusteredDataGenerator() {
}
/**
* generates randomly N distinct integers from 0 to Max.
* @param N number of integers
* @param Max maximum integer value
* @return a randomly generated array
*/
public int[] generateClustered(int N, int Max) {
int[] array = new int[N];
fillClustered(array, 0, N, 0, Max);
return array;
}
void fillClustered(int[] array, int offset, int length, int Min, int Max) {
final int range = Max - Min;
if ((range == length) || (length <= 10)) {
fillUniform(array, offset, length, Min, Max);
return;
}
final int cut = length / 2
+ ((range - length - 1 > 0) ? this.unidg.rand.nextInt(range - length - 1) : 0);
final double p = this.unidg.rand.nextDouble();
if (p < 0.25) {
fillUniform(array, offset, length / 2, Min, Min + cut);
fillClustered(array, offset + length / 2, length - length / 2, Min + cut,
Max);
} else if (p < 0.5) {
fillClustered(array, offset, length / 2, Min, Min + cut);
fillUniform(array, offset + length / 2, length - length / 2, Min + cut,
Max);
} else {
fillClustered(array, offset, length / 2, Min, Min + cut);
fillClustered(array, offset + length / 2, length - length / 2, Min + cut,
Max);
}
}
void fillUniform(int[] array, int offset, int length, int Min, int Max) {
int[] v = this.unidg.generateUniform(length, Max - Min);
for (int k = 0; k < v.length; ++k)
array[k + offset] = Min + v[k];
}
public static void main(String[] args) {
int[] example = (new ClusteredDataGenerator()).generateClustered(20, 1000);
for (int k = 0; k < example.length; ++k)
System.out.println(example[k]);
}
UniformDataGenerator unidg = new UniformDataGenerator();
}
| Better description
| src/main/java/com/googlecode/javaewah/benchmark/ClusteredDataGenerator.java | Better description | <ide><path>rc/main/java/com/googlecode/javaewah/benchmark/ClusteredDataGenerator.java
<ide>
<ide>
<ide> /**
<del> * This class will generate uniformly distributed lists of random integers.
<del> *
<add> * This class will generate lists of random integers with a "clustered" distribution.
<add> * Reference:
<add> * Anh VN, Moffat A. Index compression using 64-bit words. Software: Practice and Experience 2010; 40(2):131-147.
<add> *
<ide> * @author Daniel Lemire
<ide> */
<ide> class ClusteredDataGenerator { |
|
Java | mit | bbd5d44f2a5aa004465d27ef7009b6b76d6d7263 | 0 | RespectNetwork/csp-provisioning-application,RespectNetwork/csp-provisioning-application | package net.respectnetwork.csp.application.manager;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.respectnetwork.csp.application.exception.UserRegistrationException;
import net.respectnetwork.sdk.csp.BasicCSPInformation;
import net.respectnetwork.sdk.csp.CSP;
import net.respectnetwork.sdk.csp.UserValidator;
import net.respectnetwork.sdk.csp.discount.CloudNameDiscountCode;
import net.respectnetwork.sdk.csp.discount.RespectNetworkMembershipDiscountCode;
import net.respectnetwork.sdk.csp.exception.CSPRegistrationException;
import net.respectnetwork.sdk.csp.payment.PaymentProcessingException;
import net.respectnetwork.sdk.csp.payment.PaymentProcessor;
import net.respectnetwork.sdk.csp.payment.PaymentStatusCode;
import net.respectnetwork.sdk.csp.validation.CSPValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import xdi2.client.exceptions.Xdi2ClientException;
import xdi2.core.xri3.CloudName;
import xdi2.core.xri3.CloudNumber;
import xdi2.core.xri3.XDI3Segment;
import xdi2.discovery.XDIDiscoveryClient;
import xdi2.discovery.XDIDiscoveryResult;
public class RegistrationManager {
/** Class Logger */
private static final Logger logger = LoggerFactory
.getLogger(RegistrationManager.class);
/**
* Class for Registering User in the Respect Network
*/
private CSP cspRegistrar;
/**
* Used for validating User details.
*/
private UserValidator userValidator;
/**
* Used for processingPayment.
*/
private PaymentProcessor paymentProcesser;
/**
* Charge for Registration
*/
private String registrationAmount;
/**
* Registration Currency
*/
private String registrationCurrencyCode;
/**
* Registration Discount Code
*/
public static CloudNameDiscountCode cloudNameDiscountCode = CloudNameDiscountCode.RespectFirst;
/**
* Dependent Cloud Discount Code
*/
public static CloudNameDiscountCode depCloudNameDiscountCode = CloudNameDiscountCode.OnePersonOneName;
/** RN Discount Code */
public static RespectNetworkMembershipDiscountCode respectNetworkMembershipDiscountCode = RespectNetworkMembershipDiscountCode.IIW17;
/** Personal Cloud EndPoint */
private String personalCloudEndPoint;
/** Debug Mode: Require Uniqueness in the eMail/SMS */
private boolean requireUniqueness = true;
/** Debug Mode: Send eMail/SMS as part of validation */
private boolean sendMailAndSMS = true;
/** Debug Mode: Require Codes to be validate to proceed with registration */
private boolean validateCodes = true;
/** Controls whether an invite code is required for registration or not */
private boolean requireInviteCode = true;
/**
* CSP phone
*/
private String cspContactPhone;
/**
* CSP email
*/
private String cspContactEmail;
private String cspHomeURL;
private static String cspInviteURL;
private String cspRespectConnectBaseURL;
private static String latLongPostURL ;
private static String postRegistrationURL ;
private String cspTCURL;
public static final String GeoLocationPostURIKey = "<$https><#network.globe><$set>";
public static final String RNpostRegistrationLandingPageURIKey = "<$https><#post><#registration>";
public static final String CSPCloudRegistrationURIKey = "<$https><#registration>";
public static final String CSPDependentCloudRegistrationURIKey = "<$https><#dependent><#registration>";
public static final String CSPGiftCardPurchaseURIKey = "<$https><#giftcard><#registration>";
public static final String CloudNameRegEx = "^=[a-z\\d]+((.|-)[a-z\\d]+)*$";
/**
* Get CSP Registrar
* @return
*/
public CSP getCspRegistrar() {
return cspRegistrar;
}
/**
* Set CSP Registrar
* @param cspRegistrar
*/
public void setCspRegistrar(CSP cspRegistrar) {
this.cspRegistrar = cspRegistrar;
}
/**
* Get User Validaor
* @return
*/
public UserValidator getUserValidator() {
return userValidator;
}
/**
* Set User Validator
* @param userValidator
*/
public void setUserValidator(UserValidator userValidator) {
this.userValidator = userValidator;
}
/**
* @return the paymentProcesser
*/
public PaymentProcessor getPaymentProcesser() {
return paymentProcesser;
}
/**
* @param paymentProcesser the paymentProcesser to set
*/
public void setPaymentProcesser(PaymentProcessor paymentProcesser) {
this.paymentProcesser = paymentProcesser;
}
/**
* @return the registrationAmount
*/
public String getRegistrationAmount() {
return registrationAmount;
}
/**
* @param registrationAmount the registrationAmount to set
*/
public void setRegistrationAmount(String registrationAmount) {
this.registrationAmount = registrationAmount;
}
/**
* @return the registrationCurrencyCode
*/
public String getRegistrationCurrencyCode() {
return registrationCurrencyCode;
}
/**
* @param registrationCurrencyCode the registrationCurrencyCode to set
*/
public void setRegistrationCurrencyCode(String registrationCurrencyCode) {
this.registrationCurrencyCode = registrationCurrencyCode;
}
/**
* @return the runInTest
*/
public boolean isRequireUniqueness() {
return requireUniqueness;
}
/**
* @param runInTest the runInTest to set
*/
public void setRequireUniqueness(boolean requireUniqueness) {
this.requireUniqueness = requireUniqueness;
}
/**
* @return the personalCloudEndPoint
*/
public String getPersonalCloudEndPoint() {
return personalCloudEndPoint;
}
/**
* @param personalCloudEndPoint the personalCloudEndPoint to set
*/
@Required
public void setPersonalCloudEndPoint(String personalCloudEndPoint) {
this.personalCloudEndPoint = personalCloudEndPoint;
}
/**
* @return the sendMailAndSMS
*/
public boolean isSendMailAndSMS() {
return sendMailAndSMS;
}
/**
* @param sendMailAndSMS the sendMailAndSMS to set
*/
public void setSendMailAndSMS(boolean sendMailAndSMS) {
this.sendMailAndSMS = sendMailAndSMS;
}
/**
* @return the validateCodes
*/
public boolean isValidateCodes() {
return validateCodes;
}
/**
* @param validateCodes the validateCodes to set
*/
public void setValidateCodes(boolean validateCodes) {
this.validateCodes = validateCodes;
}
/**
* Constructor Used for Getting CSP Private Key
*/
public RegistrationManager(CSP cspRegistrar) {
this.cspRegistrar = cspRegistrar;
BasicCSPInformation theCSPInfo = (BasicCSPInformation)cspRegistrar.getCspInformation();
// Getting the CSP Private Key and Setting it in BasicCSPInformation.cspSignaturePrivateKey
try {
theCSPInfo.retrieveCspSignaturePrivateKey();
logger.debug("Private Key Algo. = {}", theCSPInfo.getCspSignaturePrivateKey().getAlgorithm() );
} catch (Exception e) {
logger.warn("Cannot get CSP Private Key", e.getMessage());
}
if ( theCSPInfo.getCspSignaturePrivateKey() != null) {
logger.debug("CSP Private Key Found: Setting setRnCspSecretToken = null");
theCSPInfo.setRnCspSecretToken(null);
}
//set the registration endpoints
//setEndpointURI(CSPCloudRegistrationURIKey, this.cspHomeURL + "/register");
//setEndpointURI(CSPDependentCloudRegistrationURIKey, this.cspHomeURL + "/dependent");
//setEndpointURI(CSPGiftCardPurchaseURIKey, this.cspHomeURL + "/invite");
postRegistrationURL = getEndpointURI(RegistrationManager.RNpostRegistrationLandingPageURIKey, theCSPInfo.getRnCloudNumber());
latLongPostURL = getEndpointURI(RegistrationManager.GeoLocationPostURIKey, theCSPInfo.getRnCloudNumber());
}
/**
* Check CloudName Availability
*
* @param cloudName
* @return
* @throws UserRegistrationException
*/
public boolean isCloudNameAvailable(String cloudName)
throws UserRegistrationException {
boolean availability = false;
try {
if (cspRegistrar.checkCloudNameAvailableInRN(CloudName.create(cloudName)) == null) {
availability = true;
}
} catch (Exception e) {
String error = "Problem checking Clould Number Avaliability: {} " + e.getMessage();
logger.warn(error);
throw new UserRegistrationException(error);
}
return availability;
}
/**
* Check Email and Mobile Phone Number Uniqueness
*
* @param email
* @param mobilePhone
* @return
* @throws UserRegistrationException
*/
public CloudNumber[] checkEmailAndMobilePhoneUniqueness(String email, String mobilePhone)
throws UserRegistrationException {
try {
CloudNumber[] existingCloudNumbers = cspRegistrar.checkPhoneAndEmailAvailableInRN(email, mobilePhone);
if (!requireUniqueness) {
logger.warn("Overriding eMail/SMS uniqueness check.");
existingCloudNumbers = new CloudNumber[2];
}
return existingCloudNumbers;
} catch (Xdi2ClientException e) {
logger.debug("Problem checking Phone/eMail Uniqueness");
throw new UserRegistrationException("Problem checking Phone/eMail Uniqueness: " + e.getMessage());
}
}
/**
* Validate Confirmation Codes
*
* @param cloudNumber
* @param emailCode
* @param smsCode
* @return
*/
public boolean validateCodes(String sessionIdentifier, String emailCode, String smsCode) {
boolean validated = false;
try {
if (validateCodes) {
logger.debug("Validating codes: validateCodes = true ");
validated = userValidator.validateCodes(sessionIdentifier, emailCode, smsCode);
} else {
logger.debug("Not Validating codes: validateCodes = false");
validated = true;
}
} catch (CSPValidationException e) {
logger.warn("Problem Validating SMS and/or Email Codes: {}", e.getMessage());
validated = false;
}
return validated;
}
/**
* Process Payment
*
* @param cardNumber
* @param cvv
* @param expMonth
* @param expYear
* @param amount
* @param currency
* @return
*/
public PaymentStatusCode processPayment(String cardNumber, String cvv, String expMonth, String expYear) {
BigDecimal amount = new BigDecimal(registrationAmount);
Currency currency = Currency.getInstance(registrationCurrencyCode);
PaymentStatusCode returnCode = null;
try {
returnCode = paymentProcesser.processPayment(cardNumber, cvv, expMonth, expYear, amount, currency);
} catch (PaymentProcessingException e) {
returnCode = PaymentStatusCode.FAILURE;
}
return returnCode;
}
/**
* Send Validation Codes
*
* @param sessionId
* @param email
* @param mobilePhone
* @throws CSPValidationException
*/
public void sendValidationCodes(String sessionId, String email, String mobilePhone)
throws CSPValidationException{
if (sendMailAndSMS) {
logger.debug("Not sending Validation messages: sendMailAndSMS = true ");
userValidator.sendValidationMessages(sessionId, email, mobilePhone);
} else {
logger.debug("Not sending Validation messages: sendMailAndSMS = false ");
}
}
public CloudNumber registerUser(CloudName cloudName, String verifiedPhone, String verifiedEmail, String userPassword , CloudNameDiscountCode cdc) throws CSPRegistrationException, Xdi2ClientException {
CloudNumber cloudNumber = CloudNumber.createRandom(cloudName.getCs());
if(cloudNumber != null)
{
RegisterUserThread rut = new RegisterUserThread();
rut.setCloudName(cloudName);
rut.setCloudNumber(cloudNumber);
rut.setCspRegistrar(cspRegistrar);
rut.setRcBaseURL(this.getCspRespectConnectBaseURL());
rut.setUserPassword(userPassword);
rut.setVerifiedEmail(verifiedEmail);
rut.setVerifiedPhone(verifiedPhone);
rut.setCdc(cdc);
Thread t = new Thread(rut);
t.start();
/*
// Step 1: Register Cloud with Cloud Number and Shared Secret
String cspSecretToken = cspRegistrar.getCspInformation().getCspSecretToken();
cspRegistrar.registerCloudInCSP(cloudNumber, cspSecretToken);
// step 2: Set Cloud Services in Cloud
Map<XDI3Segment, String> services = new HashMap<XDI3Segment, String> ();
try {
services.put(XDI3Segment.create("<$https><$connect><$xdi>"), this.getCspRespectConnectBaseURL() +
URLEncoder.encode(cloudNumber.toString(), "UTF-8") + "/connect/request");
} catch (UnsupportedEncodingException e) {
throw new CSPRegistrationException(e);
}
cspRegistrar.setCloudServicesInCloud(cloudNumber, cspSecretToken, services);
// step 3: Check if the Cloud Name is available
CloudNumber existingCloudNumber = cspRegistrar.checkCloudNameAvailableInRN(cloudName);
if (existingCloudNumber != null) {
throw new CSPRegistrationException("Cloud Name " + cloudName + " is already registered with Cloud Number " + existingCloudNumber + ".");
}
// step 5: Register Cloud Name
if(cdc != null)
{
cspRegistrar.registerCloudNameInRN(cloudName, cloudNumber, verifiedPhone, verifiedEmail, cdc);
} else
{
cspRegistrar.registerCloudNameInRN(cloudName, cloudNumber, verifiedPhone, verifiedEmail, cloudNameDiscountCode);
}
cspRegistrar.registerCloudNameInCSP(cloudName, cloudNumber);
cspRegistrar.registerCloudNameInCloud(cloudName, cloudNumber, cspSecretToken);
// step 6: Set phone number and e-mail address
cspRegistrar.setPhoneAndEmailInCloud(cloudNumber, cspSecretToken, verifiedPhone, verifiedEmail);
// step 7: Set RN/RF membership
cspRegistrar.setRespectNetworkMembershipInRN(cloudNumber, new Date(), respectNetworkMembershipDiscountCode);
cspRegistrar.setRespectFirstMembershipInRN(cloudNumber);
// Step 8: Change Secret Token
cspRegistrar.setCloudSecretTokenInCSP(cloudNumber, userPassword);
//Step 9 : save the email and phone in local DB
DAOFactory dao = DAOFactory.getInstance();
SignupInfoModel signupInfo = new SignupInfoModel();
signupInfo.setCloudName(cloudName.toString());
signupInfo.setEmail(verifiedEmail);
signupInfo.setPhone(verifiedPhone);
try
{
dao.getSignupInfoDAO().insert(signupInfo);
} catch (DAOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
return cloudNumber;
}
public boolean isRequireInviteCode() {
return requireInviteCode;
}
public void setRequireInviteCode(boolean requireInviteCode) {
this.requireInviteCode = requireInviteCode;
}
public CloudNumber registerDependent(CloudName guardianCloudName , String guardianToken , CloudName dependentCloudName, String dependentToken , String s_dependentBirthDate){
CloudNumber depCloudNumber = CloudNumber.createRandom(dependentCloudName.getCs());
RegisterDependentCloudThread rdct = new RegisterDependentCloudThread();
rdct.setCspRegistrar(cspRegistrar);
rdct.setDepCloudNumber(depCloudNumber);
rdct.setDependentCloudName(dependentCloudName);
rdct.setDependentToken(dependentToken);
rdct.setGuardianCloudName(guardianCloudName);
rdct.setGuardianToken(guardianToken);
rdct.setRcBaseURL(this.getCspRespectConnectBaseURL());
rdct.setS_dependentBirthDate(s_dependentBirthDate);
Thread t = new Thread(rdct);
t.start();
/*
// Common Data
CloudNumber guardianCloudNumber = null;
CloudNumber dependentCloudNumber = null;
PrivateKey guardianPrivateKey = null;
PrivateKey dependentPrivateKey = null;
boolean withConsent = true;
Date dependentBirthDate = null;
BasicCSPInformation cspInformation = (BasicCSPInformation)cspRegistrar.getCspInformation();
// Resolve Cloud Numbers from Name
XDIDiscoveryClient discovery = cspInformation.getXdiDiscoveryClient();
try {
SimpleDateFormat format =
new SimpleDateFormat("MM/dd/yyyy");
dependentBirthDate = format.parse(s_dependentBirthDate);
} catch (ParseException e) {
logger.debug("Invalid Dependent BirthDate.");
return null;
}
for (int tries = 0 ; tries < 5 ; tries++) {
try {
logger.debug("Waiting for five seconds to allow for the newly registered dependent name in discovery");
Thread.sleep(5000);
} catch (InterruptedException e1) {
}
try {
XDIDiscoveryResult guardianRegistry = discovery.discoverFromRegistry(
XDI3Segment.create(guardianCloudName.toString()), null);
XDIDiscoveryResult dependentRegistry = discovery.discoverFromRegistry(
XDI3Segment.create(dependentCloudName.toString()), null);
guardianCloudNumber = guardianRegistry.getCloudNumber();
dependentCloudNumber = dependentRegistry.getCloudNumber();
String guardianXdiEndpoint = guardianRegistry.getXdiEndpointUri();
String dependentXdiEndpoint = dependentRegistry.getXdiEndpointUri();
guardianPrivateKey = XDIClientUtil.retrieveSignaturePrivateKey(guardianCloudNumber, guardianXdiEndpoint, guardianToken);
logger.debug("GuardianPrivateKey Algo: " + guardianPrivateKey.getAlgorithm());
dependentPrivateKey = XDIClientUtil.retrieveSignaturePrivateKey(dependentCloudNumber, dependentXdiEndpoint, dependentToken);
logger.debug("DependentPrivateKey Algo: " + dependentPrivateKey.getAlgorithm());
if (guardianCloudNumber == null || dependentCloudNumber == null) {
logger.debug("Un-registered Cloud Name.");
continue;
}
break;
} catch (Xdi2ClientException e) {
logger.debug("Problem with Cloud Name Provided.");
e.printStackTrace();
logger.debug(e.getMessage());
continue;
} catch (GeneralSecurityException gse){
logger.debug("Problem retrieving signatures.");
gse.printStackTrace();
logger.debug(gse.getMessage());
continue;
}
}
if(guardianCloudNumber != null && dependentCloudNumber != null) {
try {
// Set User Cloud Data
cspRegistrar.setGuardianshipInCloud(cspInformation, guardianCloudNumber, dependentCloudNumber, dependentBirthDate, withConsent, guardianToken, guardianPrivateKey);
// Set CSP Cloud Data
cspRegistrar.setGuardianshipInCSP(cspInformation, guardianCloudNumber, dependentCloudNumber, dependentBirthDate, withConsent, guardianPrivateKey);
// Set MemberGraph Data
cspRegistrar.setGuardianshipInRN(cspInformation, guardianCloudNumber, dependentCloudNumber, dependentBirthDate, withConsent, guardianPrivateKey);
} catch (Xdi2ClientException e) {
logger.debug("Xdi2ClientException: " + e.getMessage());
e.printStackTrace();
}
}
*/
return depCloudNumber;
}
/**
* @param phone to set
*/
@Autowired
@Qualifier("cspContactPhone")
public void setCspContactPhone(String cspPhone) {
this.cspContactPhone = cspPhone;
}
/**
* @param email to set
*/
@Autowired
@Qualifier("cspContactEmail")
public void setCspContactEmail(String cspEmail) {
this.cspContactEmail = cspEmail;
}
public String getCSPContactInfo() {
return "Please contact the CSP at " + this.cspContactPhone + " or via email at " + this.cspContactEmail;
}
public String getCspHomeURL()
{
return cspHomeURL;
}
public void setCspHomeURL(String cspHomeURL)
{
this.cspHomeURL = cspHomeURL;
}
public static String getCspInviteURL()
{
return cspInviteURL;
}
public static void setCspInviteURL(String url)
{
cspInviteURL = url;
}
public String getEndpointURI(String key , CloudNumber cloudNumber)
{
logger.debug("getEndpointURI key=" + key + " , cloudNumber = " + cloudNumber.toString());
BasicCSPInformation cspInformation = (BasicCSPInformation)cspRegistrar.getCspInformation();
XDIDiscoveryClient discovery = cspInformation.getXdiDiscoveryClient();
discovery.setAuthorityCache(null);
try
{
XDI3Segment[] uriType = new XDI3Segment[1];
uriType[0] = XDI3Segment.create(key);
XDIDiscoveryResult discResult = discovery.discover(
XDI3Segment.create(cloudNumber.toString()), uriType);
//XDIDiscoveryResult discResult = discovery.discoverFromAuthority("https://mycloud-ote.neustar.biz/registry", cloudNumber, uriType);
Map<XDI3Segment,String> endpointURIs = discResult.getEndpointUris();
for (Map.Entry<XDI3Segment, String> epURI : endpointURIs.entrySet())
{
logger.debug("Looping ... Endpoint key = " + epURI.getKey().toString() + " ,value=" + epURI.getValue());
if(epURI.getKey().toString().equals(key))
{
logger.debug("Found match for Endpoint key = " + key);
return epURI.getValue();
}
}
} catch (Xdi2ClientException e)
{
logger.debug("Error in getEndpointURI " + e.getMessage());
}
logger.debug("Did not find match for Endpoint key = " + key);
return "";
}
public boolean setEndpointURI(String key , String endpointURI )
{
BasicCSPInformation cspInformation = (BasicCSPInformation)cspRegistrar.getCspInformation();
Map<XDI3Segment,String> endpointURIMap = new HashMap<XDI3Segment,String>();
endpointURIMap.put(XDI3Segment.create(key), endpointURI);
try
{
cspRegistrar.setCloudServicesForCSPInCSP(cspInformation.getCspCloudNumber(), cspInformation.getCspSecretToken(), cspInformation.getCspRegistryXdiEndpoint(), endpointURIMap);
} catch (Xdi2ClientException e)
{
e.printStackTrace();
return false;
}
return true;
}
public String getCspRespectConnectBaseURL()
{
return cspRespectConnectBaseURL;
}
public void setCspRespectConnectBaseURL(String cspRespectConnectBaseURL)
{
this.cspRespectConnectBaseURL = cspRespectConnectBaseURL;
}
public static String getLatLongPostURL()
{
return latLongPostURL;
}
public static void setLatLongPostURL(String latLongPostURL)
{
RegistrationManager.latLongPostURL = latLongPostURL;
}
public static String getPostRegistrationURL()
{
return postRegistrationURL;
}
public static void setPostRegistrationURL(String postRegistrationURL)
{
RegistrationManager.postRegistrationURL = postRegistrationURL;
}
public String getCspTCURL()
{
return cspTCURL;
}
public void setCspTCURL(String cspTCURL)
{
this.cspTCURL = cspTCURL;
}
public static boolean validateCloudName(String cloudName) {
if(cloudName == null || cloudName.isEmpty())
{
return false;
}
Pattern pattern = Pattern.compile(CloudNameRegEx);
Matcher matcher = pattern.matcher(cloudName);
if (matcher.find()) {
return true;
} else {
return false;
}
}
public static boolean validatePhoneNumber(String phone)
{
if(phone == null || phone.isEmpty())
{
return false;
}
if(!phone.startsWith("+"))
{
return false;
}
for(int i = 0 ; i < phone.length() ; i++)
{
if(phone.charAt(i) == '.')
{
continue;
}
if(phone.charAt(i) < '0' || phone.charAt(i) > '9' )
{
return false;
}
}
return true;
}
}
| src/main/java/net/respectnetwork/csp/application/manager/RegistrationManager.java | package net.respectnetwork.csp.application.manager;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.respectnetwork.csp.application.exception.UserRegistrationException;
import net.respectnetwork.sdk.csp.BasicCSPInformation;
import net.respectnetwork.sdk.csp.CSP;
import net.respectnetwork.sdk.csp.UserValidator;
import net.respectnetwork.sdk.csp.discount.CloudNameDiscountCode;
import net.respectnetwork.sdk.csp.discount.RespectNetworkMembershipDiscountCode;
import net.respectnetwork.sdk.csp.exception.CSPRegistrationException;
import net.respectnetwork.sdk.csp.payment.PaymentProcessingException;
import net.respectnetwork.sdk.csp.payment.PaymentProcessor;
import net.respectnetwork.sdk.csp.payment.PaymentStatusCode;
import net.respectnetwork.sdk.csp.validation.CSPValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import xdi2.client.exceptions.Xdi2ClientException;
import xdi2.core.xri3.CloudName;
import xdi2.core.xri3.CloudNumber;
import xdi2.core.xri3.XDI3Segment;
import xdi2.discovery.XDIDiscoveryClient;
import xdi2.discovery.XDIDiscoveryResult;
public class RegistrationManager {
/** Class Logger */
private static final Logger logger = LoggerFactory
.getLogger(RegistrationManager.class);
/**
* Class for Registering User in the Respect Network
*/
private CSP cspRegistrar;
/**
* Used for validating User details.
*/
private UserValidator userValidator;
/**
* Used for processingPayment.
*/
private PaymentProcessor paymentProcesser;
/**
* Charge for Registration
*/
private String registrationAmount;
/**
* Registration Currency
*/
private String registrationCurrencyCode;
/**
* Registration Discount Code
*/
public static CloudNameDiscountCode cloudNameDiscountCode = CloudNameDiscountCode.RespectFirst;
/**
* Dependent Cloud Discount Code
*/
public static CloudNameDiscountCode depCloudNameDiscountCode = CloudNameDiscountCode.OnePersonOneName;
/** RN Discount Code */
public static RespectNetworkMembershipDiscountCode respectNetworkMembershipDiscountCode = RespectNetworkMembershipDiscountCode.IIW17;
/** Personal Cloud EndPoint */
private String personalCloudEndPoint;
/** Debug Mode: Require Uniqueness in the eMail/SMS */
private boolean requireUniqueness = true;
/** Debug Mode: Send eMail/SMS as part of validation */
private boolean sendMailAndSMS = true;
/** Debug Mode: Require Codes to be validate to proceed with registration */
private boolean validateCodes = true;
/** Controls whether an invite code is required for registration or not */
private boolean requireInviteCode = true;
/**
* CSP phone
*/
private String cspContactPhone;
/**
* CSP email
*/
private String cspContactEmail;
private String cspHomeURL;
private static String cspInviteURL;
private String cspRespectConnectBaseURL;
private static String latLongPostURL ;
private static String postRegistrationURL ;
private String cspTCURL;
public static final String GeoLocationPostURIKey = "<$https><#network.globe><$set>";
public static final String RNpostRegistrationLandingPageURIKey = "<$https><#post><#registration>";
public static final String CSPCloudRegistrationURIKey = "<$https><#registration>";
public static final String CSPDependentCloudRegistrationURIKey = "<$https><#dependent><#registration>";
public static final String CSPGiftCardPurchaseURIKey = "<$https><#giftcard><#registration>";
public static final String CloudNameRegEx = "^=[a-z\\d]+((.|-)[a-z\\d]+)*$";
/**
* Get CSP Registrar
* @return
*/
public CSP getCspRegistrar() {
return cspRegistrar;
}
/**
* Set CSP Registrar
* @param cspRegistrar
*/
public void setCspRegistrar(CSP cspRegistrar) {
this.cspRegistrar = cspRegistrar;
}
/**
* Get User Validaor
* @return
*/
public UserValidator getUserValidator() {
return userValidator;
}
/**
* Set User Validator
* @param userValidator
*/
public void setUserValidator(UserValidator userValidator) {
this.userValidator = userValidator;
}
/**
* @return the paymentProcesser
*/
public PaymentProcessor getPaymentProcesser() {
return paymentProcesser;
}
/**
* @param paymentProcesser the paymentProcesser to set
*/
public void setPaymentProcesser(PaymentProcessor paymentProcesser) {
this.paymentProcesser = paymentProcesser;
}
/**
* @return the registrationAmount
*/
public String getRegistrationAmount() {
return registrationAmount;
}
/**
* @param registrationAmount the registrationAmount to set
*/
public void setRegistrationAmount(String registrationAmount) {
this.registrationAmount = registrationAmount;
}
/**
* @return the registrationCurrencyCode
*/
public String getRegistrationCurrencyCode() {
return registrationCurrencyCode;
}
/**
* @param registrationCurrencyCode the registrationCurrencyCode to set
*/
public void setRegistrationCurrencyCode(String registrationCurrencyCode) {
this.registrationCurrencyCode = registrationCurrencyCode;
}
/**
* @return the runInTest
*/
public boolean isRequireUniqueness() {
return requireUniqueness;
}
/**
* @param runInTest the runInTest to set
*/
public void setRequireUniqueness(boolean requireUniqueness) {
this.requireUniqueness = requireUniqueness;
}
/**
* @return the personalCloudEndPoint
*/
public String getPersonalCloudEndPoint() {
return personalCloudEndPoint;
}
/**
* @param personalCloudEndPoint the personalCloudEndPoint to set
*/
@Required
public void setPersonalCloudEndPoint(String personalCloudEndPoint) {
this.personalCloudEndPoint = personalCloudEndPoint;
}
/**
* @return the sendMailAndSMS
*/
public boolean isSendMailAndSMS() {
return sendMailAndSMS;
}
/**
* @param sendMailAndSMS the sendMailAndSMS to set
*/
public void setSendMailAndSMS(boolean sendMailAndSMS) {
this.sendMailAndSMS = sendMailAndSMS;
}
/**
* @return the validateCodes
*/
public boolean isValidateCodes() {
return validateCodes;
}
/**
* @param validateCodes the validateCodes to set
*/
public void setValidateCodes(boolean validateCodes) {
this.validateCodes = validateCodes;
}
/**
* Constructor Used for Getting CSP Private Key
*/
public RegistrationManager(CSP cspRegistrar) {
this.cspRegistrar = cspRegistrar;
BasicCSPInformation theCSPInfo = (BasicCSPInformation)cspRegistrar.getCspInformation();
// Getting the CSP Private Key and Setting it in BasicCSPInformation.cspSignaturePrivateKey
try {
theCSPInfo.retrieveCspSignaturePrivateKey();
logger.debug("Private Key Algo. = {}", theCSPInfo.getCspSignaturePrivateKey().getAlgorithm() );
} catch (Exception e) {
logger.warn("Cannot get CSP Private Key", e.getMessage());
}
if ( theCSPInfo.getCspSignaturePrivateKey() != null) {
logger.debug("CSP Private Key Found: Setting setRnCspSecretToken = null");
theCSPInfo.setRnCspSecretToken(null);
}
//set the registration endpoints
//setEndpointURI(CSPCloudRegistrationURIKey, this.cspHomeURL + "/register");
//setEndpointURI(CSPDependentCloudRegistrationURIKey, this.cspHomeURL + "/dependent");
//setEndpointURI(CSPGiftCardPurchaseURIKey, this.cspHomeURL + "/invite");
postRegistrationURL = getEndpointURI(RegistrationManager.RNpostRegistrationLandingPageURIKey, theCSPInfo.getRnCloudNumber());
latLongPostURL = getEndpointURI(RegistrationManager.GeoLocationPostURIKey, theCSPInfo.getRnCloudNumber());
}
/**
* Check CloudName Availability
*
* @param cloudName
* @return
* @throws UserRegistrationException
*/
public boolean isCloudNameAvailable(String cloudName)
throws UserRegistrationException {
boolean availability = false;
try {
if (cspRegistrar.checkCloudNameAvailableInRN(CloudName.create(cloudName)) == null) {
availability = true;
}
} catch (Exception e) {
String error = "Problem checking Clould Number Avaliability: {} " + e.getMessage();
logger.warn(error);
throw new UserRegistrationException(error);
}
return availability;
}
/**
* Check Email and Mobile Phone Number Uniqueness
*
* @param email
* @param mobilePhone
* @return
* @throws UserRegistrationException
*/
public CloudNumber[] checkEmailAndMobilePhoneUniqueness(String email, String mobilePhone)
throws UserRegistrationException {
try {
CloudNumber[] existingCloudNumbers = cspRegistrar.checkPhoneAndEmailAvailableInRN(email, mobilePhone);
if (!requireUniqueness) {
logger.warn("Overriding eMail/SMS uniqueness check.");
existingCloudNumbers = new CloudNumber[2];
}
return existingCloudNumbers;
} catch (Xdi2ClientException e) {
logger.debug("Problem checking Phone/eMail Uniqueness");
throw new UserRegistrationException("Problem checking Phone/eMail Uniqueness: " + e.getMessage());
}
}
/**
* Validate Confirmation Codes
*
* @param cloudNumber
* @param emailCode
* @param smsCode
* @return
*/
public boolean validateCodes(String sessionIdentifier, String emailCode, String smsCode) {
boolean validated = false;
try {
if (validateCodes) {
logger.debug("Validating codes: validateCodes = true ");
validated = userValidator.validateCodes(sessionIdentifier, emailCode, smsCode);
} else {
logger.debug("Not Validating codes: validateCodes = false");
validated = true;
}
} catch (CSPValidationException e) {
logger.warn("Problem Validating SMS and/or Email Codes: {}", e.getMessage());
validated = false;
}
return validated;
}
/**
* Process Payment
*
* @param cardNumber
* @param cvv
* @param expMonth
* @param expYear
* @param amount
* @param currency
* @return
*/
public PaymentStatusCode processPayment(String cardNumber, String cvv, String expMonth, String expYear) {
BigDecimal amount = new BigDecimal(registrationAmount);
Currency currency = Currency.getInstance(registrationCurrencyCode);
PaymentStatusCode returnCode = null;
try {
returnCode = paymentProcesser.processPayment(cardNumber, cvv, expMonth, expYear, amount, currency);
} catch (PaymentProcessingException e) {
returnCode = PaymentStatusCode.FAILURE;
}
return returnCode;
}
/**
* Send Validation Codes
*
* @param sessionId
* @param email
* @param mobilePhone
* @throws CSPValidationException
*/
public void sendValidationCodes(String sessionId, String email, String mobilePhone)
throws CSPValidationException{
if (sendMailAndSMS) {
logger.debug("Not sending Validation messages: sendMailAndSMS = true ");
userValidator.sendValidationMessages(sessionId, email, mobilePhone);
} else {
logger.debug("Not sending Validation messages: sendMailAndSMS = false ");
}
}
public CloudNumber registerUser(CloudName cloudName, String verifiedPhone, String verifiedEmail, String userPassword , CloudNameDiscountCode cdc) throws CSPRegistrationException, Xdi2ClientException {
CloudNumber cloudNumber = CloudNumber.createRandom(cloudName.getCs());
if(cloudNumber != null)
{
RegisterUserThread rut = new RegisterUserThread();
rut.setCloudName(cloudName);
rut.setCloudNumber(cloudNumber);
rut.setCspRegistrar(cspRegistrar);
rut.setRcBaseURL(this.getCspRespectConnectBaseURL());
rut.setUserPassword(userPassword);
rut.setVerifiedEmail(verifiedEmail);
rut.setVerifiedPhone(verifiedPhone);
rut.setCdc(cdc);
Thread t = new Thread(rut);
t.start();
/*
// Step 1: Register Cloud with Cloud Number and Shared Secret
String cspSecretToken = cspRegistrar.getCspInformation().getCspSecretToken();
cspRegistrar.registerCloudInCSP(cloudNumber, cspSecretToken);
// step 2: Set Cloud Services in Cloud
Map<XDI3Segment, String> services = new HashMap<XDI3Segment, String> ();
try {
services.put(XDI3Segment.create("<$https><$connect><$xdi>"), this.getCspRespectConnectBaseURL() +
URLEncoder.encode(cloudNumber.toString(), "UTF-8") + "/connect/request");
} catch (UnsupportedEncodingException e) {
throw new CSPRegistrationException(e);
}
cspRegistrar.setCloudServicesInCloud(cloudNumber, cspSecretToken, services);
// step 3: Check if the Cloud Name is available
CloudNumber existingCloudNumber = cspRegistrar.checkCloudNameAvailableInRN(cloudName);
if (existingCloudNumber != null) {
throw new CSPRegistrationException("Cloud Name " + cloudName + " is already registered with Cloud Number " + existingCloudNumber + ".");
}
// step 5: Register Cloud Name
if(cdc != null)
{
cspRegistrar.registerCloudNameInRN(cloudName, cloudNumber, verifiedPhone, verifiedEmail, cdc);
} else
{
cspRegistrar.registerCloudNameInRN(cloudName, cloudNumber, verifiedPhone, verifiedEmail, cloudNameDiscountCode);
}
cspRegistrar.registerCloudNameInCSP(cloudName, cloudNumber);
cspRegistrar.registerCloudNameInCloud(cloudName, cloudNumber, cspSecretToken);
// step 6: Set phone number and e-mail address
cspRegistrar.setPhoneAndEmailInCloud(cloudNumber, cspSecretToken, verifiedPhone, verifiedEmail);
// step 7: Set RN/RF membership
cspRegistrar.setRespectNetworkMembershipInRN(cloudNumber, new Date(), respectNetworkMembershipDiscountCode);
cspRegistrar.setRespectFirstMembershipInRN(cloudNumber);
// Step 8: Change Secret Token
cspRegistrar.setCloudSecretTokenInCSP(cloudNumber, userPassword);
//Step 9 : save the email and phone in local DB
DAOFactory dao = DAOFactory.getInstance();
SignupInfoModel signupInfo = new SignupInfoModel();
signupInfo.setCloudName(cloudName.toString());
signupInfo.setEmail(verifiedEmail);
signupInfo.setPhone(verifiedPhone);
try
{
dao.getSignupInfoDAO().insert(signupInfo);
} catch (DAOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
return cloudNumber;
}
public boolean isRequireInviteCode() {
return requireInviteCode;
}
public void setRequireInviteCode(boolean requireInviteCode) {
this.requireInviteCode = requireInviteCode;
}
public CloudNumber registerDependent(CloudName guardianCloudName , String guardianToken , CloudName dependentCloudName, String dependentToken , String s_dependentBirthDate){
CloudNumber depCloudNumber = CloudNumber.createRandom(dependentCloudName.getCs());
RegisterDependentCloudThread rdct = new RegisterDependentCloudThread();
rdct.setCspRegistrar(cspRegistrar);
rdct.setDepCloudNumber(depCloudNumber);
rdct.setDependentCloudName(dependentCloudName);
rdct.setDependentToken(dependentToken);
rdct.setGuardianCloudName(guardianCloudName);
rdct.setGuardianToken(guardianToken);
rdct.setRcBaseURL(this.getCspRespectConnectBaseURL());
rdct.setS_dependentBirthDate(s_dependentBirthDate);
Thread t = new Thread(rdct);
t.start();
/*
// Common Data
CloudNumber guardianCloudNumber = null;
CloudNumber dependentCloudNumber = null;
PrivateKey guardianPrivateKey = null;
PrivateKey dependentPrivateKey = null;
boolean withConsent = true;
Date dependentBirthDate = null;
BasicCSPInformation cspInformation = (BasicCSPInformation)cspRegistrar.getCspInformation();
// Resolve Cloud Numbers from Name
XDIDiscoveryClient discovery = cspInformation.getXdiDiscoveryClient();
try {
SimpleDateFormat format =
new SimpleDateFormat("MM/dd/yyyy");
dependentBirthDate = format.parse(s_dependentBirthDate);
} catch (ParseException e) {
logger.debug("Invalid Dependent BirthDate.");
return null;
}
for (int tries = 0 ; tries < 5 ; tries++) {
try {
logger.debug("Waiting for five seconds to allow for the newly registered dependent name in discovery");
Thread.sleep(5000);
} catch (InterruptedException e1) {
}
try {
XDIDiscoveryResult guardianRegistry = discovery.discoverFromRegistry(
XDI3Segment.create(guardianCloudName.toString()), null);
XDIDiscoveryResult dependentRegistry = discovery.discoverFromRegistry(
XDI3Segment.create(dependentCloudName.toString()), null);
guardianCloudNumber = guardianRegistry.getCloudNumber();
dependentCloudNumber = dependentRegistry.getCloudNumber();
String guardianXdiEndpoint = guardianRegistry.getXdiEndpointUri();
String dependentXdiEndpoint = dependentRegistry.getXdiEndpointUri();
guardianPrivateKey = XDIClientUtil.retrieveSignaturePrivateKey(guardianCloudNumber, guardianXdiEndpoint, guardianToken);
logger.debug("GuardianPrivateKey Algo: " + guardianPrivateKey.getAlgorithm());
dependentPrivateKey = XDIClientUtil.retrieveSignaturePrivateKey(dependentCloudNumber, dependentXdiEndpoint, dependentToken);
logger.debug("DependentPrivateKey Algo: " + dependentPrivateKey.getAlgorithm());
if (guardianCloudNumber == null || dependentCloudNumber == null) {
logger.debug("Un-registered Cloud Name.");
continue;
}
break;
} catch (Xdi2ClientException e) {
logger.debug("Problem with Cloud Name Provided.");
e.printStackTrace();
logger.debug(e.getMessage());
continue;
} catch (GeneralSecurityException gse){
logger.debug("Problem retrieving signatures.");
gse.printStackTrace();
logger.debug(gse.getMessage());
continue;
}
}
if(guardianCloudNumber != null && dependentCloudNumber != null) {
try {
// Set User Cloud Data
cspRegistrar.setGuardianshipInCloud(cspInformation, guardianCloudNumber, dependentCloudNumber, dependentBirthDate, withConsent, guardianToken, guardianPrivateKey);
// Set CSP Cloud Data
cspRegistrar.setGuardianshipInCSP(cspInformation, guardianCloudNumber, dependentCloudNumber, dependentBirthDate, withConsent, guardianPrivateKey);
// Set MemberGraph Data
cspRegistrar.setGuardianshipInRN(cspInformation, guardianCloudNumber, dependentCloudNumber, dependentBirthDate, withConsent, guardianPrivateKey);
} catch (Xdi2ClientException e) {
logger.debug("Xdi2ClientException: " + e.getMessage());
e.printStackTrace();
}
}
*/
return depCloudNumber;
}
/**
* @param phone to set
*/
@Autowired
@Qualifier("cspContactPhone")
public void setCspContactPhone(String cspPhone) {
this.cspContactPhone = cspPhone;
}
/**
* @param email to set
*/
@Autowired
@Qualifier("cspContactEmail")
public void setCspContactEmail(String cspEmail) {
this.cspContactEmail = cspEmail;
}
public String getCSPContactInfo() {
return "Please contact the CSP at " + this.cspContactPhone + " or via email at " + this.cspContactEmail;
}
public String getCspHomeURL()
{
return cspHomeURL;
}
public void setCspHomeURL(String cspHomeURL)
{
this.cspHomeURL = cspHomeURL;
}
public static String getCspInviteURL()
{
return cspInviteURL;
}
public static void setCspInviteURL(String url)
{
cspInviteURL = url;
}
public String getEndpointURI(String key , CloudNumber cloudNumber)
{
logger.debug("getEndpointURI key=" + key + " , cloudNumber = " + cloudNumber.toString());
BasicCSPInformation cspInformation = (BasicCSPInformation)cspRegistrar.getCspInformation();
XDIDiscoveryClient discovery = cspInformation.getXdiDiscoveryClient();
discovery.setAuthorityCache(null);
try
{
XDI3Segment[] uriType = new XDI3Segment[1];
uriType[0] = XDI3Segment.create(key);
XDIDiscoveryResult discResult = discovery.discover(
XDI3Segment.create(cloudNumber.toString()), uriType);
//XDIDiscoveryResult discResult = discovery.discoverFromAuthority("https://mycloud-ote.neustar.biz/registry", cloudNumber, uriType);
Map<XDI3Segment,String> endpointURIs = discResult.getEndpointUris();
for (Map.Entry<XDI3Segment, String> epURI : endpointURIs.entrySet())
{
logger.debug("Looping ... Endpoint key = " + epURI.getKey().toString() + " ,value=" + epURI.getValue());
if(epURI.getKey().toString().equals(key))
{
logger.debug("Found match for Endpoint key = " + key);
return epURI.getValue();
}
}
} catch (Xdi2ClientException e)
{
logger.debug("Error in getEndpointURI " + e.getMessage());
}
logger.debug("Did not find match for Endpoint key = " + key);
return "";
}
public boolean setEndpointURI(String key , String endpointURI )
{
BasicCSPInformation cspInformation = (BasicCSPInformation)cspRegistrar.getCspInformation();
Map<XDI3Segment,String> endpointURIMap = new HashMap<XDI3Segment,String>();
endpointURIMap.put(XDI3Segment.create(key), endpointURI);
try
{
cspRegistrar.setCloudServicesForCSPInCSP(cspInformation.getCspCloudNumber(), cspInformation.getCspSecretToken(), cspInformation.getCspRegistryXdiEndpoint(), endpointURIMap);
} catch (Xdi2ClientException e)
{
e.printStackTrace();
return false;
}
return true;
}
public String getCspRespectConnectBaseURL()
{
return cspRespectConnectBaseURL;
}
public void setCspRespectConnectBaseURL(String cspRespectConnectBaseURL)
{
this.cspRespectConnectBaseURL = cspRespectConnectBaseURL;
}
public static String getLatLongPostURL()
{
return latLongPostURL;
}
public static void setLatLongPostURL(String latLongPostURL)
{
RegistrationManager.latLongPostURL = latLongPostURL;
}
public static String getPostRegistrationURL()
{
return postRegistrationURL;
}
public static void setPostRegistrationURL(String postRegistrationURL)
{
RegistrationManager.postRegistrationURL = postRegistrationURL;
}
public String getCspTCURL()
{
return cspTCURL;
}
public void setCspTCURL(String cspTCURL)
{
this.cspTCURL = cspTCURL;
}
public static boolean validateCloudName(String cloudName) {
if(cloudName == null || cloudName.isEmpty())
{
return false;
}
Pattern pattern = Pattern.compile(CloudNameRegEx);
Matcher matcher = pattern.matcher(cloudName);
if (matcher.find()) {
return true;
} else {
return false;
}
}
public static boolean validatePhoneNumber(String phone)
{
if(phone == null || phone.isEmpty())
{
return false;
}
for(int i = 0 ; i < phone.length() ; i++)
{
if(phone.charAt(i) != '+' || phone.charAt(i) != '.')
{
continue;
}
if(phone.charAt(i) < '0' || phone.charAt(i) > '9' )
{
return false;
}
}
return true;
}
}
| fixed check for phone number | src/main/java/net/respectnetwork/csp/application/manager/RegistrationManager.java | fixed check for phone number | <ide><path>rc/main/java/net/respectnetwork/csp/application/manager/RegistrationManager.java
<ide> {
<ide> return false;
<ide> }
<add> if(!phone.startsWith("+"))
<add> {
<add> return false;
<add> }
<add>
<ide> for(int i = 0 ; i < phone.length() ; i++)
<ide> {
<del> if(phone.charAt(i) != '+' || phone.charAt(i) != '.')
<add> if(phone.charAt(i) == '.')
<ide> {
<ide> continue;
<ide> } |
|
Java | agpl-3.0 | 7c8c8f21e5701efabb80503380cdc0c10098f962 | 0 | animotron/core,animotron/core | /*
* Copyright (C) 2011 The Animo Project
* http://animotron.org
*
* 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 Lesser 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.animotron.exist.index;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.animotron.Namespaces;
import org.exist.collections.Collection;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.ElementImpl;
import org.exist.dom.NewArrayNodeSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.dom.StoredNode;
import org.exist.indexing.AbstractStreamListener;
import org.exist.indexing.IndexController;
import org.exist.indexing.IndexWorker;
import org.exist.indexing.MatchListener;
import org.exist.indexing.OrderedValuesIndex;
import org.exist.indexing.QNamedKeysIndex;
import org.exist.indexing.StreamListener;
import org.exist.storage.DBBroker;
import org.exist.storage.NodePath;
import org.exist.storage.txn.Txn;
import org.exist.util.DatabaseConfigurationException;
import org.exist.util.Occurrences;
import org.exist.xquery.XQueryContext;
import org.w3c.dom.NodeList;
/**
* @author <a href="mailto:[email protected]">Dmitriy Shabanov</a>
*
*/
public class AnimoIndexWorker implements OrderedValuesIndex, QNamedKeysIndex {
private int mode = 0;
private DocumentImpl document = null;
private AnimoIndex index;
public AnimoIndexWorker(AnimoIndex index) {
this.index = index;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getIndexId()
*/
public String getIndexId() {
return AnimoIndex.ID;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getIndexName()
*/
public String getIndexName() {
return index.getIndexName();
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#configure(org.exist.indexing.IndexController, org.w3c.dom.NodeList, java.util.Map)
*/
public Object configure(IndexController controller, NodeList configNodes,
Map<String, String> namespaces)
throws DatabaseConfigurationException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#setDocument(org.exist.dom.DocumentImpl)
*/
public void setDocument(DocumentImpl doc) {
this.document = doc;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#setDocument(org.exist.dom.DocumentImpl, int)
*/
public void setDocument(DocumentImpl doc, int mode) {
this.document = doc;
this.mode = mode;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#setMode(int)
*/
public void setMode(int mode) {
this.mode = mode;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getDocument()
*/
public DocumentImpl getDocument() {
return document;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getMode()
*/
public int getMode() {
return mode;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getReindexRoot(org.exist.dom.StoredNode, org.exist.storage.NodePath, boolean)
*/
public StoredNode getReindexRoot(StoredNode node, NodePath path,
boolean includeSelf) {
// TODO Auto-generated method stub
return null;
}
private StreamListener listener = new AnimoStreamListener();
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getListener()
*/
public StreamListener getListener() {
return listener;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getMatchListener(org.exist.storage.DBBroker, org.exist.dom.NodeProxy)
*/
public MatchListener getMatchListener(DBBroker broker, NodeProxy proxy) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#flush()
*/
public void flush() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#removeCollection(org.exist.collections.Collection, org.exist.storage.DBBroker)
*/
public void removeCollection(Collection collection, DBBroker broker) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#checkIndex(org.exist.storage.DBBroker)
*/
public boolean checkIndex(DBBroker broker) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#scanIndex(org.exist.xquery.XQueryContext, org.exist.dom.DocumentSet, org.exist.dom.NodeSet, java.util.Map)
*/
public Occurrences[] scanIndex(XQueryContext context, DocumentSet docs, NodeSet contextSet, Map hints) {
// TODO Auto-generated method stub
return null;
}
//instance name -> reference
private Map<String, NodeProxy> names = new HashMap<String, NodeProxy>();
//TODO: make this map do the job
private Map<NodeProxy, String> ids = new HashMap<NodeProxy, String>();
private NodeProxy addNode(ElementImpl element) {
String name = element.getLocalName();
if (names.containsKey(name)) {
NodeProxy proxy = names.get(name);
if (proxy.getDocument() == index.unresolvedReferenceDocument) {
proxy.update(element);
}
return proxy;
} else {
NodeProxy proxy = new NodeProxy(element);
names.put(name, proxy);
return proxy;
}
}
private NodeProxy getOrCreateNode(String name) {
NodeProxy node = names.get(name);
if (node == null) {
node = new NodeProxy(
index.unresolvedReferenceDocument,
index.unresolvedReferenceId.newChild());
names.put(name, node);
}
return node;
}
private NodeProxy getNode(String name) {
return names.get(name);
}
public String getNodeName(NodeProxy id) {
return ids.get(id);
}
//instance -> is-relations nodes (down)
private Map<NodeProxy, Set<NodeProxy>> downIsRelations = new HashMap<NodeProxy, Set<NodeProxy>>();
//instance -> is-relations nodes (up)
private Map<NodeProxy, Set<NodeProxy>> upIsRelations = new HashMap<NodeProxy, Set<NodeProxy>>();
private void addIsRelationship(NodeProxy node, NodeProxy is) {
//record down relations
Set<NodeProxy> nodes = null;
if (downIsRelations.containsKey(is)) {
nodes = downIsRelations.get(is);
} else {
nodes = new HashSet<NodeProxy>();
downIsRelations.put(is, nodes);
}
nodes.add(node);
//record up relations
nodes = null;
if (upIsRelations.containsKey(node)) {
nodes = upIsRelations.get(node);
} else {
nodes = new HashSet<NodeProxy>();
upIsRelations.put(node, nodes);
}
nodes.add(is);
}
private class AnimoStreamListener extends AbstractStreamListener {
private NodeProxy currentNode;
@Override
public void startElement(Txn transaction, ElementImpl element, NodePath path) {
if (mode == STORE) {
if (Namespaces.THE.namespace().equals(element.getQName().getNamespaceURI())) {
currentNode = addNode(element);
} else if (Namespaces.IS.namespace().equals(element.getQName().getNamespaceURI())) {
addIsRelationship(currentNode, getOrCreateNode(element.getLocalName()));
}
}
super.startElement(transaction, element, path);
}
@Override
public IndexWorker getWorker() {
return AnimoIndexWorker.this;
}
}
public NodeSet resolveUpIsLogic(String name) {
NodeProxy node = getNode(name);
if (!upIsRelations.containsKey(node))
return NodeSet.EMPTY_SET;
NodeSet set = new NewArrayNodeSet(5);
resolveUpIsLogic(node, set);
return set;
}
private void resolveUpIsLogic(NodeProxy node, NodeSet set) {
if (!upIsRelations.containsKey(node))
return;
for (NodeProxy n : upIsRelations.get(node)) {
set.add(n);
resolveUpIsLogic(n, set);
}
}
public NodeSet resolveDownIsLogic(String name) {
NodeProxy node = getNode(name);
if (!downIsRelations.containsKey(node))
return NodeSet.EMPTY_SET;
NodeSet set = new NewArrayNodeSet(5);
resolveDownIsLogic(node, set);
return set;
}
private void resolveDownIsLogic(NodeProxy node, NodeSet set) {
if (!downIsRelations.containsKey(node))
return;
for (NodeProxy n : downIsRelations.get(node)) {
set.add(n);
resolveDownIsLogic(n, set);
}
}
}
| src/main/java/org/animotron/exist/index/AnimoIndexWorker.java | /*
* Copyright (C) 2011 The Animo Project
* http://animotron.org
*
* 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 Lesser 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.animotron.exist.index;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.animotron.Namespaces;
import org.exist.collections.Collection;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.ElementImpl;
import org.exist.dom.NewArrayNodeSet;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.dom.StoredNode;
import org.exist.indexing.AbstractStreamListener;
import org.exist.indexing.IndexController;
import org.exist.indexing.IndexWorker;
import org.exist.indexing.MatchListener;
import org.exist.indexing.OrderedValuesIndex;
import org.exist.indexing.QNamedKeysIndex;
import org.exist.indexing.StreamListener;
import org.exist.storage.DBBroker;
import org.exist.storage.NodePath;
import org.exist.storage.txn.Txn;
import org.exist.util.DatabaseConfigurationException;
import org.exist.util.Occurrences;
import org.exist.xquery.XQueryContext;
import org.w3c.dom.NodeList;
/**
* @author <a href="mailto:[email protected]">Dmitriy Shabanov</a>
*
*/
public class AnimoIndexWorker implements OrderedValuesIndex, QNamedKeysIndex {
private int mode = 0;
private DocumentImpl document = null;
private AnimoIndex index;
public AnimoIndexWorker(AnimoIndex index) {
this.index = index;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getIndexId()
*/
public String getIndexId() {
return AnimoIndex.ID;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getIndexName()
*/
public String getIndexName() {
return index.getIndexName();
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#configure(org.exist.indexing.IndexController, org.w3c.dom.NodeList, java.util.Map)
*/
public Object configure(IndexController controller, NodeList configNodes,
Map<String, String> namespaces)
throws DatabaseConfigurationException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#setDocument(org.exist.dom.DocumentImpl)
*/
public void setDocument(DocumentImpl doc) {
this.document = doc;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#setDocument(org.exist.dom.DocumentImpl, int)
*/
public void setDocument(DocumentImpl doc, int mode) {
this.document = doc;
this.mode = mode;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#setMode(int)
*/
public void setMode(int mode) {
this.mode = mode;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getDocument()
*/
public DocumentImpl getDocument() {
return document;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getMode()
*/
public int getMode() {
return mode;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getReindexRoot(org.exist.dom.StoredNode, org.exist.storage.NodePath, boolean)
*/
public StoredNode getReindexRoot(StoredNode node, NodePath path,
boolean includeSelf) {
// TODO Auto-generated method stub
return null;
}
private StreamListener listener = new AnimoStreamListener();
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getListener()
*/
public StreamListener getListener() {
return listener;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#getMatchListener(org.exist.storage.DBBroker, org.exist.dom.NodeProxy)
*/
public MatchListener getMatchListener(DBBroker broker, NodeProxy proxy) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#flush()
*/
public void flush() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#removeCollection(org.exist.collections.Collection, org.exist.storage.DBBroker)
*/
public void removeCollection(Collection collection, DBBroker broker) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#checkIndex(org.exist.storage.DBBroker)
*/
public boolean checkIndex(DBBroker broker) {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see org.exist.indexing.IndexWorker#scanIndex(org.exist.xquery.XQueryContext, org.exist.dom.DocumentSet, org.exist.dom.NodeSet, java.util.Map)
*/
public Occurrences[] scanIndex(XQueryContext context, DocumentSet docs, NodeSet contextSet, Map hints) {
// TODO Auto-generated method stub
return null;
}
//instance name -> reference
private Map<String, NodeProxy> names = new HashMap<String, NodeProxy>();
//TODO: make this map do the job
private Map<NodeProxy, String> ids = new HashMap<NodeProxy, String>();
private NodeProxy addNode(ElementImpl element) {
String name = element.getLocalName();
if (names.containsKey(name)) {
NodeProxy proxy = names.get(name);
if (proxy.getDocument() == index.unresolvedReferenceDocument) {
//proxy.update(element);
}
return proxy;
} else {
NodeProxy proxy = new NodeProxy(element);
names.put(name, proxy);
return proxy;
}
}
private NodeProxy getOrCreateNode(String name) {
NodeProxy node = names.get(name);
if (node == null) {
node = new NodeProxy(
index.unresolvedReferenceDocument,
index.unresolvedReferenceId.newChild());
names.put(name, node);
}
return node;
}
private NodeProxy getNode(String name) {
return names.get(name);
}
public String getNodeName(NodeProxy id) {
return ids.get(id);
}
//instance -> is-relations nodes (down)
private Map<NodeProxy, Set<NodeProxy>> downIsRelations = new HashMap<NodeProxy, Set<NodeProxy>>();
//instance -> is-relations nodes (up)
private Map<NodeProxy, Set<NodeProxy>> upIsRelations = new HashMap<NodeProxy, Set<NodeProxy>>();
private void addIsRelationship(NodeProxy node, NodeProxy is) {
//record down relations
Set<NodeProxy> nodes = null;
if (downIsRelations.containsKey(is)) {
nodes = downIsRelations.get(is);
} else {
nodes = new HashSet<NodeProxy>();
downIsRelations.put(is, nodes);
}
nodes.add(node);
//record up relations
nodes = null;
if (upIsRelations.containsKey(node)) {
nodes = upIsRelations.get(node);
} else {
nodes = new HashSet<NodeProxy>();
upIsRelations.put(node, nodes);
}
nodes.add(is);
}
private class AnimoStreamListener extends AbstractStreamListener {
private NodeProxy currentNode;
@Override
public void startElement(Txn transaction, ElementImpl element, NodePath path) {
if (mode == STORE) {
if (Namespaces.THE.namespace().equals(element.getQName().getNamespaceURI())) {
currentNode = addNode(element);
} else if (Namespaces.IS.namespace().equals(element.getQName().getNamespaceURI())) {
addIsRelationship(currentNode, getOrCreateNode(element.getLocalName()));
}
}
super.startElement(transaction, element, path);
}
@Override
public IndexWorker getWorker() {
return AnimoIndexWorker.this;
}
}
public NodeSet resolveUpIsLogic(String name) {
NodeProxy node = getNode(name);
if (!upIsRelations.containsKey(node))
return NodeSet.EMPTY_SET;
NodeSet set = new NewArrayNodeSet(5);
resolveUpIsLogic(node, set);
return set;
}
private void resolveUpIsLogic(NodeProxy node, NodeSet set) {
if (!upIsRelations.containsKey(node))
return;
for (NodeProxy n : upIsRelations.get(node)) {
set.add(n);
resolveUpIsLogic(n, set);
}
}
public NodeSet resolveDownIsLogic(String name) {
NodeProxy node = getNode(name);
if (!downIsRelations.containsKey(node))
return NodeSet.EMPTY_SET;
NodeSet set = new NewArrayNodeSet(5);
resolveDownIsLogic(node, set);
return set;
}
private void resolveDownIsLogic(NodeProxy node, NodeSet set) {
if (!downIsRelations.containsKey(node))
return;
for (NodeProxy n : downIsRelations.get(node)) {
set.add(n);
resolveDownIsLogic(n, set);
}
}
}
| return back nodeproxy.update() | src/main/java/org/animotron/exist/index/AnimoIndexWorker.java | return back nodeproxy.update() | <ide><path>rc/main/java/org/animotron/exist/index/AnimoIndexWorker.java
<ide> if (names.containsKey(name)) {
<ide> NodeProxy proxy = names.get(name);
<ide> if (proxy.getDocument() == index.unresolvedReferenceDocument) {
<del> //proxy.update(element);
<add> proxy.update(element);
<ide> }
<ide> return proxy;
<ide> |
|
Java | apache-2.0 | 468763c954e5dea8ca7795eb37f8ed924f52580f | 0 | shaneataylor/dita-ot,doctales/dita-ot,robander/dita-ot,infotexture/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot,drmacro/dita-ot,doctales/dita-ot,eerohele/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot,dita-ot/dita-ot,infotexture/dita-ot,drmacro/dita-ot,infotexture/dita-ot,eerohele/dita-ot,doctales/dita-ot,eerohele/dita-ot,robander/dita-ot,dita-ot/dita-ot,dita-ot/dita-ot,infotexture/dita-ot,eerohele/dita-ot,drmacro/dita-ot,robander/dita-ot,dita-ot/dita-ot,drmacro/dita-ot,drmacro/dita-ot,robander/dita-ot,dita-ot/dita-ot,doctales/dita-ot,robander/dita-ot,infotexture/dita-ot | /*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2007 All Rights Reserved.
*/
package org.dita.dost.reader;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.util.FileUtils.*;
import static org.apache.commons.io.FilenameUtils.*;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.StringUtils.join;
import static org.dita.dost.util.XMLUtils.close;
import static org.dita.dost.writer.AbstractChunkTopicParser.getElementNode;
import static org.dita.dost.writer.AbstractChunkTopicParser.getText;
import static java.util.Arrays.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.*;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.module.ChunkModule.ChunkFilenameGeneratorFactory;
import org.dita.dost.module.ChunkModule.ChunkFilenameGenerator;
import org.dita.dost.util.*;
import org.dita.dost.writer.AbstractDomFilter;
import org.dita.dost.writer.ChunkTopicParser;
import org.dita.dost.writer.SeparateChunkTopicParser;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
* ChunkMapReader class, read and filter ditamap file for chunking.
*
*/
public final class ChunkMapReader extends AbstractDomFilter {
public static final String FILE_NAME_STUB_DITAMAP = "stub.ditamap";
public static final String FILE_EXTENSION_CHUNK = ".chunk";
public static final String ATTR_XTRF_VALUE_GENERATED = "generated_by_chunk";
public static final String CHUNK_SELECT_BRANCH = "select-branch";
public static final String CHUNK_SELECT_TOPIC = "select-topic";
public static final String CHUNK_SELECT_DOCUMENT = "select-document";
private static final String CHUNK_BY_DOCUMENT = "by-document";
private static final String CHUNK_BY_TOPIC = "by-topic";
public static final String CHUNK_TO_CONTENT = "to-content";
public static final String CHUNK_TO_NAVIGATION = "to-navigation";
private Collection<String> rootChunkOverride;
private String defaultChunkByToken;
// ChunkTopicParser assumes keys and values are chimera paths, i.e. systems paths with fragments.
private final LinkedHashMap<URI, URI> changeTable = new LinkedHashMap<>(128);
private final Map<URI, URI> conflictTable = new HashMap<>(128);
private boolean supportToNavigation;
private ProcessingInstruction workdir = null;
private ProcessingInstruction workdirUrl = null;
private ProcessingInstruction path2proj = null;
private ProcessingInstruction path2projUrl = null;
private final ChunkFilenameGenerator chunkFilenameGenerator = ChunkFilenameGeneratorFactory.newInstance();
/**
* Constructor.
*/
public ChunkMapReader() {
super();
}
public void setRootChunkOverride(final String chunkValue) {
rootChunkOverride = split(chunkValue);
}
private URI inputFile;
/**
* read input file.
*
* @param inputFile filename
*/
@Override
public void read(final File inputFile) {
this.inputFile = inputFile.toURI();
super.read(inputFile);
}
@Override
public Document process(final Document doc) {
readProcessingInstructions(doc);
final Element root = doc.getDocumentElement();
if (rootChunkOverride != null) {
final String c = join(rootChunkOverride, " ");
logger.debug("Use override root chunk \"" + c + "\"");
root.setAttribute(ATTRIBUTE_NAME_CHUNK, c);
}
final Collection<String> rootChunkValue = split(root.getAttribute(ATTRIBUTE_NAME_CHUNK));
defaultChunkByToken = getChunkByToken(rootChunkValue, "by-", CHUNK_BY_DOCUMENT);
// chunk value = "to-content"
// When @chunk="to-content" is specified on "map" element,
// chunk module will change its @class attribute to "topicref"
// and process it as if it were a normal topicref wich
// @chunk="to-content"
if (rootChunkValue.contains(CHUNK_TO_CONTENT)) {
chunkMap(root);
} else {
// if to-content is not specified on map element
// process the map element's immediate child node(s)
// get the immediate child nodes
final NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
final Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) node;
if (MAP_RELTABLE.matches(currentElem)) {
updateReltable(currentElem);
} else if (MAPGROUP_D_TOPICGROUP.matches(currentElem)) {
processChildTopicref(currentElem);
} else if (MAP_TOPICREF.matches(currentElem)) {
processTopicref(currentElem);
}
}
}
}
return buildOutputDocument(root);
}
public static String getChunkByToken(final Collection<String> chunkValue, final String category, final String defaultToken) {
if (chunkValue.isEmpty()) {
return defaultToken;
}
for (final String token: chunkValue) {
if (token.startsWith(category)) {
return token;
}
}
return defaultToken;
}
/**
* Process map when "to-content" is specified on map element.
*
* TODO: Instead of reclassing map element to be a topicref, add a topicref
* into the map root and move all map content into that topicref.
*/
private void chunkMap(final Element root) {
// create the reference to the new file on root element.
String newFilename = replaceExtension(new File(inputFile).getName(), FILE_EXTENSION_DITA);
URI newFile = inputFile.resolve(newFilename);
if (new File(newFile).exists()) {
newFilename = chunkFilenameGenerator.generateFilename("Chunk", FILE_EXTENSION_DITA);
newFile = inputFile.resolve(newFilename);
// Mark up the possible name changing, in case that references might be updated.
conflictTable.put(newFile, newFile.normalize());
}
changeTable.put(newFile, newFile);
// change the class attribute to "topicref"
final String originClassValue = root.getAttribute(ATTRIBUTE_NAME_CLASS);
root.setAttribute(ATTRIBUTE_NAME_CLASS, originClassValue + MAP_TOPICREF.matcher);
root.setAttribute(ATTRIBUTE_NAME_HREF, toURI(newFilename).toString());
createTopicStump(newFile);
// process chunk
processTopicref(root);
// restore original root element
if (originClassValue != null) {
root.setAttribute(ATTRIBUTE_NAME_CLASS, originClassValue);
}
root.removeAttribute(ATTRIBUTE_NAME_HREF);
}
/**
* Create the new topic stump.
*/
private void createTopicStump(final URI newFile) {
OutputStream newFileWriter = null;
try {
newFileWriter = new FileOutputStream(new File(newFile));
final XMLStreamWriter o = XMLOutputFactory.newInstance().createXMLStreamWriter(newFileWriter, UTF8);
o.writeStartDocument();
o.writeProcessingInstruction(PI_WORKDIR_TARGET, UNIX_SEPARATOR + new File(newFile.resolve(".")).getAbsolutePath());
o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.resolve(".").toString());
o.writeStartElement(ELEMENT_NAME_DITA);
o.writeEndElement();
o.writeEndDocument();
o.close();
newFileWriter.flush();
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (newFileWriter != null) {
newFileWriter.close();
}
} catch (final IOException e) {
logger.error(e.getMessage(), e);
}
}
}
/**
* Read processing metadata from processing instructions.
*/
private void readProcessingInstructions(final Document doc) {
final NodeList docNodes = doc.getChildNodes();
for (int i = 0; i < docNodes.getLength(); i++) {
final Node node = docNodes.item(i);
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
final ProcessingInstruction pi = (ProcessingInstruction) node;
if (pi.getNodeName().equals(PI_WORKDIR_TARGET)) {
workdir = pi;
} else if (pi.getNodeName().equals(PI_WORKDIR_TARGET_URI)) {
workdirUrl = pi;
} else if (pi.getNodeName().equals(PI_PATH2PROJ_TARGET)) {
path2proj = pi;
} else if (pi.getNodeName().equals(PI_PATH2PROJ_TARGET_URI)) {
path2projUrl = pi;
}
}
}
}
private void outputMapFile(final URI file, final Document doc) {
StreamResult result = null;
try {
final Transformer t = TransformerFactory.newInstance().newTransformer();
result = new StreamResult(new FileOutputStream(new File(file)));
t.transform(new DOMSource(doc), result);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
close(result);
} catch (final IOException e) {
logger.error(e.getMessage(), e);
}
}
}
private Document buildOutputDocument(final Element root) {
final Document doc = XMLUtils.getDocumentBuilder().newDocument();
if (workdir != null) {
doc.appendChild(doc.importNode(workdir, true));
}
if (workdirUrl != null) {
doc.appendChild(doc.importNode(workdirUrl, true));
}
if (path2proj != null) {
doc.appendChild(doc.importNode(path2proj, true));
}
if (path2projUrl != null) {
doc.appendChild(doc.importNode(path2projUrl, true));
}
doc.appendChild(doc.importNode(root, true));
return doc;
}
public static Collection<String> split(final String value) {
if (value == null) {
return Collections.EMPTY_LIST;
}
final String[] tokens = value.trim().split("\\s+");
return asList(tokens);
}
private void processTopicref(final Element topicref) {
final String xtrfValue = getValue(topicref, ATTRIBUTE_NAME_XTRF);
if (xtrfValue != null && xtrfValue.contains(ATTR_XTRF_VALUE_GENERATED)) {
return;
}
final Collection<String> chunkValue = split(getValue(topicref, ATTRIBUTE_NAME_CHUNK));
if (topicref.getAttributeNode(ATTRIBUTE_NAME_HREF) == null && chunkValue.contains(CHUNK_TO_CONTENT)) {
generateStumpTopic(topicref);
}
final URI hrefValue = toURI(getValue(topicref,ATTRIBUTE_NAME_HREF));
final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
final String scopeValue = getCascadeValue(topicref, ATTRIBUTE_NAME_SCOPE);
final String chunkByToken = getChunkByToken(chunkValue, "by-", defaultChunkByToken);
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scopeValue)
|| (hrefValue != null && !new File(inputFile.resolve(hrefValue.toString())).exists())
|| (chunkValue.isEmpty() && hrefValue == null)) {
processChildTopicref(topicref);
} else if (chunkValue.contains(CHUNK_TO_CONTENT)
&& (hrefValue != null || copytoValue != null || topicref.hasChildNodes())) {
if (chunkValue.contains(CHUNK_BY_TOPIC)) {
logger.warn(MessageUtils.getInstance().getMessage("DOTJ064W").setLocation(topicref).toString());
}
processChunk(topicref, false);
} else if (chunkValue.contains(CHUNK_TO_NAVIGATION)
&& supportToNavigation) {
processChildTopicref(topicref);
processNavitation(topicref);
} else if (chunkByToken.equals(CHUNK_BY_TOPIC)) {
processChunk(topicref, true);
processChildTopicref(topicref);
} else { // chunkByToken.equals(CHUNK_BY_DOCUMENT)
String currentPath = null;
if (copytoValue != null) {
currentPath = inputFile.resolve(copytoValue).getPath();
} else if (hrefValue != null) {
currentPath = inputFile.resolve(hrefValue).getPath();
}
if (currentPath != null) {
if (changeTable.containsKey(currentPath)) {
changeTable.remove(currentPath);
}
final String processingRole = getCascadeValue(topicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
changeTable.put(toURI(currentPath), toURI(currentPath));
}
}
processChildTopicref(topicref);
}
}
/**
* Create new map and refer to it with navref.
* @param topicref
*/
private void processNavitation(final Element topicref) {
// create new map's root element
final Element root = (Element) topicref.getOwnerDocument().getDocumentElement().cloneNode(false);
// create navref element
final Element navref = topicref.getOwnerDocument().createElement(MAP_NAVREF.localName);
final String newMapFile = chunkFilenameGenerator.generateFilename("MAPCHUNK", FILE_EXTENSION_DITAMAP);
navref.setAttribute(ATTRIBUTE_NAME_MAPREF, newMapFile);
navref.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_NAVREF.toString());
// replace topicref with navref
topicref.getParentNode().replaceChild(navref, topicref);
root.appendChild(topicref);
// generate new file
final URI navmap = inputFile.resolve(newMapFile);
changeTable.put(stripFragment(navmap), stripFragment(navmap));
outputMapFile(navmap, buildOutputDocument(root));
}
/**
* Generate file name.
*
* @return generated file name
*/
private String generateFilename() {
return chunkFilenameGenerator.generateFilename("XChunk", FILE_EXTENSION_DITA);
}
/**
* Generate stump topic for to-content content.
* @param topicref topicref without href to generate stump topic for
*/
private void generateStumpTopic(final Element topicref) {
logger.info("generateStumpTopic: "+ topicref.toString());
final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
final String idValue = getValue(topicref, ATTRIBUTE_NAME_ID);
URI outputFileName;
if (copytoValue != null) {
outputFileName = inputFile.resolve(copytoValue.toString());
} else if (idValue != null) {
outputFileName = inputFile.resolve(idValue + FILE_EXTENSION_DITA);
} else {
do {
outputFileName = inputFile.resolve(generateFilename());
} while (new File(outputFileName).exists());
}
final String id = getBaseName(new File(outputFileName).getName());
String navtitleValue = getChildElementValueOfTopicmeta(topicref, TOPIC_NAVTITLE);
if (navtitleValue == null) {
navtitleValue = getValue(topicref, ATTRIBUTE_NAME_NAVTITLE);
}
if (navtitleValue == null) {
navtitleValue = id;
}
final String shortDescValue = getChildElementValueOfTopicmeta(topicref, MAP_SHORTDESC);
OutputStream output = null;
try {
output = new FileOutputStream(new File(outputFileName));
final XMLSerializer serializer = XMLSerializer.newInstance(output);
serializer.writeStartDocument();
serializer.writeStartElement(TOPIC_TOPIC.localName);
serializer.writeAttribute(DITA_NAMESPACE, ATTRIBUTE_PREFIX_DITAARCHVERSION + ":" + ATTRIBUTE_NAME_DITAARCHVERSION, "1.2");
serializer.writeAttribute(ATTRIBUTE_NAME_ID, id);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TOPIC.toString());
serializer.writeAttribute(ATTRIBUTE_NAME_DOMAINS, "");
serializer.writeStartElement(TOPIC_TITLE.localName);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TITLE.toString());
serializer.writeCharacters(navtitleValue);
serializer.writeEndElement(); // title
if (shortDescValue != null) {
serializer.writeStartElement(TOPIC_SHORTDESC.localName);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_SHORTDESC.toString());
serializer.writeCharacters(shortDescValue);
serializer.writeEndElement(); // shortdesc
}
serializer.writeEndElement(); // topic
serializer.writeEndDocument();
serializer.close();
} catch (final IOException | SAXException e) {
logger.error("Failed to write generated chunk: " + e.getMessage(), e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
logger.error("Failed to close output stream: " + e.getMessage(), e);
}
}
}
// update current element's @href value
final URI relativePath = getRelativePath(inputFile.resolve(FILE_NAME_STUB_DITAMAP), outputFileName);
topicref.setAttribute(ATTRIBUTE_NAME_HREF, relativePath.toString());
final URI relativeToBase = URLUtils.getRelativePath(job.tempDir.toURI().resolve("dummy"), outputFileName);
job.add(new Job.FileInfo.Builder().uri(relativeToBase).format(ATTR_FORMAT_VALUE_DITA).build());
}
/**
* get topicmeta's child(e.g navtitle, shortdesc) tag's value(text-only).
* @param element input element
* @return text value
*/
private String getChildElementValueOfTopicmeta(final Element element, final DitaClass classValue) {
if (element.hasChildNodes()) {
final Element topicMeta = getElementNode(element, MAP_TOPICMETA);
if (topicMeta != null) {
final Element elem = getElementNode(topicMeta, classValue);
if (elem != null) {
return getText(elem);
}
}
}
return null;
}
public static String getValue(final Element elem, final String attrName) {
final Attr attr = elem.getAttributeNode(attrName);
if (attr != null && !attr.getValue().isEmpty()) {
return attr.getValue();
}
return null;
}
public static String getCascadeValue(final Element elem, final String attrName) {
Element current = elem;
while (current != null) {
final Attr attr = current.getAttributeNode(attrName);
if (attr != null) {
return attr.getValue();
}
final Node parent = current.getParentNode();
if (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
current = (Element) parent;
} else {
break;
}
}
return null;
}
private void processChildTopicref(final Element node) {
final NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) current;
final String classValue = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS);
if (MAP_TOPICREF.matches(classValue)) {
final String hrefValue = currentElem.getAttribute(ATTRIBUTE_NAME_HREF);
final String xtrfValue = currentElem.getAttribute(ATTRIBUTE_NAME_XTRF);
if (hrefValue.length() == 0) {
processTopicref(currentElem);
} else if (!ATTR_XTRF_VALUE_GENERATED.equals(xtrfValue)
&& !inputFile.resolve(hrefValue).getPath().equals(changeTable.get(inputFile.resolve(hrefValue).getPath()))) {
processTopicref(currentElem);
}
}
}
}
}
private void processChunk(final Element topicref, final boolean separate) {
try {
if (separate) {
final SeparateChunkTopicParser chunkParser = new SeparateChunkTopicParser();
chunkParser.setLogger(logger);
chunkParser.setJob(job);
chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
chunkParser.write(new File(inputFile.resolve(".")));
} else {
final ChunkTopicParser chunkParser = new ChunkTopicParser();
chunkParser.setLogger(logger);
chunkParser.setJob(job);
chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
chunkParser.write(new File(inputFile.resolve(".")));
}
} catch (final DITAOTException e) {
logger.error("Failed to process chunk: " + e.getMessage(), e);
}
}
private void updateReltable(final Element elem) {
final String hrefValue = elem.getAttribute(ATTRIBUTE_NAME_HREF);
if (hrefValue.length() != 0) {
if (changeTable.containsKey(inputFile.resolve(hrefValue).getPath())) {
URI resulthrefValue = getRelativePath(inputFile.resolve(FILE_NAME_STUB_DITAMAP),
inputFile.resolve(hrefValue));
final String fragment = getFragment(hrefValue);
if (fragment != null) {
resulthrefValue = setFragment(resulthrefValue, fragment);
}
elem.setAttribute(ATTRIBUTE_NAME_HREF, resulthrefValue.toString());
}
}
final NodeList children = elem.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) current;
final String classValue = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS);
if (MAP_TOPICREF.matches(classValue)) {
// FIXME: What should happen here?
}
}
}
}
/**
* Get changed files table.
*
* @return map of changed files
*/
public Map<URI, URI> getChangeTable() {
for (final Map.Entry<URI, URI> e: changeTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
return Collections.unmodifiableMap(changeTable);
}
/**
* get conflict table.
*
* @return conflict table
*/
public Map<URI, URI> getConflicTable() {
for (final Map.Entry<URI, URI> e: conflictTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
return conflictTable;
}
/**
* Support chunk token to-navigation.
*
* @param supportToNavigation flag to enable to-navigation support
*/
public void supportToNavigation(final boolean supportToNavigation) {
this.supportToNavigation = supportToNavigation;
}
}
| src/main/java/org/dita/dost/reader/ChunkMapReader.java | /*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2007 All Rights Reserved.
*/
package org.dita.dost.reader;
import static org.dita.dost.util.FileUtils.*;
import static org.apache.commons.io.FilenameUtils.*;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.StringUtils.join;
import static org.dita.dost.util.URLUtils.stripFragment;
import static org.dita.dost.util.URLUtils.toURI;
import static org.dita.dost.util.XMLUtils.close;
import static org.dita.dost.writer.AbstractChunkTopicParser.getElementNode;
import static org.dita.dost.writer.AbstractChunkTopicParser.getText;
import static java.util.Arrays.*;
import java.io.*;
import java.net.URI;
import java.util.*;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.module.ChunkModule.ChunkFilenameGeneratorFactory;
import org.dita.dost.module.ChunkModule.ChunkFilenameGenerator;
import org.dita.dost.util.*;
import org.dita.dost.writer.AbstractDomFilter;
import org.dita.dost.writer.ChunkTopicParser;
import org.dita.dost.writer.SeparateChunkTopicParser;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
* ChunkMapReader class, read and filter ditamap file for chunking.
*
*/
public final class ChunkMapReader extends AbstractDomFilter {
public static final String FILE_NAME_STUB_DITAMAP = "stub.ditamap";
public static final String FILE_EXTENSION_CHUNK = ".chunk";
public static final String ATTR_XTRF_VALUE_GENERATED = "generated_by_chunk";
public static final String CHUNK_SELECT_BRANCH = "select-branch";
public static final String CHUNK_SELECT_TOPIC = "select-topic";
public static final String CHUNK_SELECT_DOCUMENT = "select-document";
private static final String CHUNK_BY_DOCUMENT = "by-document";
private static final String CHUNK_BY_TOPIC = "by-topic";
public static final String CHUNK_TO_CONTENT = "to-content";
public static final String CHUNK_TO_NAVIGATION = "to-navigation";
private Collection<String> rootChunkOverride;
private String defaultChunkByToken;
/** Input file's parent directory */
private File fileDir = null;
// ChunkTopicParser assumes keys and values are chimera paths, i.e. systems paths with fragments.
private final LinkedHashMap<URI, URI> changeTable = new LinkedHashMap<>(128);
private final Map<URI, URI> conflictTable = new HashMap<>(128);
private boolean supportToNavigation;
private ProcessingInstruction workdir = null;
private ProcessingInstruction workdirUrl = null;
private ProcessingInstruction path2proj = null;
private ProcessingInstruction path2projUrl = null;
private final ChunkFilenameGenerator chunkFilenameGenerator = ChunkFilenameGeneratorFactory.newInstance();
/**
* Constructor.
*/
public ChunkMapReader() {
super();
}
public void setRootChunkOverride(final String chunkValue) {
rootChunkOverride = split(chunkValue);
}
private File inputFile;
/**
* read input file.
*
* @param inputFile filename
*/
@Override
public void read(final File inputFile) {
this.inputFile = inputFile;
fileDir = inputFile.getParentFile();
super.read(inputFile);
}
@Override
public Document process(final Document doc) {
readProcessingInstructions(doc);
final Element root = doc.getDocumentElement();
if (rootChunkOverride != null) {
final String c = join(rootChunkOverride, " ");
logger.debug("Use override root chunk \"" + c + "\"");
root.setAttribute(ATTRIBUTE_NAME_CHUNK, c);
}
final Collection<String> rootChunkValue = split(root.getAttribute(ATTRIBUTE_NAME_CHUNK));
defaultChunkByToken = getChunkByToken(rootChunkValue, "by-", CHUNK_BY_DOCUMENT);
// chunk value = "to-content"
// When @chunk="to-content" is specified on "map" element,
// chunk module will change its @class attribute to "topicref"
// and process it as if it were a normal topicref wich
// @chunk="to-content"
if (rootChunkValue.contains(CHUNK_TO_CONTENT)) {
chunkMap(root);
} else {
// if to-content is not specified on map element
// process the map element's immediate child node(s)
// get the immediate child nodes
final NodeList list = root.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
final Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) node;
if (MAP_RELTABLE.matches(currentElem)) {
updateReltable(currentElem);
} else if (MAPGROUP_D_TOPICGROUP.matches(currentElem)) {
processChildTopicref(currentElem);
} else if (MAP_TOPICREF.matches(currentElem)) {
processTopicref(currentElem);
}
}
}
}
return buildOutputDocument(root);
}
public static String getChunkByToken(final Collection<String> chunkValue, final String category, final String defaultToken) {
if (chunkValue.isEmpty()) {
return defaultToken;
}
for (final String token: chunkValue) {
if (token.startsWith(category)) {
return token;
}
}
return defaultToken;
}
/**
* Process map when "to-content" is specified on map element.
*
* TODO: Instead of reclassing map element to be a topicref, add a topicref
* into the map root and move all map content into that topicref.
*/
private void chunkMap(final Element root) {
// create the reference to the new file on root element.
String newFilename = replaceExtension(inputFile.getName(), FILE_EXTENSION_DITA);
File newFile = new File(inputFile.getParentFile().getAbsolutePath(), newFilename);
if (newFile.exists()) {
newFilename = chunkFilenameGenerator.generateFilename("Chunk", FILE_EXTENSION_DITA);
newFile = resolve(inputFile.getParentFile().getAbsolutePath(), newFilename);
// Mark up the possible name changing, in case that references might be updated.
conflictTable.put(newFile.toURI(), newFile.toURI().normalize());
}
changeTable.put(newFile.getAbsoluteFile().toURI(), newFile.getAbsoluteFile().toURI());
// change the class attribute to "topicref"
final String originClassValue = root.getAttribute(ATTRIBUTE_NAME_CLASS);
root.setAttribute(ATTRIBUTE_NAME_CLASS, originClassValue + MAP_TOPICREF.matcher);
root.setAttribute(ATTRIBUTE_NAME_HREF, toURI(newFilename).toString());
createTopicStump(newFile);
// process chunk
processTopicref(root);
// restore original root element
if (originClassValue != null) {
root.setAttribute(ATTRIBUTE_NAME_CLASS, originClassValue);
}
root.removeAttribute(ATTRIBUTE_NAME_HREF);
}
/**
* Create the new topic stump.
*/
private void createTopicStump(final File newFile) {
OutputStream newFileWriter = null;
try {
newFileWriter = new FileOutputStream(newFile);
final XMLStreamWriter o = XMLOutputFactory.newInstance().createXMLStreamWriter(newFileWriter, UTF8);
o.writeStartDocument();
o.writeProcessingInstruction(PI_WORKDIR_TARGET, UNIX_SEPARATOR + newFile.getParentFile().getAbsolutePath());
o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.getParentFile().toURI().toString());
o.writeStartElement(ELEMENT_NAME_DITA);
o.writeEndElement();
o.writeEndDocument();
o.close();
newFileWriter.flush();
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (newFileWriter != null) {
newFileWriter.close();
}
} catch (final IOException e) {
logger.error(e.getMessage(), e);
}
}
}
/**
* Read processing metadata from processing instructions.
*/
private void readProcessingInstructions(final Document doc) {
final NodeList docNodes = doc.getChildNodes();
for (int i = 0; i < docNodes.getLength(); i++) {
final Node node = docNodes.item(i);
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
final ProcessingInstruction pi = (ProcessingInstruction) node;
if (pi.getNodeName().equals(PI_WORKDIR_TARGET)) {
workdir = pi;
} else if (pi.getNodeName().equals(PI_WORKDIR_TARGET_URI)) {
workdirUrl = pi;
} else if (pi.getNodeName().equals(PI_PATH2PROJ_TARGET)) {
path2proj = pi;
} else if (pi.getNodeName().equals(PI_PATH2PROJ_TARGET_URI)) {
path2projUrl = pi;
}
}
}
}
private void outputMapFile(final File file, final Document doc) {
StreamResult result = null;
try {
final Transformer t = TransformerFactory.newInstance().newTransformer();
result = new StreamResult(new FileOutputStream(file));
t.transform(new DOMSource(doc), result);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
close(result);
} catch (final IOException e) {
logger.error(e.getMessage(), e);
}
}
}
private Document buildOutputDocument(final Element root) {
final Document doc = XMLUtils.getDocumentBuilder().newDocument();
if (workdir != null) {
doc.appendChild(doc.importNode(workdir, true));
}
if (workdirUrl != null) {
doc.appendChild(doc.importNode(workdirUrl, true));
}
if (path2proj != null) {
doc.appendChild(doc.importNode(path2proj, true));
}
if (path2projUrl != null) {
doc.appendChild(doc.importNode(path2projUrl, true));
}
doc.appendChild(doc.importNode(root, true));
return doc;
}
public static Collection<String> split(final String value) {
if (value == null) {
return Collections.EMPTY_LIST;
}
final String[] tokens = value.trim().split("\\s+");
return asList(tokens);
}
private void processTopicref(final Element topicref) {
final String xtrfValue = getValue(topicref, ATTRIBUTE_NAME_XTRF);
if (xtrfValue != null && xtrfValue.contains(ATTR_XTRF_VALUE_GENERATED)) {
return;
}
final Collection<String> chunkValue = split(getValue(topicref, ATTRIBUTE_NAME_CHUNK));
if (topicref.getAttributeNode(ATTRIBUTE_NAME_HREF) == null && chunkValue.contains(CHUNK_TO_CONTENT)) {
generateStumpTopic(topicref);
}
final URI hrefValue = toURI(getValue(topicref,ATTRIBUTE_NAME_HREF));
final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
final String scopeValue = getCascadeValue(topicref, ATTRIBUTE_NAME_SCOPE);
final String chunkByToken = getChunkByToken(chunkValue, "by-", defaultChunkByToken);
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scopeValue)
|| (hrefValue != null && !resolve(fileDir, hrefValue.toString()).exists())
|| (chunkValue.isEmpty() && hrefValue == null)) {
processChildTopicref(topicref);
} else if (chunkValue.contains(CHUNK_TO_CONTENT)
&& (hrefValue != null || copytoValue != null || topicref.hasChildNodes())) {
if (chunkValue.contains(CHUNK_BY_TOPIC)) {
logger.warn(MessageUtils.getInstance().getMessage("DOTJ064W").setLocation(topicref).toString());
}
processChunk(topicref, false);
} else if (chunkValue.contains(CHUNK_TO_NAVIGATION)
&& supportToNavigation) {
processChildTopicref(topicref);
processNavitation(topicref);
} else if (chunkByToken.equals(CHUNK_BY_TOPIC)) {
processChunk(topicref, true);
processChildTopicref(topicref);
} else { // chunkByToken.equals(CHUNK_BY_DOCUMENT)
String currentPath = null;
if (copytoValue != null) {
currentPath = resolve(fileDir, copytoValue).getPath();
} else if (hrefValue != null) {
currentPath = resolve(fileDir, hrefValue).getPath();
}
if (currentPath != null) {
if (changeTable.containsKey(currentPath)) {
changeTable.remove(currentPath);
}
final String processingRole = getCascadeValue(topicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
changeTable.put(toURI(currentPath), toURI(currentPath));
}
}
processChildTopicref(topicref);
}
}
/**
* Create new map and refer to it with navref.
* @param topicref
*/
private void processNavitation(final Element topicref) {
// create new map's root element
final Element root = (Element) topicref.getOwnerDocument().getDocumentElement().cloneNode(false);
// create navref element
final Element navref = topicref.getOwnerDocument().createElement(MAP_NAVREF.localName);
final String newMapFile = chunkFilenameGenerator.generateFilename("MAPCHUNK", FILE_EXTENSION_DITAMAP);
navref.setAttribute(ATTRIBUTE_NAME_MAPREF, newMapFile);
navref.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_NAVREF.toString());
// replace topicref with navref
topicref.getParentNode().replaceChild(navref, topicref);
root.appendChild(topicref);
// generate new file
final File navmap = resolve(fileDir, newMapFile);
changeTable.put(stripFragment(navmap.toURI()), stripFragment(navmap.toURI()));
outputMapFile(navmap, buildOutputDocument(root));
}
/**
* Generate file name.
*
* @return generated file name
*/
private String generateFilename() {
return chunkFilenameGenerator.generateFilename("XChunk", FILE_EXTENSION_DITA);
}
/**
* Generate stump topic for to-content content.
* @param topicref topicref without href to generate stump topic for
*/
private void generateStumpTopic(final Element topicref) {
logger.info("generateStumpTopic: "+ topicref.toString());
final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
final String idValue = getValue(topicref, ATTRIBUTE_NAME_ID);
File outputFileName;
if (copytoValue != null) {
outputFileName = resolve(fileDir, copytoValue.toString());
} else if (idValue != null) {
outputFileName = resolve(fileDir, idValue + FILE_EXTENSION_DITA);
} else {
do {
outputFileName = resolve(fileDir, generateFilename());
} while (outputFileName.exists());
}
final String id = getBaseName(outputFileName.getName());
String navtitleValue = getChildElementValueOfTopicmeta(topicref, TOPIC_NAVTITLE);
if (navtitleValue == null) {
navtitleValue = getValue(topicref, ATTRIBUTE_NAME_NAVTITLE);
}
if (navtitleValue == null) {
navtitleValue = id;
}
final String shortDescValue = getChildElementValueOfTopicmeta(topicref, MAP_SHORTDESC);
OutputStream output = null;
try {
output = new FileOutputStream(outputFileName);
final XMLSerializer serializer = XMLSerializer.newInstance(output);
serializer.writeStartDocument();
serializer.writeStartElement(TOPIC_TOPIC.localName);
serializer.writeAttribute(DITA_NAMESPACE, ATTRIBUTE_PREFIX_DITAARCHVERSION + ":" + ATTRIBUTE_NAME_DITAARCHVERSION, "1.2");
serializer.writeAttribute(ATTRIBUTE_NAME_ID, id);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TOPIC.toString());
serializer.writeAttribute(ATTRIBUTE_NAME_DOMAINS, "");
serializer.writeStartElement(TOPIC_TITLE.localName);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TITLE.toString());
serializer.writeCharacters(navtitleValue);
serializer.writeEndElement(); // title
if (shortDescValue != null) {
serializer.writeStartElement(TOPIC_SHORTDESC.localName);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_SHORTDESC.toString());
serializer.writeCharacters(shortDescValue);
serializer.writeEndElement(); // shortdesc
}
serializer.writeEndElement(); // topic
serializer.writeEndDocument();
serializer.close();
} catch (final IOException | SAXException e) {
logger.error("Failed to write generated chunk: " + e.getMessage(), e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
logger.error("Failed to close output stream: " + e.getMessage(), e);
}
}
}
// update current element's @href value
final URI relativePath = toURI(getRelativePath(new File(fileDir, FILE_NAME_STUB_DITAMAP), outputFileName));
topicref.setAttribute(ATTRIBUTE_NAME_HREF, relativePath.toString());
final URI relativeToBase = URLUtils.getRelativePath(job.tempDir.toURI().resolve("dummy"), outputFileName.toURI());
job.add(new Job.FileInfo.Builder().uri(relativeToBase).format(ATTR_FORMAT_VALUE_DITA).build());
}
/**
* get topicmeta's child(e.g navtitle, shortdesc) tag's value(text-only).
* @param element input element
* @return text value
*/
private String getChildElementValueOfTopicmeta(final Element element, final DitaClass classValue) {
if (element.hasChildNodes()) {
final Element topicMeta = getElementNode(element, MAP_TOPICMETA);
if (topicMeta != null) {
final Element elem = getElementNode(topicMeta, classValue);
if (elem != null) {
return getText(elem);
}
}
}
return null;
}
public static String getValue(final Element elem, final String attrName) {
final Attr attr = elem.getAttributeNode(attrName);
if (attr != null && !attr.getValue().isEmpty()) {
return attr.getValue();
}
return null;
}
public static String getCascadeValue(final Element elem, final String attrName) {
Element current = elem;
while (current != null) {
final Attr attr = current.getAttributeNode(attrName);
if (attr != null) {
return attr.getValue();
}
final Node parent = current.getParentNode();
if (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
current = (Element) parent;
} else {
break;
}
}
return null;
}
private void processChildTopicref(final Element node) {
final NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) current;
final String classValue = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS);
if (MAP_TOPICREF.matches(classValue)) {
final String hrefValue = currentElem.getAttribute(ATTRIBUTE_NAME_HREF);
final String xtrfValue = currentElem.getAttribute(ATTRIBUTE_NAME_XTRF);
if (hrefValue.length() == 0) {
processTopicref(currentElem);
} else if (!ATTR_XTRF_VALUE_GENERATED.equals(xtrfValue)
&& !resolve(fileDir, hrefValue).getPath().equals(changeTable.get(resolve(fileDir, hrefValue).getPath()))) {
processTopicref(currentElem);
}
}
}
}
}
private void processChunk(final Element topicref, final boolean separate) {
try {
if (separate) {
final SeparateChunkTopicParser chunkParser = new SeparateChunkTopicParser();
chunkParser.setLogger(logger);
chunkParser.setJob(job);
chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
chunkParser.write(fileDir);
} else {
final ChunkTopicParser chunkParser = new ChunkTopicParser();
chunkParser.setLogger(logger);
chunkParser.setJob(job);
chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
chunkParser.write(fileDir);
}
} catch (final DITAOTException e) {
logger.error("Failed to process chunk: " + e.getMessage(), e);
}
}
private void updateReltable(final Element elem) {
final String hrefValue = elem.getAttribute(ATTRIBUTE_NAME_HREF);
if (hrefValue.length() != 0) {
if (changeTable.containsKey(resolve(fileDir, hrefValue).getPath())) {
String resulthrefValue = getRelativeUnixPath(fileDir + UNIX_SEPARATOR + FILE_NAME_STUB_DITAMAP,
resolve(fileDir, hrefValue).getPath());
final String fragment = getFragment(hrefValue);
if (fragment != null) {
resulthrefValue = resulthrefValue + fragment;
}
elem.setAttribute(ATTRIBUTE_NAME_HREF, resulthrefValue);
}
}
final NodeList children = elem.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) current;
final String classValue = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS);
if (MAP_TOPICREF.matches(classValue)) {
// FIXME: What should happen here?
}
}
}
}
/**
* Get changed files table.
*
* @return map of changed files
*/
public Map<URI, URI> getChangeTable() {
for (final Map.Entry<URI, URI> e: changeTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
return Collections.unmodifiableMap(changeTable);
}
/**
* get conflict table.
*
* @return conflict table
*/
public Map<URI, URI> getConflicTable() {
for (final Map.Entry<URI, URI> e: conflictTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
return conflictTable;
}
/**
* Support chunk token to-navigation.
*
* @param supportToNavigation flag to enable to-navigation support
*/
public void supportToNavigation(final boolean supportToNavigation) {
this.supportToNavigation = supportToNavigation;
}
}
| Convert File to URI
| src/main/java/org/dita/dost/reader/ChunkMapReader.java | Convert File to URI | <ide><path>rc/main/java/org/dita/dost/reader/ChunkMapReader.java
<ide> */
<ide> package org.dita.dost.reader;
<ide>
<add>import static org.dita.dost.util.URLUtils.*;
<ide> import static org.dita.dost.util.FileUtils.*;
<ide> import static org.apache.commons.io.FilenameUtils.*;
<ide> import static org.dita.dost.util.Constants.*;
<ide> import static org.dita.dost.util.StringUtils.join;
<del>import static org.dita.dost.util.URLUtils.stripFragment;
<del>import static org.dita.dost.util.URLUtils.toURI;
<ide> import static org.dita.dost.util.XMLUtils.close;
<ide> import static org.dita.dost.writer.AbstractChunkTopicParser.getElementNode;
<ide> import static org.dita.dost.writer.AbstractChunkTopicParser.getText;
<ide> import static java.util.Arrays.*;
<ide>
<del>import java.io.*;
<add>import java.io.File;
<add>import java.io.FileOutputStream;
<add>import java.io.IOException;
<add>import java.io.OutputStream;
<ide> import java.net.URI;
<ide> import java.util.*;
<ide>
<ide> private Collection<String> rootChunkOverride;
<ide> private String defaultChunkByToken;
<ide>
<del> /** Input file's parent directory */
<del> private File fileDir = null;
<ide> // ChunkTopicParser assumes keys and values are chimera paths, i.e. systems paths with fragments.
<ide> private final LinkedHashMap<URI, URI> changeTable = new LinkedHashMap<>(128);
<ide>
<ide> rootChunkOverride = split(chunkValue);
<ide> }
<ide>
<del> private File inputFile;
<add> private URI inputFile;
<ide>
<ide> /**
<ide> * read input file.
<ide> */
<ide> @Override
<ide> public void read(final File inputFile) {
<del> this.inputFile = inputFile;
<del> fileDir = inputFile.getParentFile();
<add> this.inputFile = inputFile.toURI();
<ide>
<ide> super.read(inputFile);
<ide> }
<ide> */
<ide> private void chunkMap(final Element root) {
<ide> // create the reference to the new file on root element.
<del> String newFilename = replaceExtension(inputFile.getName(), FILE_EXTENSION_DITA);
<del> File newFile = new File(inputFile.getParentFile().getAbsolutePath(), newFilename);
<del> if (newFile.exists()) {
<add> String newFilename = replaceExtension(new File(inputFile).getName(), FILE_EXTENSION_DITA);
<add> URI newFile = inputFile.resolve(newFilename);
<add> if (new File(newFile).exists()) {
<ide> newFilename = chunkFilenameGenerator.generateFilename("Chunk", FILE_EXTENSION_DITA);
<del> newFile = resolve(inputFile.getParentFile().getAbsolutePath(), newFilename);
<add> newFile = inputFile.resolve(newFilename);
<ide> // Mark up the possible name changing, in case that references might be updated.
<del> conflictTable.put(newFile.toURI(), newFile.toURI().normalize());
<del> }
<del> changeTable.put(newFile.getAbsoluteFile().toURI(), newFile.getAbsoluteFile().toURI());
<add> conflictTable.put(newFile, newFile.normalize());
<add> }
<add> changeTable.put(newFile, newFile);
<ide>
<ide> // change the class attribute to "topicref"
<ide> final String originClassValue = root.getAttribute(ATTRIBUTE_NAME_CLASS);
<ide> /**
<ide> * Create the new topic stump.
<ide> */
<del> private void createTopicStump(final File newFile) {
<add> private void createTopicStump(final URI newFile) {
<ide> OutputStream newFileWriter = null;
<ide> try {
<del> newFileWriter = new FileOutputStream(newFile);
<add> newFileWriter = new FileOutputStream(new File(newFile));
<ide> final XMLStreamWriter o = XMLOutputFactory.newInstance().createXMLStreamWriter(newFileWriter, UTF8);
<ide> o.writeStartDocument();
<del> o.writeProcessingInstruction(PI_WORKDIR_TARGET, UNIX_SEPARATOR + newFile.getParentFile().getAbsolutePath());
<del> o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.getParentFile().toURI().toString());
<add> o.writeProcessingInstruction(PI_WORKDIR_TARGET, UNIX_SEPARATOR + new File(newFile.resolve(".")).getAbsolutePath());
<add> o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.resolve(".").toString());
<ide> o.writeStartElement(ELEMENT_NAME_DITA);
<ide> o.writeEndElement();
<ide> o.writeEndDocument();
<ide> }
<ide> }
<ide>
<del> private void outputMapFile(final File file, final Document doc) {
<add> private void outputMapFile(final URI file, final Document doc) {
<ide> StreamResult result = null;
<ide> try {
<ide> final Transformer t = TransformerFactory.newInstance().newTransformer();
<del> result = new StreamResult(new FileOutputStream(file));
<add> result = new StreamResult(new FileOutputStream(new File(file)));
<ide> t.transform(new DOMSource(doc), result);
<ide> } catch (final RuntimeException e) {
<ide> throw e;
<ide> final String chunkByToken = getChunkByToken(chunkValue, "by-", defaultChunkByToken);
<ide>
<ide> if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scopeValue)
<del> || (hrefValue != null && !resolve(fileDir, hrefValue.toString()).exists())
<add> || (hrefValue != null && !new File(inputFile.resolve(hrefValue.toString())).exists())
<ide> || (chunkValue.isEmpty() && hrefValue == null)) {
<ide> processChildTopicref(topicref);
<ide> } else if (chunkValue.contains(CHUNK_TO_CONTENT)
<ide> } else { // chunkByToken.equals(CHUNK_BY_DOCUMENT)
<ide> String currentPath = null;
<ide> if (copytoValue != null) {
<del> currentPath = resolve(fileDir, copytoValue).getPath();
<add> currentPath = inputFile.resolve(copytoValue).getPath();
<ide> } else if (hrefValue != null) {
<del> currentPath = resolve(fileDir, hrefValue).getPath();
<add> currentPath = inputFile.resolve(hrefValue).getPath();
<ide> }
<ide> if (currentPath != null) {
<ide> if (changeTable.containsKey(currentPath)) {
<ide> topicref.getParentNode().replaceChild(navref, topicref);
<ide> root.appendChild(topicref);
<ide> // generate new file
<del> final File navmap = resolve(fileDir, newMapFile);
<del> changeTable.put(stripFragment(navmap.toURI()), stripFragment(navmap.toURI()));
<add> final URI navmap = inputFile.resolve(newMapFile);
<add> changeTable.put(stripFragment(navmap), stripFragment(navmap));
<ide> outputMapFile(navmap, buildOutputDocument(root));
<ide> }
<ide>
<ide> final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
<ide> final String idValue = getValue(topicref, ATTRIBUTE_NAME_ID);
<ide>
<del> File outputFileName;
<add> URI outputFileName;
<ide> if (copytoValue != null) {
<del> outputFileName = resolve(fileDir, copytoValue.toString());
<add> outputFileName = inputFile.resolve(copytoValue.toString());
<ide> } else if (idValue != null) {
<del> outputFileName = resolve(fileDir, idValue + FILE_EXTENSION_DITA);
<add> outputFileName = inputFile.resolve(idValue + FILE_EXTENSION_DITA);
<ide> } else {
<ide> do {
<del> outputFileName = resolve(fileDir, generateFilename());
<del> } while (outputFileName.exists());
<del> }
<del>
<del> final String id = getBaseName(outputFileName.getName());
<add> outputFileName = inputFile.resolve(generateFilename());
<add> } while (new File(outputFileName).exists());
<add> }
<add>
<add> final String id = getBaseName(new File(outputFileName).getName());
<ide> String navtitleValue = getChildElementValueOfTopicmeta(topicref, TOPIC_NAVTITLE);
<ide> if (navtitleValue == null) {
<ide> navtitleValue = getValue(topicref, ATTRIBUTE_NAME_NAVTITLE);
<ide>
<ide> OutputStream output = null;
<ide> try {
<del> output = new FileOutputStream(outputFileName);
<add> output = new FileOutputStream(new File(outputFileName));
<ide> final XMLSerializer serializer = XMLSerializer.newInstance(output);
<ide> serializer.writeStartDocument();
<ide> serializer.writeStartElement(TOPIC_TOPIC.localName);
<ide> }
<ide>
<ide> // update current element's @href value
<del> final URI relativePath = toURI(getRelativePath(new File(fileDir, FILE_NAME_STUB_DITAMAP), outputFileName));
<add> final URI relativePath = getRelativePath(inputFile.resolve(FILE_NAME_STUB_DITAMAP), outputFileName);
<ide> topicref.setAttribute(ATTRIBUTE_NAME_HREF, relativePath.toString());
<ide>
<del> final URI relativeToBase = URLUtils.getRelativePath(job.tempDir.toURI().resolve("dummy"), outputFileName.toURI());
<add> final URI relativeToBase = URLUtils.getRelativePath(job.tempDir.toURI().resolve("dummy"), outputFileName);
<ide> job.add(new Job.FileInfo.Builder().uri(relativeToBase).format(ATTR_FORMAT_VALUE_DITA).build());
<ide> }
<ide>
<ide> if (hrefValue.length() == 0) {
<ide> processTopicref(currentElem);
<ide> } else if (!ATTR_XTRF_VALUE_GENERATED.equals(xtrfValue)
<del> && !resolve(fileDir, hrefValue).getPath().equals(changeTable.get(resolve(fileDir, hrefValue).getPath()))) {
<add> && !inputFile.resolve(hrefValue).getPath().equals(changeTable.get(inputFile.resolve(hrefValue).getPath()))) {
<ide> processTopicref(currentElem);
<ide> }
<ide> }
<ide> chunkParser.setLogger(logger);
<ide> chunkParser.setJob(job);
<ide> chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
<del> chunkParser.write(fileDir);
<add> chunkParser.write(new File(inputFile.resolve(".")));
<ide> } else {
<ide> final ChunkTopicParser chunkParser = new ChunkTopicParser();
<ide> chunkParser.setLogger(logger);
<ide> chunkParser.setJob(job);
<ide> chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
<del> chunkParser.write(fileDir);
<add> chunkParser.write(new File(inputFile.resolve(".")));
<ide> }
<ide> } catch (final DITAOTException e) {
<ide> logger.error("Failed to process chunk: " + e.getMessage(), e);
<ide> private void updateReltable(final Element elem) {
<ide> final String hrefValue = elem.getAttribute(ATTRIBUTE_NAME_HREF);
<ide> if (hrefValue.length() != 0) {
<del> if (changeTable.containsKey(resolve(fileDir, hrefValue).getPath())) {
<del> String resulthrefValue = getRelativeUnixPath(fileDir + UNIX_SEPARATOR + FILE_NAME_STUB_DITAMAP,
<del> resolve(fileDir, hrefValue).getPath());
<add> if (changeTable.containsKey(inputFile.resolve(hrefValue).getPath())) {
<add> URI resulthrefValue = getRelativePath(inputFile.resolve(FILE_NAME_STUB_DITAMAP),
<add> inputFile.resolve(hrefValue));
<ide> final String fragment = getFragment(hrefValue);
<ide> if (fragment != null) {
<del> resulthrefValue = resulthrefValue + fragment;
<del> }
<del> elem.setAttribute(ATTRIBUTE_NAME_HREF, resulthrefValue);
<add> resulthrefValue = setFragment(resulthrefValue, fragment);
<add> }
<add> elem.setAttribute(ATTRIBUTE_NAME_HREF, resulthrefValue.toString());
<ide> }
<ide> }
<ide> final NodeList children = elem.getChildNodes(); |
|
JavaScript | bsd-2-clause | d4deac41e4ec95a1c698ca6bef47f3e14f6537bd | 0 | fraxachun/koala-framework,darimpulso/koala-framework,Sogl/koala-framework,fraxachun/koala-framework,Sogl/koala-framework,yacon/koala-framework,nsams/koala-framework,nsams/koala-framework,nsams/koala-framework,Ben-Ho/koala-framework,Ben-Ho/koala-framework,yacon/koala-framework,kaufmo/koala-framework,yacon/koala-framework,koala-framework/koala-framework,koala-framework/koala-framework,kaufmo/koala-framework,darimpulso/koala-framework,kaufmo/koala-framework | Ext.BLANK_IMAGE_URL = '/assets/ext/resources/images/default/s.gif';
Ext.namespace(
'Vps', 'Vpc',
'Vps.Component',
'Vps.User.Login',
'Vps.Auto',
'Vps.Form',
'Vps.Binding',
'Vpc.Advanced'
);
Ext.applyIf(Array.prototype, {
//deprecated! -> forEach (ist auch ein JS-Standard!)
each : function(fn, scope){
Ext.each(this, fn, scope);
},
//to use array.forEach directly
forEach : function(fn, scope){
Ext.each(this, fn, scope);
},
//add is alias for push
add : function() {
this.push.apply(this, arguments);
}
});
Ext.applyIf(Function.prototype, {
interceptResult: function(fcn, scope) {
if(typeof fcn != "function"){
return this;
}
var method = this;
var interception=function() {
var retval = method.apply(this || window, arguments);
var callArgs = Array.prototype.slice.call(arguments, 0);
var args=[retval].concat(callArgs);
var newRetval=fcn.apply(scope || this || window, args);
return newRetval;
};
if (this.prototype){
Ext.apply(interception.prototype, this.prototype)
if (this.superclass){ interception.superclass=this.superclass; }
if (this.override){ interception.override=this.override; }
}
return interception;
}
});
//http://extjs.com/forum/showthread.php?t=26644
Vps.clone = function(o) {
if('object' !== typeof o) {
return o;
}
var c = 'function' === typeof o.pop ? [] : {};
var p, v;
for(p in o) {
if(o.hasOwnProperty(p)) {
v = o[p];
if('object' === typeof v) {
c[p] = Ext.ux.clone(v);
}
else {
c[p] = v;
}
}
}
return c;
};
Ext.onReady(function()
{
// Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
if (Ext.QuickTips) {
Ext.QuickTips.init();
}
if (Ext.isIE6) {
Ext.each(Ext.DomQuery.select('.addHover'), function(el) {
var extEl = Ext.fly(el);
extEl.hover(
function() { this.addClass('hover'); },
function() { this.removeClass('hover'); },
extEl
);
});
}
});
Vps.application = { version: '{$application.version}' };
Vps.callWithErrorHandler = function(fn, scope) {
if (Vps.debug) {
//call without error handler
return fn.call(scope || window);
}
try {
return fn.call(scope || window);
} catch(e) {
if (e.toString) e = e.toString();
if (e.message) e = e.message;
if(Ext.get('loading')) {
Ext.get('loading').fadeOut({remove: true});
}
if (Ext.Msg) {
Ext.Msg.alert(trlVps('Error'), trlVps("An error occured"));
}
Ext.Ajax.request({
url: '/vps/error/error/jsonMail',
params: {msg: e}
});
}
};
Vps.contentReadyHandlers = [];
Vps.onContentReady = function(fn, scope) {
if (Vps.currentViewport) {
//in einer Ext-Anwendung mit viewport den contentReadHandler
//nicht gleich ausfhren, das paragraphs-panel fhrt es dafr aus
Vps.contentReadyHandlers.push({
fn: fn,
scope: scope
});
} else {
//normales Frontend
Ext.onReady(fn, scope);
}
};
Vps.include = function(url, restart)
{
if (url.substr(-4) == '.css') {
var s = document.createElement('link');
s.setAttribute('type', 'text/css');
s.setAttribute('href', url+'?'+Math.random());
} else {
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', url+'?'+Math.random());
}
s.onload = function () {
if (restart) Vps.restart();
};
document.getElementsByTagName("head")[0].appendChild(s);
};
Vps.restart = function()
{
Ext.getBody().unmask();
if (Vps.currentViewport) {
Vps.currentViewport.onDestroy();
delete Vps.currentViewport;
}
Vps.main();
};
var restart = Vps.restart;
var include = Vps.include;
| Vps_js/Vps.js | Ext.BLANK_IMAGE_URL = '/assets/ext/resources/images/default/s.gif';
Ext.namespace(
'Vps', 'Vpc',
'Vps.Component',
'Vps.User.Login',
'Vps.Auto',
'Vps.Form',
'Vps.Binding',
'Vpc.Advanced'
);
Ext.applyIf(Array.prototype, {
//deprecated! -> forEach (ist auch ein JS-Standard!)
each : function(fn, scope){
Ext.each(this, fn, scope);
},
//to use array.forEach directly
forEach : function(fn, scope){
Ext.each(this, fn, scope);
},
//add is alias for push
add : function() {
this.push.apply(this, arguments);
}
});
Ext.onReady(function()
{
// Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
if (Ext.QuickTips) {
Ext.QuickTips.init();
}
if (Ext.isIE6) {
Ext.each(Ext.DomQuery.select('.addHover'), function(el) {
var extEl = Ext.fly(el);
extEl.hover(
function() { this.addClass('hover'); },
function() { this.removeClass('hover'); },
extEl
);
});
}
});
Vps.application = { version: '{$application.version}' };
Vps.callWithErrorHandler = function(fn, scope) {
if (Vps.debug) {
//call without error handler
return fn.call(scope || window);
}
try {
return fn.call(scope || window);
} catch(e) {
if (e.toString) e = e.toString();
if (e.message) e = e.message;
if(Ext.get('loading')) {
Ext.get('loading').fadeOut({remove: true});
}
if (Ext.Msg) {
Ext.Msg.alert(trlVps('Error'), trlVps("An error occured"));
}
Ext.Ajax.request({
url: '/vps/error/error/jsonMail',
params: {msg: e}
});
}
};
Vps.contentReadyHandlers = [];
Vps.onContentReady = function(fn, scope) {
if (Vps.currentViewport) {
//in einer Ext-Anwendung mit viewport den contentReadHandler
//nicht gleich ausfhren, das paragraphs-panel fhrt es dafr aus
Vps.contentReadyHandlers.push({
fn: fn,
scope: scope
});
} else {
//normales Frontend
Ext.onReady(fn, scope);
}
};
Vps.include = function(url, restart)
{
if (url.substr(-4) == '.css') {
var s = document.createElement('link');
s.setAttribute('type', 'text/css');
s.setAttribute('href', url+'?'+Math.random());
} else {
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', url+'?'+Math.random());
}
s.onload = function () {
if (restart) Vps.restart();
};
document.getElementsByTagName("head")[0].appendChild(s);
};
Vps.restart = function()
{
Ext.getBody().unmask();
if (Vps.currentViewport) {
Vps.currentViewport.onDestroy();
delete Vps.currentViewport;
}
Vps.main();
};
var restart = Vps.restart;
var include = Vps.include;
| möglicherweise nützliche hilfs-funktionen
| Vps_js/Vps.js | möglicherweise nützliche hilfs-funktionen | <ide><path>ps_js/Vps.js
<ide> this.push.apply(this, arguments);
<ide> }
<ide> });
<add>
<add>Ext.applyIf(Function.prototype, {
<add>
<add> interceptResult: function(fcn, scope) {
<add> if(typeof fcn != "function"){
<add> return this;
<add> }
<add> var method = this;
<add> var interception=function() {
<add> var retval = method.apply(this || window, arguments);
<add> var callArgs = Array.prototype.slice.call(arguments, 0);
<add> var args=[retval].concat(callArgs);
<add> var newRetval=fcn.apply(scope || this || window, args);
<add> return newRetval;
<add> };
<add> if (this.prototype){
<add> Ext.apply(interception.prototype, this.prototype)
<add> if (this.superclass){ interception.superclass=this.superclass; }
<add> if (this.override){ interception.override=this.override; }
<add> }
<add> return interception;
<add> }
<add>});
<add>
<add>//http://extjs.com/forum/showthread.php?t=26644
<add>Vps.clone = function(o) {
<add> if('object' !== typeof o) {
<add> return o;
<add> }
<add> var c = 'function' === typeof o.pop ? [] : {};
<add> var p, v;
<add> for(p in o) {
<add> if(o.hasOwnProperty(p)) {
<add> v = o[p];
<add> if('object' === typeof v) {
<add> c[p] = Ext.ux.clone(v);
<add> }
<add> else {
<add> c[p] = v;
<add> }
<add> }
<add> }
<add> return c;
<add>};
<ide>
<ide> Ext.onReady(function()
<ide> { |
|
Java | apache-2.0 | 52272df23aba35faf793281c00aab1a88d23f94c | 0 | kryptnostic/kodex | package com.kryptnostic.v2.search;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
import retrofit.http.Body;
import retrofit.http.POST;
import retrofit.http.Path;
public interface SearchApi {
String CONTROLLER = "/search";
String OBJECT_ID = "objectId";
String OBJECT_ID_PATH = "/{" + OBJECT_ID + "}";
String COUNT = "count";
String COUNT_PATH = "/{" + COUNT + "}";
/**
* The values of the returned map are sets of index segment ids;
* WARNING: the sets of UUIDs are NOT object ids corresponding to
* actual documents containing the search term!
*
* The keys correspond to the actual objects whose cryptoservices
* should be used to decrypt the index segments
*
* To obtain the actual documents containing the search terms, the client
* needs to:
* (1) For each key, value pair: load the objects specified
* in the value to obtain (encrypted) inverted index segments;
* decrypt them using the cryptoservice for the object specified
* in the key
* (2) Filter out those inverted index segments corresponding to terms that
* did not appear in the original set of search terms (this filtering
* is necessary due to potential hash collisions)
* (3) Collect the object ids appear in the remaining inverted index
* segments; loading and decrypting these objects will result in the
* actual documents containing the search terms
*/
@POST( CONTROLLER )
Map<VersionedObjectKey, Set<UUID>> search( @Body List<byte[]> fheEncryptedSearchTerms );
/**
* For a given inverted index segment corresponding to a particular object id
* and search term, we compute the "address" at which to store the inverted
* index segment as follows:
* (1) Obtain an object search pair of the nearest ancestor that has an object
* search pair (in the case of kodex, this would be the channel)
* (2) Use the client hash function, object search pair, and fhe encrypted search
* term to compute the "base address"
* (3) Compute SHA256( base_address || j ), where j is the smallest natural number
* that has not been used in calculating addresses for the ancestor object
* from step (1)
*
* The result of step (3) is the "address" at which we store the inverted
* index segment.
*
* The motivation for using distinct values of j is to avoid having multiple
* inverted index segments corresponding to a particular search term getting
* stored at the same address, because we want to avoid leaking information
* about the distribution of term frequencies.
*
* The client and server must cooperate to prevent reusing values of j. The
* current segment count is the smallest value of j that's safe to use;
* calling getAndAddSegmentCount with count = N will cause the server to
* "reserve" the next N values of j and then return the current count.
*
* Note that the client shuffles its inverted index segments before computing
* addresses, to partially protect against the case of a malicious server that
* fails to increase its stored segment counts (and e.g. returns 0 every time
* getAndAddSegmentCount is called, no matter what count the client passes in)
*/
@POST( CONTROLLER + OBJECT_ID_PATH + COUNT_PATH )
public int getAndAddSegmentCount( @Path( OBJECT_ID ) UUID objectId, @Path( COUNT ) int count );
}
| src/main/java/com/kryptnostic/v2/search/SearchApi.java | package com.kryptnostic.v2.search;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
import retrofit.http.Body;
import retrofit.http.POST;
import retrofit.http.Path;
public interface SearchApi {
String CONTROLLER = "/search";
String OBJECT_ID = "objectId";
String OBJECT_ID_PATH = "/{" + OBJECT_ID + "}";
String COUNT = "count";
String COUNT_PATH = "/{" + COUNT + "}";
/**
* The values of the returned map are lists of index segment ids;
* WARNING: the list of UUIDs are NOT object ids corresponding to
* actual documents containing the search term!
*
* The keys correspond to the actual objects whose cryptoservices
* should be used to decrypt the index segments after loading them
*
* To obtain the actual documents containing the search terms, the client
* needs to:
* (1) Load and decrypt the objects specified in the keys
* to obtain inverted index segments
* (2) Filter out those inverted index segments corresponding to terms that
* did not appear in the original set of search terms (this filtering
* is necessary due to potential hash collisions)
* (3) Collect the object ids appear in the remaining inverted index
* segments; loading and decrypting these objects will result in the
* actual documents containing the search terms
*/
@POST( CONTROLLER )
Map<VersionedObjectKey, Set<UUID>> search( @Body List<byte[]> fheEncryptedSearchTerms );
/**
* For a given inverted index segment corresponding to a particular object id
* and search term, we compute the "address" at which to store the inverted
* index segment as follows:
* (1) Obtain an object search pair of the nearest ancestor that has an object
* search pair (in the case of kodex, this would be the channel)
* (2) Use the client hash function, object search pair, and fhe encrypted search
* term to compute the "base address"
* (3) Compute SHA256( base_address || j ), where j is the smallest natural number
* that has not been used in calculating addresses for the ancestor object
* from step (1)
*
* The result of step (3) is the "address" at which we store the inverted
* index segment.
*
* The motivation for using distinct values of j is to avoid having multiple
* inverted index segments corresponding to a particular search term getting
* stored at the same address, because we want to avoid leaking information
* about the distribution of term frequencies.
*
* The client and server must cooperate to prevent reusing values of j. The
* current segment count is the smallest value of j that's safe to use;
* calling getAndAddSegmentCount with count = N will cause the server to
* "reserve" the next N values of j and then return the current count.
*
* Note that the client shuffles its inverted index segments before computing
* addresses, to partially protect against the case of a malicious server that
* fails to increase its stored segment counts (and e.g. returns 0 every time
* getAndAddSegmentCount is called, no matter what count the client passes in)
*/
@POST( CONTROLLER + OBJECT_ID_PATH + COUNT_PATH )
public int getAndAddSegmentCount( @Path( OBJECT_ID ) UUID objectId, @Path( COUNT ) int count );
}
| Update comments on SearchApi
| src/main/java/com/kryptnostic/v2/search/SearchApi.java | Update comments on SearchApi | <ide><path>rc/main/java/com/kryptnostic/v2/search/SearchApi.java
<ide> String COUNT_PATH = "/{" + COUNT + "}";
<ide>
<ide> /**
<del> * The values of the returned map are lists of index segment ids;
<del> * WARNING: the list of UUIDs are NOT object ids corresponding to
<add> * The values of the returned map are sets of index segment ids;
<add> * WARNING: the sets of UUIDs are NOT object ids corresponding to
<ide> * actual documents containing the search term!
<ide> *
<ide> * The keys correspond to the actual objects whose cryptoservices
<del> * should be used to decrypt the index segments after loading them
<add> * should be used to decrypt the index segments
<ide> *
<ide> * To obtain the actual documents containing the search terms, the client
<ide> * needs to:
<del> * (1) Load and decrypt the objects specified in the keys
<del> * to obtain inverted index segments
<add> * (1) For each key, value pair: load the objects specified
<add> * in the value to obtain (encrypted) inverted index segments;
<add> * decrypt them using the cryptoservice for the object specified
<add> * in the key
<ide> * (2) Filter out those inverted index segments corresponding to terms that
<ide> * did not appear in the original set of search terms (this filtering
<ide> * is necessary due to potential hash collisions) |
|
Java | mit | 57832f901daf9549bf64cd8f3e224ddaeb856d3e | 0 | flesire/ontrack,flesire/ontrack,nemerosa/ontrack,nemerosa/ontrack,nemerosa/ontrack,nemerosa/ontrack,flesire/ontrack,flesire/ontrack,nemerosa/ontrack,flesire/ontrack | package net.nemerosa.ontrack.service;
import com.fasterxml.jackson.databind.JsonNode;
import net.nemerosa.ontrack.model.security.BranchEdit;
import net.nemerosa.ontrack.model.security.SecurityService;
import net.nemerosa.ontrack.model.structure.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CopyServiceImpl implements CopyService {
private final StructureService structureService;
private final PropertyService propertyService;
private final SecurityService securityService;
@Autowired
public CopyServiceImpl(StructureService structureService, PropertyService propertyService, SecurityService securityService) {
this.structureService = structureService;
this.propertyService = propertyService;
this.securityService = securityService;
}
@Override
public Branch copy(Branch targetBranch, BranchCopyRequest request) {
// Gets the source branch
Branch sourceBranch = structureService.getBranch(request.getSourceBranchId());
// If same branch, rejects
if (sourceBranch.id() == targetBranch.id()) {
throw new IllegalArgumentException("Cannot copy the branch into itself.");
}
// Checks the rights on the target branch
securityService.checkProjectFunction(targetBranch, BranchEdit.class);
// Now, we can work in a secure context
securityService.asAdmin(() -> doCopy(sourceBranch, targetBranch, request));
return targetBranch;
}
protected void doCopy(Branch sourceBranch, Branch targetBranch, BranchCopyRequest request) {
// Same project?
boolean sameProject = (sourceBranch.projectId() == targetBranch.projectId());
// TODO Branch properties
// Promotion level and properties
doCopyPromotionLevels(sourceBranch, targetBranch, request);
// TODO Validation stamps and properties
// TODO User filters
}
protected void doCopyPromotionLevels(Branch sourceBranch, Branch targetBranch, BranchCopyRequest request) {
List<PromotionLevel> sourcePromotionLevels = structureService.getPromotionLevelListForBranch(sourceBranch.getId());
for (PromotionLevel sourcePromotionLevel : sourcePromotionLevels) {
Optional<PromotionLevel> targetPromotionLevelOpt = structureService.findPromotionLevelByName(targetBranch.getProject().getName(), targetBranch.getName(), sourcePromotionLevel.getName());
if (!targetPromotionLevelOpt.isPresent()) {
// Copy of the promotion level
PromotionLevel targetPromotionLevel = structureService.newPromotionLevel(
PromotionLevel.of(
targetBranch,
NameDescription.nd(
sourcePromotionLevel.getName(),
applyReplacements(sourcePromotionLevel.getDescription(), request.getPromotionLevelReplacements())
)
)
);
// Copy of the image
Document image = structureService.getPromotionLevelImage(sourcePromotionLevel.getId());
if (image != null) {
structureService.setPromotionLevelImage(targetPromotionLevel.getId(), image);
}
// Copy of properties
// Gets the properties of the source promotion level
List<Property<?>> properties = propertyService.getProperties(sourcePromotionLevel);
for (Property<?> property : properties) {
doCopyProperty(property, targetPromotionLevel, request.getPromotionLevelReplacements());
}
}
}
}
protected <T> void doCopyProperty(Property<T> property, ProjectEntity targetEntity, List<Replacement> replacements) {
if (!property.isEmpty()) {
// Property value replacement
T data = property.getType().replaceValue(property.getValue(), s -> applyReplacements(s, replacements));
// Property data
JsonNode jsonData = property.getType().forStorage(data);
// Creates the property
propertyService.editProperty(
targetEntity,
property.getType().getTypeName(),
jsonData
);
}
}
protected static String applyReplacements(final String value, List<Replacement> replacements) {
String transformedValue = value;
for (Replacement replacement : replacements) {
transformedValue = replacement.replace(transformedValue);
}
return transformedValue;
}
}
| ontrack-service/src/main/java/net/nemerosa/ontrack/service/CopyServiceImpl.java | package net.nemerosa.ontrack.service;
import com.fasterxml.jackson.databind.JsonNode;
import net.nemerosa.ontrack.model.security.BranchEdit;
import net.nemerosa.ontrack.model.security.SecurityService;
import net.nemerosa.ontrack.model.structure.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CopyServiceImpl implements CopyService {
private final StructureService structureService;
private final PropertyService propertyService;
private final SecurityService securityService;
@Autowired
public CopyServiceImpl(StructureService structureService, PropertyService propertyService, SecurityService securityService) {
this.structureService = structureService;
this.propertyService = propertyService;
this.securityService = securityService;
}
@Override
public Branch copy(Branch targetBranch, BranchCopyRequest request) {
// Gets the source branch
Branch sourceBranch = structureService.getBranch(request.getSourceBranchId());
// If same branch, rejects
if (sourceBranch.id() == targetBranch.id()) {
throw new IllegalArgumentException("Cannot copy the branch into itself.");
}
// Checks the rights on the target branch
securityService.checkProjectFunction(targetBranch, BranchEdit.class);
// Now, we can work in a secure context
securityService.asAdmin(() -> doCopy(sourceBranch, targetBranch, request));
return targetBranch;
}
protected void doCopy(Branch sourceBranch, Branch targetBranch, BranchCopyRequest request) {
// Same project?
boolean sameProject = (sourceBranch.projectId() == targetBranch.projectId());
// TODO Branch properties
// Promotion level and properties
doCopyPromotionLevels(sourceBranch, targetBranch, request);
// TODO Validation stamps and properties
// TODO User filters
}
protected void doCopyPromotionLevels(Branch sourceBranch, Branch targetBranch, BranchCopyRequest request) {
List<PromotionLevel> sourcePromotionLevels = structureService.getPromotionLevelListForBranch(sourceBranch.getId());
for (PromotionLevel sourcePromotionLevel : sourcePromotionLevels) {
Optional<PromotionLevel> targetPromotionLevelOpt = structureService.findPromotionLevelByName(targetBranch.getProject().getName(), targetBranch.getName(), sourcePromotionLevel.getName());
if (!targetPromotionLevelOpt.isPresent()) {
// Copy of the promotion level
PromotionLevel targetPromotionLevel = structureService.newPromotionLevel(
PromotionLevel.of(
targetBranch,
NameDescription.nd(
sourcePromotionLevel.getName(),
applyReplacements(sourcePromotionLevel.getDescription(), request.getPromotionLevelReplacements())
)
)
);
// Copy of properties
// Gets the properties of the source promotion level
List<Property<?>> properties = propertyService.getProperties(sourcePromotionLevel);
for (Property<?> property : properties) {
doCopyProperty(property, targetPromotionLevel, request.getPromotionLevelReplacements());
}
}
}
}
protected <T> void doCopyProperty(Property<T> property, ProjectEntity targetEntity, List<Replacement> replacements) {
if (!property.isEmpty()) {
// Property value replacement
T data = property.getType().replaceValue(property.getValue(), s -> applyReplacements(s, replacements));
// Property data
JsonNode jsonData = property.getType().forStorage(data);
// Creates the property
propertyService.editProperty(
targetEntity,
property.getType().getTypeName(),
jsonData
);
}
}
protected static String applyReplacements(final String value, List<Replacement> replacements) {
String transformedValue = value;
for (Replacement replacement : replacements) {
transformedValue = replacement.replace(transformedValue);
}
return transformedValue;
}
}
| #39 Copy of promotion levels images
| ontrack-service/src/main/java/net/nemerosa/ontrack/service/CopyServiceImpl.java | #39 Copy of promotion levels images | <ide><path>ntrack-service/src/main/java/net/nemerosa/ontrack/service/CopyServiceImpl.java
<ide> )
<ide> )
<ide> );
<add> // Copy of the image
<add> Document image = structureService.getPromotionLevelImage(sourcePromotionLevel.getId());
<add> if (image != null) {
<add> structureService.setPromotionLevelImage(targetPromotionLevel.getId(), image);
<add> }
<ide> // Copy of properties
<ide> // Gets the properties of the source promotion level
<ide> List<Property<?>> properties = propertyService.getProperties(sourcePromotionLevel); |
|
Java | apache-2.0 | e9dd5b487b765782ecfd6a4b574b936c03fe2fca | 0 | xargsgrep/PortKnocker | /*
* Copyright 2014 Ahsan Rabbani
*
* 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.xargsgrep.portknocker.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import com.xargsgrep.portknocker.model.Host;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String TAG = "DatabaseHelper";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_FILENAME = "hosts.db";
public static final String HOST_TABLE_NAME = "host";
public static final String HOST_ID_COLUMN = BaseColumns._ID;
public static final String HOST_LABEL_COLUMN = "label";
public static final String HOST_HOSTNAME_COLUMN = "hostname";
public static final String HOST_DELAY_COLUMN = "delay";
public static final String HOST_TCP_CONNECT_TIMEOUT_COLUMN = "tcp_connect_timeout";
public static final String HOST_LAUNCH_INTENT_PACKAGE_COLUMN = "launch_intent_package";
public static final String HOST_USERNAME_COLUMN = "username";
public static final String HOST_TARGET_PORT_COLUMN = "target_port";
public static final String PORT_TABLE_NAME = "port";
public static final String PORT_HOST_ID_COLUMN = "host_id";
public static final String PORT_INDEX_COLUMN = "idx";
public static final String PORT_PORT_COLUMN = "port";
public static final String PORT_PROTOCOL_COLUMN = "protocol";
public static final String[] HOST_TABLE_COLUMNS = new String[]
{
HOST_ID_COLUMN,
HOST_LABEL_COLUMN,
HOST_HOSTNAME_COLUMN,
HOST_DELAY_COLUMN,
HOST_LAUNCH_INTENT_PACKAGE_COLUMN,
HOST_USERNAME_COLUMN,
HOST_TARGET_PORT_COLUMN,
HOST_TCP_CONNECT_TIMEOUT_COLUMN
};
public static final String[] PORT_TABLE_COLUMNS = new String[]
{
PORT_HOST_ID_COLUMN,
PORT_INDEX_COLUMN,
PORT_PORT_COLUMN,
PORT_PROTOCOL_COLUMN
};
public DatabaseHelper(Context context)
{
super(context, DATABASE_FILENAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String createHostTableSQL =
"create table %s (" +
" %s integer primary key autoincrement," +
" %s string not null," +
" %s string not null," +
" %s integer not null default %d," +
" %s string," +
" %s string," +
" %s integer," +
" %s integer not null default %d" +
");";
createHostTableSQL = String.format(
createHostTableSQL,
HOST_TABLE_NAME,
HOST_ID_COLUMN,
HOST_LABEL_COLUMN,
HOST_HOSTNAME_COLUMN,
HOST_DELAY_COLUMN, Host.DEFAULT_DELAY,
HOST_LAUNCH_INTENT_PACKAGE_COLUMN,
HOST_USERNAME_COLUMN,
HOST_TARGET_PORT_COLUMN,
HOST_TCP_CONNECT_TIMEOUT_COLUMN, Host.DEFAULT_TCP_CONNECT_TIMEOUT
);
String createPortTableSQL =
"create table %s (" +
" %s integer not null," +
" %s integer not null," +
" %s integer not null," +
" %s integer not null" +
");";
createPortTableSQL = String.format(
createPortTableSQL,
PORT_TABLE_NAME,
PORT_HOST_ID_COLUMN,
PORT_INDEX_COLUMN,
PORT_PORT_COLUMN,
PORT_PROTOCOL_COLUMN
);
db.execSQL(createHostTableSQL);
db.execSQL(createPortTableSQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.d(TAG, "Upgrading database from version " + oldVersion + " to version " + newVersion);
switch (newVersion)
{
case DATABASE_VERSION:
db.execSQL(String.format(
"alter table %s add column %s integer not null default %d;",
HOST_TABLE_NAME,
HOST_TCP_CONNECT_TIMEOUT_COLUMN,
Host.DEFAULT_TCP_CONNECT_TIMEOUT
));
return;
default:
throw new IllegalStateException("Invalid newVersion: " + newVersion);
}
}
}
/*
Version 1:
create table host(
_id integer primary key autoincrement,
label string not null,
hostname string not null,
delay integer not null default 0,
launch_intent_package string,
username string,
target_port integer
);
Version 2:
create table host(
_id integer primary key autoincrement,
label string not null,
hostname string not null,
delay integer not null default 1000,
launch_intent_package string,
username string,
target_port integer,
tcp_connect_timeout integer not null default 100,
);
*/
| app/src/main/java/com/xargsgrep/portknocker/db/DatabaseHelper.java | /*
* Copyright 2014 Ahsan Rabbani
*
* 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.xargsgrep.portknocker.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import com.xargsgrep.portknocker.model.Host;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String TAG = "DatabaseHelper";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_FILENAME = "hosts.db";
public static final String HOST_TABLE_NAME = "host";
public static final String HOST_ID_COLUMN = BaseColumns._ID;
public static final String HOST_LABEL_COLUMN = "label";
public static final String HOST_HOSTNAME_COLUMN = "hostname";
public static final String HOST_DELAY_COLUMN = "delay";
public static final String HOST_TCP_CONNECT_TIMEOUT_COLUMN = "tcp_connect_timeout";
public static final String HOST_LAUNCH_INTENT_PACKAGE_COLUMN = "launch_intent_package";
public static final String HOST_USERNAME_COLUMN = "username";
public static final String HOST_TARGET_PORT_COLUMN = "target_port";
public static final String PORT_TABLE_NAME = "port";
public static final String PORT_HOST_ID_COLUMN = "host_id";
public static final String PORT_INDEX_COLUMN = "idx";
public static final String PORT_PORT_COLUMN = "port";
public static final String PORT_PROTOCOL_COLUMN = "protocol";
public static final String[] HOST_TABLE_COLUMNS = new String[]
{
HOST_ID_COLUMN,
HOST_LABEL_COLUMN,
HOST_HOSTNAME_COLUMN,
HOST_DELAY_COLUMN,
HOST_LAUNCH_INTENT_PACKAGE_COLUMN,
HOST_USERNAME_COLUMN,
HOST_TARGET_PORT_COLUMN,
HOST_TCP_CONNECT_TIMEOUT_COLUMN
};
public static final String[] PORT_TABLE_COLUMNS = new String[]
{
PORT_HOST_ID_COLUMN,
PORT_INDEX_COLUMN,
PORT_PORT_COLUMN,
PORT_PROTOCOL_COLUMN
};
public DatabaseHelper(Context context)
{
super(context, DATABASE_FILENAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String createHostTableSQL =
"create table %s (" +
" %s integer primary key autoincrement," +
" %s string not null," +
" %s string not null," +
" %s integer not null default %d," +
" %s string," +
" %s string," +
" %s integer," +
" %s integer not null default %d" +
");";
createHostTableSQL = String.format(
createHostTableSQL,
HOST_TABLE_NAME,
HOST_ID_COLUMN,
HOST_LABEL_COLUMN,
HOST_HOSTNAME_COLUMN,
HOST_DELAY_COLUMN, Host.DEFAULT_DELAY,
HOST_LAUNCH_INTENT_PACKAGE_COLUMN,
HOST_USERNAME_COLUMN,
HOST_TARGET_PORT_COLUMN,
HOST_TCP_CONNECT_TIMEOUT_COLUMN, Host.DEFAULT_TCP_CONNECT_TIMEOUT
);
String createPortTableSQL =
"create table %s (" +
" %s integer not null," +
" %s integer not null," +
" %s integer not null," +
" %s integer not null" +
");";
createPortTableSQL = String.format(
createPortTableSQL,
PORT_TABLE_NAME,
PORT_HOST_ID_COLUMN,
PORT_INDEX_COLUMN,
PORT_PORT_COLUMN,
PORT_PROTOCOL_COLUMN
);
db.execSQL(createHostTableSQL);
db.execSQL(createPortTableSQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.d(TAG, "Upgrading database from version " + oldVersion + " to version " + newVersion);
switch (newVersion)
{
case DATABASE_VERSION:
db.execSQL(String.format(
"alter table %s add column %s integer not null default %d;",
HOST_TABLE_NAME,
HOST_TCP_CONNECT_TIMEOUT_COLUMN,
Host.DEFAULT_TCP_CONNECT_TIMEOUT
));
return;
default:
throw new IllegalStateException("Invalid newVersion: " + newVersion);
}
}
}
/*
Version 1:
create table host(
_id integer primary key autoincrement,
label string not null,
hostname string not null,
delay integer not null default 0,
launch_intent_package string,
username string,
target_port integer
);
Version 2:
create table host(
_id integer primary key autoincrement,
label string not null,
hostname string not null,
delay integer not null default 1000,
launch_intent_package string,
username string,
target_port integer,
tcp_connect_timeout integer not null default 100,
);
*/
| formatting
| app/src/main/java/com/xargsgrep/portknocker/db/DatabaseHelper.java | formatting | <ide><path>pp/src/main/java/com/xargsgrep/portknocker/db/DatabaseHelper.java
<ide> public static final String PORT_PROTOCOL_COLUMN = "protocol";
<ide>
<ide> public static final String[] HOST_TABLE_COLUMNS = new String[]
<del> {
<del> HOST_ID_COLUMN,
<del> HOST_LABEL_COLUMN,
<del> HOST_HOSTNAME_COLUMN,
<del> HOST_DELAY_COLUMN,
<del> HOST_LAUNCH_INTENT_PACKAGE_COLUMN,
<del> HOST_USERNAME_COLUMN,
<del> HOST_TARGET_PORT_COLUMN,
<del> HOST_TCP_CONNECT_TIMEOUT_COLUMN
<del> };
<add> {
<add> HOST_ID_COLUMN,
<add> HOST_LABEL_COLUMN,
<add> HOST_HOSTNAME_COLUMN,
<add> HOST_DELAY_COLUMN,
<add> HOST_LAUNCH_INTENT_PACKAGE_COLUMN,
<add> HOST_USERNAME_COLUMN,
<add> HOST_TARGET_PORT_COLUMN,
<add> HOST_TCP_CONNECT_TIMEOUT_COLUMN
<add> };
<ide> public static final String[] PORT_TABLE_COLUMNS = new String[]
<del> {
<del> PORT_HOST_ID_COLUMN,
<del> PORT_INDEX_COLUMN,
<del> PORT_PORT_COLUMN,
<del> PORT_PROTOCOL_COLUMN
<del> };
<add> {
<add> PORT_HOST_ID_COLUMN,
<add> PORT_INDEX_COLUMN,
<add> PORT_PORT_COLUMN,
<add> PORT_PROTOCOL_COLUMN
<add> };
<ide>
<ide> public DatabaseHelper(Context context)
<ide> { |
|
Java | mit | ce4ce7719b69b1e26707939a18811bf466594c7b | 0 | CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab | package org.xcolab.portlets.admintasks.migration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.ext.portlet.service.*;
import com.liferay.portal.model.User;
import org.xcolab.portlets.admintasks.migration.persistence.NewPersistenceCleaner;
import org.xcolab.portlets.admintasks.migration.persistence.NewPersistenceQueries;
import org.xcolab.portlets.admintasks.migration.persistence.OldPersistenceQueries;
import com.ext.portlet.ProposalAttributeKeys;
import com.ext.portlet.model.ContestPhaseRibbonType;
import com.ext.portlet.model.Plan2Proposal;
import com.ext.portlet.model.PlanAttribute;
import com.ext.portlet.model.PlanDescription;
import com.ext.portlet.model.PlanFan;
import com.ext.portlet.model.PlanItem;
import com.ext.portlet.model.PlanMeta;
import com.ext.portlet.model.PlanModelRun;
import com.ext.portlet.model.PlanSection;
import com.ext.portlet.model.PlanType;
import com.ext.portlet.model.PlanVote;
import com.ext.portlet.model.Proposal;
import com.ext.portlet.model.Proposal2Phase;
import com.ext.portlet.model.ProposalSupporter;
import com.ext.portlet.model.ProposalVersion;
import com.ext.portlet.model.ProposalVote;
import com.ext.portlet.plans.PlanConstants;
import com.icesoft.faces.async.render.SessionRenderer;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.UserLocalServiceUtil;
/**
* Created with IntelliJ IDEA.
* User: patrickhiesel
* Date: 9/17/13
* Time: 12:33 PM
* To change this template use File | Settings | File Templates.
*/
public class DataMigrator implements Runnable {
List<String> reference;
private boolean TESTING = true;
public boolean STOP = false;
private final static String[] regionsDevelopedArr = {"United States", "European Union",
"Russia/Former Soviet Union", "OECD Asia", "Canada"};
private final static String[] regionsRapidlyDevelopingArr = {"China", "India", "Brazil", "South Africa", "Mexico",
"Rapidly developing Asia",};
private final static String[] regionsOtherDevelopingArr = {"Middle East", "Latin America", "Africa",
"Other developing Asia"};
private final static Set<String> regionsDeveloped = new HashSet<String>(Arrays.asList(regionsDevelopedArr));
private final static Set<String> regionsRapidlyDeveloping = new HashSet<String>(
Arrays.asList(regionsRapidlyDevelopingArr));
private final static Set<String> regionsOtherDeveloping = new HashSet<String>(
Arrays.asList(regionsOtherDevelopingArr));
public DataMigrator(List<String> reference){
this.reference = reference;
}
public void run() {
setPermissions();
if (!(new NewPersistenceCleaner(reference).deleteAllRecordsForNewEntities())) return;
List<Pair<Long,List<PlanItem>>> groupedPlans = getAllDistinctPlanGroupIds();
pushAjaxUpdate("Creating new Proposals");
pushAjaxUpdate("0%");
int counter = 0;
boolean skippedFirstRecords = false;
for(Iterator<Pair<Long,List<PlanItem>>> i = groupedPlans.iterator(); i.hasNext(); ) {
if (STOP) break;
// for testing skip first 100 plans
if (TESTING && !skippedFirstRecords) {
for (int z=0; z<100;z++) i.next();
skippedFirstRecords = true;
}
if (++counter > 0 && (counter % (groupedPlans.size() / 33)) == 0) updateLastAjaxUpdate((100 * counter / groupedPlans.size()) + "%");
Pair<Long,List<PlanItem>> pair = i.next();
createNewPlan(pair.getLeft(),pair.getRight());
if (counter > (groupedPlans.size()/10) && TESTING) break;
}
pushAjaxUpdate("-- MIGRATION FINISHED --");
}
private void setPermissions(){
PrincipalThreadLocal.setName(10144L);
PermissionChecker permissionChecker;
try {
permissionChecker = PermissionCheckerFactoryUtil.create(UserLocalServiceUtil.getUser(10144L), true);
} catch (Exception e) {
throw new RuntimeException(e);
}
PermissionThreadLocal.setPermissionChecker(permissionChecker);
}
private List<Pair<Long,List<PlanItem>>> getAllDistinctPlanGroupIds(){
pushAjaxUpdate("Getting Distinct PlanGroupIDs");
List<PlanItem> allPlans;
List<Pair<Long,List<PlanItem>>> results = new LinkedList<Pair<Long,List<PlanItem>>>();
try {
allPlans = PlanItemLocalServiceUtil.getPlans();
} catch (Exception e){
pushAjaxUpdate("Error: " + e);
return null;
}
pushAjaxUpdate("Got " + allPlans.size() + " Plans");
pushAjaxUpdate("Grouping Plans");
pushAjaxUpdate("0%");
int counter=0;
for(PlanItem plan : allPlans) {
if (++counter > 0 && (counter % (allPlans.size() / 3)) == 0)
updateLastAjaxUpdate((100 * counter / allPlans.size() + 1) + "%");
try{
long groupID = PlanItemGroupLocalServiceUtil.getPlanItemGroup(plan.getPlanId()).getGroupId();
boolean didFindGroupIdInSet = false;
for(Pair<Long,List<PlanItem>> pair : results) {
if (pair.getLeft().longValue() == groupID){
pair.getRight().add(0,plan);
didFindGroupIdInSet = true;
break;
}
}
if (!didFindGroupIdInSet){
Pair<Long,List<PlanItem>> newPair = new Pair<Long,List<PlanItem>>(groupID,new LinkedList<PlanItem>());
newPair.getRight().add(plan);
results.add(newPair);
}
} catch (Exception e){
System.out.println("No Group Found for ID " + plan.getPlanId());
}
}
pushAjaxUpdate("Done Getting Distinct PlanGroupIDs (count: " + results.size() + ")");
return results;
}
private void createNewPlan(long groupID, List<PlanItem> plans){
if (groupID == 1001501){
System.out.println("..");
}
// sort plans by create date
Collections.sort(plans, new Comparator<PlanItem>() {
public int compare(PlanItem o1, PlanItem o2) {
return o1.getUpdated().compareTo(o2.getUpdated());
}
});
PlanMeta currentPlanMeta = null;
Proposal2Phase latestP2P = null;
long currentContestPhase = 0;
// get current plan meta for setting proposal entity attributes
try{
currentPlanMeta = PlanMetaLocalServiceUtil.getCurrentForPlan(plans.get(0));
} catch (Exception e){
pushAjaxUpdate("Error while getting PlanMetas " + plans.get(0).getId() + ": " + e);
return;
}
long authorID = currentPlanMeta.getAuthorId();
Proposal proposal = null;
try {
proposal = ProposalLocalServiceUtil.create(authorID, 0);
} catch (Exception e){
pushAjaxUpdate("Error while creating Proposal " + groupID + ": " + e);
}
// set create date
proposal.setCreateDate(plans.get(0).getUpdated());
// set initial user group and discussion
proposal.setGroupId(currentPlanMeta.getPlanGroupId());
proposal.setDiscussionId(currentPlanMeta.getCategoryGroupId());
// update proposal
try {
ProposalLocalServiceUtil.updateProposal(proposal);
} catch (Exception e){
pushAjaxUpdate("Error while updating Proposal " + groupID + ": " + e);
}
List<Long> planFans = new ArrayList<Long>();
// Loop through all plans - each representing one contest phase
boolean isFirstInGroup = true;
for(PlanItem plan : plans) {
// get updated proposal
try {
proposal = ProposalLocalServiceUtil.getProposal(proposal.getProposalId());
} catch (Exception e){
pushAjaxUpdate("Error while updating Proposal " + groupID + ": " + e);
}
// add mapping to old DB schema
createPlan2ProposalMapping(plan,proposal);
// map proposal to contest phases
latestP2P = createProposal2PhaseMapping(plan,proposal, latestP2P, currentContestPhase);
currentContestPhase++;
// plan entity represents a last version of a plan (for given planId) so we need to iterate over all of it's versions
// to create respective attributes of a proposal
if (isFirstInGroup) {
// transfer regional attributes if they exist
try {
PlanAttribute regionAttribute = PlanItemLocalServiceUtil.getPlanAttribute(plan, "REGION");
if (regionAttribute != null) {
String region = regionAttribute.getAttributeValue();
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.REGION, region);
String regionEconomy = "Other Developing";
if (regionsDeveloped.contains(region)) {
regionEconomy = "Developed";
} else if (regionsRapidlyDeveloping.contains(region)) {
regionEconomy = "Rapidly Developing";
}
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.REGION_ECONOMY, regionEconomy);
}
PlanAttribute subregionAttribute = PlanItemLocalServiceUtil.getPlanAttribute(plan, "SUBREGION");
if (subregionAttribute != null) {
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.SUBREGION, subregionAttribute.getAttributeValue());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
// migrate team name
try {
PlanAttribute teamAttribute = PlanItemLocalServiceUtil.getPlanAttribute(plan, "TEAM");
if (teamAttribute != null) {
String teamName = teamAttribute.getAttributeValue();
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.TEAM, teamName);
}
}
catch (Exception e) {
e.printStackTrace();
}
createProposalAttributesFromPlan(plan,proposal);
createVotesFromPlan(plan,proposal);
// copy supporters (fans)
createSupporters(plan,proposal,planFans);
// create ribbons for this plan
createRibbons(plan, proposal);
// add supporters
copySupporters(plan,proposal);
// refresh discussion id, group id, updated date
copyMetaInfo(plan,proposal);
}
}
private void createVotesFromPlan(PlanItem plan, Proposal proposal){
List<PlanVote> planVotes = null;
long contestPhase = 0;
try{
planVotes = PlanVoteLocalServiceUtil.getPlanVotes(plan.getPlanId());
contestPhase = PlanItemLocalServiceUtil.getContestPhase(plan).getContestPhasePK();
} catch (Exception e){
pushAjaxUpdate("Error while getting Votes " + plan.getPlanId() + ": " + e);
return;
}
for (PlanVote planVote : planVotes){
ProposalVote vote = ProposalVoteLocalServiceUtil.create(contestPhase, planVote.getUserId());
vote.setCreateDate(planVote.getCreateDate());
vote.setProposalId(proposal.getProposalId());
try{
ProposalVoteLocalServiceUtil.addProposalVote(vote);
} catch (Exception e){
pushAjaxUpdate("Error while persisting Votes " + plan.getPlanId() + ": " + e);
return;
}
}
}
private void createSupporters(PlanItem plan, Proposal proposal, List<Long> proposalSupporter){
List<PlanFan> planFans = null;
long contestPhase = 0;
try{
planFans = PlanFanLocalServiceUtil.getPlanFansForPlan(plan.getPlanId());
} catch (Exception e){
pushAjaxUpdate("Error while getting Fans " + plan.getPlanId() + ": " + e);
return;
}
for (PlanFan planFan : planFans){
// add supporter if not already added
if (!proposalSupporter.contains(planFan.getUserId())){
ProposalSupporter supporter = ProposalSupporterLocalServiceUtil.create(proposal.getProposalId(),planFan.getUserId());
supporter.setCreateDate(planFan.getCreated());
try{
ProposalSupporterLocalServiceUtil.addProposalSupporter(supporter);
} catch (Exception e){
pushAjaxUpdate("Error while persisting Supporters " + plan.getPlanId() + ": " + e);
return;
}
proposalSupporter.add(planFan.getUserId());
}
}
}
private void createPlan2ProposalMapping(PlanItem plan, Proposal proposal){
Plan2Proposal plan2Proposal = Plan2ProposalLocalServiceUtil.createPlan2Proposal(plan.getPlanId());
plan2Proposal.setProposalId(proposal.getProposalId());
try {
Plan2ProposalLocalServiceUtil.addPlan2Proposal(plan2Proposal);
} catch (SystemException e1) {
pushAjaxUpdate("Error while creating mapping between plan " + plan.getPlanId() + " and proposal: " + proposal.getProposalId() + "\n" + e1);
}
}
private Proposal2Phase createProposal2PhaseMapping(PlanItem plan, Proposal proposal, Proposal2Phase latestP2P, long currentContestPhase){
// handle new Proposal2Contest Phase Mapping
if (currentContestPhase > 0){
// set VersionTo for old p2p mapping
latestP2P.setVersionTo(proposal.getCurrentVersion());
try{
Proposal2PhaseLocalServiceUtil.updateProposal2Phase(latestP2P);
}catch (SystemException e1) {
pushAjaxUpdate("Error while storing Proposal2Phase mapping" + e1);
}
}
// add new p2p record
//System.out.println("Current Version:" + proposal.getCurrentVersion() + " ID: " + proposal.getProposalId() + " ContestPhase: " + currentContestPhase);
PlanMeta matchingMeta = null;
try {
for (PlanMeta pm : PlanMetaLocalServiceUtil.getAllForPlan(plan)){
if (pm.getPlanVersion() == 0){
matchingMeta = pm;
}
}
} catch (SystemException e1) {
pushAjaxUpdate("Error while creating mapping between plan " + plan.getPlanId() + " and proposal: " + proposal.getProposalId() + "\n" + e1);
}
if(matchingMeta != null){
Proposal2Phase p2p = Proposal2PhaseLocalServiceUtil.create(proposal.getProposalId(),matchingMeta.getContestPhase());
p2p.setSortWeight(1);
p2p.setAutopromoteCandidate(false);
p2p.setVersionFrom(proposal.getCurrentVersion()); /* TODO how should we increment the version set/get attr?*/
p2p.setVersionTo(-1);
try{
Proposal2PhaseLocalServiceUtil.addProposal2Phase(p2p);
}catch (SystemException e1) {
pushAjaxUpdate("Error while storing Proposal2Phase mapping" + e1);
}
return p2p;
} else{
System.out.println("Not matching meta found: " + plan.getPlanId());
return null;
}
}
private void createProposalAttributesFromPlan(PlanItem plan, Proposal proposal){
List<PlanItem> planVersions = OldPersistenceQueries.getAllVersionsForPlanASC(plan.getPlanId());
for (PlanItem planVersion : planVersions) {
if (planVersion.getUpdateType().equalsIgnoreCase("CREATED")){
// ignore use just for transferring from one phase to another
} else if (planVersion.getUpdateType().equalsIgnoreCase("MODEL_UPDATED")){
// IGNORE because modelID is deprecated
} else if (planVersion.getUpdateType().equalsIgnoreCase("SCENARIO_UPDATED")){
// Get scenarioId from xcolab_PlanModelRun and use it to create attribute
setAttributeRelatedToScenario(planVersion,proposal,"SCENARIO_UPDATED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_POSITIONS_UPDATED")){
// IGNORE
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_DELETED")){
// SET visibility = false
proposal.setVisible(false);
} else if (planVersion.getUpdateType().equalsIgnoreCase("DESCRIPTION_UPDATED")){
// Get description from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"DESCRIPTION");
} else if (planVersion.getUpdateType().equalsIgnoreCase("NAME_UPDATED")){
// Get name from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"NAME");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_STATUS_UPDATED")){
// IGNORE (connected to PlanMeta (col: Status)
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_CLOSED")){
// Get open from PlanMeta - anyone can edit (open), only team members can edit
setAttributeRelatedToPlanMeta(planVersion,proposal,"PLAN_CLOSED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_OPENED")){
// Get open from PlanMeta - anyone can edit (open), only team members can edit
setAttributeRelatedToPlanMeta(planVersion,proposal,"PLAN_OPENED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_SECTION_UPDATED")){
// Get PlanSection -> .setAttr. (col: additionalId = planSectionDef. and String = content (date from PlanITem)
setAttributeRelatedToPlanSection(planVersion,proposal,"PLAN_SECTION_UPDATED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PITCH_UPDATED")){
// Get pitch from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"PITCH");
} else if (planVersion.getUpdateType().equalsIgnoreCase("IMAGE_UPDATED")){
// Get image_id from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"IMAGE_ID");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_REVERTED")){
// IGNORE
}
}
}
private void updateLatestVersionDate(Proposal proposal, Date date){
try{
ProposalVersion latestVersion = NewPersistenceQueries.getLatestVersionForProposal(proposal);
if (latestVersion != null){
latestVersion.setCreateDate(date);
ProposalVersionLocalServiceUtil.updateProposalVersion(latestVersion);
} else {
System.out.println("Could not update Version at proposalId: " + proposal.getProposalId());
}
} catch (Exception e){
e.printStackTrace();
pushAjaxUpdate("Could not find latest version for proposal: " + proposal.getProposalId());
return;
}
}
private void setAttributeRelatedToScenario(PlanItem plan, Proposal p, String attribute){
List<PlanModelRun> pmrs = null;
try{
pmrs = PlanModelRunLocalServiceUtil.getAllForPlan(plan);
} catch(Exception e){
pushAjaxUpdate("Error while getting ScenarioID " + plan.getPlanId() + ": " + e);
}
for(PlanModelRun pmr : pmrs) {
if (pmr.getPlanVersion() == plan.getVersion()){
try{
PlanType planType = PlanItemLocalServiceUtil.getPlanType(plan);
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),ProposalAttributeKeys.SCENARIO_ID,planType.getDefaultModelId(),null,pmr.getScenarioId(),0);
Map<String, String> attributes = getAttributes(plan);
Map<String, String> planAttributesToCopy = new HashMap<String, String>();
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_CO2_CONCENTRATION, "CO2_CONCENTRATION");
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_TEMP_CHANGE, "TEMP_CHANGE");
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_MITIGATION_COST_NO_ERRORS, "MITIGATION_COST_NO_ERRORS");
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_DAMAGE_COST, "DAMAGE_COST");
for (Map.Entry<String, String> attributeToCopy: planAttributesToCopy.entrySet()) {
if (attributes.containsKey(attributeToCopy.getValue())) {
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attributeToCopy.getKey(),
planType.getModelId(), attributes.get(attributeToCopy.getValue()),0, 0);
}
}
updateLatestVersionDate(p,plan.getUpdated());
} catch(Exception e){
pushAjaxUpdate("Error while setting ScenarioID " + plan.getPlanId() + ": " + e);
}
break;
}
}
}
private void setAttributeRelatedToPlanMeta(PlanItem plan, Proposal p, String attribute){
List<PlanMeta> planMetas = null;
try{
planMetas = PlanMetaLocalServiceUtil.getAllForPlan(plan);
} catch(Exception e){
pushAjaxUpdate("Error while getting description record " + plan.getPlanId() + ": " + e);
}
for(PlanMeta planMeta : planMetas) {
if (planMeta.getPlanVersion() == plan.getVersion()){
try{
if(attribute.equalsIgnoreCase("PLAN_OPENED") || attribute.equalsIgnoreCase("PLAN_CLOSED"))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),ProposalAttributeKeys.OPEN,0,null,planMeta.getOpen() ? 1 : 0,0);
updateLatestVersionDate(p,plan.getUpdated());
} catch(Exception e){
pushAjaxUpdate("Error while setting Attribute " + plan.getPlanId() + ": " + e);
}
break;
}
}
}
private void setAttributeRelatedToPlanSection(PlanItem plan, Proposal p, String attribute){
List<PlanSection> planSections = OldPersistenceQueries.getPlanSectionsForPlan(plan);
if (planSections == null) {
pushAjaxUpdate("Error while getting PlanSections");
return;
}
for(PlanSection planSection : planSections) {
try{
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),ProposalAttributeKeys.SECTION,
planSection.getPlanSectionDefinitionId(),planSection.getContent(),0,0);
updateLatestVersionDate(p,plan.getUpdated());
} catch (Exception e){
pushAjaxUpdate("Error while setting Section " + plan.getPlanId() + ": " + e);
}
}
}
private void setAttributeRelatedToPlanDescription(PlanItem plan, Proposal p, String attribute){
List<PlanDescription> planDescriptions = null;
try{
planDescriptions = PlanDescriptionLocalServiceUtil.getAllForPlan(plan);
} catch(Exception e){
pushAjaxUpdate("Error while getting description record " + plan.getPlanId() + ": " + e);
}
for(PlanDescription planDescription : planDescriptions) {
if (planDescription.getPlanVersion() == plan.getVersion()){
try{
if(attribute.equalsIgnoreCase(ProposalAttributeKeys.NAME))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,planDescription.getName(),0,0);
else if(attribute.equalsIgnoreCase(ProposalAttributeKeys.DESCRIPTION))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,planDescription.getDescription(),0,0);
else if(attribute.equalsIgnoreCase(ProposalAttributeKeys.PITCH))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,planDescription.getPitch(),0,0);
else if(attribute.equalsIgnoreCase(ProposalAttributeKeys.IMAGE_ID))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,null,planDescription.getImage(),0);
updateLatestVersionDate(p,plan.getUpdated());
} catch(Exception e){
pushAjaxUpdate("Error while setting Attribute " + plan.getPlanId() + ": " + e);
}
break;
}
}
}
private void copySupporters(PlanItem plan, Proposal p){
List<User> subscribers = null;
try{
subscribers = ActivitySubscriptionLocalServiceUtil.getSubscribedUsers(PlanItem.class,plan.getPlanId());
} catch (Exception e){ e.printStackTrace(); }
if (subscribers == null || subscribers.size() < 1) return;
for (User u : subscribers){
try{
ProposalLocalServiceUtil.subscribe(p.getProposalId(),u.getUserId());
} catch (Exception e){ e.printStackTrace(); }
}
}
private void createRibbons(PlanItem plan, Proposal p){
Pair<Long,String> ribbon = OldPersistenceQueries.getRibbonAndHoverTextForPlan(plan);
if (ribbon == null) return;
PlanMeta currentPlanMeta = null;
// Get current plan meta for setting proposal entity attributes
try{
currentPlanMeta = PlanMetaLocalServiceUtil.getCurrentForPlan(plan);
} catch (Exception e){
pushAjaxUpdate("Error while getting PlanMetas " + plan.getId() + ": " + e);
return;
}
long ribbonContestPhaseAttributeTypeId = NewPersistenceQueries
.getContestPhaseRibbonTypeIdForRibbon(ribbon.getLeft().intValue(), ribbon.getRight());
if (ribbonContestPhaseAttributeTypeId > 0){
// Create new ContestPhaseAttribute
NewPersistenceQueries.associateProposalWithRibbon(
p.getProposalId(), ribbonContestPhaseAttributeTypeId, currentPlanMeta.getContestPhase());
} else {
// Set up new ContestPhaseAttributeType
ContestPhaseRibbonType ribbonType = NewPersistenceQueries
.createNewContestPhaseRibbonType(ribbon.getLeft() + "", ribbon.getRight());
if (ribbonType == null){
pushAjaxUpdate("Error while creating AttributeType");
return;
}
// Create new ContestPhaseAttribute
NewPersistenceQueries.associateProposalWithRibbon(
p.getProposalId(), ribbonType.getId(), currentPlanMeta.getContestPhase());
}
}
private void pushAjaxUpdate(String message){
reference.add(message);
SessionRenderer.render("migration");
}
private void updateLastAjaxUpdate(String message){
reference.remove(reference.size()-1);
reference.add((message));
SessionRenderer.render("migration");
}
private Map<String, String> getAttributes(PlanItem plan) throws SystemException, PortalException {
// if (planAttributes == null) {
Map<String, String> planAttributes = new HashMap<String, String>();
for (PlanAttribute attr : PlanItemLocalServiceUtil.getPlanAttributes(plan)) {
planAttributes.put(attr.getAttributeName(), attr.getAttributeValue());
}
for (PlanConstants.Columns column : PlanConstants.Columns.values()) {
planAttributes.put(column.name(), column.getValue(plan));
}
// }
return planAttributes;
}
private void copyMetaInfo(PlanItem plan, Proposal p){
// get updated proposal
try {
p = ProposalLocalServiceUtil.getProposal(p.getProposalId());
} catch (Exception e){
pushAjaxUpdate("Error while updating Proposal " + e);
}
PlanMeta currentPlanMeta = null;
// get current plan meta for setting proposal entity attributes
try{
currentPlanMeta = PlanMetaLocalServiceUtil.getCurrentForPlan(plan);
} catch (Exception e){
pushAjaxUpdate("Error while getting PlanMeta " + plan.getId() + ": " + e);
return;
}
if (currentPlanMeta == null) return;
if (currentPlanMeta.getCategoryGroupId() == 0) return;
p.setDiscussionId(currentPlanMeta.getCategoryGroupId());
p.setGroupId(currentPlanMeta.getPlanGroupId());
p.setUpdatedDate(currentPlanMeta.getCreated());
// update proposal
try {
ProposalLocalServiceUtil.updateProposal(p);
} catch (Exception e){
pushAjaxUpdate("Error while updating Proposal " + e);
}
}
} | portlets/adminstasks-portlet/src/main/java/org/xcolab/portlets/admintasks/migration/DataMigrator.java | package org.xcolab.portlets.admintasks.migration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.ext.portlet.service.*;
import com.liferay.portal.model.User;
import org.xcolab.portlets.admintasks.migration.persistence.NewPersistenceCleaner;
import org.xcolab.portlets.admintasks.migration.persistence.NewPersistenceQueries;
import org.xcolab.portlets.admintasks.migration.persistence.OldPersistenceQueries;
import com.ext.portlet.ProposalAttributeKeys;
import com.ext.portlet.model.ContestPhaseRibbonType;
import com.ext.portlet.model.Plan2Proposal;
import com.ext.portlet.model.PlanAttribute;
import com.ext.portlet.model.PlanDescription;
import com.ext.portlet.model.PlanFan;
import com.ext.portlet.model.PlanItem;
import com.ext.portlet.model.PlanMeta;
import com.ext.portlet.model.PlanModelRun;
import com.ext.portlet.model.PlanSection;
import com.ext.portlet.model.PlanType;
import com.ext.portlet.model.PlanVote;
import com.ext.portlet.model.Proposal;
import com.ext.portlet.model.Proposal2Phase;
import com.ext.portlet.model.ProposalSupporter;
import com.ext.portlet.model.ProposalVersion;
import com.ext.portlet.model.ProposalVote;
import com.ext.portlet.plans.PlanConstants;
import com.icesoft.faces.async.render.SessionRenderer;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.security.auth.PrincipalThreadLocal;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.service.UserLocalServiceUtil;
/**
* Created with IntelliJ IDEA.
* User: patrickhiesel
* Date: 9/17/13
* Time: 12:33 PM
* To change this template use File | Settings | File Templates.
*/
public class DataMigrator implements Runnable {
List<String> reference;
private boolean TESTING = false;
public boolean STOP = false;
private final static String[] regionsDevelopedArr = {"United States", "European Union",
"Russia/Former Soviet Union", "OECD Asia", "Canada"};
private final static String[] regionsRapidlyDevelopingArr = {"China", "India", "Brazil", "South Africa", "Mexico",
"Rapidly developing Asia",};
private final static String[] regionsOtherDevelopingArr = {"Middle East", "Latin America", "Africa",
"Other developing Asia"};
private final static Set<String> regionsDeveloped = new HashSet<String>(Arrays.asList(regionsDevelopedArr));
private final static Set<String> regionsRapidlyDeveloping = new HashSet<String>(
Arrays.asList(regionsRapidlyDevelopingArr));
private final static Set<String> regionsOtherDeveloping = new HashSet<String>(
Arrays.asList(regionsOtherDevelopingArr));
public DataMigrator(List<String> reference){
this.reference = reference;
}
public void run() {
setPermissions();
if (!(new NewPersistenceCleaner(reference).deleteAllRecordsForNewEntities())) return;
List<Pair<Long,List<PlanItem>>> groupedPlans = getAllDistinctPlanGroupIds();
pushAjaxUpdate("Creating new Proposals");
pushAjaxUpdate("0%");
int counter = 0;
boolean skippedFirstRecords = false;
for(Iterator<Pair<Long,List<PlanItem>>> i = groupedPlans.iterator(); i.hasNext(); ) {
if (STOP) break;
// for testing skip first 100 plans
if (TESTING && !skippedFirstRecords) {
for (int z=0; z<100;z++) i.next();
skippedFirstRecords = true;
}
if (++counter > 0 && (counter % (groupedPlans.size() / 33)) == 0) updateLastAjaxUpdate((100 * counter / groupedPlans.size()) + "%");
Pair<Long,List<PlanItem>> pair = i.next();
createNewPlan(pair.getLeft(),pair.getRight());
if (counter > (groupedPlans.size()/10) && TESTING) break;
}
pushAjaxUpdate("-- MIGRATION FINISHED --");
}
private void setPermissions(){
PrincipalThreadLocal.setName(10144L);
PermissionChecker permissionChecker;
try {
permissionChecker = PermissionCheckerFactoryUtil.create(UserLocalServiceUtil.getUser(10144L), true);
} catch (Exception e) {
throw new RuntimeException(e);
}
PermissionThreadLocal.setPermissionChecker(permissionChecker);
}
private List<Pair<Long,List<PlanItem>>> getAllDistinctPlanGroupIds(){
pushAjaxUpdate("Getting Distinct PlanGroupIDs");
List<PlanItem> allPlans;
List<Pair<Long,List<PlanItem>>> results = new LinkedList<Pair<Long,List<PlanItem>>>();
try {
allPlans = PlanItemLocalServiceUtil.getPlans();
} catch (Exception e){
pushAjaxUpdate("Error: " + e);
return null;
}
pushAjaxUpdate("Got " + allPlans.size() + " Plans");
pushAjaxUpdate("Grouping Plans");
pushAjaxUpdate("0%");
int counter=0;
for(PlanItem plan : allPlans) {
if (++counter > 0 && (counter % (allPlans.size() / 3)) == 0)
updateLastAjaxUpdate((100 * counter / allPlans.size() + 1) + "%");
try{
long groupID = PlanItemGroupLocalServiceUtil.getPlanItemGroup(plan.getPlanId()).getGroupId();
boolean didFindGroupIdInSet = false;
for(Pair<Long,List<PlanItem>> pair : results) {
if (pair.getLeft().longValue() == groupID){
pair.getRight().add(0,plan);
didFindGroupIdInSet = true;
break;
}
}
if (!didFindGroupIdInSet){
Pair<Long,List<PlanItem>> newPair = new Pair<Long,List<PlanItem>>(groupID,new LinkedList<PlanItem>());
newPair.getRight().add(plan);
results.add(newPair);
}
} catch (Exception e){
System.out.println("No Group Found for ID " + plan.getPlanId());
}
}
pushAjaxUpdate("Done Getting Distinct PlanGroupIDs (count: " + results.size() + ")");
return results;
}
private void createNewPlan(long groupID, List<PlanItem> plans){
if (groupID == 1001501){
System.out.println("..");
}
// sort plans by create date
Collections.sort(plans, new Comparator<PlanItem>() {
public int compare(PlanItem o1, PlanItem o2) {
return o1.getUpdated().compareTo(o2.getUpdated());
}
});
PlanMeta currentPlanMeta = null;
Proposal2Phase latestP2P = null;
long currentContestPhase = 0;
// get current plan meta for setting proposal entity attributes
try{
currentPlanMeta = PlanMetaLocalServiceUtil.getCurrentForPlan(plans.get(0));
} catch (Exception e){
pushAjaxUpdate("Error while getting PlanMetas " + plans.get(0).getId() + ": " + e);
return;
}
long authorID = currentPlanMeta.getAuthorId();
Proposal proposal = null;
try {
proposal = ProposalLocalServiceUtil.create(authorID, 0);
} catch (Exception e){
pushAjaxUpdate("Error while creating Proposal " + groupID + ": " + e);
}
// set create date
proposal.setCreateDate(plans.get(0).getUpdated());
// set user group
proposal.setGroupId(currentPlanMeta.getPlanGroupId());
proposal.setDiscussionId(currentPlanMeta.getCategoryGroupId());
// update proposal
try {
ProposalLocalServiceUtil.updateProposal(proposal);
} catch (Exception e){
pushAjaxUpdate("Error while updating Proposal " + groupID + ": " + e);
}
List<Long> planFans = new ArrayList<Long>();
// Loop through all plans - each representing one contest phase
boolean isFirstInGroup = true;
for(PlanItem plan : plans) {
// get updated proposal
try {
proposal = ProposalLocalServiceUtil.getProposal(proposal.getProposalId());
} catch (Exception e){
pushAjaxUpdate("Error while updating Proposal " + groupID + ": " + e);
}
// add mapping to old DB schema
createPlan2ProposalMapping(plan,proposal);
// map proposal to contest phases
latestP2P = createProposal2PhaseMapping(plan,proposal, latestP2P, currentContestPhase);
currentContestPhase++;
// plan entity represents a last version of a plan (for given planId) so we need to iterate over all of it's versions
// to create respective attributes of a proposal
if (isFirstInGroup) {
// transfer regional attributes if they exist
try {
PlanAttribute regionAttribute = PlanItemLocalServiceUtil.getPlanAttribute(plan, "REGION");
if (regionAttribute != null) {
String region = regionAttribute.getAttributeValue();
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.REGION, region);
String regionEconomy = "Other Developing";
if (regionsDeveloped.contains(region)) {
regionEconomy = "Developed";
} else if (regionsRapidlyDeveloping.contains(region)) {
regionEconomy = "Rapidly Developing";
}
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.REGION_ECONOMY, regionEconomy);
}
PlanAttribute subregionAttribute = PlanItemLocalServiceUtil.getPlanAttribute(plan, "SUBREGION");
if (subregionAttribute != null) {
ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.SUBREGION, subregionAttribute.getAttributeValue());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
createProposalAttributesFromPlan(plan,proposal);
createVotesFromPlan(plan,proposal);
// copy supporters (fans)
createSupporters(plan,proposal,planFans);
// create ribbons for this plan
createRibbons(plan, proposal);
// add supporters
copySupporters(plan,proposal);
}
}
private void createVotesFromPlan(PlanItem plan, Proposal proposal){
List<PlanVote> planVotes = null;
long contestPhase = 0;
try{
planVotes = PlanVoteLocalServiceUtil.getPlanVotes(plan.getPlanId());
contestPhase = PlanItemLocalServiceUtil.getContestPhase(plan).getContestPhasePK();
} catch (Exception e){
pushAjaxUpdate("Error while getting Votes " + plan.getPlanId() + ": " + e);
return;
}
for (PlanVote planVote : planVotes){
ProposalVote vote = ProposalVoteLocalServiceUtil.create(contestPhase, planVote.getUserId());
vote.setCreateDate(planVote.getCreateDate());
vote.setProposalId(proposal.getProposalId());
try{
ProposalVoteLocalServiceUtil.addProposalVote(vote);
} catch (Exception e){
pushAjaxUpdate("Error while persisting Votes " + plan.getPlanId() + ": " + e);
return;
}
}
}
private void createSupporters(PlanItem plan, Proposal proposal, List<Long> proposalSupporter){
List<PlanFan> planFans = null;
long contestPhase = 0;
try{
planFans = PlanFanLocalServiceUtil.getPlanFansForPlan(plan.getPlanId());
} catch (Exception e){
pushAjaxUpdate("Error while getting Fans " + plan.getPlanId() + ": " + e);
return;
}
for (PlanFan planFan : planFans){
// add supporter if not already added
if (!proposalSupporter.contains(planFan.getUserId())){
ProposalSupporter supporter = ProposalSupporterLocalServiceUtil.create(proposal.getProposalId(),planFan.getUserId());
supporter.setCreateDate(planFan.getCreated());
try{
ProposalSupporterLocalServiceUtil.addProposalSupporter(supporter);
} catch (Exception e){
pushAjaxUpdate("Error while persisting Supporters " + plan.getPlanId() + ": " + e);
return;
}
proposalSupporter.add(planFan.getUserId());
}
}
}
private void createPlan2ProposalMapping(PlanItem plan, Proposal proposal){
Plan2Proposal plan2Proposal = Plan2ProposalLocalServiceUtil.createPlan2Proposal(plan.getPlanId());
plan2Proposal.setProposalId(proposal.getProposalId());
try {
Plan2ProposalLocalServiceUtil.addPlan2Proposal(plan2Proposal);
} catch (SystemException e1) {
pushAjaxUpdate("Error while creating mapping between plan " + plan.getPlanId() + " and proposal: " + proposal.getProposalId() + "\n" + e1);
}
}
private Proposal2Phase createProposal2PhaseMapping(PlanItem plan, Proposal proposal, Proposal2Phase latestP2P, long currentContestPhase){
// handle new Proposal2Contest Phase Mapping
if (currentContestPhase > 0){
// set VersionTo for old p2p mapping
latestP2P.setVersionTo(proposal.getCurrentVersion());
try{
Proposal2PhaseLocalServiceUtil.updateProposal2Phase(latestP2P);
}catch (SystemException e1) {
pushAjaxUpdate("Error while storing Proposal2Phase mapping" + e1);
}
}
// add new p2p record
//System.out.println("Current Version:" + proposal.getCurrentVersion() + " ID: " + proposal.getProposalId() + " ContestPhase: " + currentContestPhase);
PlanMeta matchingMeta = null;
try {
for (PlanMeta pm : PlanMetaLocalServiceUtil.getAllForPlan(plan)){
if (pm.getPlanVersion() == 0){
matchingMeta = pm;
}
}
} catch (SystemException e1) {
pushAjaxUpdate("Error while creating mapping between plan " + plan.getPlanId() + " and proposal: " + proposal.getProposalId() + "\n" + e1);
}
if(matchingMeta != null){
Proposal2Phase p2p = Proposal2PhaseLocalServiceUtil.create(proposal.getProposalId(),matchingMeta.getContestPhase());
p2p.setSortWeight(1);
p2p.setAutopromoteCandidate(false);
p2p.setVersionFrom(proposal.getCurrentVersion()); /* TODO how should we increment the version set/get attr?*/
p2p.setVersionTo(-1);
try{
Proposal2PhaseLocalServiceUtil.addProposal2Phase(p2p);
}catch (SystemException e1) {
pushAjaxUpdate("Error while storing Proposal2Phase mapping" + e1);
}
return p2p;
} else{
System.out.println("Not matching meta found: " + plan.getPlanId());
return null;
}
}
private void createProposalAttributesFromPlan(PlanItem plan, Proposal proposal){
List<PlanItem> planVersions = OldPersistenceQueries.getAllVersionsForPlanASC(plan.getPlanId());
for (PlanItem planVersion : planVersions) {
if (planVersion.getUpdateType().equalsIgnoreCase("CREATED")){
// ignore use just for transferring from one phase to another
} else if (planVersion.getUpdateType().equalsIgnoreCase("MODEL_UPDATED")){
// IGNORE because modelID is deprecated
} else if (planVersion.getUpdateType().equalsIgnoreCase("SCENARIO_UPDATED")){
// Get scenarioId from xcolab_PlanModelRun and use it to create attribute
setAttributeRelatedToScenario(planVersion,proposal,"SCENARIO_UPDATED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_POSITIONS_UPDATED")){
// IGNORE
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_DELETED")){
// SET visibility = false
proposal.setVisible(false);
} else if (planVersion.getUpdateType().equalsIgnoreCase("DESCRIPTION_UPDATED")){
// Get description from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"DESCRIPTION");
} else if (planVersion.getUpdateType().equalsIgnoreCase("NAME_UPDATED")){
// Get name from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"NAME");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_STATUS_UPDATED")){
// IGNORE (connected to PlanMeta (col: Status)
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_CLOSED")){
// Get open from PlanMeta - anyone can edit (open), only team members can edit
setAttributeRelatedToPlanMeta(planVersion,proposal,"PLAN_CLOSED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_OPENED")){
// Get open from PlanMeta - anyone can edit (open), only team members can edit
setAttributeRelatedToPlanMeta(planVersion,proposal,"PLAN_OPENED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_SECTION_UPDATED")){
// Get PlanSection -> .setAttr. (col: additionalId = planSectionDef. and String = content (date from PlanITem)
setAttributeRelatedToPlanSection(planVersion,proposal,"PLAN_SECTION_UPDATED");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PITCH_UPDATED")){
// Get pitch from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"PITCH");
} else if (planVersion.getUpdateType().equalsIgnoreCase("IMAGE_UPDATED")){
// Get image_id from xcolab_PlanDescription and use setAttribute
setAttributeRelatedToPlanDescription(planVersion,proposal,"IMAGE_ID");
} else if (planVersion.getUpdateType().equalsIgnoreCase("PLAN_REVERTED")){
// IGNORE
}
}
}
private void updateLatestVersionDate(Proposal proposal, Date date){
try{
ProposalVersion latestVersion = NewPersistenceQueries.getLatestVersionForProposal(proposal);
if (latestVersion != null){
latestVersion.setCreateDate(date);
ProposalVersionLocalServiceUtil.updateProposalVersion(latestVersion);
} else {
System.out.println("Could not update Version at proposalId: " + proposal.getProposalId());
}
} catch (Exception e){
e.printStackTrace();
pushAjaxUpdate("Could not find latest version for proposal: " + proposal.getProposalId());
return;
}
}
private void setAttributeRelatedToScenario(PlanItem plan, Proposal p, String attribute){
List<PlanModelRun> pmrs = null;
try{
pmrs = PlanModelRunLocalServiceUtil.getAllForPlan(plan);
} catch(Exception e){
pushAjaxUpdate("Error while getting ScenarioID " + plan.getPlanId() + ": " + e);
}
for(PlanModelRun pmr : pmrs) {
if (pmr.getPlanVersion() == plan.getVersion()){
try{
PlanType planType = PlanItemLocalServiceUtil.getPlanType(plan);
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),ProposalAttributeKeys.SCENARIO_ID,planType.getDefaultModelId(),null,pmr.getScenarioId(),0);
Map<String, String> attributes = getAttributes(plan);
Map<String, String> planAttributesToCopy = new HashMap<String, String>();
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_CO2_CONCENTRATION, "CO2_CONCENTRATION");
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_TEMP_CHANGE, "TEMP_CHANGE");
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_MITIGATION_COST_NO_ERRORS, "MITIGATION_COST_NO_ERRORS");
planAttributesToCopy.put(ProposalAttributeKeys.SCENARIO_DAMAGE_COST, "DAMAGE_COST");
for (Map.Entry<String, String> attributeToCopy: planAttributesToCopy.entrySet()) {
if (attributes.containsKey(attributeToCopy.getValue())) {
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attributeToCopy.getKey(),
planType.getModelId(), attributes.get(attributeToCopy.getValue()),0, 0);
}
}
updateLatestVersionDate(p,plan.getUpdated());
} catch(Exception e){
pushAjaxUpdate("Error while setting ScenarioID " + plan.getPlanId() + ": " + e);
}
break;
}
}
}
private void setAttributeRelatedToPlanMeta(PlanItem plan, Proposal p, String attribute){
List<PlanMeta> planMetas = null;
try{
planMetas = PlanMetaLocalServiceUtil.getAllForPlan(plan);
} catch(Exception e){
pushAjaxUpdate("Error while getting description record " + plan.getPlanId() + ": " + e);
}
for(PlanMeta planMeta : planMetas) {
if (planMeta.getPlanVersion() == plan.getVersion()){
try{
if(attribute.equalsIgnoreCase("PLAN_OPENED") || attribute.equalsIgnoreCase("PLAN_CLOSED"))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),ProposalAttributeKeys.OPEN,0,null,planMeta.getOpen() ? 1 : 0,0);
updateLatestVersionDate(p,plan.getUpdated());
} catch(Exception e){
pushAjaxUpdate("Error while setting Attribute " + plan.getPlanId() + ": " + e);
}
break;
}
}
}
private void setAttributeRelatedToPlanSection(PlanItem plan, Proposal p, String attribute){
List<PlanSection> planSections = OldPersistenceQueries.getPlanSectionsForPlan(plan);
if (planSections == null) {
pushAjaxUpdate("Error while getting PlanSections");
return;
}
for(PlanSection planSection : planSections) {
try{
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),ProposalAttributeKeys.SECTION,
planSection.getPlanSectionDefinitionId(),planSection.getContent(),0,0);
updateLatestVersionDate(p,plan.getUpdated());
} catch (Exception e){
pushAjaxUpdate("Error while setting Section " + plan.getPlanId() + ": " + e);
}
}
}
private void setAttributeRelatedToPlanDescription(PlanItem plan, Proposal p, String attribute){
List<PlanDescription> planDescriptions = null;
try{
planDescriptions = PlanDescriptionLocalServiceUtil.getAllForPlan(plan);
} catch(Exception e){
pushAjaxUpdate("Error while getting description record " + plan.getPlanId() + ": " + e);
}
for(PlanDescription planDescription : planDescriptions) {
if (planDescription.getPlanVersion() == plan.getVersion()){
try{
if(attribute.equalsIgnoreCase(ProposalAttributeKeys.NAME))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,planDescription.getName(),0,0);
else if(attribute.equalsIgnoreCase(ProposalAttributeKeys.DESCRIPTION))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,planDescription.getDescription(),0,0);
else if(attribute.equalsIgnoreCase(ProposalAttributeKeys.PITCH))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,planDescription.getPitch(),0,0);
else if(attribute.equalsIgnoreCase(ProposalAttributeKeys.IMAGE_ID))
ProposalLocalServiceUtil.setAttribute(plan.getUpdateAuthorId(),p.getProposalId(),attribute,0,null,planDescription.getImage(),0);
updateLatestVersionDate(p,plan.getUpdated());
} catch(Exception e){
pushAjaxUpdate("Error while setting Attribute " + plan.getPlanId() + ": " + e);
}
break;
}
}
}
private void copySupporters(PlanItem plan, Proposal p){
List<User> subscribers = null;
try{
subscribers = ActivitySubscriptionLocalServiceUtil.getSubscribedUsers(PlanItem.class,plan.getPlanId());
} catch (Exception e){ e.printStackTrace(); }
if (subscribers == null || subscribers.size() < 1) return;
for (User u : subscribers){
try{
ProposalLocalServiceUtil.subscribe(p.getProposalId(),u.getUserId());
} catch (Exception e){ e.printStackTrace(); }
}
}
private void createRibbons(PlanItem plan, Proposal p){
Pair<Long,String> ribbon = OldPersistenceQueries.getRibbonAndHoverTextForPlan(plan);
if (ribbon == null) return;
PlanMeta currentPlanMeta = null;
// Get current plan meta for setting proposal entity attributes
try{
currentPlanMeta = PlanMetaLocalServiceUtil.getCurrentForPlan(plan);
} catch (Exception e){
pushAjaxUpdate("Error while getting PlanMetas " + plan.getId() + ": " + e);
return;
}
long ribbonContestPhaseAttributeTypeId = NewPersistenceQueries
.getContestPhaseRibbonTypeIdForRibbon(ribbon.getLeft().intValue(), ribbon.getRight());
if (ribbonContestPhaseAttributeTypeId > 0){
// Create new ContestPhaseAttribute
NewPersistenceQueries.associateProposalWithRibbon(
p.getProposalId(), ribbonContestPhaseAttributeTypeId, currentPlanMeta.getContestPhase());
} else {
// Set up new ContestPhaseAttributeType
ContestPhaseRibbonType ribbonType = NewPersistenceQueries
.createNewContestPhaseRibbonType(ribbon.getLeft() + "", ribbon.getRight());
if (ribbonType == null){
pushAjaxUpdate("Error while creating AttributeType");
return;
}
// Create new ContestPhaseAttribute
NewPersistenceQueries.associateProposalWithRibbon(
p.getProposalId(), ribbonType.getId(), currentPlanMeta.getContestPhase());
}
}
private void pushAjaxUpdate(String message){
reference.add(message);
SessionRenderer.render("migration");
}
private void updateLastAjaxUpdate(String message){
reference.remove(reference.size()-1);
reference.add((message));
SessionRenderer.render("migration");
}
private Map<String, String> getAttributes(PlanItem plan) throws SystemException, PortalException {
// if (planAttributes == null) {
Map<String, String> planAttributes = new HashMap<String, String>();
for (PlanAttribute attr : PlanItemLocalServiceUtil.getPlanAttributes(plan)) {
planAttributes.put(attr.getAttributeName(), attr.getAttributeValue());
}
for (PlanConstants.Columns column : PlanConstants.Columns.values()) {
planAttributes.put(column.name(), column.getValue(plan));
}
// }
return planAttributes;
}
} | fixed bugs related to migration: merging of comments, copy of team name and group ids (contributors)
| portlets/adminstasks-portlet/src/main/java/org/xcolab/portlets/admintasks/migration/DataMigrator.java | fixed bugs related to migration: merging of comments, copy of team name and group ids (contributors) | <ide><path>ortlets/adminstasks-portlet/src/main/java/org/xcolab/portlets/admintasks/migration/DataMigrator.java
<ide> */
<ide> public class DataMigrator implements Runnable {
<ide> List<String> reference;
<del> private boolean TESTING = false;
<add> private boolean TESTING = true;
<ide> public boolean STOP = false;
<ide>
<ide>
<ide> // set create date
<ide> proposal.setCreateDate(plans.get(0).getUpdated());
<ide>
<del> // set user group
<add> // set initial user group and discussion
<ide> proposal.setGroupId(currentPlanMeta.getPlanGroupId());
<ide> proposal.setDiscussionId(currentPlanMeta.getCategoryGroupId());
<ide>
<ide> e.printStackTrace();
<ide> }
<ide> }
<add>
<add> // migrate team name
<add> try {
<add> PlanAttribute teamAttribute = PlanItemLocalServiceUtil.getPlanAttribute(plan, "TEAM");
<add> if (teamAttribute != null) {
<add> String teamName = teamAttribute.getAttributeValue();
<add> ProposalLocalServiceUtil.setAttribute(authorID, proposal.getProposalId(), ProposalAttributeKeys.TEAM, teamName);
<add> }
<add> }
<add> catch (Exception e) {
<add> e.printStackTrace();
<add> }
<add>
<ide> createProposalAttributesFromPlan(plan,proposal);
<ide> createVotesFromPlan(plan,proposal);
<ide> // copy supporters (fans)
<ide>
<ide> // add supporters
<ide> copySupporters(plan,proposal);
<add>
<add> // refresh discussion id, group id, updated date
<add> copyMetaInfo(plan,proposal);
<add>
<ide> }
<ide> }
<ide>
<ide> return planAttributes;
<ide>
<ide> }
<add>
<add>
<add>
<add> private void copyMetaInfo(PlanItem plan, Proposal p){
<add> // get updated proposal
<add> try {
<add> p = ProposalLocalServiceUtil.getProposal(p.getProposalId());
<add> } catch (Exception e){
<add> pushAjaxUpdate("Error while updating Proposal " + e);
<add> }
<add> PlanMeta currentPlanMeta = null;
<add> // get current plan meta for setting proposal entity attributes
<add> try{
<add> currentPlanMeta = PlanMetaLocalServiceUtil.getCurrentForPlan(plan);
<add> } catch (Exception e){
<add> pushAjaxUpdate("Error while getting PlanMeta " + plan.getId() + ": " + e);
<add> return;
<add> }
<add> if (currentPlanMeta == null) return;
<add> if (currentPlanMeta.getCategoryGroupId() == 0) return;
<add> p.setDiscussionId(currentPlanMeta.getCategoryGroupId());
<add> p.setGroupId(currentPlanMeta.getPlanGroupId());
<add> p.setUpdatedDate(currentPlanMeta.getCreated());
<add> // update proposal
<add> try {
<add> ProposalLocalServiceUtil.updateProposal(p);
<add> } catch (Exception e){
<add> pushAjaxUpdate("Error while updating Proposal " + e);
<add> }
<add>
<add> }
<ide> } |
|
Java | apache-2.0 | 869019a9e8b57e6de0a796ebeeaa830bf769e604 | 0 | PRIDE-Archive/pride-web-utils | package uk.ac.ebi.pride.web.util.twitter;
import org.springframework.social.twitter.api.Tweet;
import java.util.ArrayList;
import java.util.Collection;
/**
* {@code HyperLinkTweetTextFormatter} scans the tweet text and wrap any hyperlinks with
* html 'a' tags
*
* @author Rui Wang
* @version $Id$
*/
public class HyperLinkTweetTextFormatter implements TweetTextFormatter {
public static final String HYPERLINK_PATTERN = "((http|https|ftp|mailto):\\S+)";
@Override
public Collection<Tweet> format(Collection<Tweet> tweets) {
Collection<Tweet> newTweets = new ArrayList<Tweet>(tweets.size());
for (Tweet tweet : tweets) {
newTweets.add(formatTweetText(tweet));
}
tweets.clear();
tweets.addAll(newTweets);
return tweets;
}
private Tweet formatTweetText(Tweet tweet) {
String tweetText = tweet.getText();
tweetText = tweetText.replaceAll(HYPERLINK_PATTERN, "<a href=\"$1\">$1</a>");
return new Tweet(tweet.getId(), tweetText,
tweet.getCreatedAt(), tweet.getFromUser(),
tweet.getProfileImageUrl(), tweet.getToUserId(),
tweet.getFromUserId(), tweet.getLanguageCode(),
tweet.getSource());
}
}
| src/main/java/uk/ac/ebi/pride/web/util/twitter/HyperLinkTweetTextFormatter.java | package uk.ac.ebi.pride.web.util.twitter;
import org.springframework.social.twitter.api.Tweet;
import java.util.ArrayList;
import java.util.Collection;
/**
* {@code HyperLinkTweetTextFormatter} scans the tweet text and wrap any hyperlinks with
* html 'a' tags
*
* @author Rui Wang
* @version $Id$
*/
public class HyperLinkTweetTextFormatter implements TweetTextFormatter {
public static final String HYPERLINK_PATTERN = "((http|https|ftp|mailto):\\S+)";
@Override
public Collection<Tweet> format(Collection<Tweet> tweets) {
Collection<Tweet> newTweets = new ArrayList<Tweet>(tweets.size());
for (Tweet tweet : tweets) {
newTweets.add(formatTweetText(tweet));
}
return newTweets;
}
private Tweet formatTweetText(Tweet tweet) {
String tweetText = tweet.getText();
tweetText = tweetText.replaceAll(HYPERLINK_PATTERN, "<a href=\"$1\">$1</a>");
return new Tweet(tweet.getId(), tweetText,
tweet.getCreatedAt(), tweet.getFromUser(),
tweet.getProfileImageUrl(), tweet.getToUserId(),
tweet.getFromUserId(), tweet.getLanguageCode(),
tweet.getSource());
}
}
| fixed a bug with formatting hyperlink for tweets | src/main/java/uk/ac/ebi/pride/web/util/twitter/HyperLinkTweetTextFormatter.java | fixed a bug with formatting hyperlink for tweets | <ide><path>rc/main/java/uk/ac/ebi/pride/web/util/twitter/HyperLinkTweetTextFormatter.java
<ide> for (Tweet tweet : tweets) {
<ide> newTweets.add(formatTweetText(tweet));
<ide> }
<del> return newTweets;
<add> tweets.clear();
<add> tweets.addAll(newTweets);
<add>
<add> return tweets;
<ide> }
<ide>
<ide> private Tweet formatTweetText(Tweet tweet) { |
|
Java | apache-2.0 | 03db9cf1e6d0fd35c64e751f95de528aa272396e | 0 | google/tsunami-security-scanner-plugins,google/tsunami-security-scanner-plugins,google/tsunami-security-scanner-plugins | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.tsunami.plugins.detectors.directorytraversal.genericpathtraversaldetector;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import com.google.tsunami.common.net.http.HttpRequest;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PathParameterInjection}. */
@RunWith(JUnit4.class)
public final class PathParameterInjectionTest {
private static final PathParameterInjection INJECTION_POINT = new PathParameterInjection();
@Test
public void injectPayload_onRelativePathTraversalPayload_generatesExploitsForRoot() {
HttpRequest exploitAtRoot =
HttpRequest.get("https://google.com/../../../../etc/passwd").withEmptyHeaders().build();
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.contains(exploitAtRoot);
}
@Test
public void injectPayload_onRelativePathTraversalPayload_generatesExploitsForCurrentPath() {
HttpRequest exploitAtCurrentPath =
HttpRequest.get("https://google.com/path/to/../../../../etc/passwd")
.withEmptyHeaders()
.build();
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.contains(exploitAtCurrentPath);
}
@Test
public void injectPayload_onRelativePathTraversalPayload_generatesExploitsForCommonPaths() {
ImmutableSet<String> targets =
ImmutableSet.of(
// go/keep-sorted start
"https://google.com/admin/../../../../etc/passwd",
"https://google.com/album/../../../../etc/passwd",
"https://google.com/app/../../../../etc/passwd",
"https://google.com/assets/../../../../etc/passwd",
"https://google.com/bin/../../../../etc/passwd",
"https://google.com/console/../../../../etc/passwd",
"https://google.com/css/../../../../etc/passwd",
"https://google.com/demo/../../../../etc/passwd",
"https://google.com/doc/../../../../etc/passwd",
"https://google.com/eqx/../../../../etc/passwd",
"https://google.com/files/../../../../etc/passwd",
"https://google.com/fs/../../../../etc/passwd",
"https://google.com/html/../../../../etc/passwd",
"https://google.com/img-sys/../../../../etc/passwd",
"https://google.com/jquery_ui/../../../../etc/passwd",
"https://google.com/js/../../../../etc/passwd",
"https://google.com/media/../../../../etc/passwd",
"https://google.com/public/../../../../etc/passwd",
"https://google.com/scripts/../../../../etc/passwd",
"https://google.com/static/../../../../etc/passwd",
"https://google.com/tmp/../../../../etc/passwd",
"https://google.com/upload/../../../../etc/passwd",
"https://google.com/xls/../../../../etc/passwd"
// go/keep-sorted end
);
Set<HttpRequest> requests = new HashSet<>();
for (String target : targets) {
requests.add(HttpRequest.get(target).withEmptyHeaders().build());
}
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.containsAtLeastElementsIn(requests);
}
@Test
public void injectPayload_whenInjectionAtRoot_doesNotGenerateAdditionalExploitsAtCurrentPath() {
assertThat(
INJECTION_POINT
.injectPayload(
HttpRequest.get("https://google.com").withEmptyHeaders().build(),
"../../../../etc/passwd")
.size())
.isLessThan(
INJECTION_POINT
.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd")
.size());
}
@Test
public void injectPayload_whenInjectionAtRoot_ignoresTrailingSlash() {
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.containsExactlyElementsIn(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/").withEmptyHeaders().build(),
"../../../../etc/passwd"));
}
}
| google/detectors/directorytraversal/generic_path_traversal_detector/src/test/java/com/google/tsunami/plugins/detectors/directorytraversal/genericpathtraversaldetector/PathParameterInjectionTest.java | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.tsunami.plugins.detectors.directorytraversal.genericpathtraversaldetector;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import com.google.tsunami.common.net.http.HttpRequest;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link PathParameterInjection}. */
@RunWith(JUnit4.class)
public final class PathParameterInjectionTest {
private static final PathParameterInjection INJECTION_POINT = new PathParameterInjection();
@Test
public void injectPayload_onRelativePathTraversalPayload_generatesExploitsForRoot() {
HttpRequest exploitAtRoot =
HttpRequest.get("https://google.com/../../../../etc/passwd").withEmptyHeaders().build();
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.contains(exploitAtRoot);
}
@Test
public void injectPayload_onRelativePathTraversalPayload_generatesExploitsForCurrentPath() {
HttpRequest exploitAtCurrentPath =
HttpRequest.get("https://google.com/path/to/../../../../etc/passwd")
.withEmptyHeaders()
.build();
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.contains(exploitAtCurrentPath);
}
@Test
public void injectPayload_onRelativePathTraversalPayload_generatesExploitsForCommonPaths() {
ImmutableSet<String> targets =
ImmutableSet.of(
// go/keep-sorted start
"https://google.com/admin/../../../../etc/passwd",
"https://google.com/album/../../../../etc/passwd",
"https://google.com/app/../../../../etc/passwd",
"https://google.com/assets/../../../../etc/passwd",
"https://google.com/bin/../../../../etc/passwd",
"https://google.com/console/../../../../etc/passwd",
"https://google.com/css/../../../../etc/passwd",
"https://google.com/demo/../../../../etc/passwd",
"https://google.com/doc/../../../../etc/passwd",
"https://google.com/eqx/../../../../etc/passwd",
"https://google.com/files/../../../../etc/passwd",
"https://google.com/fs/../../../../etc/passwd",
"https://google.com/html/../../../../etc/passwd",
"https://google.com/img-sys/../../../../etc/passwd",
"https://google.com/jquery_ui/../../../../etc/passwd",
"https://google.com/js/../../../../etc/passwd",
"https://google.com/media/../../../../etc/passwd",
"https://google.com/public/../../../../etc/passwd",
"https://google.com/scripts/../../../../etc/passwd",
"https://google.com/static/../../../../etc/passwd",
"https://google.com/tmp/../../../../etc/passwd",
"https://google.com/upload/../../../../etc/passwd",
"https://google.com/xls/../../../../etc/passwd"
// go/keep-sorted end
);
Set<HttpRequest> requests = new HashSet<>();
for (String target : targets) {
requests.add(HttpRequest.get(target).withEmptyHeaders().build());
}
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.containsAtLeastElementsIn(requests);
}
@Test
public void injectPayload_onAbsolutePathTraversalPayload_generatesExploitsForRoot() {
HttpRequest exploitAtRoot =
HttpRequest.get("https://google.com//etc/passwd").withEmptyHeaders().build();
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"/etc/passwd"))
.contains(exploitAtRoot);
}
@Test
public void injectPayload_onAbsolutePathTraversalPayload_generatesExploitsForCurrentPath() {
HttpRequest exploitAtCurrentPath =
HttpRequest.get("https://google.com/path/to//etc/passwd").withEmptyHeaders().build();
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"/etc/passwd"))
.contains(exploitAtCurrentPath);
}
@Test
public void injectPayload_onAbsolutePathTraversalPayload_generatesExploitsForCommonPaths() {
ImmutableSet<String> targets =
ImmutableSet.of(
// go/keep-sorted start
"https://google.com/admin//etc/passwd",
"https://google.com/album//etc/passwd",
"https://google.com/app//etc/passwd",
"https://google.com/assets//etc/passwd",
"https://google.com/bin//etc/passwd",
"https://google.com/console//etc/passwd",
"https://google.com/css//etc/passwd",
"https://google.com/demo//etc/passwd",
"https://google.com/doc//etc/passwd",
"https://google.com/eqx//etc/passwd",
"https://google.com/files//etc/passwd",
"https://google.com/fs//etc/passwd",
"https://google.com/html//etc/passwd",
"https://google.com/img-sys//etc/passwd",
"https://google.com/jquery_ui//etc/passwd",
"https://google.com/js//etc/passwd",
"https://google.com/media//etc/passwd",
"https://google.com/public//etc/passwd",
"https://google.com/scripts//etc/passwd",
"https://google.com/static//etc/passwd",
"https://google.com/tmp//etc/passwd",
"https://google.com/upload//etc/passwd",
"https://google.com/xls//etc/passwd"
// go/keep-sorted end
);
Set<HttpRequest> requests = new HashSet<>();
for (String target : targets) {
requests.add(HttpRequest.get(target).withEmptyHeaders().build());
}
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"/etc/passwd"))
.containsAtLeastElementsIn(requests);
}
@Test
public void injectPayload_whenInjectionAtRoot_doesNotGenerateAdditionalExploitsAtCurrentPath() {
assertThat(
INJECTION_POINT
.injectPayload(
HttpRequest.get("https://google.com").withEmptyHeaders().build(),
"../../../../etc/passwd")
.size())
.isLessThan(
INJECTION_POINT
.injectPayload(
HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
"../../../../etc/passwd")
.size());
}
@Test
public void injectPayload_whenInjectionAtRoot_ignoresTrailingSlash() {
assertThat(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com").withEmptyHeaders().build(),
"../../../../etc/passwd"))
.containsExactlyElementsIn(
INJECTION_POINT.injectPayload(
HttpRequest.get("https://google.com/").withEmptyHeaders().build(),
"../../../../etc/passwd"));
}
}
| Remove redundant test cases in PathParameterInjectionTest.
PiperOrigin-RevId: 480658835
Change-Id: I603f404ea44d18dc869d953bcfa9bc138ae541a5
| google/detectors/directorytraversal/generic_path_traversal_detector/src/test/java/com/google/tsunami/plugins/detectors/directorytraversal/genericpathtraversaldetector/PathParameterInjectionTest.java | Remove redundant test cases in PathParameterInjectionTest. | <ide><path>oogle/detectors/directorytraversal/generic_path_traversal_detector/src/test/java/com/google/tsunami/plugins/detectors/directorytraversal/genericpathtraversaldetector/PathParameterInjectionTest.java
<ide> }
<ide>
<ide> @Test
<del> public void injectPayload_onAbsolutePathTraversalPayload_generatesExploitsForRoot() {
<del> HttpRequest exploitAtRoot =
<del> HttpRequest.get("https://google.com//etc/passwd").withEmptyHeaders().build();
<del>
<del> assertThat(
<del> INJECTION_POINT.injectPayload(
<del> HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
<del> "/etc/passwd"))
<del> .contains(exploitAtRoot);
<del> }
<del>
<del> @Test
<del> public void injectPayload_onAbsolutePathTraversalPayload_generatesExploitsForCurrentPath() {
<del> HttpRequest exploitAtCurrentPath =
<del> HttpRequest.get("https://google.com/path/to//etc/passwd").withEmptyHeaders().build();
<del>
<del> assertThat(
<del> INJECTION_POINT.injectPayload(
<del> HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
<del> "/etc/passwd"))
<del> .contains(exploitAtCurrentPath);
<del> }
<del>
<del> @Test
<del> public void injectPayload_onAbsolutePathTraversalPayload_generatesExploitsForCommonPaths() {
<del> ImmutableSet<String> targets =
<del> ImmutableSet.of(
<del> // go/keep-sorted start
<del> "https://google.com/admin//etc/passwd",
<del> "https://google.com/album//etc/passwd",
<del> "https://google.com/app//etc/passwd",
<del> "https://google.com/assets//etc/passwd",
<del> "https://google.com/bin//etc/passwd",
<del> "https://google.com/console//etc/passwd",
<del> "https://google.com/css//etc/passwd",
<del> "https://google.com/demo//etc/passwd",
<del> "https://google.com/doc//etc/passwd",
<del> "https://google.com/eqx//etc/passwd",
<del> "https://google.com/files//etc/passwd",
<del> "https://google.com/fs//etc/passwd",
<del> "https://google.com/html//etc/passwd",
<del> "https://google.com/img-sys//etc/passwd",
<del> "https://google.com/jquery_ui//etc/passwd",
<del> "https://google.com/js//etc/passwd",
<del> "https://google.com/media//etc/passwd",
<del> "https://google.com/public//etc/passwd",
<del> "https://google.com/scripts//etc/passwd",
<del> "https://google.com/static//etc/passwd",
<del> "https://google.com/tmp//etc/passwd",
<del> "https://google.com/upload//etc/passwd",
<del> "https://google.com/xls//etc/passwd"
<del> // go/keep-sorted end
<del> );
<del> Set<HttpRequest> requests = new HashSet<>();
<del> for (String target : targets) {
<del> requests.add(HttpRequest.get(target).withEmptyHeaders().build());
<del> }
<del>
<del> assertThat(
<del> INJECTION_POINT.injectPayload(
<del> HttpRequest.get("https://google.com/path/to/file").withEmptyHeaders().build(),
<del> "/etc/passwd"))
<del> .containsAtLeastElementsIn(requests);
<del> }
<del>
<del> @Test
<ide> public void injectPayload_whenInjectionAtRoot_doesNotGenerateAdditionalExploitsAtCurrentPath() {
<ide> assertThat(
<ide> INJECTION_POINT |
|
Java | mit | 775faca7e57ba4b50938c2641c966257a0d8c178 | 0 | DePaul2015SEStudioTeam1/agent,DePaul2015SEStudioTeam1/agent | package edu.depaul.agent;
import java.lang.reflect.Field;
import junit.framework.Assert;
import org.junit.Test;
import edu.depaul.armada.model.AgentContainerLog;
public class LogCollectorTest {
@Test
public void setcAdvisorURLTest() throws Exception {
LogCollector logCollector = new LogCollector();
logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
//access private field
Field field = logCollector.getClass().getDeclaredField("cAdvisorURL");
field.setAccessible(true);
Assert.assertSame(field.get(logCollector), "http://140.192.249.16:8890/api/v1.2/docker");
}
@Test
public void ListNotEmptyTest() {
LogCollector logCollector = new LogCollector();
logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
Assert.assertFalse(list.isEmpty());
}
@Test
public void emptyCollectionTest() {
LogCollector logCollector = new LogCollector();
logCollector.setcAdvisorURL("List should be empty");
java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
Assert.assertTrue(list.isEmpty());
}
@Test
public void checkFieldInitializationTest() {
LogCollector logCollector = new LogCollector();
logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
for (AgentContainerLog containerLog : list) {
Assert.assertNotNull(containerLog.containerUniqueId);
Assert.assertNotNull(containerLog.name);
Assert.assertNotNull(containerLog.cpuTotal);
Assert.assertNotNull(containerLog.memTotal);
Assert.assertNotNull(containerLog.timestamp);
Assert.assertNotNull(containerLog.cpuUsed);
Assert.assertNotNull(containerLog.memUsed);
Assert.assertNotNull(containerLog.diskTotal);
Assert.assertNotNull(containerLog.diskUsed);
}
}
@Test
public void checkContainerUniqueId() {
LogCollector logCollector = new LogCollector();
//create a string with the JSON that we're test parsing
String testJson = "{ /docker/17e93e2b85aff1233a841746a6b28f73e0ef7413ebf36f0f658837f0d13db51e: {\n" +
"name: \"/docker/17e93e2b85aff1233a841746a6b28f73e0ef7413ebf36f0f658837f0d13db51e\",\n" +
"aliases: [\n" +
"\"deployer-classtest-1\",\n" +
"\"17e93e2b85aff1233a841746a6b28f73e0ef7413ebf36f0f658837f0d13db51e\"\n" +
"],\n" +
"namespace: \"docker\",\n" +
"spec: {\n" +
"has_cpu: true,\n" +
"cpu: {\n" +
"limit: 1024,\n" +
"max_limit: 0,\n" +
"mask: \"0-7\"\n" +
"},\n" +
"has_memory: true,\n" +
"memory: {\n" +
"limit: 18446744073709552000,\n" +
"swap_limit: 18446744073709552000\n" +
"},\n" +
"has_network: true,\n" +
"has_filesystem: true\n" +
"},\n" +
"stats: [\n" +
"{\n" +
"timestamp: \"2015-02-23T22:51:25.014432807Z\",\n" +
"cpu: {\n" +
"usage: {\n" +
"total: 6545364430269,\n" +
"per_cpu_usage: [\n" +
"2768354142138,\n" +
"972900962624,\n" +
"915988367371,\n" +
"1575576553625,\n" +
"56474072829,\n" +
"96769364658,\n" +
"73995651958,\n" +
"85305315066\n" +
"],\n" +
"user: 2215200000000,\n" +
"system: 3351510000000\n" +
"},\n" +
"load: 0\n" +
"},\n" +
"diskio: { },\n" +
"memory: {\n" +
"usage: 162570240,\n" +
"working_set: 58372096,\n" +
"container_data: {\n" +
"pgfault: 21876626,\n" +
"pgmajfault: 131\n" +
"},\n" +
"hierarchical_data: {\n" +
"pgfault: 21876626,\n" +
"pgmajfault: 131\n" +
"}\n" +
"},\n" +
"network: {\n" +
"rx_bytes: 0,\n" +
"rx_packets: 0,\n" +
"rx_errors: 0,\n" +
"rx_dropped: 0,\n" +
"tx_bytes: 0,\n" +
"tx_packets: 0,\n" +
"tx_errors: 0,\n" +
"tx_dropped: 0\n" +
"},\n" +
"filesystem: [\n" +
"{\n" +
"device: \"/dev/disk/by-uuid/1a3998f2-2fd1-4af8-8556-de86d8d361b2\",\n" +
"capacity: 978034905088,\n" +
"usage: 69632,\n" +
"reads_completed: 0,\n" +
"reads_merged: 0,\n" +
"sectors_read: 0,\n" +
"read_time: 0,\n" +
"writes_completed: 0,\n" +
"writes_merged: 0,\n" +
"sectors_written: 0,\n" +
"write_time: 0,\n" +
"io_in_progress: 0,\n" +
"io_time: 0,\n" +
"weighted_io_time: 0\n" +
"}\n" +
"]\n" +
"} }";
//create an input stream from that string
//set logCollector's JsonParser to parse that stream
//Create a new empty loglist
//call logCollector.parseJson(logList)
//assert that the log list's log fits criteria for this test
}
}
| src/test/java/edu/depaul/agent/LogCollectorTest.java | package edu.depaul.agent;
import java.lang.reflect.Field;
import junit.framework.Assert;
import org.junit.Test;
import edu.depaul.armada.model.AgentContainerLog;
public class LogCollectorTest {
// @Test
// public void setcAdvisorURLTest() throws Exception {
//
// LogCollector logCollector = new LogCollector();
// logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
//
// //access private field
// Field field = logCollector.getClass().getDeclaredField("cAdvisorURL");
// field.setAccessible(true);
//
// Assert.assertSame(field.get(logCollector), "http://140.192.249.16:8890/api/v1.2/docker");
// }
//
// @Test
// public void ListNotEmptyTest() {
// LogCollector logCollector = new LogCollector();
// logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
// java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
//
// Assert.assertFalse(list.isEmpty());
// }
//
// @Test
// public void emptyCollectionTest() {
// LogCollector logCollector = new LogCollector();
// logCollector.setcAdvisorURL("List should be empty");
// java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
//
// Assert.assertTrue(list.isEmpty());
// }
//
// @Test
// public void checkFieldInitializationTest() {
// LogCollector logCollector = new LogCollector();
// logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
// java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
//
// for (AgentContainerLog containerLog : list) {
// Assert.assertNotNull(containerLog.containerUniqueId);
// Assert.assertNotNull(containerLog.name);
// Assert.assertTrue(containerLog.cpuTotal > 0);
// //Assert.assertTrue(l.memTotal > 0);
// Assert.assertNotNull(containerLog.timestamp);
// Assert.assertTrue(containerLog.cpuUsed > 0);
// Assert.assertTrue(containerLog.memUsed > 0);
// Assert.assertTrue(containerLog.diskTotal > 0);
// Assert.assertTrue(containerLog.diskUsed > 0);
//
// }
// }
@Test
public void checkContainerUniqueId() {
LogCollector logCollector = new LogCollector();
//create a string with the JSON that we're test parsing
String testJson = "{ /docker/17e93e2b85aff1233a841746a6b28f73e0ef7413ebf36f0f658837f0d13db51e: {\n" +
"name: \"/docker/17e93e2b85aff1233a841746a6b28f73e0ef7413ebf36f0f658837f0d13db51e\",\n" +
"aliases: [\n" +
"\"deployer-classtest-1\",\n" +
"\"17e93e2b85aff1233a841746a6b28f73e0ef7413ebf36f0f658837f0d13db51e\"\n" +
"],\n" +
"namespace: \"docker\",\n" +
"spec: {\n" +
"has_cpu: true,\n" +
"cpu: {\n" +
"limit: 1024,\n" +
"max_limit: 0,\n" +
"mask: \"0-7\"\n" +
"},\n" +
"has_memory: true,\n" +
"memory: {\n" +
"limit: 18446744073709552000,\n" +
"swap_limit: 18446744073709552000\n" +
"},\n" +
"has_network: true,\n" +
"has_filesystem: true\n" +
"},\n" +
"stats: [\n" +
"{\n" +
"timestamp: \"2015-02-23T22:51:25.014432807Z\",\n" +
"cpu: {\n" +
"usage: {\n" +
"total: 6545364430269,\n" +
"per_cpu_usage: [\n" +
"2768354142138,\n" +
"972900962624,\n" +
"915988367371,\n" +
"1575576553625,\n" +
"56474072829,\n" +
"96769364658,\n" +
"73995651958,\n" +
"85305315066\n" +
"],\n" +
"user: 2215200000000,\n" +
"system: 3351510000000\n" +
"},\n" +
"load: 0\n" +
"},\n" +
"diskio: { },\n" +
"memory: {\n" +
"usage: 162570240,\n" +
"working_set: 58372096,\n" +
"container_data: {\n" +
"pgfault: 21876626,\n" +
"pgmajfault: 131\n" +
"},\n" +
"hierarchical_data: {\n" +
"pgfault: 21876626,\n" +
"pgmajfault: 131\n" +
"}\n" +
"},\n" +
"network: {\n" +
"rx_bytes: 0,\n" +
"rx_packets: 0,\n" +
"rx_errors: 0,\n" +
"rx_dropped: 0,\n" +
"tx_bytes: 0,\n" +
"tx_packets: 0,\n" +
"tx_errors: 0,\n" +
"tx_dropped: 0\n" +
"},\n" +
"filesystem: [\n" +
"{\n" +
"device: \"/dev/disk/by-uuid/1a3998f2-2fd1-4af8-8556-de86d8d361b2\",\n" +
"capacity: 978034905088,\n" +
"usage: 69632,\n" +
"reads_completed: 0,\n" +
"reads_merged: 0,\n" +
"sectors_read: 0,\n" +
"read_time: 0,\n" +
"writes_completed: 0,\n" +
"writes_merged: 0,\n" +
"sectors_written: 0,\n" +
"write_time: 0,\n" +
"io_in_progress: 0,\n" +
"io_time: 0,\n" +
"weighted_io_time: 0\n" +
"}\n" +
"]\n" +
"} }";
//create an input stream from that string
//set logCollector's JsonParser to parse that stream
//Create a new empty loglist
//call logCollector.parseJson(logList)
//assert that the log list's log fits criteria for this test
}
}
| Re-enabled agent tests
| src/test/java/edu/depaul/agent/LogCollectorTest.java | Re-enabled agent tests | <ide><path>rc/test/java/edu/depaul/agent/LogCollectorTest.java
<ide>
<ide> public class LogCollectorTest {
<ide>
<del>// @Test
<del>// public void setcAdvisorURLTest() throws Exception {
<del>//
<del>// LogCollector logCollector = new LogCollector();
<del>// logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
<del>//
<del>// //access private field
<del>// Field field = logCollector.getClass().getDeclaredField("cAdvisorURL");
<del>// field.setAccessible(true);
<del>//
<del>// Assert.assertSame(field.get(logCollector), "http://140.192.249.16:8890/api/v1.2/docker");
<del>// }
<del>//
<del>// @Test
<del>// public void ListNotEmptyTest() {
<del>// LogCollector logCollector = new LogCollector();
<del>// logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
<del>// java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
<del>//
<del>// Assert.assertFalse(list.isEmpty());
<del>// }
<del>//
<del>// @Test
<del>// public void emptyCollectionTest() {
<del>// LogCollector logCollector = new LogCollector();
<del>// logCollector.setcAdvisorURL("List should be empty");
<del>// java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
<del>//
<del>// Assert.assertTrue(list.isEmpty());
<del>// }
<del>//
<del>// @Test
<del>// public void checkFieldInitializationTest() {
<del>// LogCollector logCollector = new LogCollector();
<del>// logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
<del>// java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
<del>//
<del>// for (AgentContainerLog containerLog : list) {
<del>// Assert.assertNotNull(containerLog.containerUniqueId);
<del>// Assert.assertNotNull(containerLog.name);
<del>// Assert.assertTrue(containerLog.cpuTotal > 0);
<del>// //Assert.assertTrue(l.memTotal > 0);
<del>// Assert.assertNotNull(containerLog.timestamp);
<del>// Assert.assertTrue(containerLog.cpuUsed > 0);
<del>// Assert.assertTrue(containerLog.memUsed > 0);
<del>// Assert.assertTrue(containerLog.diskTotal > 0);
<del>// Assert.assertTrue(containerLog.diskUsed > 0);
<del>//
<del>// }
<del>// }
<add> @Test
<add> public void setcAdvisorURLTest() throws Exception {
<add>
<add> LogCollector logCollector = new LogCollector();
<add> logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
<add>
<add> //access private field
<add> Field field = logCollector.getClass().getDeclaredField("cAdvisorURL");
<add> field.setAccessible(true);
<add>
<add> Assert.assertSame(field.get(logCollector), "http://140.192.249.16:8890/api/v1.2/docker");
<add> }
<add>
<add> @Test
<add> public void ListNotEmptyTest() {
<add> LogCollector logCollector = new LogCollector();
<add> logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
<add> java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
<add>
<add> Assert.assertFalse(list.isEmpty());
<add> }
<add>
<add> @Test
<add> public void emptyCollectionTest() {
<add> LogCollector logCollector = new LogCollector();
<add> logCollector.setcAdvisorURL("List should be empty");
<add> java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
<add>
<add> Assert.assertTrue(list.isEmpty());
<add> }
<add>
<add> @Test
<add> public void checkFieldInitializationTest() {
<add> LogCollector logCollector = new LogCollector();
<add> logCollector.setcAdvisorURL("http://140.192.249.16:8890/api/v1.2/docker");
<add> java.util.List<AgentContainerLog> list = logCollector.getCurrentLogs();
<add>
<add> for (AgentContainerLog containerLog : list) {
<add> Assert.assertNotNull(containerLog.containerUniqueId);
<add> Assert.assertNotNull(containerLog.name);
<add> Assert.assertNotNull(containerLog.cpuTotal);
<add> Assert.assertNotNull(containerLog.memTotal);
<add> Assert.assertNotNull(containerLog.timestamp);
<add> Assert.assertNotNull(containerLog.cpuUsed);
<add> Assert.assertNotNull(containerLog.memUsed);
<add> Assert.assertNotNull(containerLog.diskTotal);
<add> Assert.assertNotNull(containerLog.diskUsed);
<add>
<add> }
<add> }
<ide>
<ide> @Test
<ide> public void checkContainerUniqueId() { |
|
Java | apache-2.0 | 0fda96eba95779a1450e62ffefe73cbe0e0184b2 | 0 | HashEngineering/dashj,HashEngineering/dashj,HashEngineering/dashj,HashEngineering/darkcoinj,HashEngineering/darkcoinj,HashEngineering/darkcoinj,HashEngineering/dashj | package org.bitcoinj.evolution;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import org.bitcoinj.core.*;
import org.bitcoinj.core.listeners.ChainDownloadStartedEventListener;
import org.bitcoinj.core.listeners.NewBestBlockListener;
import org.bitcoinj.core.listeners.PeerConnectedEventListener;
import org.bitcoinj.core.listeners.PeerDisconnectedEventListener;
import org.bitcoinj.core.listeners.ReorganizeListener;
import org.bitcoinj.evolution.listeners.MasternodeListDownloadedListener;
import org.bitcoinj.quorums.LLMQParameters;
import org.bitcoinj.quorums.LLMQUtils;
import org.bitcoinj.quorums.SigningManager;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.quorums.SimplifiedQuorumList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
public class SimplifiedMasternodeListManager extends AbstractManager {
private static final Logger log = LoggerFactory.getLogger(SimplifiedMasternodeListManager.class);
private ReentrantLock lock = Threading.lock("SimplifiedMasternodeListManager");
static final int DMN_FORMAT_VERSION = 1;
static final int LLMQ_FORMAT_VERSION = 2;
public static final int SNAPSHOT_LIST_PERIOD = 576; // once per day
public static final int LISTS_CACHE_SIZE = 576;
public static final int SNAPSHOT_TIME_PERIOD = 60 * 60 * 26;
public static int MAX_CACHE_SIZE = 10;
public static int MIN_CACHE_SIZE = 1;
public enum SaveOptions {
SAVE_EVERY_BLOCK,
SAVE_EVERY_CHANGE,
};
public SaveOptions saveOptions;
public enum SyncOptions {
SYNC_SNAPSHOT_PERIOD,
SYNC_CACHE_PERIOD,
SYNC_MINIMUM;
}
public SyncOptions syncOptions;
public int syncInterval;
LinkedHashMap<Sha256Hash, SimplifiedMasternodeList> mnListsCache = new LinkedHashMap<Sha256Hash, SimplifiedMasternodeList>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, SimplifiedMasternodeList> eldest) {
return size() > (syncOptions == SyncOptions.SYNC_MINIMUM ? MIN_CACHE_SIZE : MAX_CACHE_SIZE);
}
};
LinkedHashMap<Sha256Hash, SimplifiedQuorumList> quorumsCache = new LinkedHashMap<Sha256Hash, SimplifiedQuorumList>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, SimplifiedQuorumList> eldest) {
return size() > (syncOptions == SyncOptions.SYNC_MINIMUM ? MIN_CACHE_SIZE : MAX_CACHE_SIZE);
}
};
SimplifiedMasternodeList mnList;
SimplifiedQuorumList quorumList;
long tipHeight;
Sha256Hash tipBlockHash;
AbstractBlockChain blockChain;
AbstractBlockChain headersChain;
Sha256Hash lastRequestHash = Sha256Hash.ZERO_HASH;
GetSimplifiedMasternodeListDiff lastRequestMessage;
long lastRequestTime;
static final long WAIT_GETMNLISTDIFF = 5000;
Peer downloadPeer;
boolean waitingForMNListDiff;
boolean initChainTipSyncComplete = false;
LinkedHashMap<Sha256Hash, StoredBlock> pendingBlocksMap;
ArrayList<StoredBlock> pendingBlocks;
int failedAttempts;
static final int MAX_ATTEMPTS = 10;
boolean loadedFromFile;
boolean requiresLoadingFromFile;
PeerGroup peerGroup;
public SimplifiedMasternodeListManager(Context context) {
super(context);
tipBlockHash = params.getGenesisBlock().getHash();
mnList = new SimplifiedMasternodeList(context.getParams());
quorumList = new SimplifiedQuorumList(context.getParams());
lastRequestTime = 0;
waitingForMNListDiff = false;
pendingBlocks = new ArrayList<StoredBlock>();
pendingBlocksMap = new LinkedHashMap<Sha256Hash, StoredBlock>();
saveOptions = SaveOptions.SAVE_EVERY_CHANGE;
syncOptions = SyncOptions.SYNC_MINIMUM;
syncInterval = 8;
loadedFromFile = false;
requiresLoadingFromFile = true;
lastRequestMessage = new GetSimplifiedMasternodeListDiff(Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH);
initChainTipSyncComplete = !context.getSyncFlags().contains(MasternodeSync.SYNC_FLAGS.SYNC_HEADERS_MN_LIST_FIRST);
}
@Override
public int calculateMessageSizeInBytes() {
return 0;
}
@Override
public AbstractManager createEmpty() {
return new SimplifiedMasternodeListManager(Context.get());
}
@Override
public void checkAndRemove() {
}
@Override
public void clear() {
}
@Override
protected void parse() throws ProtocolException {
mnList = new SimplifiedMasternodeList(params, payload, cursor);
cursor += mnList.getMessageSize();
tipBlockHash = readHash();
tipHeight = readUint32();
if(getFormatVersion() >= 2) {
quorumList = new SimplifiedQuorumList(params, payload, cursor);
cursor += quorumList.getMessageSize();
//read pending blocks
int size = (int)readVarInt();
ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
for(int i = 0; i < size; ++i) {
buffer.put(readBytes(StoredBlock.COMPACT_SERIALIZED_SIZE));
buffer.rewind();
StoredBlock block = StoredBlock.deserializeCompact(params, buffer);
if(block.getHeight() != 0 && syncOptions != SyncOptions.SYNC_MINIMUM) {
pendingBlocks.add(block);
pendingBlocksMap.put(block.getHeader().getHash(), block);
}
buffer.rewind();
}
} else {
quorumList = new SimplifiedQuorumList(params);
}
length = cursor - offset;
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
lock.lock();
try {
SimplifiedMasternodeList mnListToSave = null;
SimplifiedQuorumList quorumListToSave = null;
ArrayList<StoredBlock> otherPendingBlocks = new ArrayList<StoredBlock>(MAX_CACHE_SIZE);
if(mnListsCache.size() > 0) {
for(Map.Entry<Sha256Hash, SimplifiedMasternodeList> entry : mnListsCache.entrySet()) {
if(mnListToSave == null) {
mnListToSave = entry.getValue();
quorumListToSave = quorumsCache.get(entry.getKey());
} else {
otherPendingBlocks.add(entry.getValue().getStoredBlock());
}
}
} else {
mnListToSave = mnList;
quorumListToSave = quorumList;
}
mnListToSave.bitcoinSerialize(stream);
stream.write(mnListToSave.getBlockHash().getReversedBytes());
Utils.uint32ToByteStreamLE(mnListToSave.getHeight(), stream);
if(getFormatVersion() >= 2) {
quorumListToSave.bitcoinSerialize(stream);
if(syncOptions != SyncOptions.SYNC_MINIMUM) {
stream.write(new VarInt(pendingBlocks.size() + otherPendingBlocks.size()).encode());
ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
log.info("saving {} blocks to catch up mnList", otherPendingBlocks.size());
for (StoredBlock block : otherPendingBlocks) {
block.serializeCompact(buffer);
stream.write(buffer.array());
buffer.clear();
}
for (StoredBlock block : pendingBlocks) {
block.serializeCompact(buffer);
stream.write(buffer.array());
buffer.clear();
}
} else stream.write(new VarInt(0).encode());
}
} finally {
lock.unlock();
}
}
public void updatedBlockTip(StoredBlock tip) {
}
protected boolean shouldProcessMNListDiff() {
return context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_DMN_LIST) ||
context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_QUORUM_LIST);
}
public void processMasternodeListDiff(Peer peer, SimplifiedMasternodeListDiff mnlistdiff) {
if(!shouldProcessMNListDiff())
return;
processMasternodeListDiff(peer, mnlistdiff, false);
}
public void processMasternodeListDiff(@Nullable Peer peer, SimplifiedMasternodeListDiff mnlistdiff, boolean isLoadingBootStrap) {
StoredBlock block = null;
long newHeight = ((CoinbaseTx) mnlistdiff.coinBaseTx.getExtraPayloadObject()).getHeight();
if (peer != null) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.Received, mnlistdiff);
Stopwatch watch = Stopwatch.createStarted();
Stopwatch watchMNList = Stopwatch.createUnstarted();
Stopwatch watchQuorums = Stopwatch.createUnstarted();
boolean isSyncingHeadersFirst = context.peerGroup.getSyncStage() == PeerGroup.SyncStage.MNLIST;
AbstractBlockChain chain = isSyncingHeadersFirst ? headersChain : blockChain;
log.info("processing mnlistdiff between : " + mnList.getHeight() + " & " + newHeight + "; " + mnlistdiff);
lock.lock();
try {
block = chain.getBlockStore().get(mnlistdiff.blockHash);
if(!isLoadingBootStrap && block.getHeight() != newHeight)
throw new ProtocolException("mnlistdiff blockhash (height="+block.getHeight()+" doesn't match coinbase blockheight: " + newHeight);
watchMNList.start();
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.Processing, mnlistdiff);
SimplifiedMasternodeList newMNList = mnList.applyDiff(mnlistdiff);
if(context.masternodeSync.hasVerifyFlag(MasternodeSync.VERIFY_FLAGS.MNLISTDIFF_MNLIST))
newMNList.verify(mnlistdiff.coinBaseTx, mnlistdiff, mnList);
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.ProcessedMasternodes, mnlistdiff);
newMNList.setBlock(block, block == null ? false : block.getHeader().getPrevBlockHash().equals(mnlistdiff.prevBlockHash));
SimplifiedQuorumList newQuorumList = quorumList;
if(mnlistdiff.coinBaseTx.getExtraPayloadObject().getVersion() >= 2) {
watchQuorums.start();
newQuorumList = quorumList.applyDiff(mnlistdiff, isLoadingBootStrap, chain);
if(context.masternodeSync.hasVerifyFlag(MasternodeSync.VERIFY_FLAGS.MNLISTDIFF_QUORUM))
newQuorumList.verify(mnlistdiff.coinBaseTx, mnlistdiff, quorumList, newMNList);
} else {
quorumList.syncWithMasternodeList(newMNList);
}
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.ProcessedQuorums, mnlistdiff);
mnListsCache.put(newMNList.getBlockHash(), newMNList);
quorumsCache.put(newQuorumList.getBlockHash(), newQuorumList);
mnList = newMNList;
quorumList = newQuorumList;
log.info(this.toString());
unCache();
failedAttempts = 0;
if(!pendingBlocks.isEmpty()) {
StoredBlock thisBlock = pendingBlocks.get(0);
pendingBlocks.remove(0);
pendingBlocksMap.remove(thisBlock.getHeader().getHash());
} else log.warn("pendingBlocks is empty");
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.Finished, mnlistdiff);
if(mnlistdiff.coinBaseTx.getExtraPayloadObject().getVersion() >= 2 && quorumList.size() > 0)
setFormatVersion(LLMQ_FORMAT_VERSION);
if(mnlistdiff.hasChanges() || pendingBlocks.size() < MAX_CACHE_SIZE || saveOptions == SaveOptions.SAVE_EVERY_BLOCK)
save();
} catch(MasternodeListDiffException x) {
//we already have this mnlistdiff or doesn't match our current tipBlockHash
if(mnList.getBlockHash().equals(mnlistdiff.blockHash)) {
log.info("heights are the same: " + x.getMessage());
log.info("mnList = {} vs mnlistdiff {}", mnList.getBlockHash(), mnlistdiff.prevBlockHash);
log.info("mnlistdiff {} -> {}", mnlistdiff.prevBlockHash, mnlistdiff.blockHash);
log.info("lastRequest {} -> {}", lastRequestMessage.baseBlockHash, lastRequestMessage.blockHash);
//remove this block from the list
if(pendingBlocks.size() > 0) {
StoredBlock thisBlock = pendingBlocks.get(0);
if(thisBlock.getHeader().getPrevBlockHash().equals(mnlistdiff.prevBlockHash) &&
thisBlock.getHeader().getHash().equals(mnlistdiff.prevBlockHash)) {
pendingBlocks.remove(0);
pendingBlocksMap.remove(thisBlock.getHeader().getHash());
}
}
} else {
log.info("heights are different " + x.getMessage());
log.info("mnlistdiff height = {}; mnList: {}; quorumList: {}", newHeight, mnList.getHeight(), quorumList.getHeight());
log.info("mnList = {} vs mnlistdiff = {}", mnList.getBlockHash(), mnlistdiff.prevBlockHash);
log.info("mnlistdiff {} -> {}", mnlistdiff.prevBlockHash, mnlistdiff.blockHash);
log.info("lastRequest {} -> {}", lastRequestMessage.baseBlockHash, lastRequestMessage.blockHash);
failedAttempts++;
if(failedAttempts > MAX_ATTEMPTS)
resetMNList(true);
}
} catch(VerificationException x) {
//request this block again and close this peer
log.info("verification error: close this peer" + x.getMessage());
failedAttempts++;
throw x;
} catch(NullPointerException x) {
log.info("NPE: close this peer" + x.getMessage());
failedAttempts++;
throw new VerificationException("verification error: " + x.getMessage());
} catch(FileNotFoundException x) {
//file name is not set, do not save
log.info(x.getMessage());
} catch(BlockStoreException x) {
log.info(x.getMessage());
failedAttempts++;
throw new ProtocolException(x);
} finally {
watch.stop();
log.info("processing mnlistdiff times : Total: " + watch + "mnList: " + watchMNList + " quorums" + watchQuorums + "mnlistdiff" + mnlistdiff);
waitingForMNListDiff = false;
if (isSyncingHeadersFirst) {
if (downloadPeer != null) {
log.info("initChainTipSync=false");
context.peerGroup.triggerMnListDownloadComplete();
log.info("initChainTipSync=true");
initChainTipSyncComplete = true;
} else {
context.peerGroup.triggerMnListDownloadComplete();
initChainTipSyncComplete = true;
}
}
requestNextMNListDiff();
lock.unlock();
}
}
public NewBestBlockListener newBestBlockListener = new NewBestBlockListener() {
@Override
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
boolean value = initChainTipSyncComplete || !context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_HEADERS_MN_LIST_FIRST);
if(value && getListAtChainTip().getHeight() < blockChain.getBestChainHeight() && isDeterministicMNsSporkActive() && isLoadedFromFile()) {
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (Utils.currentTimeSeconds() - block.getHeader().getTimeSeconds() < timePeriod) {
if(syncOptions == SyncOptions.SYNC_MINIMUM) {
try {
StoredBlock requestBlock = blockChain.getBlockStore().get(block.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if(getListAtChainTip().getHeight() > requestBlock.getHeight())
requestBlock = blockChain.getBlockStore().get((int)getListAtChainTip().getHeight()+1);
if (requestBlock != null) {
block = requestBlock;
}
} catch (BlockStoreException x) {
//do nothing
}
}
requestMNListDiff(block);
}
}
}
};
public PeerConnectedEventListener peerConnectedEventListener = new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
lock.lock();
try {
if (downloadPeer == null)
downloadPeer = peer;
boolean value = initChainTipSyncComplete;
if (value && getListAtChainTip().getHeight() < blockChain.getBestChainHeight() && isDeterministicMNsSporkActive() && isLoadedFromFile()) {
maybeGetMNListDiffFresh();
if (!waitingForMNListDiff && mnList.getBlockHash().equals(params.getGenesisBlock().getHash()) || mnList.getHeight() < blockChain.getBestChainHeight()) {
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (Utils.currentTimeSeconds() - blockChain.getChainHead().getHeader().getTimeSeconds() < timePeriod) {
StoredBlock block = blockChain.getChainHead();
if (syncOptions == SyncOptions.SYNC_MINIMUM) {
try {
StoredBlock requestBlock = blockChain.getBlockStore().get(block.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if (getListAtChainTip().getHeight() > requestBlock.getHeight())
requestBlock = blockChain.getBlockStore().get((int) getListAtChainTip().getHeight() + 1);
if (requestBlock != null) {
block = requestBlock;
}
} catch (BlockStoreException x) {
//do nothing
}
}
if (!pendingBlocksMap.containsKey(block.getHeader().getHash()))
requestMNListDiff(peer, block);
}
}
}
} finally {
lock.unlock();
}
}
};
PeerDisconnectedEventListener peerDisconnectedEventListener = new PeerDisconnectedEventListener() {
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
log.info("Peer disconnected: " + peer.getAddress());
if(downloadPeer == peer) {
downloadPeer = null;
chooseRandomDownloadPeer();
}
}
};
ReorganizeListener reorganizeListener = new ReorganizeListener() {
@Override
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException {
if (!shouldProcessMNListDiff()) {
return;
}
lock.lock();
try {
SimplifiedMasternodeList mnlistAtSplitPoint = mnListsCache.get(splitPoint.getHeader().getHash());
if (mnlistAtSplitPoint != null) {
Iterator<Map.Entry<Sha256Hash, SimplifiedMasternodeList>> iterator = mnListsCache.entrySet().iterator();
boolean foundSplitPoint = true;
while (iterator.hasNext()) {
Map.Entry<Sha256Hash, SimplifiedMasternodeList> entry = iterator.next();
if (entry.getValue().equals(splitPoint.getHeader().getHash())) {
foundSplitPoint = true;
continue;
}
if (foundSplitPoint)
iterator.remove();
}
pendingBlocks.clear();
pendingBlocksMap.clear();
for (StoredBlock newBlock : newBlocks) {
pendingBlocks.add(newBlock);
pendingBlocksMap.put(newBlock.getHeader().getHash(), newBlock);
}
requestNextMNListDiff();
} else {
resetMNList(true);
}
} finally {
lock.unlock();
}
}
};
void chooseRandomDownloadPeer() {
List<Peer> peers = context.peerGroup.getConnectedPeers();
if(peers != null && !peers.isEmpty()) {
downloadPeer = peers.get(new Random().nextInt(peers.size()));
}
}
ChainDownloadStartedEventListener chainDownloadStartedEventListener = new ChainDownloadStartedEventListener() {
@Override
public void onChainDownloadStarted(Peer peer, int blocksLeft) {
lock.lock();
try {
downloadPeer = peer;
if(isLoadedFromFile())
maybeGetMNListDiffFresh();
} finally {
lock.unlock();
}
}
};
void maybeGetMNListDiffFresh() {
if(!shouldProcessMNListDiff())
return;
lock.lock();
try {
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (pendingBlocks.size() > 0) {
if (!waitingForMNListDiff) {
requestNextMNListDiff();
return;
}
if (lastRequestTime + WAIT_GETMNLISTDIFF < Utils.currentTimeMillis()) {
waitingForMNListDiff = false;
requestNextMNListDiff();
return;
}
//if (lastRequestTime + WAIT_GETMNLISTDIFF < Utils.currentTimeMillis())
// return;
return;
} else if (lastRequestTime + WAIT_GETMNLISTDIFF > Utils.currentTimeMillis() ||
blockChain.getChainHead().getHeader().getTimeSeconds() < Utils.currentTimeSeconds() - timePeriod) {
return;
}
//Should we reset our masternode/quorum list
if (mnList.size() == 0 || mnList.getBlockHash().equals(params.getGenesisBlock().getHash())) {
mnList = new SimplifiedMasternodeList(params);
quorumList = new SimplifiedQuorumList(params);
} else {
if (mnList.getBlockHash().equals(blockChain.getChainHead().getHeader().getHash()))
return;
}
if (downloadPeer == null) {
downloadPeer = context.peerGroup.getDownloadPeer();
}
StoredBlock block = blockChain.getChainHead();
log.info("maybe requesting mnlistdiff from {} to {}; \n From {}\n To {}", mnList.getHeight(), block.getHeight(), mnList.getBlockHash(), block.getHeader().getHash());
if (mnList.getBlockHash().equals(params.getGenesisBlock().getHash())) {
resetMNList(true);
return;
}
if (!blockChain.getChainHead().getHeader().getPrevBlockHash().equals(mnList.getBlockHash())) {
if (syncOptions != SyncOptions.SYNC_MINIMUM)
fillPendingBlocksList(mnList.getBlockHash(), blockChain.getChainHead().getHeader().getHash(), pendingBlocks.size());
requestNextMNListDiff();
return;
}
StoredBlock endBlock = blockChain.getChainHead();
try {
if (syncOptions == SyncOptions.SYNC_MINIMUM)
endBlock = blockChain.getBlockStore().get(endBlock.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if (mnListsCache.containsKey(endBlock.getHeader().getHash()))
endBlock = blockChain.getBlockStore().get((int) getListAtChainTip().getHeight() + 1);
if (endBlock == null)
endBlock = blockChain.getChainHead();
} catch (BlockStoreException x) {
// do nothing
}
lastRequestMessage = new GetSimplifiedMasternodeListDiff(mnList.getBlockHash(), endBlock.getHeader().getHash());
downloadPeer.sendMessage(lastRequestMessage);
lastRequestHash = mnList.getBlockHash();
lastRequestTime = Utils.currentTimeMillis();
waitingForMNListDiff = true;
} finally {
lock.unlock();
}
}
void requestNextMNListDiff() {
if(!shouldProcessMNListDiff())
return;
lock.lock();
try {
if(waitingForMNListDiff)
return;
log.info("handling next mnlistdiff: " + pendingBlocks.size());
//fill up the pending list with recent blocks
if(syncOptions != SyncOptions.SYNC_MINIMUM) {
Sha256Hash tipHash = blockChain.getChainHead().getHeader().getHash();
ArrayList<StoredBlock> blocksToAdd = new ArrayList<StoredBlock>();
if (!mnListsCache.containsKey(tipHash) && !pendingBlocksMap.containsKey(tipHash)) {
StoredBlock cursor = blockChain.getChainHead();
do {
if (!pendingBlocksMap.containsKey(cursor.getHeader().getHash())) {
blocksToAdd.add(0, cursor);
} else break;
try {
cursor = cursor.getPrev(blockChain.getBlockStore());
} catch (BlockStoreException x) {
break;
}
} while (cursor != null);
for (StoredBlock block : blocksToAdd) {
pendingBlocks.add(block);
pendingBlocksMap.put(block.getHeader().getHash(), block);
}
}
}
if(pendingBlocks.size() == 0)
return;
//if(downloadPeer == null)
// chooseRandomDownloadPeer();
if(downloadPeer != null) {
Iterator<StoredBlock> blockIterator = pendingBlocks.iterator();
StoredBlock nextBlock;
while(blockIterator.hasNext()) {
nextBlock = blockIterator.next();
if(nextBlock.getHeight() <= mnList.getHeight()) {
blockIterator.remove();
pendingBlocksMap.remove(nextBlock.getHeader().getHash());
}
else break;
}
if(pendingBlocks.size() != 0) {
nextBlock = pendingBlocks.get(0);
if(syncInterval > 1 && nextBlock.getHeader().getTimeSeconds() < Utils.currentTimeSeconds() - 60 * 60 && pendingBlocks.size() > syncInterval) {
//lets skip up to the next syncInterval blocks
while(blockIterator.hasNext()) {
nextBlock = blockIterator.next();
if(nextBlock.getHeight() % syncInterval == 0) break;
blockIterator.remove();
}
}
log.info("requesting mnlistdiff from {} to {}; \n From {}\n To {}", mnList.getHeight(), nextBlock.getHeight(), mnList.getBlockHash(), nextBlock.getHeader().getHash());
GetSimplifiedMasternodeListDiff requestMessage = new GetSimplifiedMasternodeListDiff(mnList.getBlockHash(), nextBlock.getHeader().getHash());
if(requestMessage.equals(lastRequestMessage)) {
log.info("request for mnlistdiff is the same as the last request");
}
//try {
downloadPeer.sendMessage(requestMessage);
/*} catch (CancelledKeyException x) {
//the connection was closed
chooseRandomDownloadPeer();
downloadPeer.sendMessage(requestMessage);
}*/
lastRequestMessage = requestMessage;
lastRequestTime = Utils.currentTimeMillis();
waitingForMNListDiff = true;
}
}
} finally {
lock.unlock();
}
}
public void setBlockChain(AbstractBlockChain blockChain, @Nullable AbstractBlockChain headersChain, @Nullable PeerGroup peerGroup) {
this.blockChain = blockChain;
this.peerGroup = peerGroup;
this.headersChain = headersChain;
if(shouldProcessMNListDiff()) {
blockChain.addNewBestBlockListener(Threading.SAME_THREAD, newBestBlockListener);
blockChain.addReorganizeListener(reorganizeListener);
if (peerGroup != null) {
peerGroup.addConnectedEventListener(peerConnectedEventListener);
peerGroup.addChainDownloadStartedEventListener(chainDownloadStartedEventListener);
peerGroup.addDisconnectedEventListener(peerDisconnectedEventListener);
}
}
}
@Override
public void close() {
if(shouldProcessMNListDiff()) {
blockChain.removeNewBestBlockListener(newBestBlockListener);
blockChain.removeReorganizeListener(reorganizeListener);
peerGroup.removeConnectedEventListener(peerConnectedEventListener);
peerGroup.removeChainDownloadStartedEventListener(chainDownloadStartedEventListener);
peerGroup.removeDisconnectedEventListener(peerDisconnectedEventListener);
try {
save();
} catch (FileNotFoundException x) {
//do nothing
}
}
}
public void requestMNListDiff(StoredBlock block) {
requestMNListDiff(null, block);
}
public void requestMNListDiff(Peer peer, StoredBlock block) {
Sha256Hash hash = block.getHeader().getHash();
//log.info("getmnlistdiff: current block: " + tipHeight + " requested block " + block.getHeight());
if(block.getHeader().getTimeSeconds() < Utils.currentTimeSeconds() - SNAPSHOT_TIME_PERIOD)
return;
if(failedAttempts > MAX_ATTEMPTS) {
log.info("failed attempts maximum reached");
failedAttempts = 0;
resetMNList(true);
}
if(pendingBlocksMap.put(hash, block) == null) {
log.info("adding 1 block to the pending queue: {} - {}", block.getHeight(), block.getHeader().getHash());
pendingBlocks.add(block);
}
if(!waitingForMNListDiff)
requestNextMNListDiff();
if(lastRequestTime + WAIT_GETMNLISTDIFF * 4 < Utils.currentTimeMillis()) {
maybeGetMNListDiffFresh();
}
}
public void updateMNList() {
requestMNListDiff(context.blockChain.getChainHead());
}
@Override
public String toString() {
return "SimplifiedMNListManager: {tip:" + mnList + ", " + quorumList + ", pending blocks: " + pendingBlocks.size() + "}";
}
@Deprecated
public long getSpork15Value() {
return 0;
}
public boolean isDeterministicMNsSporkActive(long height) {
if(height == -1) {
height = mnList.getHeight();
}
return height > params.getDeterministicMasternodesEnabledHeight();
}
public boolean isDeterministicMNsSporkActive() {
return isDeterministicMNsSporkActive(-1) || params.isDeterministicMasternodesEnabled();
}
public SimplifiedMasternodeList getListAtChainTip() {
return mnList;
}
public SimplifiedQuorumList getQuorumListAtTip() {
return quorumList;
}
@Override
public int getCurrentFormatVersion() {
return quorumList.size() != 0 ? LLMQ_FORMAT_VERSION : DMN_FORMAT_VERSION;
}
public void resetMNList() {
resetMNList(false, true);
}
public void resetMNList(boolean force) {
resetMNList(force, true);
}
public void resetMNList(boolean force, boolean requestFreshList) {
try {
if(force || getFormatVersion() < LLMQ_FORMAT_VERSION) {
log.info("resetting masternode list");
mnList = new SimplifiedMasternodeList(context.getParams());
quorumList = new SimplifiedQuorumList(context.getParams());
mnListsCache.clear();
quorumsCache.clear();
pendingBlocks.clear();
pendingBlocksMap.clear();
waitingForMNListDiff = false;
initChainTipSyncComplete = false;
unCache();
try {
if(bootStrapFilePath == null)
save();
} catch (FileNotFoundException x) {
//swallow, the file has no name
}
if(requestFreshList) {
if(bootStrapFilePath == null && bootStrapStream == null) {
requestAfterMNListReset();
} else {
waitingForMNListDiff = true;
isLoadingBootStrap = true;
loadBootstrapAndSync();
}
}
}
} catch (BlockStoreException x) {
throw new RuntimeException(x);
}
}
protected void requestAfterMNListReset() throws BlockStoreException {
if(blockChain == null) //not initialized
return;
int rewindBlockCount = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_LIST_PERIOD : MAX_CACHE_SIZE;
int height = blockChain.getBestChainHeight() - rewindBlockCount;
if (height < params.getDIP0008BlockHeight())
height = params.getDIP0008BlockHeight();
if (syncOptions == SyncOptions.SYNC_MINIMUM)
height = blockChain.getBestChainHeight() - SigningManager.SIGN_HEIGHT_OFFSET;
StoredBlock resetBlock = blockChain.getBlockStore().get(height);
if (resetBlock == null)
resetBlock = blockChain.getChainHead();
requestMNListDiff(resetBlock != null ? resetBlock : blockChain.getChainHead());
}
public SimplifiedMasternodeList getListForBlock(Sha256Hash blockHash) {
lock.lock();
try {
return mnListsCache.get(blockHash);
} finally {
lock.unlock();
}
}
public SimplifiedQuorumList getQuorumListForBlock(Sha256Hash blockHash) {
lock.lock();
try {
return quorumsCache.get(blockHash);
} finally {
lock.unlock();
}
}
public ArrayList<Masternode> getAllQuorumMembers(LLMQParameters.LLMQType llmqType, Sha256Hash blockHash)
{
lock.lock();
try {
LLMQParameters llmqParameters = params.getLlmqs().get(llmqType);
SimplifiedMasternodeList allMns = getListForBlock(blockHash);
if (allMns != null) {
Sha256Hash modifier = LLMQUtils.buildLLMQBlockHash(llmqType, blockHash);
return allMns.calculateQuorum(llmqParameters.getSize(), modifier);
}
return null;
} finally {
lock.unlock();
}
}
public boolean isSynced() {
return pendingBlocks.isEmpty();
}
void fillPendingBlocksList(Sha256Hash first, Sha256Hash last, int insertIndex) {
lock.lock();
try {
StoredBlock cursor = blockChain.getBlockStore().get(last);
while(cursor != null && !cursor.getHeader().getHash().equals(first)) {
if(!pendingBlocksMap.containsKey(cursor.getHeader().getHash())) {
pendingBlocks.add(insertIndex, cursor);
pendingBlocksMap.put(cursor.getHeader().getHash(), cursor);
}
cursor = cursor.getPrev(blockChain.getBlockStore());
}
} catch (BlockStoreException x) {
throw new RuntimeException(x);
} finally {
lock.unlock();
}
}
public void setRequiresLoadingFromFile(boolean requiresLoadingFromFile) {
this.requiresLoadingFromFile = requiresLoadingFromFile;
}
public void setLoadedFromFile(boolean loadedFromFile) {
this.loadedFromFile = loadedFromFile;
}
public boolean isLoadedFromFile() {
return loadedFromFile || !requiresLoadingFromFile;
}
@Override
public void onFirstSaveComplete() {
lock.lock();
try {
if(blockChain == null || blockChain.getBestChainHeight() >= getListAtChainTip().getHeight())
return;
StoredBlock block = blockChain.getChainHead();
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (Utils.currentTimeSeconds() - block.getHeader().getTimeSeconds() < timePeriod) {
if (syncOptions == SyncOptions.SYNC_MINIMUM) {
try {
StoredBlock requestBlock = blockChain.getBlockStore().get(block.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if (getListAtChainTip().getHeight() > requestBlock.getHeight())
requestBlock = blockChain.getBlockStore().get((int) getListAtChainTip().getHeight() + 1);
if (requestBlock != null) {
block = requestBlock;
}
} catch (BlockStoreException x) {
//do nothing
}
}
requestMNListDiff(block);
}
} finally {
lock.unlock();
}
}
static String bootStrapFilePath = null;
static InputStream bootStrapStream = null;
boolean isLoadingBootStrap = false;
public static void setBootStrapFilePath(String bootStrapFilePath) {
SimplifiedMasternodeListManager.bootStrapFilePath = bootStrapFilePath;
}
public static void setBootStrapStream(InputStream bootStrapStream) {
SimplifiedMasternodeListManager.bootStrapStream = bootStrapStream;
}
protected void loadBootstrapAndSync() {
Preconditions.checkState(bootStrapFilePath != null || bootStrapStream != null);
Preconditions.checkState(mnList.size() == 0);
Preconditions.checkState(quorumList.size() == 0);
Preconditions.checkState(mnListsCache.size() == 0);
Preconditions.checkState(quorumsCache.size() == 0);
new Thread(new Runnable() {
@Override
public void run() {
log.info("loading mnlistdiff bootstrap file: " + bootStrapFilePath != null ? bootStrapFilePath : "input stream");
Context.propagate(context);
//load the file
InputStream stream = bootStrapStream;
try {
if(stream != null)
stream.reset();
stream = stream != null ? stream : new FileInputStream(bootStrapFilePath);
byte[] buffer = new byte[(int) stream.available()];
stream.read(buffer);
isLoadingBootStrap = true;
SimplifiedMasternodeListDiff mnlistdiff = new SimplifiedMasternodeListDiff(params, buffer);
processMasternodeListDiff(null, mnlistdiff, true);
log.info("finished loading mnlist bootstrap file");
} catch (VerificationException | FileNotFoundException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} catch (IOException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} catch (IllegalStateException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} catch (NullPointerException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} finally {
isLoadingBootStrap = false;
try {
if (stream != null)
stream.close();
requestAfterMNListReset();
} catch (IOException x) {
} catch (BlockStoreException x) {
}
}
}
}).start();
}
public ReentrantLock getLock() {
return lock;
}
public Peer getDownloadPeer() {
return downloadPeer != null ? downloadPeer : peerGroup.getDownloadPeer();
}
}
| core/src/main/java/org/bitcoinj/evolution/SimplifiedMasternodeListManager.java | package org.bitcoinj.evolution;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import org.bitcoinj.core.*;
import org.bitcoinj.core.listeners.ChainDownloadStartedEventListener;
import org.bitcoinj.core.listeners.NewBestBlockListener;
import org.bitcoinj.core.listeners.PeerConnectedEventListener;
import org.bitcoinj.core.listeners.PeerDisconnectedEventListener;
import org.bitcoinj.core.listeners.ReorganizeListener;
import org.bitcoinj.evolution.listeners.MasternodeListDownloadedListener;
import org.bitcoinj.quorums.LLMQParameters;
import org.bitcoinj.quorums.LLMQUtils;
import org.bitcoinj.quorums.SigningManager;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.quorums.SimplifiedQuorumList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
public class SimplifiedMasternodeListManager extends AbstractManager {
private static final Logger log = LoggerFactory.getLogger(SimplifiedMasternodeListManager.class);
private ReentrantLock lock = Threading.lock("SimplifiedMasternodeListManager");
static final int DMN_FORMAT_VERSION = 1;
static final int LLMQ_FORMAT_VERSION = 2;
public static final int SNAPSHOT_LIST_PERIOD = 576; // once per day
public static final int LISTS_CACHE_SIZE = 576;
public static final int SNAPSHOT_TIME_PERIOD = 60 * 60 * 26;
public static int MAX_CACHE_SIZE = 10;
public static int MIN_CACHE_SIZE = 1;
public enum SaveOptions {
SAVE_EVERY_BLOCK,
SAVE_EVERY_CHANGE,
};
public SaveOptions saveOptions;
public enum SyncOptions {
SYNC_SNAPSHOT_PERIOD,
SYNC_CACHE_PERIOD,
SYNC_MINIMUM;
}
public SyncOptions syncOptions;
public int syncInterval;
LinkedHashMap<Sha256Hash, SimplifiedMasternodeList> mnListsCache = new LinkedHashMap<Sha256Hash, SimplifiedMasternodeList>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, SimplifiedMasternodeList> eldest) {
return size() > (syncOptions == SyncOptions.SYNC_MINIMUM ? MIN_CACHE_SIZE : MAX_CACHE_SIZE);
}
};
LinkedHashMap<Sha256Hash, SimplifiedQuorumList> quorumsCache = new LinkedHashMap<Sha256Hash, SimplifiedQuorumList>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Sha256Hash, SimplifiedQuorumList> eldest) {
return size() > (syncOptions == SyncOptions.SYNC_MINIMUM ? MIN_CACHE_SIZE : MAX_CACHE_SIZE);
}
};
SimplifiedMasternodeList mnList;
SimplifiedQuorumList quorumList;
long tipHeight;
Sha256Hash tipBlockHash;
AbstractBlockChain blockChain;
AbstractBlockChain headersChain;
Sha256Hash lastRequestHash = Sha256Hash.ZERO_HASH;
GetSimplifiedMasternodeListDiff lastRequestMessage;
long lastRequestTime;
static final long WAIT_GETMNLISTDIFF = 5000;
Peer downloadPeer;
boolean waitingForMNListDiff;
boolean initChainTipSyncComplete = false;
LinkedHashMap<Sha256Hash, StoredBlock> pendingBlocksMap;
ArrayList<StoredBlock> pendingBlocks;
int failedAttempts;
static final int MAX_ATTEMPTS = 10;
boolean loadedFromFile;
boolean requiresLoadingFromFile;
PeerGroup peerGroup;
public SimplifiedMasternodeListManager(Context context) {
super(context);
tipBlockHash = params.getGenesisBlock().getHash();
mnList = new SimplifiedMasternodeList(context.getParams());
quorumList = new SimplifiedQuorumList(context.getParams());
lastRequestTime = 0;
waitingForMNListDiff = false;
pendingBlocks = new ArrayList<StoredBlock>();
pendingBlocksMap = new LinkedHashMap<Sha256Hash, StoredBlock>();
saveOptions = SaveOptions.SAVE_EVERY_CHANGE;
syncOptions = SyncOptions.SYNC_MINIMUM;
syncInterval = 8;
loadedFromFile = false;
requiresLoadingFromFile = true;
lastRequestMessage = new GetSimplifiedMasternodeListDiff(Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH);
initChainTipSyncComplete = !context.getSyncFlags().contains(MasternodeSync.SYNC_FLAGS.SYNC_HEADERS_MN_LIST_FIRST);
}
@Override
public int calculateMessageSizeInBytes() {
return 0;
}
@Override
public AbstractManager createEmpty() {
return new SimplifiedMasternodeListManager(Context.get());
}
@Override
public void checkAndRemove() {
}
@Override
public void clear() {
}
@Override
protected void parse() throws ProtocolException {
mnList = new SimplifiedMasternodeList(params, payload, cursor);
cursor += mnList.getMessageSize();
tipBlockHash = readHash();
tipHeight = readUint32();
if(getFormatVersion() >= 2) {
quorumList = new SimplifiedQuorumList(params, payload, cursor);
cursor += quorumList.getMessageSize();
//read pending blocks
int size = (int)readVarInt();
ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
for(int i = 0; i < size; ++i) {
buffer.put(readBytes(StoredBlock.COMPACT_SERIALIZED_SIZE));
buffer.rewind();
StoredBlock block = StoredBlock.deserializeCompact(params, buffer);
if(block.getHeight() != 0 && syncOptions != SyncOptions.SYNC_MINIMUM) {
pendingBlocks.add(block);
pendingBlocksMap.put(block.getHeader().getHash(), block);
}
buffer.rewind();
}
} else {
quorumList = new SimplifiedQuorumList(params);
}
length = cursor - offset;
}
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
lock.lock();
try {
SimplifiedMasternodeList mnListToSave = null;
SimplifiedQuorumList quorumListToSave = null;
ArrayList<StoredBlock> otherPendingBlocks = new ArrayList<StoredBlock>(MAX_CACHE_SIZE);
if(mnListsCache.size() > 0) {
for(Map.Entry<Sha256Hash, SimplifiedMasternodeList> entry : mnListsCache.entrySet()) {
if(mnListToSave == null) {
mnListToSave = entry.getValue();
quorumListToSave = quorumsCache.get(entry.getKey());
} else {
otherPendingBlocks.add(entry.getValue().getStoredBlock());
}
}
} else {
mnListToSave = mnList;
quorumListToSave = quorumList;
}
mnListToSave.bitcoinSerialize(stream);
stream.write(mnListToSave.getBlockHash().getReversedBytes());
Utils.uint32ToByteStreamLE(mnListToSave.getHeight(), stream);
if(getFormatVersion() >= 2) {
quorumListToSave.bitcoinSerialize(stream);
if(syncOptions != SyncOptions.SYNC_MINIMUM) {
stream.write(new VarInt(pendingBlocks.size() + otherPendingBlocks.size()).encode());
ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
log.info("saving {} blocks to catch up mnList", otherPendingBlocks.size());
for (StoredBlock block : otherPendingBlocks) {
block.serializeCompact(buffer);
stream.write(buffer.array());
buffer.clear();
}
for (StoredBlock block : pendingBlocks) {
block.serializeCompact(buffer);
stream.write(buffer.array());
buffer.clear();
}
} else stream.write(new VarInt(0).encode());
}
} finally {
lock.unlock();
}
}
public void updatedBlockTip(StoredBlock tip) {
}
protected boolean shouldProcessMNListDiff() {
return context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_DMN_LIST) ||
context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_QUORUM_LIST);
}
public void processMasternodeListDiff(Peer peer, SimplifiedMasternodeListDiff mnlistdiff) {
if(!shouldProcessMNListDiff())
return;
processMasternodeListDiff(peer, mnlistdiff, false);
}
public void processMasternodeListDiff(@Nullable Peer peer, SimplifiedMasternodeListDiff mnlistdiff, boolean isLoadingBootStrap) {
StoredBlock block = null;
long newHeight = ((CoinbaseTx) mnlistdiff.coinBaseTx.getExtraPayloadObject()).getHeight();
if (peer != null) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.Received, mnlistdiff);
Stopwatch watch = Stopwatch.createStarted();
Stopwatch watchMNList = Stopwatch.createUnstarted();
Stopwatch watchQuorums = Stopwatch.createUnstarted();
boolean isSyncingHeadersFirst = context.peerGroup.getSyncStage() == PeerGroup.SyncStage.MNLIST;
AbstractBlockChain chain = isSyncingHeadersFirst ? headersChain : blockChain;
log.info("processing mnlistdiff between : " + mnList.getHeight() + " & " + newHeight + "; " + mnlistdiff);
lock.lock();
try {
block = chain.getBlockStore().get(mnlistdiff.blockHash);
if(!isLoadingBootStrap && block.getHeight() != newHeight)
throw new ProtocolException("mnlistdiff blockhash (height="+block.getHeight()+" doesn't match coinbase blockheight: " + newHeight);
watchMNList.start();
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.Processing, mnlistdiff);
SimplifiedMasternodeList newMNList = mnList.applyDiff(mnlistdiff);
if(context.masternodeSync.hasVerifyFlag(MasternodeSync.VERIFY_FLAGS.MNLISTDIFF_MNLIST))
newMNList.verify(mnlistdiff.coinBaseTx, mnlistdiff, mnList);
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.ProcessedMasternodes, mnlistdiff);
newMNList.setBlock(block, block == null ? false : block.getHeader().getPrevBlockHash().equals(mnlistdiff.prevBlockHash));
SimplifiedQuorumList newQuorumList = quorumList;
if(mnlistdiff.coinBaseTx.getExtraPayloadObject().getVersion() >= 2) {
watchQuorums.start();
newQuorumList = quorumList.applyDiff(mnlistdiff, isLoadingBootStrap, chain);
if(context.masternodeSync.hasVerifyFlag(MasternodeSync.VERIFY_FLAGS.MNLISTDIFF_QUORUM))
newQuorumList.verify(mnlistdiff.coinBaseTx, mnlistdiff, quorumList, newMNList);
} else {
quorumList.syncWithMasternodeList(newMNList);
}
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.ProcessedQuorums, mnlistdiff);
mnListsCache.put(newMNList.getBlockHash(), newMNList);
quorumsCache.put(newQuorumList.getBlockHash(), newQuorumList);
mnList = newMNList;
quorumList = newQuorumList;
log.info(this.toString());
unCache();
failedAttempts = 0;
if(!pendingBlocks.isEmpty()) {
StoredBlock thisBlock = pendingBlocks.get(0);
pendingBlocks.remove(0);
pendingBlocksMap.remove(thisBlock.getHeader().getHash());
} else log.warn("pendingBlocks is empty");
if (peer != null && isSyncingHeadersFirst) peer.queueMasternodeListDownloadedListeners(MasternodeListDownloadedListener.Stage.Finished, mnlistdiff);
if(mnlistdiff.coinBaseTx.getExtraPayloadObject().getVersion() >= 2 && quorumList.size() > 0)
setFormatVersion(LLMQ_FORMAT_VERSION);
if(mnlistdiff.hasChanges() || pendingBlocks.size() < MAX_CACHE_SIZE || saveOptions == SaveOptions.SAVE_EVERY_BLOCK)
save();
} catch(MasternodeListDiffException x) {
//we already have this mnlistdiff or doesn't match our current tipBlockHash
if(mnList.getBlockHash().equals(mnlistdiff.blockHash)) {
log.info("heights are the same: " + x.getMessage());
log.info("mnList = {} vs mnlistdiff {}", mnList.getBlockHash(), mnlistdiff.prevBlockHash);
log.info("mnlistdiff {} -> {}", mnlistdiff.prevBlockHash, mnlistdiff.blockHash);
log.info("lastRequest {} -> {}", lastRequestMessage.baseBlockHash, lastRequestMessage.blockHash);
//remove this block from the list
if(pendingBlocks.size() > 0) {
StoredBlock thisBlock = pendingBlocks.get(0);
if(thisBlock.getHeader().getPrevBlockHash().equals(mnlistdiff.prevBlockHash) &&
thisBlock.getHeader().getHash().equals(mnlistdiff.prevBlockHash)) {
pendingBlocks.remove(0);
pendingBlocksMap.remove(thisBlock.getHeader().getHash());
}
}
} else {
log.info("heights are different " + x.getMessage());
log.info("mnlistdiff height = {}; mnList: {}; quorumList: {}", newHeight, mnList.getHeight(), quorumList.getHeight());
log.info("mnList = {} vs mnlistdiff = {}", mnList.getBlockHash(), mnlistdiff.prevBlockHash);
log.info("mnlistdiff {} -> {}", mnlistdiff.prevBlockHash, mnlistdiff.blockHash);
log.info("lastRequest {} -> {}", lastRequestMessage.baseBlockHash, lastRequestMessage.blockHash);
failedAttempts++;
if(failedAttempts > MAX_ATTEMPTS)
resetMNList(true);
}
} catch(VerificationException x) {
//request this block again and close this peer
log.info("verification error: close this peer" + x.getMessage());
failedAttempts++;
throw x;
} catch(NullPointerException x) {
log.info("NPE: close this peer" + x.getMessage());
failedAttempts++;
throw new VerificationException("verification error: " + x.getMessage());
} catch(FileNotFoundException x) {
//file name is not set, do not save
log.info(x.getMessage());
} catch(BlockStoreException x) {
log.info(x.getMessage());
failedAttempts++;
throw new ProtocolException(x);
} finally {
watch.stop();
log.info("processing mnlistdiff times : Total: " + watch + "mnList: " + watchMNList + " quorums" + watchQuorums + "mnlistdiff" + mnlistdiff);
waitingForMNListDiff = false;
if (isSyncingHeadersFirst) {
if (downloadPeer != null) {
log.info("initChainTipSync=false");
context.peerGroup.triggerMnListDownloadComplete();
log.info("initChainTipSync=true");
initChainTipSyncComplete = true;
} else {
context.peerGroup.triggerMnListDownloadComplete();
initChainTipSyncComplete = true;
}
}
requestNextMNListDiff();
lock.unlock();
}
}
public NewBestBlockListener newBestBlockListener = new NewBestBlockListener() {
@Override
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
log.info("masternodeListManager.notifyNewBestBlock: {}/{}", block.getHeight(), block.getHeader().getHash());
boolean value = initChainTipSyncComplete || !context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_HEADERS_MN_LIST_FIRST);
if(value && getListAtChainTip().getHeight() < blockChain.getBestChainHeight() && isDeterministicMNsSporkActive() && isLoadedFromFile()) {
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (Utils.currentTimeSeconds() - block.getHeader().getTimeSeconds() < timePeriod) {
if(syncOptions == SyncOptions.SYNC_MINIMUM) {
try {
StoredBlock requestBlock = blockChain.getBlockStore().get(block.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if(getListAtChainTip().getHeight() > requestBlock.getHeight())
requestBlock = blockChain.getBlockStore().get((int)getListAtChainTip().getHeight()+1);
if (requestBlock != null) {
block = requestBlock;
}
} catch (BlockStoreException x) {
//do nothing
}
}
requestMNListDiff(block);
}
}
}
};
public PeerConnectedEventListener peerConnectedEventListener = new PeerConnectedEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
lock.lock();
try {
if (downloadPeer == null)
downloadPeer = peer;
boolean value = initChainTipSyncComplete;
if (value && getListAtChainTip().getHeight() < blockChain.getBestChainHeight() && isDeterministicMNsSporkActive() && isLoadedFromFile()) {
maybeGetMNListDiffFresh();
if (!waitingForMNListDiff && mnList.getBlockHash().equals(params.getGenesisBlock().getHash()) || mnList.getHeight() < blockChain.getBestChainHeight()) {
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (Utils.currentTimeSeconds() - blockChain.getChainHead().getHeader().getTimeSeconds() < timePeriod) {
StoredBlock block = blockChain.getChainHead();
if (syncOptions == SyncOptions.SYNC_MINIMUM) {
try {
StoredBlock requestBlock = blockChain.getBlockStore().get(block.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if (getListAtChainTip().getHeight() > requestBlock.getHeight())
requestBlock = blockChain.getBlockStore().get((int) getListAtChainTip().getHeight() + 1);
if (requestBlock != null) {
block = requestBlock;
}
} catch (BlockStoreException x) {
//do nothing
}
}
if (!pendingBlocksMap.containsKey(block.getHeader().getHash()))
requestMNListDiff(peer, block);
}
}
}
} finally {
lock.unlock();
}
}
};
PeerDisconnectedEventListener peerDisconnectedEventListener = new PeerDisconnectedEventListener() {
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
log.info("Peer disconnected: " + peer.getAddress());
if(downloadPeer == peer) {
downloadPeer = null;
chooseRandomDownloadPeer();
}
}
};
ReorganizeListener reorganizeListener = new ReorganizeListener() {
@Override
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException {
if (!shouldProcessMNListDiff()) {
return;
}
lock.lock();
try {
SimplifiedMasternodeList mnlistAtSplitPoint = mnListsCache.get(splitPoint.getHeader().getHash());
if (mnlistAtSplitPoint != null) {
Iterator<Map.Entry<Sha256Hash, SimplifiedMasternodeList>> iterator = mnListsCache.entrySet().iterator();
boolean foundSplitPoint = true;
while (iterator.hasNext()) {
Map.Entry<Sha256Hash, SimplifiedMasternodeList> entry = iterator.next();
if (entry.getValue().equals(splitPoint.getHeader().getHash())) {
foundSplitPoint = true;
continue;
}
if (foundSplitPoint)
iterator.remove();
}
pendingBlocks.clear();
pendingBlocksMap.clear();
for (StoredBlock newBlock : newBlocks) {
pendingBlocks.add(newBlock);
pendingBlocksMap.put(newBlock.getHeader().getHash(), newBlock);
}
requestNextMNListDiff();
} else {
resetMNList(true);
}
} finally {
lock.unlock();
}
}
};
void chooseRandomDownloadPeer() {
List<Peer> peers = context.peerGroup.getConnectedPeers();
if(peers != null && !peers.isEmpty()) {
downloadPeer = peers.get(new Random().nextInt(peers.size()));
}
}
ChainDownloadStartedEventListener chainDownloadStartedEventListener = new ChainDownloadStartedEventListener() {
@Override
public void onChainDownloadStarted(Peer peer, int blocksLeft) {
lock.lock();
try {
downloadPeer = peer;
if(isLoadedFromFile())
maybeGetMNListDiffFresh();
} finally {
lock.unlock();
}
}
};
void maybeGetMNListDiffFresh() {
if(!shouldProcessMNListDiff())
return;
lock.lock();
try {
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (pendingBlocks.size() > 0) {
if (!waitingForMNListDiff) {
requestNextMNListDiff();
return;
}
if (lastRequestTime + WAIT_GETMNLISTDIFF < Utils.currentTimeMillis()) {
waitingForMNListDiff = false;
requestNextMNListDiff();
return;
}
//if (lastRequestTime + WAIT_GETMNLISTDIFF < Utils.currentTimeMillis())
// return;
return;
} else if (lastRequestTime + WAIT_GETMNLISTDIFF > Utils.currentTimeMillis() ||
blockChain.getChainHead().getHeader().getTimeSeconds() < Utils.currentTimeSeconds() - timePeriod) {
return;
}
//Should we reset our masternode/quorum list
if (mnList.size() == 0 || mnList.getBlockHash().equals(params.getGenesisBlock().getHash())) {
mnList = new SimplifiedMasternodeList(params);
quorumList = new SimplifiedQuorumList(params);
} else {
if (mnList.getBlockHash().equals(blockChain.getChainHead().getHeader().getHash()))
return;
}
if (downloadPeer == null) {
downloadPeer = context.peerGroup.getDownloadPeer();
}
StoredBlock block = blockChain.getChainHead();
log.info("maybe requesting mnlistdiff from {} to {}; \n From {}\n To {}", mnList.getHeight(), block.getHeight(), mnList.getBlockHash(), block.getHeader().getHash());
if (mnList.getBlockHash().equals(params.getGenesisBlock().getHash())) {
resetMNList(true);
return;
}
if (!blockChain.getChainHead().getHeader().getPrevBlockHash().equals(mnList.getBlockHash())) {
if (syncOptions != SyncOptions.SYNC_MINIMUM)
fillPendingBlocksList(mnList.getBlockHash(), blockChain.getChainHead().getHeader().getHash(), pendingBlocks.size());
requestNextMNListDiff();
return;
}
StoredBlock endBlock = blockChain.getChainHead();
try {
if (syncOptions == SyncOptions.SYNC_MINIMUM)
endBlock = blockChain.getBlockStore().get(endBlock.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if (mnListsCache.containsKey(endBlock.getHeader().getHash()))
endBlock = blockChain.getBlockStore().get((int) getListAtChainTip().getHeight() + 1);
if (endBlock == null)
endBlock = blockChain.getChainHead();
} catch (BlockStoreException x) {
// do nothing
}
lastRequestMessage = new GetSimplifiedMasternodeListDiff(mnList.getBlockHash(), endBlock.getHeader().getHash());
downloadPeer.sendMessage(lastRequestMessage);
lastRequestHash = mnList.getBlockHash();
lastRequestTime = Utils.currentTimeMillis();
waitingForMNListDiff = true;
} finally {
lock.unlock();
}
}
void requestNextMNListDiff() {
if(!shouldProcessMNListDiff())
return;
lock.lock();
try {
if(waitingForMNListDiff)
return;
log.info("handling next mnlistdiff: " + pendingBlocks.size());
//fill up the pending list with recent blocks
if(syncOptions != SyncOptions.SYNC_MINIMUM) {
Sha256Hash tipHash = blockChain.getChainHead().getHeader().getHash();
ArrayList<StoredBlock> blocksToAdd = new ArrayList<StoredBlock>();
if (!mnListsCache.containsKey(tipHash) && !pendingBlocksMap.containsKey(tipHash)) {
StoredBlock cursor = blockChain.getChainHead();
do {
if (!pendingBlocksMap.containsKey(cursor.getHeader().getHash())) {
blocksToAdd.add(0, cursor);
} else break;
try {
cursor = cursor.getPrev(blockChain.getBlockStore());
} catch (BlockStoreException x) {
break;
}
} while (cursor != null);
for (StoredBlock block : blocksToAdd) {
pendingBlocks.add(block);
pendingBlocksMap.put(block.getHeader().getHash(), block);
}
}
}
if(pendingBlocks.size() == 0)
return;
//if(downloadPeer == null)
// chooseRandomDownloadPeer();
if(downloadPeer != null) {
Iterator<StoredBlock> blockIterator = pendingBlocks.iterator();
StoredBlock nextBlock;
while(blockIterator.hasNext()) {
nextBlock = blockIterator.next();
if(nextBlock.getHeight() <= mnList.getHeight()) {
blockIterator.remove();
pendingBlocksMap.remove(nextBlock.getHeader().getHash());
}
else break;
}
if(pendingBlocks.size() != 0) {
nextBlock = pendingBlocks.get(0);
if(syncInterval > 1 && nextBlock.getHeader().getTimeSeconds() < Utils.currentTimeSeconds() - 60 * 60 && pendingBlocks.size() > syncInterval) {
//lets skip up to the next syncInterval blocks
while(blockIterator.hasNext()) {
nextBlock = blockIterator.next();
if(nextBlock.getHeight() % syncInterval == 0) break;
blockIterator.remove();
}
}
log.info("requesting mnlistdiff from {} to {}; \n From {}\n To {}", mnList.getHeight(), nextBlock.getHeight(), mnList.getBlockHash(), nextBlock.getHeader().getHash());
GetSimplifiedMasternodeListDiff requestMessage = new GetSimplifiedMasternodeListDiff(mnList.getBlockHash(), nextBlock.getHeader().getHash());
if(requestMessage.equals(lastRequestMessage)) {
log.info("request for mnlistdiff is the same as the last request");
}
//try {
downloadPeer.sendMessage(requestMessage);
/*} catch (CancelledKeyException x) {
//the connection was closed
chooseRandomDownloadPeer();
downloadPeer.sendMessage(requestMessage);
}*/
lastRequestMessage = requestMessage;
lastRequestTime = Utils.currentTimeMillis();
waitingForMNListDiff = true;
}
}
} finally {
lock.unlock();
}
}
public void setBlockChain(AbstractBlockChain blockChain, @Nullable AbstractBlockChain headersChain, @Nullable PeerGroup peerGroup) {
this.blockChain = blockChain;
this.peerGroup = peerGroup;
this.headersChain = headersChain;
if(shouldProcessMNListDiff()) {
blockChain.addNewBestBlockListener(Threading.SAME_THREAD, newBestBlockListener);
blockChain.addReorganizeListener(reorganizeListener);
if (peerGroup != null) {
peerGroup.addConnectedEventListener(peerConnectedEventListener);
peerGroup.addChainDownloadStartedEventListener(chainDownloadStartedEventListener);
peerGroup.addDisconnectedEventListener(peerDisconnectedEventListener);
}
}
}
@Override
public void close() {
if(shouldProcessMNListDiff()) {
blockChain.removeNewBestBlockListener(newBestBlockListener);
blockChain.removeReorganizeListener(reorganizeListener);
peerGroup.removeConnectedEventListener(peerConnectedEventListener);
peerGroup.removeChainDownloadStartedEventListener(chainDownloadStartedEventListener);
peerGroup.removeDisconnectedEventListener(peerDisconnectedEventListener);
try {
save();
} catch (FileNotFoundException x) {
//do nothing
}
}
}
public void requestMNListDiff(StoredBlock block) {
requestMNListDiff(null, block);
}
public void requestMNListDiff(Peer peer, StoredBlock block) {
Sha256Hash hash = block.getHeader().getHash();
//log.info("getmnlistdiff: current block: " + tipHeight + " requested block " + block.getHeight());
if(block.getHeader().getTimeSeconds() < Utils.currentTimeSeconds() - SNAPSHOT_TIME_PERIOD)
return;
if(failedAttempts > MAX_ATTEMPTS) {
log.info("failed attempts maximum reached");
failedAttempts = 0;
resetMNList(true);
}
if(pendingBlocksMap.put(hash, block) == null) {
log.info("adding 1 block to the pending queue: {} - {}", block.getHeight(), block.getHeader().getHash());
pendingBlocks.add(block);
}
if(!waitingForMNListDiff)
requestNextMNListDiff();
if(lastRequestTime + WAIT_GETMNLISTDIFF * 4 < Utils.currentTimeMillis()) {
maybeGetMNListDiffFresh();
}
}
public void updateMNList() {
requestMNListDiff(context.blockChain.getChainHead());
}
@Override
public String toString() {
return "SimplifiedMNListManager: {tip:" + mnList + ", " + quorumList + ", pending blocks: " + pendingBlocks.size() + "}";
}
@Deprecated
public long getSpork15Value() {
return 0;
}
public boolean isDeterministicMNsSporkActive(long height) {
if(height == -1) {
height = mnList.getHeight();
}
return height > params.getDeterministicMasternodesEnabledHeight();
}
public boolean isDeterministicMNsSporkActive() {
return isDeterministicMNsSporkActive(-1) || params.isDeterministicMasternodesEnabled();
}
public SimplifiedMasternodeList getListAtChainTip() {
return mnList;
}
public SimplifiedQuorumList getQuorumListAtTip() {
return quorumList;
}
@Override
public int getCurrentFormatVersion() {
return quorumList.size() != 0 ? LLMQ_FORMAT_VERSION : DMN_FORMAT_VERSION;
}
public void resetMNList() {
resetMNList(false, true);
}
public void resetMNList(boolean force) {
resetMNList(force, true);
}
public void resetMNList(boolean force, boolean requestFreshList) {
try {
if(force || getFormatVersion() < LLMQ_FORMAT_VERSION) {
log.info("resetting masternode list");
mnList = new SimplifiedMasternodeList(context.getParams());
quorumList = new SimplifiedQuorumList(context.getParams());
mnListsCache.clear();
quorumsCache.clear();
pendingBlocks.clear();
pendingBlocksMap.clear();
waitingForMNListDiff = false;
initChainTipSyncComplete = false;
unCache();
try {
if(bootStrapFilePath == null)
save();
} catch (FileNotFoundException x) {
//swallow, the file has no name
}
if(requestFreshList) {
if(bootStrapFilePath == null && bootStrapStream == null) {
requestAfterMNListReset();
} else {
waitingForMNListDiff = true;
isLoadingBootStrap = true;
loadBootstrapAndSync();
}
}
}
} catch (BlockStoreException x) {
throw new RuntimeException(x);
}
}
protected void requestAfterMNListReset() throws BlockStoreException {
if(blockChain == null) //not initialized
return;
int rewindBlockCount = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_LIST_PERIOD : MAX_CACHE_SIZE;
int height = blockChain.getBestChainHeight() - rewindBlockCount;
if (height < params.getDIP0008BlockHeight())
height = params.getDIP0008BlockHeight();
if (syncOptions == SyncOptions.SYNC_MINIMUM)
height = blockChain.getBestChainHeight() - SigningManager.SIGN_HEIGHT_OFFSET;
StoredBlock resetBlock = blockChain.getBlockStore().get(height);
if (resetBlock == null)
resetBlock = blockChain.getChainHead();
requestMNListDiff(resetBlock != null ? resetBlock : blockChain.getChainHead());
}
public SimplifiedMasternodeList getListForBlock(Sha256Hash blockHash) {
lock.lock();
try {
return mnListsCache.get(blockHash);
} finally {
lock.unlock();
}
}
public SimplifiedQuorumList getQuorumListForBlock(Sha256Hash blockHash) {
lock.lock();
try {
return quorumsCache.get(blockHash);
} finally {
lock.unlock();
}
}
public ArrayList<Masternode> getAllQuorumMembers(LLMQParameters.LLMQType llmqType, Sha256Hash blockHash)
{
lock.lock();
try {
LLMQParameters llmqParameters = params.getLlmqs().get(llmqType);
SimplifiedMasternodeList allMns = getListForBlock(blockHash);
if (allMns != null) {
Sha256Hash modifier = LLMQUtils.buildLLMQBlockHash(llmqType, blockHash);
return allMns.calculateQuorum(llmqParameters.getSize(), modifier);
}
return null;
} finally {
lock.unlock();
}
}
public boolean isSynced() {
return pendingBlocks.isEmpty();
}
void fillPendingBlocksList(Sha256Hash first, Sha256Hash last, int insertIndex) {
lock.lock();
try {
StoredBlock cursor = blockChain.getBlockStore().get(last);
while(cursor != null && !cursor.getHeader().getHash().equals(first)) {
if(!pendingBlocksMap.containsKey(cursor.getHeader().getHash())) {
pendingBlocks.add(insertIndex, cursor);
pendingBlocksMap.put(cursor.getHeader().getHash(), cursor);
}
cursor = cursor.getPrev(blockChain.getBlockStore());
}
} catch (BlockStoreException x) {
throw new RuntimeException(x);
} finally {
lock.unlock();
}
}
public void setRequiresLoadingFromFile(boolean requiresLoadingFromFile) {
this.requiresLoadingFromFile = requiresLoadingFromFile;
}
public void setLoadedFromFile(boolean loadedFromFile) {
this.loadedFromFile = loadedFromFile;
}
public boolean isLoadedFromFile() {
return loadedFromFile || !requiresLoadingFromFile;
}
@Override
public void onFirstSaveComplete() {
lock.lock();
try {
if(blockChain == null || blockChain.getBestChainHeight() >= getListAtChainTip().getHeight())
return;
StoredBlock block = blockChain.getChainHead();
long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60;
if (Utils.currentTimeSeconds() - block.getHeader().getTimeSeconds() < timePeriod) {
if (syncOptions == SyncOptions.SYNC_MINIMUM) {
try {
StoredBlock requestBlock = blockChain.getBlockStore().get(block.getHeight() - SigningManager.SIGN_HEIGHT_OFFSET);
if (getListAtChainTip().getHeight() > requestBlock.getHeight())
requestBlock = blockChain.getBlockStore().get((int) getListAtChainTip().getHeight() + 1);
if (requestBlock != null) {
block = requestBlock;
}
} catch (BlockStoreException x) {
//do nothing
}
}
requestMNListDiff(block);
}
} finally {
lock.unlock();
}
}
static String bootStrapFilePath = null;
static InputStream bootStrapStream = null;
boolean isLoadingBootStrap = false;
public static void setBootStrapFilePath(String bootStrapFilePath) {
SimplifiedMasternodeListManager.bootStrapFilePath = bootStrapFilePath;
}
public static void setBootStrapStream(InputStream bootStrapStream) {
SimplifiedMasternodeListManager.bootStrapStream = bootStrapStream;
}
protected void loadBootstrapAndSync() {
Preconditions.checkState(bootStrapFilePath != null || bootStrapStream != null);
Preconditions.checkState(mnList.size() == 0);
Preconditions.checkState(quorumList.size() == 0);
Preconditions.checkState(mnListsCache.size() == 0);
Preconditions.checkState(quorumsCache.size() == 0);
new Thread(new Runnable() {
@Override
public void run() {
log.info("loading mnlistdiff bootstrap file: " + bootStrapFilePath != null ? bootStrapFilePath : "input stream");
Context.propagate(context);
//load the file
InputStream stream = bootStrapStream;
try {
if(stream != null)
stream.reset();
stream = stream != null ? stream : new FileInputStream(bootStrapFilePath);
byte[] buffer = new byte[(int) stream.available()];
stream.read(buffer);
isLoadingBootStrap = true;
SimplifiedMasternodeListDiff mnlistdiff = new SimplifiedMasternodeListDiff(params, buffer);
processMasternodeListDiff(null, mnlistdiff, true);
log.info("finished loading mnlist bootstrap file");
} catch (VerificationException | FileNotFoundException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} catch (IOException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} catch (IllegalStateException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} catch (NullPointerException x) {
log.info("failed loading mnlist bootstrap file" + x.getMessage());
} finally {
isLoadingBootStrap = false;
try {
if (stream != null)
stream.close();
requestAfterMNListReset();
} catch (IOException x) {
} catch (BlockStoreException x) {
}
}
}
}).start();
}
public ReentrantLock getLock() {
return lock;
}
public Peer getDownloadPeer() {
return downloadPeer != null ? downloadPeer : peerGroup.getDownloadPeer();
}
}
| fix: removing logging each block
Signed-off-by: HashEngineering <[email protected]>
| core/src/main/java/org/bitcoinj/evolution/SimplifiedMasternodeListManager.java | fix: removing logging each block | <ide><path>ore/src/main/java/org/bitcoinj/evolution/SimplifiedMasternodeListManager.java
<ide> public NewBestBlockListener newBestBlockListener = new NewBestBlockListener() {
<ide> @Override
<ide> public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
<del> log.info("masternodeListManager.notifyNewBestBlock: {}/{}", block.getHeight(), block.getHeader().getHash());
<ide> boolean value = initChainTipSyncComplete || !context.masternodeSync.hasSyncFlag(MasternodeSync.SYNC_FLAGS.SYNC_HEADERS_MN_LIST_FIRST);
<ide> if(value && getListAtChainTip().getHeight() < blockChain.getBestChainHeight() && isDeterministicMNsSporkActive() && isLoadedFromFile()) {
<ide> long timePeriod = syncOptions == SyncOptions.SYNC_SNAPSHOT_PERIOD ? SNAPSHOT_TIME_PERIOD : MAX_CACHE_SIZE * 3 * 60; |
|
Java | mit | 9976cb1cddbed3367e115124360c094c715828c4 | 0 | erisazani/MissionInsectible | package com.inspector.missioninsectible;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
import org.andengine.ui.activity.BaseGameActivity;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainGameActivity extends BaseGameActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_game);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_game, menu);
return true;
}
@Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
Log.d("Tes","Tes");
return null;
}
@Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
}
}
| src/com/inspector/missioninsectible/MainGameActivity.java | package com.inspector.missioninsectible;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
import org.andengine.ui.activity.BaseGameActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainGameActivity extends BaseGameActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_game);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_game, menu);
return true;
}
@Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
}
}
| initial branch commit
| src/com/inspector/missioninsectible/MainGameActivity.java | initial branch commit | <ide><path>rc/com/inspector/missioninsectible/MainGameActivity.java
<ide>
<ide> import android.os.Bundle;
<ide> import android.app.Activity;
<add>import android.util.Log;
<ide> import android.view.Menu;
<ide>
<ide> public class MainGameActivity extends BaseGameActivity {
<ide> @Override
<ide> public EngineOptions onCreateEngineOptions() {
<ide> // TODO Auto-generated method stub
<add> Log.d("Tes","Tes");
<ide> return null;
<ide> }
<ide> |
|
Java | bsd-2-clause | fa98773a0eeed3e6468d0bb837d2b25b8dee273a | 0 | scifio/scifio | //
// LociUploader.java
//
/*
LOCI Plugins for ImageJ: a collection of ImageJ plugins including
the 4D Data Browser, OME Plugin and Bio-Formats Exporter.
Copyright (C) 2006-@year@ Melissa Linkert, Christopher Peterson,
Curtis Rueden, Philip Huettl and Francis Wong.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library 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 Library General Public License for more details.
You should have received a copy of the GNU Library 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
*/
package loci.plugins;
import java.awt.TextField;
import java.util.Vector;
import ij.*;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import ij.process.*;
import ij.io.FileInfo;
import loci.formats.*;
import loci.ome.upload.*;
/**
* ImageJ plugin for uploading images to an OME server.
*
* @author Melissa Linkert linket at wisc.edu
*/
public class LociUploader implements PlugIn {
// -- Fields --
private String server;
private String user;
private String pass;
// -- PlugIn API methods --
public synchronized void run(String arg) {
// check that we can safely execute the plugin
if (Util.checkVersion() && Util.checkLibraries(true, true, true, false)) {
promptForLogin();
uploadStack();
}
else {
}
}
// -- Helper methods --
/** Open a dialog box that prompts for a username, password, and server. */
private void promptForLogin() {
GenericDialog prompt = new GenericDialog("Login to OME");
prompt.addStringField("Server: ", Prefs.get("uploader.server", ""), 120);
prompt.addStringField("Username: ", Prefs.get("uploader.user", ""), 120);
prompt.addStringField("Password: ", "", 120);
((TextField) prompt.getStringFields().get(2)).setEchoChar('*');
prompt.showDialog();
server = prompt.getNextString();
user = prompt.getNextString();
pass = prompt.getNextString();
Prefs.set("uploader.server", server);
Prefs.set("uploader.user", user);
}
/** Log in to the OME server and upload the current image stack. */
private void uploadStack() {
try {
IJ.showStatus("Starting upload...");
OMEUploader ul = new OMEUploader(server, user, pass);
ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
IJ.error("No open images!");
IJ.showStatus("");
return;
}
ImageStack is = imp.getImageStack();
Vector pixels = new Vector();
FileInfo fi = imp.getOriginalFileInfo();
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
// if we opened this stack with the Bio-Formats importer, then the
// appropriate OME-XML is in fi.description
if (fi.description != null && fi.description.endsWith("</OME>")) {
store.createRoot(fi.description);
}
else {
store.createRoot();
int pixelType = FormatReader.UINT8;
switch (imp.getBitDepth()) {
case 16: pixelType = FormatReader.UINT16; break;
case 32: pixelType = FormatReader.FLOAT; break;
}
store.setPixels(
new Integer(imp.getWidth()),
new Integer(imp.getHeight()),
new Integer(imp.getNSlices()),
new Integer(imp.getNChannels()),
new Integer(imp.getNFrames()),
new Integer(pixelType),
new Boolean(!fi.intelByteOrder),
"XYCZT", // TODO : figure out a way to calculate the dimension order
null,
null);
store.setImage(fi.fileName, null, fi.info, null);
}
boolean little = !store.getBigEndian(null).booleanValue();
for (int i=0; i<is.getSize(); i++) {
IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize());
Object pix = is.getProcessor(i + 1).getPixels();
if (pix instanceof byte[]) {
pixels.add((byte[]) pix);
}
else if (pix instanceof short[]) {
short[] s = (short[]) pix;
byte[] b = new byte[s.length * 2];
for (int j=0; j<s.length; j++) {
byte[] a = DataTools.shortToBytes(s[j], little);
b[i*2] = a[0];
b[i*2 + 1] = a[1];
}
pixels.add(b);
}
else if (pix instanceof int[]) {
int[] j = (int[]) pix;
int channels = is.getProcessor(i+1) instanceof ColorProcessor ? 3 : 1;
byte[] b = new byte[j.length * channels];
for (int k=0; k<j.length; k++) {
byte[] a = DataTools.intToBytes(j[k], little);
b[k*3] = a[0];
b[k*3 + 1] = a[1];
b[k*3 + 2] = a[2];
}
pixels.add(b);
}
else if (pix instanceof float[]) {
float[] f = (float[]) pix;
byte[] b = new byte[f.length * 4];
for (int j=0; j<f.length; j++) {
int k = Float.floatToIntBits(f[j]);
byte[] a = DataTools.intToBytes(k, little);
b[i*4] = a[0];
b[i*4 + 1] = a[1];
b[i*4 + 2] = a[2];
b[i*4 + 3] = a[3];
}
pixels.add(b);
}
}
byte[][] planes = new byte[pixels.size()][];
for (int i=0; i<pixels.size(); i++) {
planes[i] = (byte[]) pixels.get(i);
}
IJ.showStatus("Sending data to server...");
ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true);
ul.logout();
IJ.showStatus("Upload finished.");
}
catch (UploadException e) {
IJ.error("Upload failed:\n" + e);
}
}
}
| loci/plugins/LociUploader.java | //
// LociUploader.java
//
/*
LOCI Plugins for ImageJ: a collection of ImageJ plugins including
the 4D Data Browser, OME Plugin and Bio-Formats Exporter.
Copyright (C) 2006-@year@ Melissa Linkert, Christopher Peterson,
Curtis Rueden, Philip Huettl and Francis Wong.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library 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 Library General Public License for more details.
You should have received a copy of the GNU Library 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
*/
package loci.plugins;
import java.awt.TextField;
import java.util.Vector;
import ij.*;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import ij.process.*;
import ij.io.FileInfo;
import loci.formats.*;
import loci.ome.upload.*;
/**
* ImageJ plugin for uploading images to an OME server.
*
* @author Melissa Linkert linket at wisc.edu
*/
public class LociUploader implements PlugIn {
// -- Fields --
private String server;
private String user;
private String pass;
// -- PlugIn API methods --
public synchronized void run(String arg) {
// check that we can safely execute the plugin
if (Util.checkVersion() && Util.checkLibraries(true, true, true, false)) {
promptForLogin();
uploadStack();
}
else {
}
}
// -- Helper methods --
/** Open a dialog box that prompts for a username, password, and server. */
private void promptForLogin() {
GenericDialog prompt = new GenericDialog("Login to OME");
prompt.addStringField("Server: ", Prefs.get("uploader.server", ""), 120);
prompt.addStringField("Username: ", Prefs.get("uploader.user", ""), 120);
prompt.addStringField("Password: ", "", 120);
((TextField) prompt.getStringFields().get(2)).setEchoChar('*');
prompt.showDialog();
server = prompt.getNextString();
user = prompt.getNextString();
pass = prompt.getNextString();
Prefs.set("uploader.server", server);
Prefs.set("uploader.user", user);
}
/** Log in to the OME server and upload the current image stack. */
private void uploadStack() {
try {
IJ.showStatus("Starting upload...");
OMEUploader ul = new OMEUploader(server, user, pass);
ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
IJ.error("No open images!");
IJ.showStatus("");
return;
}
ImageStack is = imp.getImageStack();
Vector pixels = new Vector();
FileInfo fi = imp.getOriginalFileInfo();
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
// if we opened this stack with the Bio-Formats importer, then the
// appropriate OME-XML is in fi.description
if (fi.description != null && fi.description.endsWith("</OME>")) {
store.createRoot(fi.description);
}
else {
store.createRoot();
int pixelType = FormatReader.UINT8;
switch (imp.getBitDepth()) {
case 16: pixelType = FormatReader.UINT16; break;
case 32: pixelType = FormatReader.FLOAT; break;
}
store.setPixels(
new Integer(imp.getWidth()),
new Integer(imp.getHeight()),
new Integer(imp.getNSlices()),
new Integer(imp.getNChannels()),
new Integer(imp.getNFrames()),
new Integer(pixelType),
new Boolean(!fi.intelByteOrder),
"XYCZT", // TODO : figure out a way to calculate the dimension order
null);
store.setImage(fi.fileName, null, fi.info, null);
}
boolean little = !store.getBigEndian(null).booleanValue();
for (int i=0; i<is.getSize(); i++) {
IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize());
Object pix = is.getProcessor(i + 1).getPixels();
if (pix instanceof byte[]) {
pixels.add((byte[]) pix);
}
else if (pix instanceof short[]) {
short[] s = (short[]) pix;
byte[] b = new byte[s.length * 2];
for (int j=0; j<s.length; j++) {
byte[] a = DataTools.shortToBytes(s[j], little);
b[i*2] = a[0];
b[i*2 + 1] = a[1];
}
pixels.add(b);
}
else if (pix instanceof int[]) {
int[] j = (int[]) pix;
int channels = is.getProcessor(i+1) instanceof ColorProcessor ? 3 : 1;
byte[] b = new byte[j.length * channels];
for (int k=0; k<j.length; k++) {
byte[] a = DataTools.intToBytes(j[k], little);
b[k*3] = a[0];
b[k*3 + 1] = a[1];
b[k*3 + 2] = a[2];
}
pixels.add(b);
}
else if (pix instanceof float[]) {
float[] f = (float[]) pix;
byte[] b = new byte[f.length * 4];
for (int j=0; j<f.length; j++) {
int k = Float.floatToIntBits(f[j]);
byte[] a = DataTools.intToBytes(k, little);
b[i*4] = a[0];
b[i*4 + 1] = a[1];
b[i*4 + 2] = a[2];
b[i*4 + 3] = a[3];
}
pixels.add(b);
}
}
byte[][] planes = new byte[pixels.size()][];
for (int i=0; i<pixels.size(); i++) {
planes[i] = (byte[]) pixels.get(i);
}
IJ.showStatus("Sending data to server...");
ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true);
ul.logout();
IJ.showStatus("Upload finished.");
}
catch (UploadException e) {
IJ.error("Upload failed:\n" + e);
}
}
}
| Switch to new setPixels signature.
| loci/plugins/LociUploader.java | Switch to new setPixels signature. | <ide><path>oci/plugins/LociUploader.java
<ide> new Integer(pixelType),
<ide> new Boolean(!fi.intelByteOrder),
<ide> "XYCZT", // TODO : figure out a way to calculate the dimension order
<add> null,
<ide> null);
<ide>
<ide> store.setImage(fi.fileName, null, fi.info, null); |
|
JavaScript | mit | 73b243261fbf85fd110a7b02fccfac2d3a74a918 | 0 | nteract/hydrogen,nteract/hydrogen | /* @flow */
import {
Emitter,
CompositeDisposable,
Disposable,
Point,
TextEditor
} from "atom";
import _ from "lodash";
import { autorun } from "mobx";
import React from "react";
import KernelPicker from "./kernel-picker";
import WSKernelPicker from "./ws-kernel-picker";
import ExistingKernelPicker from "./existing-kernel-picker";
import SignalListView from "./signal-list-view";
import * as codeManager from "./code-manager";
import Inspector from "./components/inspector";
import ResultView from "./components/result-view";
import StatusBar from "./components/status-bar";
import InspectorPane from "./panes/inspector";
import WatchesPane from "./panes/watches";
import OutputPane from "./panes/output-area";
import KernelMonitorPane from "./panes/kernel-monitor";
import { toggleInspector, toggleOutputMode } from "./commands";
import store from "./store";
import OutputStore from "./store/output";
import Config from "./config";
import kernelManager from "./kernel-manager";
import ZMQKernel from "./zmq-kernel";
import WSKernel from "./ws-kernel";
import Kernel from "./kernel";
import AutocompleteProvider from "./autocomplete-provider";
import HydrogenProvider from "./plugin-api/hydrogen-provider";
import {
log,
reactFactory,
isMultilanguageGrammar,
renderDevTools,
INSPECTOR_URI,
WATCHES_URI,
OUTPUT_AREA_URI,
KERNEL_MONITOR_URI,
hotReloadPackage,
openOrShowDock,
kernelSpecProvidesGrammar
} from "./utils";
import exportNotebook from "./export-notebook";
import { importNotebook, ipynbOpener } from "./import-notebook";
const Hydrogen = {
config: Config.schema,
activate() {
this.emitter = new Emitter();
let skipLanguageMappingsChange = false;
store.subscriptions.add(
atom.config.onDidChange(
"Hydrogen.languageMappings",
({ newValue, oldValue }) => {
if (skipLanguageMappingsChange) {
skipLanguageMappingsChange = false;
return;
}
if (store.runningKernels.length != 0) {
skipLanguageMappingsChange = true;
atom.config.set("Hydrogen.languageMappings", oldValue);
atom.notifications.addError("Hydrogen", {
description:
"`languageMappings` cannot be updated while kernels are running",
dismissable: false
});
}
}
)
);
store.subscriptions.add(
// enable/disable mobx-react-devtools logging
atom.config.onDidChange("Hydrogen.debug", ({ newValue }) =>
renderDevTools(newValue)
)
);
store.subscriptions.add(
atom.config.observe("Hydrogen.statusBarDisable", newValue => {
store.setConfigValue("Hydrogen.statusBarDisable", Boolean(newValue));
})
);
store.subscriptions.add(
atom.commands.add("atom-text-editor:not([mini])", {
"hydrogen:run": () => this.run(),
"hydrogen:run-all": () => this.runAll(),
"hydrogen:run-all-above": () => this.runAllAbove(),
"hydrogen:run-and-move-down": () => this.run(true),
"hydrogen:run-cell": () => this.runCell(),
"hydrogen:run-cell-and-move-down": () => this.runCell(true),
"hydrogen:toggle-watches": () => atom.workspace.toggle(WATCHES_URI),
"hydrogen:toggle-output-area": () => toggleOutputMode(),
"hydrogen:toggle-kernel-monitor": async () => {
const lastItem = atom.workspace.getActivePaneItem();
const lastPane = atom.workspace.paneForItem(lastItem);
await atom.workspace.toggle(KERNEL_MONITOR_URI);
lastPane.activate();
},
"hydrogen:start-local-kernel": () => this.startZMQKernel(),
"hydrogen:connect-to-remote-kernel": () => this.connectToWSKernel(),
"hydrogen:connect-to-existing-kernel": () =>
this.connectToExistingKernel(),
"hydrogen:add-watch": () => {
if (store.kernel) {
store.kernel.watchesStore.addWatchFromEditor(store.editor);
openOrShowDock(WATCHES_URI);
}
},
"hydrogen:remove-watch": () => {
if (store.kernel) {
store.kernel.watchesStore.removeWatch();
openOrShowDock(WATCHES_URI);
}
},
"hydrogen:update-kernels": () => kernelManager.updateKernelSpecs(),
"hydrogen:toggle-inspector": () => toggleInspector(store),
"hydrogen:interrupt-kernel": () =>
this.handleKernelCommand({ command: "interrupt-kernel" }),
"hydrogen:restart-kernel": () =>
this.handleKernelCommand({ command: "restart-kernel" }),
"hydrogen:shutdown-kernel": () =>
this.handleKernelCommand({ command: "shutdown-kernel" }),
"hydrogen:clear-result": () => this.clearResult(),
"hydrogen:export-notebook": () => exportNotebook(),
"hydrogen:fold-current-cell": () => this.foldCurrentCell(),
"hydrogen:fold-all-but-current-cell": () => this.foldAllButCurrentCell()
})
);
store.subscriptions.add(
atom.commands.add("atom-workspace", {
"hydrogen:clear-results": () => {
const { kernel, markers } = store;
if (markers) markers.clear();
if (!kernel) return;
kernel.outputStore.clear();
},
"hydrogen:import-notebook": importNotebook
})
);
if (atom.inDevMode()) {
store.subscriptions.add(
atom.commands.add("atom-workspace", {
"hydrogen:hot-reload-package": () => hotReloadPackage()
})
);
}
store.subscriptions.add(
atom.workspace.observeActiveTextEditor(editor => {
store.updateEditor(editor);
})
);
store.subscriptions.add(
atom.workspace.observeTextEditors(editor => {
const editorSubscriptions = new CompositeDisposable();
editorSubscriptions.add(
editor.onDidChangeGrammar(() => {
store.setGrammar(editor);
})
);
if (isMultilanguageGrammar(editor.getGrammar())) {
editorSubscriptions.add(
editor.onDidChangeCursorPosition(
_.debounce(() => {
store.setGrammar(editor);
}, 75)
)
);
}
editorSubscriptions.add(
editor.onDidDestroy(() => {
editorSubscriptions.dispose();
})
);
editorSubscriptions.add(
editor.onDidChangeTitle(newTitle => store.forceEditorUpdate())
);
store.subscriptions.add(editorSubscriptions);
})
);
this.hydrogenProvider = null;
store.subscriptions.add(
atom.workspace.addOpener(uri => {
switch (uri) {
case INSPECTOR_URI:
return new InspectorPane(store);
case WATCHES_URI:
return new WatchesPane(store);
case OUTPUT_AREA_URI:
return new OutputPane(store);
case KERNEL_MONITOR_URI:
return new KernelMonitorPane(store);
}
})
);
store.subscriptions.add(atom.workspace.addOpener(ipynbOpener));
store.subscriptions.add(
// Destroy any Panes when the package is deactivated.
new Disposable(() => {
atom.workspace.getPaneItems().forEach(item => {
if (
item instanceof InspectorPane ||
item instanceof WatchesPane ||
item instanceof OutputPane ||
item instanceof KernelMonitorPane
) {
item.destroy();
}
});
})
);
renderDevTools(atom.config.get("Hydrogen.debug") === true);
autorun(() => {
this.emitter.emit("did-change-kernel", store.kernel);
});
},
deactivate() {
store.dispose();
},
provideHydrogen() {
if (!this.hydrogenProvider) {
this.hydrogenProvider = new HydrogenProvider(this);
}
return this.hydrogenProvider;
},
consumeStatusBar(statusBar: atom$StatusBar) {
const statusBarElement = document.createElement("div");
statusBarElement.classList.add("inline-block", "hydrogen");
statusBar.addLeftTile({
item: statusBarElement,
priority: 100
});
const onClick = this.showKernelCommands.bind(this);
reactFactory(
<StatusBar store={store} onClick={onClick} />,
statusBarElement
);
// We should return a disposable here but Atom fails while calling .destroy()
// return new Disposable(statusBarTile.destroy);
},
provide() {
if (atom.config.get("Hydrogen.autocomplete") === true) {
return AutocompleteProvider();
}
return null;
},
showKernelCommands() {
if (!this.signalListView) {
this.signalListView = new SignalListView();
this.signalListView.onConfirmed = (kernelCommand: { command: string }) =>
this.handleKernelCommand(kernelCommand);
}
this.signalListView.toggle();
},
connectToExistingKernel() {
if (!this.existingKernelPicker) {
this.existingKernelPicker = new ExistingKernelPicker();
}
this.existingKernelPicker.toggle();
},
handleKernelCommand({
command,
payload
}: {
command: string,
payload: ?Kernelspec
}) {
log("handleKernelCommand:", arguments);
const { kernel, grammar, markers } = store;
if (!grammar) {
atom.notifications.addError("Undefined grammar");
return;
}
if (!kernel) {
const message = `No running kernel for grammar \`${grammar.name}\` found`;
atom.notifications.addError(message);
return;
}
if (command === "interrupt-kernel") {
kernel.interrupt();
} else if (command === "restart-kernel") {
kernel.restart();
} else if (command === "shutdown-kernel") {
if (markers) markers.clear();
// Note that destroy alone does not shut down a WSKernel
kernel.shutdown();
kernel.destroy();
} else if (
command === "rename-kernel" &&
kernel.transport instanceof WSKernel
) {
kernel.transport.promptRename();
} else if (command === "disconnect-kernel") {
if (markers) markers.clear();
kernel.destroy();
}
},
createResultBubble(
editor: atom$TextEditor,
codeBlock: { code: string, row: number, cellType: HydrogenCellType }
) {
const { grammar, filePath, kernel } = store;
if (!filePath || !grammar) {
return atom.notifications.addError(
"The language grammar must be set in order to start a kernel. The easiest way to do this is to save the file."
);
}
if (kernel) {
this._createResultBubble(editor, kernel, codeBlock);
return;
}
kernelManager.startKernelFor(
grammar,
editor,
filePath,
(kernel: ZMQKernel) => {
this._createResultBubble(editor, kernel, codeBlock);
}
);
},
_createResultBubble(
editor: atom$TextEditor,
kernel: Kernel,
codeBlock: { code: string, row: number, cellType: HydrogenCellType }
) {
if (atom.workspace.getActivePaneItem() instanceof WatchesPane) {
kernel.watchesStore.run();
return;
}
const globalOutputStore =
atom.config.get("Hydrogen.outputAreaDefault") ||
atom.workspace.getPaneItems().find(item => item instanceof OutputPane)
? kernel.outputStore
: null;
if (globalOutputStore) openOrShowDock(OUTPUT_AREA_URI);
const { markers } = store;
if (!markers) return;
const { outputStore } = new ResultView(
markers,
kernel,
editor,
codeBlock.row,
!globalOutputStore || codeBlock.cellType == "markdown"
);
if (codeBlock.code.search(/[\S]/) != -1) {
switch (codeBlock.cellType) {
case "markdown":
outputStore.appendOutput({
output_type: "display_data",
data: {
"text/markdown": codeBlock.code
},
metadata: {}
});
outputStore.appendOutput({ data: "ok", stream: "status" });
break;
case "codecell":
kernel.execute(codeBlock.code, result => {
outputStore.appendOutput(result);
if (globalOutputStore) globalOutputStore.appendOutput(result);
});
break;
}
} else {
outputStore.appendOutput({ data: "ok", stream: "status" });
}
},
clearResult() {
const { editor, kernel, markers } = store;
if (!editor || !markers) return;
const [startRow, endRow] = editor.getLastSelection().getBufferRowRange();
for (let row = startRow; row <= endRow; row++) {
markers.clearOnRow(row);
}
},
run(moveDown: boolean = false) {
const editor = store.editor;
if (!editor) return;
// https://github.com/nteract/hydrogen/issues/1452
atom.commands.dispatch(editor.element, "autocomplete-plus:cancel");
const codeBlock = codeManager.findCodeBlock(editor);
if (!codeBlock) {
return;
}
const { row } = codeBlock;
let { code } = codeBlock;
const cellType = codeManager.getMetadataForRow(editor, new Point(row, 0));
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
if (moveDown === true) {
codeManager.moveDown(editor, row);
}
this.createResultBubble(editor, { code, row, cellType });
}
},
runAll(breakpoints: ?Array<atom$Point>) {
const { editor, kernel, grammar, filePath } = store;
if (!editor || !grammar || !filePath) return;
if (isMultilanguageGrammar(editor.getGrammar())) {
atom.notifications.addError(
'"Run All" is not supported for this file type!'
);
return;
}
if (editor && kernel) {
this._runAll(editor, kernel, breakpoints);
return;
}
kernelManager.startKernelFor(
grammar,
editor,
filePath,
(kernel: ZMQKernel) => {
this._runAll(editor, kernel, breakpoints);
}
);
},
_runAll(
editor: atom$TextEditor,
kernel: Kernel,
breakpoints?: Array<atom$Point>
) {
let cells = codeManager.getCells(editor, breakpoints);
for (const cell of cells) {
const { start, end } = cell;
let code = codeManager.getTextInRange(editor, start, end);
const row = codeManager.escapeBlankRows(
editor,
start.row,
end.row == editor.getLastBufferRow() ? end.row : end.row - 1
);
const cellType = codeManager.getMetadataForRow(editor, start);
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
this._createResultBubble(editor, kernel, { code, row, cellType });
}
}
},
runAllAbove() {
const { editor, kernel, grammar, filePath } = store;
if (!editor || !grammar || !filePath) return;
if (isMultilanguageGrammar(editor.getGrammar())) {
atom.notifications.addError(
'"Run All Above" is not supported for this file type!'
);
return;
}
if (editor && kernel) {
this._runAllAbove(editor, kernel);
return;
}
kernelManager.startKernelFor(
grammar,
editor,
filePath,
(kernel: ZMQKernel) => {
this._runAllAbove(editor, kernel);
}
);
},
_runAllAbove(editor: atom$TextEditor, kernel: Kernel) {
const cursor = editor.getCursorBufferPosition();
cursor.column = editor.getBuffer().lineLengthForRow(cursor.row);
const breakpoints = codeManager.getBreakpoints(editor);
breakpoints.push(cursor);
const cells = codeManager.getCells(editor, breakpoints);
for (const cell of cells) {
const { start, end } = cell;
let code = codeManager.getTextInRange(editor, start, end);
const row = codeManager.escapeBlankRows(
editor,
start.row,
end.row == editor.getLastBufferRow() ? end.row : end.row - 1
);
const cellType = codeManager.getMetadataForRow(editor, start);
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
this.createResultBubble(editor, { code, row, cellType });
}
if (cell.containsPoint(cursor)) {
break;
}
}
},
runCell(moveDown: boolean = false) {
const editor = store.editor;
if (!editor) return;
// https://github.com/nteract/hydrogen/issues/1452
atom.commands.dispatch(editor.element, "autocomplete-plus:cancel");
const { start, end } = codeManager.getCurrentCell(editor);
let code = codeManager.getTextInRange(editor, start, end);
const row = codeManager.escapeBlankRows(
editor,
start.row,
end.row == editor.getLastBufferRow() ? end.row : end.row - 1
);
const cellType = codeManager.getMetadataForRow(editor, start);
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
if (moveDown === true) {
codeManager.moveDown(editor, row);
}
this.createResultBubble(editor, { code, row, cellType });
}
},
foldCurrentCell() {
const editor = store.editor;
if (!editor) return;
codeManager.foldCurrentCell(editor);
},
foldAllButCurrentCell() {
const editor = store.editor;
if (!editor) return;
codeManager.foldAllButCurrentCell(editor);
},
startZMQKernel() {
kernelManager
.getAllKernelSpecsForGrammar(store.grammar)
.then(kernelSpecs => {
if (this.kernelPicker) {
this.kernelPicker.kernelSpecs = kernelSpecs;
} else {
this.kernelPicker = new KernelPicker(kernelSpecs);
this.kernelPicker.onConfirmed = (kernelSpec: Kernelspec) => {
const { editor, grammar, filePath, markers } = store;
if (!editor || !grammar || !filePath || !markers) return;
markers.clear();
kernelManager.startKernel(kernelSpec, grammar, editor, filePath);
};
}
this.kernelPicker.toggle();
});
},
connectToWSKernel() {
if (!this.wsKernelPicker) {
this.wsKernelPicker = new WSKernelPicker((transport: WSKernel) => {
const kernel = new Kernel(transport);
const { editor, grammar, filePath, markers } = store;
if (!editor || !grammar || !filePath || !markers) return;
markers.clear();
if (kernel.transport instanceof ZMQKernel) kernel.destroy();
store.newKernel(kernel, filePath, editor, grammar);
});
}
this.wsKernelPicker.toggle((kernelSpec: Kernelspec) =>
kernelSpecProvidesGrammar(kernelSpec, store.grammar)
);
}
};
export default Hydrogen;
| lib/main.js | /* @flow */
import {
Emitter,
CompositeDisposable,
Disposable,
Point,
TextEditor
} from "atom";
import _ from "lodash";
import { autorun } from "mobx";
import React from "react";
import KernelPicker from "./kernel-picker";
import WSKernelPicker from "./ws-kernel-picker";
import ExistingKernelPicker from "./existing-kernel-picker";
import SignalListView from "./signal-list-view";
import * as codeManager from "./code-manager";
import Inspector from "./components/inspector";
import ResultView from "./components/result-view";
import StatusBar from "./components/status-bar";
import InspectorPane from "./panes/inspector";
import WatchesPane from "./panes/watches";
import OutputPane from "./panes/output-area";
import KernelMonitorPane from "./panes/kernel-monitor";
import { toggleInspector, toggleOutputMode } from "./commands";
import store from "./store";
import OutputStore from "./store/output";
import Config from "./config";
import kernelManager from "./kernel-manager";
import ZMQKernel from "./zmq-kernel";
import WSKernel from "./ws-kernel";
import Kernel from "./kernel";
import AutocompleteProvider from "./autocomplete-provider";
import HydrogenProvider from "./plugin-api/hydrogen-provider";
import {
log,
reactFactory,
isMultilanguageGrammar,
renderDevTools,
INSPECTOR_URI,
WATCHES_URI,
OUTPUT_AREA_URI,
KERNEL_MONITOR_URI,
hotReloadPackage,
openOrShowDock,
kernelSpecProvidesGrammar
} from "./utils";
import exportNotebook from "./export-notebook";
import { importNotebook, ipynbOpener } from "./import-notebook";
const Hydrogen = {
config: Config.schema,
activate() {
this.emitter = new Emitter();
let skipLanguageMappingsChange = false;
store.subscriptions.add(
atom.config.onDidChange(
"Hydrogen.languageMappings",
({ newValue, oldValue }) => {
if (skipLanguageMappingsChange) {
skipLanguageMappingsChange = false;
return;
}
if (store.runningKernels.length != 0) {
skipLanguageMappingsChange = true;
atom.config.set("Hydrogen.languageMappings", oldValue);
atom.notifications.addError("Hydrogen", {
description:
"`languageMappings` cannot be updated while kernels are running",
dismissable: false
});
}
}
)
);
store.subscriptions.add(
// enable/disable mobx-react-devtools logging
atom.config.onDidChange("Hydrogen.debug", ({ newValue }) =>
renderDevTools(newValue)
)
);
store.subscriptions.add(
atom.config.observe("Hydrogen.statusBarDisable", newValue => {
store.setConfigValue("Hydrogen.statusBarDisable", Boolean(newValue));
})
);
store.subscriptions.add(
atom.commands.add("atom-text-editor:not([mini])", {
"hydrogen:run": () => this.run(),
"hydrogen:run-all": () => this.runAll(),
"hydrogen:run-all-above": () => this.runAllAbove(),
"hydrogen:run-and-move-down": () => this.run(true),
"hydrogen:run-cell": () => this.runCell(),
"hydrogen:run-cell-and-move-down": () => this.runCell(true),
"hydrogen:toggle-watches": () => atom.workspace.toggle(WATCHES_URI),
"hydrogen:toggle-output-area": () => toggleOutputMode(),
"hydrogen:toggle-kernel-monitor": () =>
atom.workspace.toggle(KERNEL_MONITOR_URI),
"hydrogen:start-local-kernel": () => this.startZMQKernel(),
"hydrogen:connect-to-remote-kernel": () => this.connectToWSKernel(),
"hydrogen:connect-to-existing-kernel": () =>
this.connectToExistingKernel(),
"hydrogen:add-watch": () => {
if (store.kernel) {
store.kernel.watchesStore.addWatchFromEditor(store.editor);
openOrShowDock(WATCHES_URI);
}
},
"hydrogen:remove-watch": () => {
if (store.kernel) {
store.kernel.watchesStore.removeWatch();
openOrShowDock(WATCHES_URI);
}
},
"hydrogen:update-kernels": () => kernelManager.updateKernelSpecs(),
"hydrogen:toggle-inspector": () => toggleInspector(store),
"hydrogen:interrupt-kernel": () =>
this.handleKernelCommand({ command: "interrupt-kernel" }),
"hydrogen:restart-kernel": () =>
this.handleKernelCommand({ command: "restart-kernel" }),
"hydrogen:shutdown-kernel": () =>
this.handleKernelCommand({ command: "shutdown-kernel" }),
"hydrogen:clear-result": () => this.clearResult(),
"hydrogen:export-notebook": () => exportNotebook(),
"hydrogen:fold-current-cell": () => this.foldCurrentCell(),
"hydrogen:fold-all-but-current-cell": () => this.foldAllButCurrentCell()
})
);
store.subscriptions.add(
atom.commands.add("atom-workspace", {
"hydrogen:clear-results": () => {
const { kernel, markers } = store;
if (markers) markers.clear();
if (!kernel) return;
kernel.outputStore.clear();
},
"hydrogen:import-notebook": importNotebook
})
);
if (atom.inDevMode()) {
store.subscriptions.add(
atom.commands.add("atom-workspace", {
"hydrogen:hot-reload-package": () => hotReloadPackage()
})
);
}
store.subscriptions.add(
atom.workspace.observeActiveTextEditor(editor => {
store.updateEditor(editor);
})
);
store.subscriptions.add(
atom.workspace.observeTextEditors(editor => {
const editorSubscriptions = new CompositeDisposable();
editorSubscriptions.add(
editor.onDidChangeGrammar(() => {
store.setGrammar(editor);
})
);
if (isMultilanguageGrammar(editor.getGrammar())) {
editorSubscriptions.add(
editor.onDidChangeCursorPosition(
_.debounce(() => {
store.setGrammar(editor);
}, 75)
)
);
}
editorSubscriptions.add(
editor.onDidDestroy(() => {
editorSubscriptions.dispose();
})
);
editorSubscriptions.add(
editor.onDidChangeTitle(newTitle => store.forceEditorUpdate())
);
store.subscriptions.add(editorSubscriptions);
})
);
this.hydrogenProvider = null;
store.subscriptions.add(
atom.workspace.addOpener(uri => {
switch (uri) {
case INSPECTOR_URI:
return new InspectorPane(store);
case WATCHES_URI:
return new WatchesPane(store);
case OUTPUT_AREA_URI:
return new OutputPane(store);
case KERNEL_MONITOR_URI:
return new KernelMonitorPane(store);
}
})
);
store.subscriptions.add(atom.workspace.addOpener(ipynbOpener));
store.subscriptions.add(
// Destroy any Panes when the package is deactivated.
new Disposable(() => {
atom.workspace.getPaneItems().forEach(item => {
if (
item instanceof InspectorPane ||
item instanceof WatchesPane ||
item instanceof OutputPane ||
item instanceof KernelMonitorPane
) {
item.destroy();
}
});
})
);
renderDevTools(atom.config.get("Hydrogen.debug") === true);
autorun(() => {
this.emitter.emit("did-change-kernel", store.kernel);
});
},
deactivate() {
store.dispose();
},
provideHydrogen() {
if (!this.hydrogenProvider) {
this.hydrogenProvider = new HydrogenProvider(this);
}
return this.hydrogenProvider;
},
consumeStatusBar(statusBar: atom$StatusBar) {
const statusBarElement = document.createElement("div");
statusBarElement.classList.add("inline-block", "hydrogen");
statusBar.addLeftTile({
item: statusBarElement,
priority: 100
});
const onClick = this.showKernelCommands.bind(this);
reactFactory(
<StatusBar store={store} onClick={onClick} />,
statusBarElement
);
// We should return a disposable here but Atom fails while calling .destroy()
// return new Disposable(statusBarTile.destroy);
},
provide() {
if (atom.config.get("Hydrogen.autocomplete") === true) {
return AutocompleteProvider();
}
return null;
},
showKernelCommands() {
if (!this.signalListView) {
this.signalListView = new SignalListView();
this.signalListView.onConfirmed = (kernelCommand: { command: string }) =>
this.handleKernelCommand(kernelCommand);
}
this.signalListView.toggle();
},
connectToExistingKernel() {
if (!this.existingKernelPicker) {
this.existingKernelPicker = new ExistingKernelPicker();
}
this.existingKernelPicker.toggle();
},
handleKernelCommand({
command,
payload
}: {
command: string,
payload: ?Kernelspec
}) {
log("handleKernelCommand:", arguments);
const { kernel, grammar, markers } = store;
if (!grammar) {
atom.notifications.addError("Undefined grammar");
return;
}
if (!kernel) {
const message = `No running kernel for grammar \`${grammar.name}\` found`;
atom.notifications.addError(message);
return;
}
if (command === "interrupt-kernel") {
kernel.interrupt();
} else if (command === "restart-kernel") {
kernel.restart();
} else if (command === "shutdown-kernel") {
if (markers) markers.clear();
// Note that destroy alone does not shut down a WSKernel
kernel.shutdown();
kernel.destroy();
} else if (
command === "rename-kernel" &&
kernel.transport instanceof WSKernel
) {
kernel.transport.promptRename();
} else if (command === "disconnect-kernel") {
if (markers) markers.clear();
kernel.destroy();
}
},
createResultBubble(
editor: atom$TextEditor,
codeBlock: { code: string, row: number, cellType: HydrogenCellType }
) {
const { grammar, filePath, kernel } = store;
if (!filePath || !grammar) {
return atom.notifications.addError(
"The language grammar must be set in order to start a kernel. The easiest way to do this is to save the file."
);
}
if (kernel) {
this._createResultBubble(editor, kernel, codeBlock);
return;
}
kernelManager.startKernelFor(
grammar,
editor,
filePath,
(kernel: ZMQKernel) => {
this._createResultBubble(editor, kernel, codeBlock);
}
);
},
_createResultBubble(
editor: atom$TextEditor,
kernel: Kernel,
codeBlock: { code: string, row: number, cellType: HydrogenCellType }
) {
if (atom.workspace.getActivePaneItem() instanceof WatchesPane) {
kernel.watchesStore.run();
return;
}
const globalOutputStore =
atom.config.get("Hydrogen.outputAreaDefault") ||
atom.workspace.getPaneItems().find(item => item instanceof OutputPane)
? kernel.outputStore
: null;
if (globalOutputStore) openOrShowDock(OUTPUT_AREA_URI);
const { markers } = store;
if (!markers) return;
const { outputStore } = new ResultView(
markers,
kernel,
editor,
codeBlock.row,
!globalOutputStore || codeBlock.cellType == "markdown"
);
if (codeBlock.code.search(/[\S]/) != -1) {
switch (codeBlock.cellType) {
case "markdown":
outputStore.appendOutput({
output_type: "display_data",
data: {
"text/markdown": codeBlock.code
},
metadata: {}
});
outputStore.appendOutput({ data: "ok", stream: "status" });
break;
case "codecell":
kernel.execute(codeBlock.code, result => {
outputStore.appendOutput(result);
if (globalOutputStore) globalOutputStore.appendOutput(result);
});
break;
}
} else {
outputStore.appendOutput({ data: "ok", stream: "status" });
}
},
clearResult() {
const { editor, kernel, markers } = store;
if (!editor || !markers) return;
const [startRow, endRow] = editor.getLastSelection().getBufferRowRange();
for (let row = startRow; row <= endRow; row++) {
markers.clearOnRow(row);
}
},
run(moveDown: boolean = false) {
const editor = store.editor;
if (!editor) return;
// https://github.com/nteract/hydrogen/issues/1452
atom.commands.dispatch(editor.element, "autocomplete-plus:cancel");
const codeBlock = codeManager.findCodeBlock(editor);
if (!codeBlock) {
return;
}
const { row } = codeBlock;
let { code } = codeBlock;
const cellType = codeManager.getMetadataForRow(editor, new Point(row, 0));
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
if (moveDown === true) {
codeManager.moveDown(editor, row);
}
this.createResultBubble(editor, { code, row, cellType });
}
},
runAll(breakpoints: ?Array<atom$Point>) {
const { editor, kernel, grammar, filePath } = store;
if (!editor || !grammar || !filePath) return;
if (isMultilanguageGrammar(editor.getGrammar())) {
atom.notifications.addError(
'"Run All" is not supported for this file type!'
);
return;
}
if (editor && kernel) {
this._runAll(editor, kernel, breakpoints);
return;
}
kernelManager.startKernelFor(
grammar,
editor,
filePath,
(kernel: ZMQKernel) => {
this._runAll(editor, kernel, breakpoints);
}
);
},
_runAll(
editor: atom$TextEditor,
kernel: Kernel,
breakpoints?: Array<atom$Point>
) {
let cells = codeManager.getCells(editor, breakpoints);
for (const cell of cells) {
const { start, end } = cell;
let code = codeManager.getTextInRange(editor, start, end);
const row = codeManager.escapeBlankRows(
editor,
start.row,
end.row == editor.getLastBufferRow() ? end.row : end.row - 1
);
const cellType = codeManager.getMetadataForRow(editor, start);
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
this._createResultBubble(editor, kernel, { code, row, cellType });
}
}
},
runAllAbove() {
const { editor, kernel, grammar, filePath } = store;
if (!editor || !grammar || !filePath) return;
if (isMultilanguageGrammar(editor.getGrammar())) {
atom.notifications.addError(
'"Run All Above" is not supported for this file type!'
);
return;
}
if (editor && kernel) {
this._runAllAbove(editor, kernel);
return;
}
kernelManager.startKernelFor(
grammar,
editor,
filePath,
(kernel: ZMQKernel) => {
this._runAllAbove(editor, kernel);
}
);
},
_runAllAbove(editor: atom$TextEditor, kernel: Kernel) {
const cursor = editor.getCursorBufferPosition();
cursor.column = editor.getBuffer().lineLengthForRow(cursor.row);
const breakpoints = codeManager.getBreakpoints(editor);
breakpoints.push(cursor);
const cells = codeManager.getCells(editor, breakpoints);
for (const cell of cells) {
const { start, end } = cell;
let code = codeManager.getTextInRange(editor, start, end);
const row = codeManager.escapeBlankRows(
editor,
start.row,
end.row == editor.getLastBufferRow() ? end.row : end.row - 1
);
const cellType = codeManager.getMetadataForRow(editor, start);
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
this.createResultBubble(editor, { code, row, cellType });
}
if (cell.containsPoint(cursor)) {
break;
}
}
},
runCell(moveDown: boolean = false) {
const editor = store.editor;
if (!editor) return;
// https://github.com/nteract/hydrogen/issues/1452
atom.commands.dispatch(editor.element, "autocomplete-plus:cancel");
const { start, end } = codeManager.getCurrentCell(editor);
let code = codeManager.getTextInRange(editor, start, end);
const row = codeManager.escapeBlankRows(
editor,
start.row,
end.row == editor.getLastBufferRow() ? end.row : end.row - 1
);
const cellType = codeManager.getMetadataForRow(editor, start);
if (code || code === "") {
if (cellType === "markdown") {
code = codeManager.removeCommentsMarkdownCell(editor, code);
}
if (moveDown === true) {
codeManager.moveDown(editor, row);
}
this.createResultBubble(editor, { code, row, cellType });
}
},
foldCurrentCell() {
const editor = store.editor;
if (!editor) return;
codeManager.foldCurrentCell(editor);
},
foldAllButCurrentCell() {
const editor = store.editor;
if (!editor) return;
codeManager.foldAllButCurrentCell(editor);
},
startZMQKernel() {
kernelManager
.getAllKernelSpecsForGrammar(store.grammar)
.then(kernelSpecs => {
if (this.kernelPicker) {
this.kernelPicker.kernelSpecs = kernelSpecs;
} else {
this.kernelPicker = new KernelPicker(kernelSpecs);
this.kernelPicker.onConfirmed = (kernelSpec: Kernelspec) => {
const { editor, grammar, filePath, markers } = store;
if (!editor || !grammar || !filePath || !markers) return;
markers.clear();
kernelManager.startKernel(kernelSpec, grammar, editor, filePath);
};
}
this.kernelPicker.toggle();
});
},
connectToWSKernel() {
if (!this.wsKernelPicker) {
this.wsKernelPicker = new WSKernelPicker((transport: WSKernel) => {
const kernel = new Kernel(transport);
const { editor, grammar, filePath, markers } = store;
if (!editor || !grammar || !filePath || !markers) return;
markers.clear();
if (kernel.transport instanceof ZMQKernel) kernel.destroy();
store.newKernel(kernel, filePath, editor, grammar);
});
}
this.wsKernelPicker.toggle((kernelSpec: Kernelspec) =>
kernelSpecProvidesGrammar(kernelSpec, store.grammar)
);
}
};
export default Hydrogen;
| Don't focus on kernel monitor after toggling
| lib/main.js | Don't focus on kernel monitor after toggling | <ide><path>ib/main.js
<ide> "hydrogen:run-cell-and-move-down": () => this.runCell(true),
<ide> "hydrogen:toggle-watches": () => atom.workspace.toggle(WATCHES_URI),
<ide> "hydrogen:toggle-output-area": () => toggleOutputMode(),
<del> "hydrogen:toggle-kernel-monitor": () =>
<del> atom.workspace.toggle(KERNEL_MONITOR_URI),
<add> "hydrogen:toggle-kernel-monitor": async () => {
<add> const lastItem = atom.workspace.getActivePaneItem();
<add> const lastPane = atom.workspace.paneForItem(lastItem);
<add> await atom.workspace.toggle(KERNEL_MONITOR_URI);
<add> lastPane.activate();
<add> },
<ide> "hydrogen:start-local-kernel": () => this.startZMQKernel(),
<ide> "hydrogen:connect-to-remote-kernel": () => this.connectToWSKernel(),
<ide> "hydrogen:connect-to-existing-kernel": () => |
|
Java | apache-2.0 | error: pathspec 'restful/FileUploadForMobile.java' did not match any file(s) known to git
| 980eedc4057eef3be10a784d68634ecf932b2a27 | 1 | icejim/webapp | @POST
@Path("File/UploadOld")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFileOld(
@QueryParam("user") String userName,
@QueryParam("stamp") String stamp,
@QueryParam("sig") String sig,
@Context HttpServletRequest request,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("appointment") String appointment,
@FormDataParam("filename") String filename,
@FormDataParam("filesize") String filesize,
@FormDataParam("filedescription") String filedescription) {
Utils.logRequest(request);
LOGGER.info("authing fileUpload("+userName+", "+stamp+", "+sig+")");
RestUtils.authenticationByUserName(request, userName, stamp, sig);
String result = "success";
try {
if(StringUtils.isNotBlank(appointment) && StringUtils.isNotBlank(fileDetail.getFileName())){
String folderName = Utils.getChcProperties().getProperty("cloud_root") + "/" + appointment;
final String fileName = URLDecoder.decode(filename,"UTF-8");
List<File> folders = HibernateDao.findByProperty(File.class, "marketAppointmentID", appointment);
File folder;
Set<File> children;
if(folders.size() > 0){
folder = folders.get(0);
children = folder.getFiles();
}else{
folder = new File();
folder.setMarketAppointmentID(appointment);
folder.setFileSystem(Constants.FILESYSTEM_DIRECTORY);
folder.setFolderName(folderName);
children = new HashSet<File>();
folder.setFiles(children);
}
File newfile = new File();
newfile.setFileName(fileName);
newfile.setDesc(URLDecoder.decode(filedescription,"UTF-8"));
newfile.setSize(Long.parseLong(filesize));
newfile.setFileSystem(Constants.FILESYSTEM_FILE);
newfile.setFolderName(folderName);
newfile.setInputDate(new Date());
newfile.setCategory(Constants.CLOUD_IMAGE_FILE_CATEGORY_3);
HibernateDao.saveOrUpdate(newfile);
children.add(newfile);
HibernateDao.saveOrUpdate(folder);
String extension ="";
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i);
}
final String fileId = newfile.getId();
final String uploadedFileLocation = Utils.padFileName(folderName, fileId+extension);
int read = 0;
byte[] bytes = new byte[1024];
java.io.File target = new java.io.File(uploadedFileLocation);
if(!target.getParentFile().exists()){
target.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(target);
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
LOGGER.info("File "+fileName+" being uploaded to "+uploadedFileLocation);
Thread aliyunThread = new Thread(new Runnable() {
@Override
public void run() {
try {
LOGGER.info("convertThread["+uploadedFileLocation+"] START ...");
java.io.File uploadedFile = new java.io.File(uploadedFileLocation);
OSSUtility.putFile(OSSUtility.BUCKET_PUB, Constants.MARKET_FILE + fileId+"/"+ fileName, uploadedFile);
LOGGER.info("convertThread["+uploadedFileLocation+"] DONE");
} catch (Exception e) {
LOGGER.info(e.getMessage(), e);
}
}
}, "aliyunThread["+uploadedFileLocation+"]");
aliyunThread.start();
out.flush();
out.close();
result = "File uploaded. Name: " + fileName +". Size: "+filesize +". ID: "+fileId;
}
} catch (Exception e) {
LOGGER.info(e.getMessage(), e);
result = e.getMessage();
} finally {
try {
HibernateUtil.closeSession();
} catch (HibernateException e) {
LOGGER.info(e.getMessage(), e);
}
}
return result;
}
| restful/FileUploadForMobile.java | Create FileUploadForMobile.java | restful/FileUploadForMobile.java | Create FileUploadForMobile.java | <ide><path>estful/FileUploadForMobile.java
<add> @POST
<add> @Path("File/UploadOld")
<add> @Consumes(MediaType.MULTIPART_FORM_DATA)
<add> public String uploadFileOld(
<add> @QueryParam("user") String userName,
<add> @QueryParam("stamp") String stamp,
<add> @QueryParam("sig") String sig,
<add> @Context HttpServletRequest request,
<add> @FormDataParam("file") InputStream uploadedInputStream,
<add> @FormDataParam("file") FormDataContentDisposition fileDetail,
<add> @FormDataParam("appointment") String appointment,
<add> @FormDataParam("filename") String filename,
<add> @FormDataParam("filesize") String filesize,
<add> @FormDataParam("filedescription") String filedescription) {
<add> Utils.logRequest(request);
<add> LOGGER.info("authing fileUpload("+userName+", "+stamp+", "+sig+")");
<add> RestUtils.authenticationByUserName(request, userName, stamp, sig);
<add> String result = "success";
<add>
<add> try {
<add> if(StringUtils.isNotBlank(appointment) && StringUtils.isNotBlank(fileDetail.getFileName())){
<add> String folderName = Utils.getChcProperties().getProperty("cloud_root") + "/" + appointment;
<add> final String fileName = URLDecoder.decode(filename,"UTF-8");
<add> List<File> folders = HibernateDao.findByProperty(File.class, "marketAppointmentID", appointment);
<add> File folder;
<add> Set<File> children;
<add> if(folders.size() > 0){
<add> folder = folders.get(0);
<add> children = folder.getFiles();
<add> }else{
<add> folder = new File();
<add> folder.setMarketAppointmentID(appointment);
<add> folder.setFileSystem(Constants.FILESYSTEM_DIRECTORY);
<add> folder.setFolderName(folderName);
<add> children = new HashSet<File>();
<add> folder.setFiles(children);
<add> }
<add> File newfile = new File();
<add> newfile.setFileName(fileName);
<add> newfile.setDesc(URLDecoder.decode(filedescription,"UTF-8"));
<add> newfile.setSize(Long.parseLong(filesize));
<add> newfile.setFileSystem(Constants.FILESYSTEM_FILE);
<add> newfile.setFolderName(folderName);
<add> newfile.setInputDate(new Date());
<add> newfile.setCategory(Constants.CLOUD_IMAGE_FILE_CATEGORY_3);
<add> HibernateDao.saveOrUpdate(newfile);
<add> children.add(newfile);
<add> HibernateDao.saveOrUpdate(folder);
<add>
<add> String extension ="";
<add> int i = fileName.lastIndexOf('.');
<add> if (i > 0) {
<add> extension = fileName.substring(i);
<add> }
<add> final String fileId = newfile.getId();
<add> final String uploadedFileLocation = Utils.padFileName(folderName, fileId+extension);
<add>
<add> int read = 0;
<add> byte[] bytes = new byte[1024];
<add>
<add> java.io.File target = new java.io.File(uploadedFileLocation);
<add> if(!target.getParentFile().exists()){
<add> target.getParentFile().mkdirs();
<add> }
<add> OutputStream out = new FileOutputStream(target);
<add> while ((read = uploadedInputStream.read(bytes)) != -1) {
<add> out.write(bytes, 0, read);
<add> }
<add>
<add> LOGGER.info("File "+fileName+" being uploaded to "+uploadedFileLocation);
<add>
<add> Thread aliyunThread = new Thread(new Runnable() {
<add> @Override
<add> public void run() {
<add> try {
<add> LOGGER.info("convertThread["+uploadedFileLocation+"] START ...");
<add> java.io.File uploadedFile = new java.io.File(uploadedFileLocation);
<add> OSSUtility.putFile(OSSUtility.BUCKET_PUB, Constants.MARKET_FILE + fileId+"/"+ fileName, uploadedFile);
<add> LOGGER.info("convertThread["+uploadedFileLocation+"] DONE");
<add> } catch (Exception e) {
<add> LOGGER.info(e.getMessage(), e);
<add> }
<add> }
<add> }, "aliyunThread["+uploadedFileLocation+"]");
<add>
<add> aliyunThread.start();
<add> out.flush();
<add> out.close();
<add> result = "File uploaded. Name: " + fileName +". Size: "+filesize +". ID: "+fileId;
<add> }
<add> } catch (Exception e) {
<add> LOGGER.info(e.getMessage(), e);
<add> result = e.getMessage();
<add> } finally {
<add> try {
<add> HibernateUtil.closeSession();
<add> } catch (HibernateException e) {
<add> LOGGER.info(e.getMessage(), e);
<add> }
<add> }
<add>
<add> return result;
<add> } |
|
Java | apache-2.0 | 186880337e71845fd2e9c35fa92a44d73022e70d | 0 | S-Bartfast/cgeo,auricgoldfinger/cgeo,auricgoldfinger/cgeo,matej116/cgeo,S-Bartfast/cgeo,cgeo/cgeo,rsudev/c-geo-opensource,auricgoldfinger/cgeo,S-Bartfast/cgeo,tobiasge/cgeo,cgeo/cgeo,tobiasge/cgeo,tobiasge/cgeo,rsudev/c-geo-opensource,Bananeweizen/cgeo,Bananeweizen/cgeo,matej116/cgeo,cgeo/cgeo,matej116/cgeo,Bananeweizen/cgeo,cgeo/cgeo,rsudev/c-geo-opensource | package cgeo.geocaching.maps.mapsforge.v6;
import cgeo.geocaching.AbstractDialogFragment;
import cgeo.geocaching.AbstractDialogFragment.TargetInfo;
import cgeo.geocaching.CacheListActivity;
import cgeo.geocaching.CachePopup;
import cgeo.geocaching.CompassActivity;
import cgeo.geocaching.EditWaypointActivity;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.WaypointPopup;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.gc.GCMap;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.CoordinatesType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.maps.LivemapStrategy;
import cgeo.geocaching.maps.MapMode;
import cgeo.geocaching.maps.MapOptions;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.MapState;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapSource;
import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle;
import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef;
import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer;
import cgeo.geocaching.maps.routing.Routing;
import cgeo.geocaching.maps.routing.RoutingMode;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.utils.AngleUtils;
import cgeo.geocaching.utils.DisposableHandler;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.functions.Action1;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import butterknife.ButterKnife;
import io.reactivex.disposables.CompositeDisposable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.graphics.AndroidResourceBitmap;
import org.mapsforge.map.android.input.MapZoomControls;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.DisplayModel;
import org.mapsforge.map.rendertheme.ExternalRenderTheme;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.rule.RenderThemeHandler;
import org.xmlpull.v1.XmlPullParserException;
@SuppressLint("ClickableViewAccessibility")
public class NewMap extends AbstractActionBarActivity {
private MfMapView mapView;
private TileCache tileCache;
private ITileLayer tileLayer;
private HistoryLayer historyLayer;
private PositionLayer positionLayer;
private NavigationLayer navigationLayer;
private CachesBundle caches;
private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this));
private DistanceView distanceView;
private ArrayList<Location> trailHistory = null;
private String targetGeocode = null;
private Geopoint lastNavTarget = null;
private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>();
private ProgressDialog waitDialog;
private LoadDetails loadDetailsThread;
private final UpdateLoc geoDirUpdate = new UpdateLoc(this);
/**
* initialization with an empty subscription to make static code analysis tools more happy
*/
private final CompositeDisposable resumeDisposables = new CompositeDisposable();
private CheckBox myLocSwitch;
private MapOptions mapOptions;
private TargetView targetView;
private static boolean followMyLocation = true;
private static final String BUNDLE_MAP_STATE = "mapState";
private static final String BUNDLE_TRAIL_HISTORY = "trailHistory";
// Handler messages
// DisplayHandler
public static final int UPDATE_TITLE = 0;
public static final int INVALIDATE_MAP = 1;
// ShowProgressHandler
public static final int HIDE_PROGRESS = 0;
public static final int SHOW_PROGRESS = 1;
// LoadDetailsHandler
public static final int UPDATE_PROGRESS = 0;
public static final int FINISHED_LOADING_DETAILS = 1;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("NewMap: onCreate");
ResourceBitmapCacheMonitor.addRef();
AndroidGraphicFactory.createInstance(this.getApplication());
// some tiles are rather big, see https://github.com/mapsforge/mapsforge/issues/868
Parameters.MAXIMUM_BUFFER_SIZE = 6500000;
// Get parameters from the intent
mapOptions = new MapOptions(this, getIntent().getExtras());
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE);
trailHistory = savedInstanceState.getParcelableArrayList(BUNDLE_TRAIL_HISTORY);
followMyLocation = mapOptions.mapState.followsMyLocation();
} else {
followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE;
}
ActivityMixin.onCreate(this, true);
// set layout
ActivityMixin.setTheme(this);
setContentView(R.layout.map_mapsforge_v6);
setTitle();
// initialize map
mapView = (MfMapView) findViewById(R.id.mfmapv5);
mapView.setClickable(true);
mapView.getMapScaleBar().setVisible(true);
mapView.setBuiltInZoomControls(true);
// create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles)
tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor());
// attach drag handler
final DragHandler dragHandler = new DragHandler(this);
mapView.setOnMapDragListener(dragHandler);
// prepare initial settings of mapView
if (mapOptions.mapState != null) {
this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter()));
this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel());
this.targetGeocode = mapOptions.mapState.getTargetGeocode();
this.lastNavTarget = mapOptions.mapState.getLastNavTarget();
mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled();
mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled();
} else if (mapOptions.searchResult != null) {
final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes());
if (viewport != null) {
postZoomToViewport(viewport);
}
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport viewport = DataStore.getBounds(mapOptions.geocode);
if (viewport != null) {
postZoomToViewport(viewport);
}
targetGeocode = mapOptions.geocode;
} else if (mapOptions.coords != null) {
postZoomToViewport(new Viewport(mapOptions.coords, 0, 0));
} else {
postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0));
}
prepareFilterBar();
Routing.connect();
}
private void postZoomToViewport(final Viewport viewport) {
mapView.post(new Runnable() {
@Override
public void run() {
mapView.zoomToViewport(viewport);
}
});
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final boolean result = super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.map_activity, menu);
MapProviderFactory.addMapviewMenuItems(menu);
final MenuItem item = menu.findItem(R.id.menu_toggle_mypos);
myLocSwitch = new CheckBox(this);
myLocSwitch.setButtonDrawable(R.drawable.ic_menu_myposition);
item.setActionView(myLocSwitch);
initMyLocationSwitchButton(myLocSwitch);
return result;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
super.onPrepareOptionsMenu(menu);
for (final MapSource mapSource : MapProviderFactory.getMapSources()) {
final MenuItem menuItem = menu.findItem(mapSource.getNumericalId());
if (menuItem != null) {
menuItem.setVisible(mapSource.isAvailable());
}
}
try {
final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live);
if (mapOptions.isLiveEnabled) {
itemMapLive.setTitle(res.getString(R.string.map_live_disable));
} else {
itemMapLive.setTitle(res.getString(R.string.map_live_enable));
}
itemMapLive.setVisible(mapOptions.coords == null);
final Set<String> visibleCacheGeocodes = caches.getVisibleCacheGeocodes();
menu.findItem(R.id.menu_store_caches).setVisible(false);
menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty());
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false);
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleCacheGeocodes).hasUnsavedCaches());
menu.findItem(R.id.menu_mycaches_mode).setChecked(Settings.isExcludeMyCaches());
menu.findItem(R.id.menu_disabled_mode).setChecked(Settings.isExcludeDisabledCaches());
menu.findItem(R.id.menu_direction_line).setChecked(Settings.isMapDirection());
//TODO: circles menu.findItem(R.id.menu_circle_mode).setChecked(this.searchOverlay.getCircles());
menu.findItem(R.id.menu_circle_mode).setVisible(false);
menu.findItem(R.id.menu_trail_mode).setChecked(Settings.isMapTrail());
menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes());
menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleCachesCount() > 1);
menu.findItem(R.id.submenu_strategy).setVisible(mapOptions.isLiveEnabled);
switch (Settings.getLiveMapStrategy()) {
case FAST:
menu.findItem(R.id.menu_strategy_fast).setChecked(true);
break;
case AUTO:
menu.findItem(R.id.menu_strategy_auto).setChecked(true);
break;
default: // DETAILED
menu.findItem(R.id.menu_strategy_detailed).setChecked(true);
break;
}
menu.findItem(R.id.submenu_routing).setVisible(Routing.isAvailable());
switch (Settings.getRoutingMode()) {
case STRAIGHT:
menu.findItem(R.id.menu_routing_straight).setChecked(true);
break;
case WALK:
menu.findItem(R.id.menu_routing_walk).setChecked(true);
break;
case BIKE:
menu.findItem(R.id.menu_routing_bike).setChecked(true);
break;
case CAR:
menu.findItem(R.id.menu_routing_car).setChecked(true);
break;
}
menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE);
menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE);
} catch (final RuntimeException e) {
Log.e("NewMap.onPrepareOptionsMenu", e);
}
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
switch (id) {
case android.R.id.home:
ActivityMixin.navigateUp(this);
return true;
case R.id.menu_trail_mode:
Settings.setMapTrail(!Settings.isMapTrail());
historyLayer.requestRedraw();
ActivityMixin.invalidateOptionsMenu(this);
return true;
case R.id.menu_direction_line:
Settings.setMapDirection(!Settings.isMapDirection());
navigationLayer.requestRedraw();
ActivityMixin.invalidateOptionsMenu(this);
return true;
case R.id.menu_map_live:
mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled;
if (mapOptions.isLiveEnabled) {
mapOptions.isStoredEnabled = true;
}
if (mapOptions.mapMode == MapMode.LIVE) {
Settings.setLiveMap(mapOptions.isLiveEnabled);
}
caches.enableStoredLayers(mapOptions.isStoredEnabled);
caches.handleLiveLayers(mapOptions.isLiveEnabled);
ActivityMixin.invalidateOptionsMenu(this);
if (mapOptions.mapMode != MapMode.SINGLE) {
mapOptions.title = StringUtils.EMPTY;
} else {
// reset target cache on single mode map
targetGeocode = mapOptions.geocode;
}
return true;
case R.id.menu_store_caches:
return storeCaches(caches.getVisibleCacheGeocodes());
case R.id.menu_store_unsaved_caches:
return storeCaches(getUnsavedGeocodes(caches.getVisibleCacheGeocodes()));
case R.id.menu_circle_mode:
// overlayCaches.switchCircles();
// mapView.repaintRequired(overlayCaches);
// ActivityMixin.invalidateOptionsMenu(activity);
return true;
case R.id.menu_mycaches_mode:
Settings.setExcludeMine(!Settings.isExcludeMyCaches());
caches.invalidate();
ActivityMixin.invalidateOptionsMenu(this);
if (!Settings.isExcludeMyCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_disabled_mode:
Settings.setExcludeDisabled(!Settings.isExcludeDisabledCaches());
caches.invalidate();
ActivityMixin.invalidateOptionsMenu(this);
if (!Settings.isExcludeDisabledCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_theme_mode:
selectMapTheme();
return true;
case R.id.menu_as_list: {
CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleCacheGeocodes()));
return true;
}
case R.id.menu_strategy_fast: {
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.FAST);
return true;
}
case R.id.menu_strategy_auto: {
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.AUTO);
return true;
}
case R.id.menu_strategy_detailed: {
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.DETAILED);
return true;
}
case R.id.menu_routing_straight: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.STRAIGHT);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_routing_walk: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.WALK);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_routing_bike: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.BIKE);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_routing_car: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.CAR);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_hint:
menuShowHint();
return true;
case R.id.menu_compass:
menuCompass();
return true;
default:
final MapSource mapSource = MapProviderFactory.getMapSource(id);
if (mapSource != null) {
item.setChecked(true);
changeMapSource(mapSource);
return true;
}
}
return false;
}
private Set<String> getUnsavedGeocodes(final Set<String> geocodes) {
final Set<String> unsavedGeocodes = new HashSet<>();
for (final String geocode : geocodes) {
if (!DataStore.isOffline(geocode, null)) {
unsavedGeocodes.add(geocode);
}
}
return unsavedGeocodes;
}
private boolean storeCaches(final Set<String> geocodes) {
if (!caches.isDownloading()) {
if (geocodes.isEmpty()) {
ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing));
return true;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForMultiListSelection(R.string.list_title, new Action1<Set<Integer>>() {
@Override
public void call(final Set<Integer> selectedListIds) {
storeCaches(geocodes, selectedListIds);
}
}, true, Collections.singleton(StoredList.TEMPORARY_LIST.id), false);
} else {
storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
return true;
}
private void menuCompass() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
CompassActivity.startActivityCache(this, cache);
}
}
private void menuShowHint() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
cache.showHintToast(this);
}
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
final String cacheType = Settings.getCacheType().getL10n();
final TextView filterTitleView = ButterKnife.findById(this, R.id.filter_text);
filterTitleView.setText(cacheType);
findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
/**
* @param view Not used here, required by layout
*/
public void showFilterMenu(final View view) {
// do nothing, the filter bar only shows the global filter
}
private void selectMapTheme() {
final File[] themeFiles = Settings.getMapThemeFiles();
String currentTheme = StringUtils.EMPTY;
final String currentThemePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isNotEmpty(currentThemePath)) {
final File currentThemeFile = new File(currentThemePath);
currentTheme = currentThemeFile.getName();
}
final List<String> names = new ArrayList<>();
names.add(res.getString(R.string.map_theme_builtin));
int currentItem = 0;
for (final File file : themeFiles) {
if (currentTheme.equalsIgnoreCase(file.getName())) {
currentItem = names.size();
}
names.add(file.getName());
}
final int selectedItem = currentItem;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.map_theme_select);
builder.setSingleChoiceItems(names.toArray(new String[names.size()]), selectedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int newItem) {
if (newItem != selectedItem) {
// Adjust index because of <default> selection
if (newItem > 0) {
Settings.setCustomRenderThemeFile(themeFiles[newItem - 1].getPath());
} else {
Settings.setCustomRenderThemeFile(StringUtils.EMPTY);
}
setMapTheme();
}
dialog.cancel();
}
});
builder.show();
}
protected void setMapTheme() {
if (tileLayer == null || tileLayer.getTileLayer() == null) {
return;
}
if (!tileLayer.hasThemes()) {
tileLayer.getTileLayer().requestRedraw();
return;
}
final TileRendererLayer rendererLayer = (TileRendererLayer) tileLayer.getTileLayer();
final String themePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isEmpty(themePath)) {
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
} else {
try {
final XmlRenderTheme xmlRenderTheme = new ExternalRenderTheme(new File(themePath));
// Validate the theme file
RenderThemeHandler.getRenderTheme(AndroidGraphicFactory.INSTANCE, new DisplayModel(), xmlRenderTheme);
rendererLayer.setXmlRenderTheme(xmlRenderTheme);
} catch (final IOException e) {
Log.w("Failed to set render theme", e);
ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_file_unreadable));
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
} catch (final XmlPullParserException e) {
Log.w("render theme invalid", e);
ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_invalid));
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
}
}
tileCache.purge();
rendererLayer.requestRedraw();
}
private void changeMapSource(@NonNull final MapSource newSource) {
final MapSource oldSource = Settings.getMapSource();
final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource);
// Update MapSource in settings
Settings.setMapSource(newSource);
if (restartRequired) {
mapRestart();
} else if (mapView != null) { // changeMapSource can be called by onCreate()
switchTileLayer(newSource);
}
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
mapOptions.mapState = currentMapState();
finish();
mapOptions.startIntent(this, Settings.getMapProvider().getMapClass());
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private MapState currentMapState() {
if (mapView == null) {
return null;
}
final Geopoint mapCenter = mapView.getViewport().getCenter();
return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void switchTileLayer(final MapSource newSource) {
final ITileLayer oldLayer = this.tileLayer;
ITileLayer newLayer = null;
if (newSource instanceof MapsforgeMapSource) {
newLayer = ((MapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition);
}
// Exchange layer
if (newLayer != null) {
this.mapView.getModel().displayModel.setFixedTileSize(newLayer.getFixedTileSize());
final MapZoomControls zoomControls = mapView.getMapZoomControls();
zoomControls.setZoomLevelMax(newLayer.getZoomLevelMax());
zoomControls.setZoomLevelMin(newLayer.getZoomLevelMin());
final Layers layers = this.mapView.getLayerManager().getLayers();
int index = 0;
if (oldLayer != null) {
index = layers.indexOf(oldLayer.getTileLayer()) + 1;
}
layers.add(index, newLayer.getTileLayer());
this.tileLayer = newLayer;
this.setMapTheme();
} else {
this.tileLayer = null;
}
// Cleanup
if (oldLayer != null) {
this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer());
oldLayer.getTileLayer().onDestroy();
}
tileCache.purge();
}
private void resumeTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onResume();
}
}
private void pauseTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onPause();
}
}
private boolean tileLayerHasThemes() {
if (tileLayer != null) {
return tileLayer.hasThemes();
}
return false;
}
@Override
protected void onResume() {
super.onResume();
Log.d("NewMap: onResume");
resumeTileLayer();
}
@Override
protected void onStart() {
super.onStart();
Log.d("NewMap: onStart");
initializeLayers();
}
private void initializeLayers() {
switchTileLayer(Settings.getMapSource());
// History Layer
this.historyLayer = new HistoryLayer(trailHistory);
this.mapView.getLayerManager().getLayers().add(this.historyLayer);
// NavigationLayer
Geopoint navTarget = lastNavTarget;
if (navTarget == null) {
navTarget = mapOptions.coords;
if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport bounds = DataStore.getBounds(mapOptions.geocode);
if (bounds != null) {
navTarget = bounds.center;
}
}
}
this.navigationLayer = new NavigationLayer(navTarget);
this.mapView.getLayerManager().getLayers().add(this.navigationLayer);
// TapHandler
final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler());
this.mapView.getLayerManager().getLayers().add(tapHandlerLayer);
// Caches bundle
if (mapOptions.searchResult != null) {
this.caches = new CachesBundle(mapOptions.searchResult, this.mapView, this.mapHandlers);
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
this.caches = new CachesBundle(mapOptions.geocode, this.mapView, this.mapHandlers);
} else if (mapOptions.coords != null) {
this.caches = new CachesBundle(mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers);
} else {
caches = new CachesBundle(this.mapView, this.mapHandlers);
}
// Stored enabled map
caches.enableStoredLayers(mapOptions.isStoredEnabled);
// Live enabled map
caches.handleLiveLayers(mapOptions.isLiveEnabled);
// Position layer
this.positionLayer = new PositionLayer();
this.mapView.getLayerManager().getLayers().add(positionLayer);
//Distance view
this.distanceView = new DistanceView(navTarget, (TextView) findViewById(R.id.distance));
//Target view
this.targetView = new TargetView((TextView) findViewById(R.id.target), StringUtils.EMPTY, StringUtils.EMPTY);
final Geocache target = getCurrentTargetCache();
if (target != null) {
targetView.setTarget(target.getGeocode(), target.getName());
}
this.resumeDisposables.add(this.geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR));
}
@Override
public void onPause() {
Log.d("NewMap: onPause");
savePrefs();
pauseTileLayer();
super.onPause();
}
@Override
protected void onStop() {
Log.d("NewMap: onStop");
waitDialog = null;
terminateLayers();
super.onStop();
}
private void terminateLayers() {
this.resumeDisposables.clear();
this.caches.onDestroy();
this.caches = null;
this.mapView.getLayerManager().getLayers().remove(this.positionLayer);
this.positionLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.navigationLayer);
this.navigationLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.historyLayer);
this.historyLayer = null;
if (this.tileLayer != null) {
this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer());
this.tileLayer.getTileLayer().onDestroy();
this.tileLayer = null;
}
}
/**
* store caches, invoked by "store offline" menu item
*
* @param listIds the lists to store the caches in
*/
private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) {
final int count = geocodes.size();
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this);
waitDialog = new ProgressDialog(this);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage());
waitDialog.setMax(count);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(final DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
} catch (final Exception e) {
Log.e("CGeoMap.storeCaches.onCancel", e);
}
}
});
final float etaTime = count * 7.0f / 60.0f;
final int roundedEta = Math.round(etaTime);
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta));
}
loadDetailsHandler.setStart();
waitDialog.show();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds);
loadDetailsThread.start();
}
@Override
protected void onDestroy() {
Log.d("NewMap: onDestroy");
this.tileCache.destroy();
this.mapView.getModel().mapViewPosition.destroy();
this.mapView.destroy();
ResourceBitmapCacheMonitor.release();
Routing.disconnect();
super.onDestroy();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
final MapState state = prepareMapState();
outState.putParcelable(BUNDLE_MAP_STATE, state);
if (historyLayer != null) {
outState.putParcelableArrayList(BUNDLE_TRAIL_HISTORY, historyLayer.getHistory());
}
}
private MapState prepareMapState() {
return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void centerMap(final Geopoint geopoint) {
mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude()));
}
public Location getCoordinates() {
final LatLong center = mapView.getModel().mapViewPosition.getCenter();
final Location loc = new Location("newmap");
loc.setLatitude(center.latitude);
loc.setLongitude(center.longitude);
return loc;
}
private void initMyLocationSwitchButton(final CheckBox locSwitch) {
myLocSwitch = locSwitch;
/*
* TODO: Switch back to ImageSwitcher for animations?
* myLocSwitch.setFactory(this);
* myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
* myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
*/
myLocSwitch.setOnClickListener(new MyLocationListener(this));
switchMyLocationButton();
}
// switch My Location button image
private void switchMyLocationButton() {
myLocSwitch.setChecked(followMyLocation);
if (followMyLocation) {
myLocationInMiddle(Sensors.getInstance().currentGeo());
}
}
public void showAddWaypoint(final LatLong tapLatLong) {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude));
}
}
// set my location listener
private static class MyLocationListener implements View.OnClickListener {
@NonNull
private final WeakReference<NewMap> mapRef;
MyLocationListener(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
private void onFollowMyLocationClicked() {
followMyLocation = !followMyLocation;
final NewMap map = mapRef.get();
if (map != null) {
map.switchMyLocationButton();
}
}
@Override
public void onClick(final View view) {
onFollowMyLocationClicked();
}
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final GeoData geo) {
if (followMyLocation) {
centerMap(geo.getCoords());
}
}
private static final class DisplayHandler extends Handler {
@NonNull
private final WeakReference<NewMap> mapRef;
DisplayHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
map.setTitle();
map.setSubtitle();
break;
case INVALIDATE_MAP:
map.mapView.repaint();
break;
default:
break;
}
}
}
private void setTitle() {
final String title = calculateTitle();
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}
}
@NonNull
private String calculateTitle() {
if (mapOptions.isLiveEnabled) {
return res.getString(R.string.map_live);
}
if (mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return cache.getName();
}
}
return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_map));
}
private void setSubtitle() {
final String subtitle = calculateSubtitle();
if (StringUtils.isEmpty(subtitle)) {
return;
}
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(subtitle);
}
}
@NonNull
private String calculateSubtitle() {
if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return Formatter.formatMapSubtitle(cache);
}
}
// count caches in the sub title
final int visible = countVisibleCaches();
final int total = countTotalCaches();
final StringBuilder subtitle = new StringBuilder();
if (total != 0) {
if (visible != total && Settings.isDebug()) {
subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total));
} else {
subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible));
}
}
// if (Settings.isDebug() && lastSearchResult != null && StringUtils.isNotBlank(lastSearchResult.getUrl())) {
// subtitle.append(" [").append(lastSearchResult.getUrl()).append(']');
// }
return subtitle.toString();
}
private int countVisibleCaches() {
return caches != null ? caches.getVisibleCachesCount() : 0;
}
private int countTotalCaches() {
return caches != null ? caches.getCachesCount() : 0;
}
/**
* Updates the progress.
*/
private static final class ShowProgressHandler extends Handler {
private int counter = 0;
@NonNull
private final WeakReference<NewMap> mapRef;
ShowProgressHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
showProgress(false);
}
} else if (what == SHOW_PROGRESS) {
showProgress(true);
counter++;
}
}
private void showProgress(final boolean show) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
map.setProgressBarIndeterminateVisibility(show);
}
}
private static final class LoadDetailsHandler extends DisposableHandler {
private final int detailTotal;
private int detailProgress;
private long detailProgressTime;
private final WeakReference<NewMap> mapRef;
LoadDetailsHandler(final int detailTotal, final NewMap map) {
super();
this.detailTotal = detailTotal;
this.detailProgress = 0;
this.mapRef = new WeakReference<>(map);
}
public void setStart() {
detailProgressTime = System.currentTimeMillis();
}
@Override
public void handleRegularMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (msg.what == UPDATE_PROGRESS) {
if (detailProgress < detailTotal) {
detailProgress++;
}
if (map.waitDialog != null) {
final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
final int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
map.waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm));
} else {
final int minsRemaining = secondsRemaining / 60;
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) {
map.waitDialog.dismiss();
map.waitDialog.setOnCancelListener(null);
}
}
@Override
public void handleDispose() {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (map.loadDetailsThread != null) {
map.loadDetailsThread.stopIt();
}
}
}
// class: update location
private static class UpdateLoc extends GeoDirHandler {
// use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible
// minimum time in milliseconds between position overlay updates
private static final long MIN_UPDATE_INTERVAL = 500;
// minimum change of heading in grad for position overlay update
private static final float MIN_HEADING_DELTA = 15f;
// minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update
private static final float MIN_LOCATION_DELTA = 0.01f;
@NonNull
Location currentLocation = Sensors.getInstance().currentGeo();
float currentHeading;
private long timeLastPositionOverlayCalculation = 0;
/**
* weak reference to the outer class
*/
@NonNull
private final WeakReference<NewMap> mapRef;
UpdateLoc(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void updateGeoDir(@NonNull final GeoData geo, final float dir) {
currentLocation = geo;
currentHeading = AngleUtils.getDirectionNow(dir);
repaintPositionOverlay();
}
@NonNull
public Location getCurrentLocation() {
return currentLocation;
}
/**
* Repaint position overlay but only with a max frequency and if position or heading changes sufficiently.
*/
void repaintPositionOverlay() {
final long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) {
timeLastPositionOverlayCalculation = currentTimeMillis;
try {
final NewMap map = mapRef.get();
if (map != null) {
final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy();
final boolean needsRepaintForHeading = needsRepaintForHeading();
if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) {
map.centerMap(new Geopoint(currentLocation));
}
if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) {
map.historyLayer.setCoordinates(currentLocation);
map.navigationLayer.setCoordinates(currentLocation);
map.distanceView.setCoordinates(currentLocation);
map.positionLayer.setCoordinates(currentLocation);
map.positionLayer.setHeading(currentHeading);
map.positionLayer.requestRedraw();
}
}
} catch (final RuntimeException e) {
Log.w("Failed to update location", e);
}
}
}
boolean needsRepaintForHeading() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA;
}
boolean needsRepaintForDistanceOrAccuracy() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
final Location lastLocation = map.getCoordinates();
float dist = Float.MAX_VALUE;
if (lastLocation != null) {
if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) {
return true;
}
dist = currentLocation.distanceTo(lastLocation);
}
final float[] mapDimension = new float[1];
if (map.mapView.getWidth() < map.mapView.getHeight()) {
final double span = map.mapView.getLongitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension);
} else {
final double span = map.mapView.getLatitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension);
}
return dist > (mapDimension[0] * MIN_LOCATION_DELTA);
}
}
private static class DragHandler implements OnMapDragListener {
@NonNull
private final WeakReference<NewMap> mapRef;
DragHandler(@NonNull final NewMap parent) {
mapRef = new WeakReference<>(parent);
}
@Override
public void onDrag() {
final NewMap map = mapRef.get();
if (map != null && NewMap.followMyLocation) {
NewMap.followMyLocation = false;
map.switchMyLocationButton();
}
}
}
public void showSelection(@NonNull final List<GeoitemRef> items) {
if (items.isEmpty()) {
return;
}
if (items.size() == 1) {
showPopup(items.get(0));
return;
}
try {
final ArrayList<GeoitemRef> sorted = new ArrayList<>(items);
Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR);
final LayoutInflater inflater = LayoutInflater.from(this);
final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
final View view = convertView == null ? inflater.inflate(R.layout.cacheslist_item_select, parent, false) : convertView;
final TextView tv = (TextView) view.findViewById(R.id.text);
final GeoitemRef item = getItem(position);
tv.setText(item.getName());
//Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(item.getMarkerId(), 0, 0, 0);
final TextView infoView = (TextView) view.findViewById(R.id.info);
final StringBuilder text = new StringBuilder(item.getItemCode());
if (item.getType() == CoordinatesType.WAYPOINT && StringUtils.isNotEmpty(item.getGeocode())) {
text.append(Formatter.SEPARATOR).append(item.getGeocode());
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
text.append(Formatter.SEPARATOR).append(cache.getName());
}
}
infoView.setText(text.toString());
return view;
}
};
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(res.getString(R.string.map_select_multiple_items))
.setAdapter(adapter, new SelectionClickListener(sorted))
.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
} catch (final NotFoundException e) {
Log.e("NewMap.showSelection", e);
}
}
private class SelectionClickListener implements DialogInterface.OnClickListener {
@NonNull
private final List<GeoitemRef> items;
SelectionClickListener(@NonNull final List<GeoitemRef> items) {
this.items = items;
}
@Override
public void onClick(final DialogInterface dialog, final int which) {
if (which >= 0 && which < items.size()) {
final GeoitemRef item = items.get(which);
showPopup(item);
}
}
}
private void showPopup(final GeoitemRef item) {
if (item == null || StringUtils.isEmpty(item.getGeocode())) {
return;
}
try {
if (item.getType() == CoordinatesType.CACHE) {
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
final RequestDetailsThread requestDetailsThread = new RequestDetailsThread(cache, this);
requestDetailsThread.start();
return;
}
return;
}
if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) {
popupGeocodes.add(item.getGeocode());
WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode());
}
} catch (final NotFoundException e) {
Log.e("NewMap.showPopup", e);
}
}
@Nullable
private Geocache getSingleModeCache() {
if (StringUtils.isNotBlank(mapOptions.geocode)) {
return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
@Nullable
private Geocache getCurrentTargetCache() {
if (StringUtils.isNotBlank(targetGeocode)) {
return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
private void savePrefs() {
Settings.setMapZoom(MapMode.SINGLE, mapView.getMapZoomLevel());
Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter()));
}
private static class RequestDetailsThread extends Thread {
@NonNull
private final Geocache cache;
@NonNull
private final WeakReference<NewMap> map;
RequestDetailsThread(@NonNull final Geocache cache, @NonNull final NewMap map) {
this.cache = cache;
this.map = new WeakReference<>(map);
}
public boolean requestRequired() {
return CacheType.UNKNOWN == cache.getType() || cache.getDifficulty() == 0;
}
@Override
public void run() {
final NewMap map = this.map.get();
if (map == null) {
return;
}
if (requestRequired()) {
try {
/* final SearchResult search = */
GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode()));
} catch (final Exception ex) {
Log.w("Error requesting cache popup info", ex);
ActivityMixin.showToast(map, R.string.err_request_popup_info);
}
}
map.popupGeocodes.add(cache.getGeocode());
CachePopup.startActivityAllowTarget(map, cache.getGeocode());
}
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
private final DisposableHandler handler;
private final Collection<String> geocodes;
private final Set<Integer> listIds;
LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) {
this.handler = handler;
this.geocodes = geocodes;
this.listIds = listIds;
}
public void stopIt() {
handler.dispose();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
for (final String geocode : geocodes) {
try {
if (handler.isDisposed()) {
break;
}
if (!DataStore.isOffline(geocode, null)) {
Geocache.storeCache(null, geocode, listIds, false, handler);
}
} catch (final Exception e) {
Log.e("CGeoMap.LoadDetails.run", e);
} finally {
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
}
// we're done, but map might even have been closed.
if (caches != null) caches.invalidate(geocodes);
invalidateOptionsMenuCompatible();
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) {
if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) {
final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO);
if (targetInfo != null) {
lastNavTarget = targetInfo.coords;
if (navigationLayer != null) {
navigationLayer.setDestination(targetInfo.coords);
navigationLayer.requestRedraw();
}
if (distanceView != null) {
distanceView.setDestination(targetInfo.coords);
distanceView.setCoordinates(geoDirUpdate.getCurrentLocation());
}
if (StringUtils.isNotBlank(targetInfo.geocode)) {
targetGeocode = targetInfo.geocode;
final Geocache target = getCurrentTargetCache();
targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY);
}
}
}
final List<String> changedGeocodes = new ArrayList<>();
String geocode = popupGeocodes.poll();
while (geocode != null) {
changedGeocodes.add(geocode);
geocode = popupGeocodes.poll();
}
if (caches != null) {
caches.invalidate(changedGeocodes);
}
}
}
private static class ResourceBitmapCacheMonitor {
private static int refCount = 0;
static synchronized void addRef() {
refCount++;
Log.d("ResourceBitmapCacheMonitor.addRef");
}
static synchronized void release() {
if (refCount > 0) {
refCount--;
Log.d("ResourceBitmapCacheMonitor.release");
if (refCount == 0) {
Log.d("ResourceBitmapCacheMonitor.clearResourceBitmaps");
AndroidResourceBitmap.clearResourceBitmaps();
}
}
}
}
}
| main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java | package cgeo.geocaching.maps.mapsforge.v6;
import cgeo.geocaching.AbstractDialogFragment;
import cgeo.geocaching.AbstractDialogFragment.TargetInfo;
import cgeo.geocaching.CacheListActivity;
import cgeo.geocaching.CachePopup;
import cgeo.geocaching.CompassActivity;
import cgeo.geocaching.EditWaypointActivity;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.WaypointPopup;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.gc.GCMap;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.CoordinatesType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.maps.LivemapStrategy;
import cgeo.geocaching.maps.MapMode;
import cgeo.geocaching.maps.MapOptions;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.MapState;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapSource;
import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle;
import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef;
import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer;
import cgeo.geocaching.maps.routing.Routing;
import cgeo.geocaching.maps.routing.RoutingMode;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.utils.AngleUtils;
import cgeo.geocaching.utils.DisposableHandler;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.functions.Action1;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import butterknife.ButterKnife;
import io.reactivex.disposables.CompositeDisposable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.graphics.AndroidResourceBitmap;
import org.mapsforge.map.android.input.MapZoomControls;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.DisplayModel;
import org.mapsforge.map.rendertheme.ExternalRenderTheme;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.rule.RenderThemeHandler;
import org.xmlpull.v1.XmlPullParserException;
@SuppressLint("ClickableViewAccessibility")
public class NewMap extends AbstractActionBarActivity {
private MfMapView mapView;
private TileCache tileCache;
private ITileLayer tileLayer;
private HistoryLayer historyLayer;
private PositionLayer positionLayer;
private NavigationLayer navigationLayer;
private CachesBundle caches;
private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this));
private DistanceView distanceView;
private ArrayList<Location> trailHistory = null;
private String targetGeocode = null;
private Geopoint lastNavTarget = null;
private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>();
private ProgressDialog waitDialog;
private LoadDetails loadDetailsThread;
private final UpdateLoc geoDirUpdate = new UpdateLoc(this);
/**
* initialization with an empty subscription to make static code analysis tools more happy
*/
private final CompositeDisposable resumeDisposables = new CompositeDisposable();
private CheckBox myLocSwitch;
private MapOptions mapOptions;
private TargetView targetView;
private static boolean followMyLocation = true;
private static final String BUNDLE_MAP_STATE = "mapState";
private static final String BUNDLE_TRAIL_HISTORY = "trailHistory";
// Handler messages
// DisplayHandler
public static final int UPDATE_TITLE = 0;
public static final int INVALIDATE_MAP = 1;
// ShowProgressHandler
public static final int HIDE_PROGRESS = 0;
public static final int SHOW_PROGRESS = 1;
// LoadDetailsHandler
public static final int UPDATE_PROGRESS = 0;
public static final int FINISHED_LOADING_DETAILS = 1;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("NewMap: onCreate");
ResourceBitmapCacheMonitor.addRef();
AndroidGraphicFactory.createInstance(this.getApplication());
// some tiles are rather big, see https://github.com/mapsforge/mapsforge/issues/868
Parameters.MAXIMUM_BUFFER_SIZE = 6500000;
// Get parameters from the intent
mapOptions = new MapOptions(this, getIntent().getExtras());
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE);
trailHistory = savedInstanceState.getParcelableArrayList(BUNDLE_TRAIL_HISTORY);
followMyLocation = mapOptions.mapState.followsMyLocation();
} else {
followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE;
}
ActivityMixin.onCreate(this, true);
// set layout
ActivityMixin.setTheme(this);
setContentView(R.layout.map_mapsforge_v6);
setTitle();
// initialize map
mapView = (MfMapView) findViewById(R.id.mfmapv5);
mapView.setClickable(true);
mapView.getMapScaleBar().setVisible(true);
mapView.setBuiltInZoomControls(true);
// create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles)
tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor());
// attach drag handler
final DragHandler dragHandler = new DragHandler(this);
mapView.setOnMapDragListener(dragHandler);
// prepare initial settings of mapView
if (mapOptions.mapState != null) {
this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter()));
this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel());
this.targetGeocode = mapOptions.mapState.getTargetGeocode();
this.lastNavTarget = mapOptions.mapState.getLastNavTarget();
mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled();
mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled();
} else if (mapOptions.searchResult != null) {
final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes());
if (viewport != null) {
postZoomToViewport(viewport);
}
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport viewport = DataStore.getBounds(mapOptions.geocode);
if (viewport != null) {
postZoomToViewport(viewport);
}
targetGeocode = mapOptions.geocode;
} else if (mapOptions.coords != null) {
postZoomToViewport(new Viewport(mapOptions.coords, 0, 0));
} else {
postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0));
}
prepareFilterBar();
Routing.connect();
}
private void postZoomToViewport(final Viewport viewport) {
mapView.post(new Runnable() {
@Override
public void run() {
mapView.zoomToViewport(viewport);
}
});
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final boolean result = super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.map_activity, menu);
MapProviderFactory.addMapviewMenuItems(menu);
final MenuItem item = menu.findItem(R.id.menu_toggle_mypos);
myLocSwitch = new CheckBox(this);
myLocSwitch.setButtonDrawable(R.drawable.ic_menu_myposition);
item.setActionView(myLocSwitch);
initMyLocationSwitchButton(myLocSwitch);
return result;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
super.onPrepareOptionsMenu(menu);
for (final MapSource mapSource : MapProviderFactory.getMapSources()) {
final MenuItem menuItem = menu.findItem(mapSource.getNumericalId());
if (menuItem != null) {
menuItem.setVisible(mapSource.isAvailable());
}
}
try {
final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live);
if (mapOptions.isLiveEnabled) {
itemMapLive.setTitle(res.getString(R.string.map_live_disable));
} else {
itemMapLive.setTitle(res.getString(R.string.map_live_enable));
}
itemMapLive.setVisible(mapOptions.coords == null);
final Set<String> visibleCacheGeocodes = caches.getVisibleCacheGeocodes();
menu.findItem(R.id.menu_store_caches).setVisible(false);
menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty());
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false);
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleCacheGeocodes).hasUnsavedCaches());
menu.findItem(R.id.menu_mycaches_mode).setChecked(Settings.isExcludeMyCaches());
menu.findItem(R.id.menu_disabled_mode).setChecked(Settings.isExcludeDisabledCaches());
menu.findItem(R.id.menu_direction_line).setChecked(Settings.isMapDirection());
//TODO: circles menu.findItem(R.id.menu_circle_mode).setChecked(this.searchOverlay.getCircles());
menu.findItem(R.id.menu_circle_mode).setVisible(false);
menu.findItem(R.id.menu_trail_mode).setChecked(Settings.isMapTrail());
menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes());
menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleCachesCount() > 1);
menu.findItem(R.id.submenu_strategy).setVisible(mapOptions.isLiveEnabled);
switch (Settings.getLiveMapStrategy()) {
case FAST:
menu.findItem(R.id.menu_strategy_fast).setChecked(true);
break;
case AUTO:
menu.findItem(R.id.menu_strategy_auto).setChecked(true);
break;
default: // DETAILED
menu.findItem(R.id.menu_strategy_detailed).setChecked(true);
break;
}
menu.findItem(R.id.submenu_routing).setVisible(Routing.isAvailable());
switch (Settings.getRoutingMode()) {
case STRAIGHT:
menu.findItem(R.id.menu_routing_straight).setChecked(true);
break;
case WALK:
menu.findItem(R.id.menu_routing_walk).setChecked(true);
break;
case BIKE:
menu.findItem(R.id.menu_routing_bike).setChecked(true);
break;
case CAR:
menu.findItem(R.id.menu_routing_car).setChecked(true);
break;
}
menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE);
menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE);
} catch (final RuntimeException e) {
Log.e("NewMap.onPrepareOptionsMenu", e);
}
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
switch (id) {
case android.R.id.home:
ActivityMixin.navigateUp(this);
return true;
case R.id.menu_trail_mode:
Settings.setMapTrail(!Settings.isMapTrail());
historyLayer.requestRedraw();
ActivityMixin.invalidateOptionsMenu(this);
return true;
case R.id.menu_direction_line:
Settings.setMapDirection(!Settings.isMapDirection());
navigationLayer.requestRedraw();
ActivityMixin.invalidateOptionsMenu(this);
return true;
case R.id.menu_map_live:
mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled;
if (mapOptions.isLiveEnabled) {
mapOptions.isStoredEnabled = true;
}
if (mapOptions.mapMode == MapMode.LIVE) {
Settings.setLiveMap(mapOptions.isLiveEnabled);
}
caches.enableStoredLayers(mapOptions.isStoredEnabled);
caches.handleLiveLayers(mapOptions.isLiveEnabled);
ActivityMixin.invalidateOptionsMenu(this);
if (mapOptions.mapMode != MapMode.SINGLE) {
mapOptions.title = StringUtils.EMPTY;
} else {
// reset target cache on single mode map
targetGeocode = mapOptions.geocode;
}
return true;
case R.id.menu_store_caches:
return storeCaches(caches.getVisibleCacheGeocodes());
case R.id.menu_store_unsaved_caches:
return storeCaches(getUnsavedGeocodes(caches.getVisibleCacheGeocodes()));
case R.id.menu_circle_mode:
// overlayCaches.switchCircles();
// mapView.repaintRequired(overlayCaches);
// ActivityMixin.invalidateOptionsMenu(activity);
return true;
case R.id.menu_mycaches_mode:
Settings.setExcludeMine(!Settings.isExcludeMyCaches());
caches.invalidate();
ActivityMixin.invalidateOptionsMenu(this);
if (!Settings.isExcludeMyCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_disabled_mode:
Settings.setExcludeDisabled(!Settings.isExcludeDisabledCaches());
caches.invalidate();
ActivityMixin.invalidateOptionsMenu(this);
if (!Settings.isExcludeDisabledCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_theme_mode:
selectMapTheme();
return true;
case R.id.menu_as_list: {
CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleCacheGeocodes()));
return true;
}
case R.id.menu_strategy_fast: {
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.FAST);
return true;
}
case R.id.menu_strategy_auto: {
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.AUTO);
return true;
}
case R.id.menu_strategy_detailed: {
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.DETAILED);
return true;
}
case R.id.menu_routing_straight: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.STRAIGHT);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_routing_walk: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.WALK);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_routing_bike: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.BIKE);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_routing_car: {
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.CAR);
navigationLayer.requestRedraw();
return true;
}
case R.id.menu_hint:
menuShowHint();
return true;
case R.id.menu_compass:
menuCompass();
return true;
default:
final MapSource mapSource = MapProviderFactory.getMapSource(id);
if (mapSource != null) {
item.setChecked(true);
changeMapSource(mapSource);
return true;
}
}
return false;
}
private Set<String> getUnsavedGeocodes(final Set<String> geocodes) {
final Set<String> unsavedGeocodes = new HashSet<>();
for (final String geocode : geocodes) {
if (!DataStore.isOffline(geocode, null)) {
unsavedGeocodes.add(geocode);
}
}
return unsavedGeocodes;
}
private boolean storeCaches(final Set<String> geocodes) {
if (!caches.isDownloading()) {
if (geocodes.isEmpty()) {
ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing));
return true;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForMultiListSelection(R.string.list_title, new Action1<Set<Integer>>() {
@Override
public void call(final Set<Integer> selectedListIds) {
storeCaches(geocodes, selectedListIds);
}
}, true, Collections.singleton(StoredList.TEMPORARY_LIST.id), false);
} else {
storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
return true;
}
private void menuCompass() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
CompassActivity.startActivityCache(this, cache);
}
}
private void menuShowHint() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
cache.showHintToast(this);
}
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
final String cacheType = Settings.getCacheType().getL10n();
final TextView filterTitleView = ButterKnife.findById(this, R.id.filter_text);
filterTitleView.setText(cacheType);
findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
/**
* @param view Not used here, required by layout
*/
public void showFilterMenu(final View view) {
// do nothing, the filter bar only shows the global filter
}
private void selectMapTheme() {
final File[] themeFiles = Settings.getMapThemeFiles();
String currentTheme = StringUtils.EMPTY;
final String currentThemePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isNotEmpty(currentThemePath)) {
final File currentThemeFile = new File(currentThemePath);
currentTheme = currentThemeFile.getName();
}
final List<String> names = new ArrayList<>();
names.add(res.getString(R.string.map_theme_builtin));
int currentItem = 0;
for (final File file : themeFiles) {
if (currentTheme.equalsIgnoreCase(file.getName())) {
currentItem = names.size();
}
names.add(file.getName());
}
final int selectedItem = currentItem;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.map_theme_select);
builder.setSingleChoiceItems(names.toArray(new String[names.size()]), selectedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int newItem) {
if (newItem != selectedItem) {
// Adjust index because of <default> selection
if (newItem > 0) {
Settings.setCustomRenderThemeFile(themeFiles[newItem - 1].getPath());
} else {
Settings.setCustomRenderThemeFile(StringUtils.EMPTY);
}
setMapTheme();
}
dialog.cancel();
}
});
builder.show();
}
protected void setMapTheme() {
if (tileLayer == null || tileLayer.getTileLayer() == null) {
return;
}
if (!tileLayer.hasThemes()) {
tileLayer.getTileLayer().requestRedraw();
return;
}
final TileRendererLayer rendererLayer = (TileRendererLayer) tileLayer.getTileLayer();
final String themePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isEmpty(themePath)) {
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
} else {
try {
final XmlRenderTheme xmlRenderTheme = new ExternalRenderTheme(new File(themePath));
// Validate the theme file
RenderThemeHandler.getRenderTheme(AndroidGraphicFactory.INSTANCE, new DisplayModel(), xmlRenderTheme);
rendererLayer.setXmlRenderTheme(xmlRenderTheme);
} catch (final IOException e) {
Log.w("Failed to set render theme", e);
ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_file_unreadable));
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
} catch (final XmlPullParserException e) {
Log.w("render theme invalid", e);
ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_invalid));
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
}
}
tileCache.purge();
rendererLayer.requestRedraw();
}
private void changeMapSource(@NonNull final MapSource newSource) {
final MapSource oldSource = Settings.getMapSource();
final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource);
// Update MapSource in settings
Settings.setMapSource(newSource);
if (restartRequired) {
mapRestart();
} else if (mapView != null) { // changeMapSource can be called by onCreate()
switchTileLayer(newSource);
}
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
mapOptions.mapState = currentMapState();
finish();
mapOptions.startIntent(this, Settings.getMapProvider().getMapClass());
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private MapState currentMapState() {
if (mapView == null) {
return null;
}
final Geopoint mapCenter = mapView.getViewport().getCenter();
return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void switchTileLayer(final MapSource newSource) {
final ITileLayer oldLayer = this.tileLayer;
ITileLayer newLayer = null;
if (newSource instanceof MapsforgeMapSource) {
newLayer = ((MapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition);
}
// Exchange layer
if (newLayer != null) {
this.mapView.getModel().displayModel.setFixedTileSize(newLayer.getFixedTileSize());
final MapZoomControls zoomControls = mapView.getMapZoomControls();
zoomControls.setZoomLevelMax(newLayer.getZoomLevelMax());
zoomControls.setZoomLevelMin(newLayer.getZoomLevelMin());
final Layers layers = this.mapView.getLayerManager().getLayers();
int index = 0;
if (oldLayer != null) {
index = layers.indexOf(oldLayer.getTileLayer()) + 1;
}
layers.add(index, newLayer.getTileLayer());
this.tileLayer = newLayer;
this.setMapTheme();
} else {
this.tileLayer = null;
}
// Cleanup
if (oldLayer != null) {
this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer());
oldLayer.getTileLayer().onDestroy();
}
tileCache.purge();
}
private void resumeTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onResume();
}
}
private void pauseTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onPause();
}
}
private boolean tileLayerHasThemes() {
if (tileLayer != null) {
return tileLayer.hasThemes();
}
return false;
}
@Override
protected void onResume() {
super.onResume();
Log.d("NewMap: onResume");
resumeTileLayer();
}
@Override
protected void onStart() {
super.onStart();
Log.d("NewMap: onStart");
initializeLayers();
}
private void initializeLayers() {
switchTileLayer(Settings.getMapSource());
// History Layer
this.historyLayer = new HistoryLayer(trailHistory);
this.mapView.getLayerManager().getLayers().add(this.historyLayer);
// NavigationLayer
Geopoint navTarget = lastNavTarget;
if (navTarget == null) {
navTarget = mapOptions.coords;
if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport bounds = DataStore.getBounds(mapOptions.geocode);
if (bounds != null) {
navTarget = bounds.center;
}
}
}
this.navigationLayer = new NavigationLayer(navTarget);
this.mapView.getLayerManager().getLayers().add(this.navigationLayer);
// TapHandler
final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler());
this.mapView.getLayerManager().getLayers().add(tapHandlerLayer);
// Caches bundle
if (mapOptions.searchResult != null) {
this.caches = new CachesBundle(mapOptions.searchResult, this.mapView, this.mapHandlers);
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
this.caches = new CachesBundle(mapOptions.geocode, this.mapView, this.mapHandlers);
} else if (mapOptions.coords != null) {
this.caches = new CachesBundle(mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers);
} else {
caches = new CachesBundle(this.mapView, this.mapHandlers);
}
// Stored enabled map
caches.enableStoredLayers(mapOptions.isStoredEnabled);
// Live enabled map
caches.handleLiveLayers(mapOptions.isLiveEnabled);
// Position layer
this.positionLayer = new PositionLayer();
this.mapView.getLayerManager().getLayers().add(positionLayer);
//Distance view
this.distanceView = new DistanceView(navTarget, (TextView) findViewById(R.id.distance));
//Target view
this.targetView = new TargetView((TextView) findViewById(R.id.target), StringUtils.EMPTY, StringUtils.EMPTY);
final Geocache target = getCurrentTargetCache();
if (target != null) {
targetView.setTarget(target.getGeocode(), target.getName());
}
this.resumeDisposables.add(this.geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR));
}
@Override
public void onPause() {
Log.d("NewMap: onPause");
savePrefs();
pauseTileLayer();
super.onPause();
}
@Override
protected void onStop() {
Log.d("NewMap: onStop");
waitDialog = null;
terminateLayers();
super.onStop();
}
private void terminateLayers() {
this.resumeDisposables.clear();
this.caches.onDestroy();
this.caches = null;
this.mapView.getLayerManager().getLayers().remove(this.positionLayer);
this.positionLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.navigationLayer);
this.navigationLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.historyLayer);
this.historyLayer = null;
if (this.tileLayer != null) {
this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer());
this.tileLayer.getTileLayer().onDestroy();
this.tileLayer = null;
}
}
/**
* store caches, invoked by "store offline" menu item
*
* @param listIds the lists to store the caches in
*/
private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) {
final int count = geocodes.size();
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this);
waitDialog = new ProgressDialog(this);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage());
waitDialog.setMax(count);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(final DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
} catch (final Exception e) {
Log.e("CGeoMap.storeCaches.onCancel", e);
}
}
});
final float etaTime = count * 7.0f / 60.0f;
final int roundedEta = Math.round(etaTime);
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta));
}
loadDetailsHandler.setStart();
waitDialog.show();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds);
loadDetailsThread.start();
}
@Override
protected void onDestroy() {
Log.d("NewMap: onDestroy");
this.tileCache.destroy();
this.mapView.getModel().mapViewPosition.destroy();
this.mapView.destroy();
ResourceBitmapCacheMonitor.release();
Routing.disconnect();
super.onDestroy();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
final MapState state = prepareMapState();
outState.putParcelable(BUNDLE_MAP_STATE, state);
if (historyLayer != null) {
outState.putParcelableArrayList(BUNDLE_TRAIL_HISTORY, historyLayer.getHistory());
}
}
private MapState prepareMapState() {
return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void centerMap(final Geopoint geopoint) {
mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude()));
}
public Location getCoordinates() {
final LatLong center = mapView.getModel().mapViewPosition.getCenter();
final Location loc = new Location("newmap");
loc.setLatitude(center.latitude);
loc.setLongitude(center.longitude);
return loc;
}
private void initMyLocationSwitchButton(final CheckBox locSwitch) {
myLocSwitch = locSwitch;
/*
* TODO: Switch back to ImageSwitcher for animations?
* myLocSwitch.setFactory(this);
* myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
* myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
*/
myLocSwitch.setOnClickListener(new MyLocationListener(this));
switchMyLocationButton();
}
// switch My Location button image
private void switchMyLocationButton() {
myLocSwitch.setChecked(followMyLocation);
if (followMyLocation) {
myLocationInMiddle(Sensors.getInstance().currentGeo());
}
}
public void showAddWaypoint(final LatLong tapLatLong) {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude));
}
}
// set my location listener
private static class MyLocationListener implements View.OnClickListener {
@NonNull
private final WeakReference<NewMap> mapRef;
MyLocationListener(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
private void onFollowMyLocationClicked() {
followMyLocation = !followMyLocation;
final NewMap map = mapRef.get();
if (map != null) {
map.switchMyLocationButton();
}
}
@Override
public void onClick(final View view) {
onFollowMyLocationClicked();
}
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final GeoData geo) {
if (followMyLocation) {
centerMap(geo.getCoords());
}
}
private static final class DisplayHandler extends Handler {
@NonNull
private final WeakReference<NewMap> mapRef;
DisplayHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
map.setTitle();
map.setSubtitle();
break;
case INVALIDATE_MAP:
map.mapView.repaint();
break;
default:
break;
}
}
}
private void setTitle() {
final String title = calculateTitle();
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}
}
@NonNull
private String calculateTitle() {
if (mapOptions.isLiveEnabled) {
return res.getString(R.string.map_live);
}
if (mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return cache.getName();
}
}
return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_map));
}
private void setSubtitle() {
final String subtitle = calculateSubtitle();
if (StringUtils.isEmpty(subtitle)) {
return;
}
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(subtitle);
}
}
@NonNull
private String calculateSubtitle() {
if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return Formatter.formatMapSubtitle(cache);
}
}
// count caches in the sub title
final int visible = countVisibleCaches();
final int total = countTotalCaches();
final StringBuilder subtitle = new StringBuilder();
if (total != 0) {
if (visible != total && Settings.isDebug()) {
subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total));
} else {
subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible));
}
}
// if (Settings.isDebug() && lastSearchResult != null && StringUtils.isNotBlank(lastSearchResult.getUrl())) {
// subtitle.append(" [").append(lastSearchResult.getUrl()).append(']');
// }
return subtitle.toString();
}
private int countVisibleCaches() {
return caches != null ? caches.getVisibleCachesCount() : 0;
}
private int countTotalCaches() {
return caches != null ? caches.getCachesCount() : 0;
}
/**
* Updates the progress.
*/
private static final class ShowProgressHandler extends Handler {
private int counter = 0;
@NonNull
private final WeakReference<NewMap> mapRef;
ShowProgressHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
showProgress(false);
}
} else if (what == SHOW_PROGRESS) {
showProgress(true);
counter++;
}
}
private void showProgress(final boolean show) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
map.setProgressBarIndeterminateVisibility(show);
}
}
private static final class LoadDetailsHandler extends DisposableHandler {
private final int detailTotal;
private int detailProgress;
private long detailProgressTime;
private final WeakReference<NewMap> mapRef;
LoadDetailsHandler(final int detailTotal, final NewMap map) {
super();
this.detailTotal = detailTotal;
this.detailProgress = 0;
this.mapRef = new WeakReference<>(map);
}
public void setStart() {
detailProgressTime = System.currentTimeMillis();
}
@Override
public void handleRegularMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (msg.what == UPDATE_PROGRESS) {
if (detailProgress < detailTotal) {
detailProgress++;
}
if (map.waitDialog != null) {
final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
final int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
map.waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm));
} else {
final int minsRemaining = secondsRemaining / 60;
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) {
map.waitDialog.dismiss();
map.waitDialog.setOnCancelListener(null);
}
}
@Override
public void handleDispose() {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (map.loadDetailsThread != null) {
map.loadDetailsThread.stopIt();
}
}
}
// class: update location
private static class UpdateLoc extends GeoDirHandler {
// use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible
// minimum time in milliseconds between position overlay updates
private static final long MIN_UPDATE_INTERVAL = 500;
// minimum change of heading in grad for position overlay update
private static final float MIN_HEADING_DELTA = 15f;
// minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update
private static final float MIN_LOCATION_DELTA = 0.01f;
@NonNull
Location currentLocation = Sensors.getInstance().currentGeo();
float currentHeading;
private long timeLastPositionOverlayCalculation = 0;
/**
* weak reference to the outer class
*/
@NonNull
private final WeakReference<NewMap> mapRef;
UpdateLoc(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void updateGeoDir(@NonNull final GeoData geo, final float dir) {
currentLocation = geo;
currentHeading = AngleUtils.getDirectionNow(dir);
repaintPositionOverlay();
}
@NonNull
public Location getCurrentLocation() {
return currentLocation;
}
/**
* Repaint position overlay but only with a max frequency and if position or heading changes sufficiently.
*/
void repaintPositionOverlay() {
final long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) {
timeLastPositionOverlayCalculation = currentTimeMillis;
try {
final NewMap map = mapRef.get();
if (map != null) {
final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy();
final boolean needsRepaintForHeading = needsRepaintForHeading();
if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) {
map.centerMap(new Geopoint(currentLocation));
}
if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) {
map.historyLayer.setCoordinates(currentLocation);
map.navigationLayer.setCoordinates(currentLocation);
map.distanceView.setCoordinates(currentLocation);
map.positionLayer.setCoordinates(currentLocation);
map.positionLayer.setHeading(currentHeading);
map.positionLayer.requestRedraw();
}
}
} catch (final RuntimeException e) {
Log.w("Failed to update location", e);
}
}
}
boolean needsRepaintForHeading() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA;
}
boolean needsRepaintForDistanceOrAccuracy() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
final Location lastLocation = map.getCoordinates();
float dist = Float.MAX_VALUE;
if (lastLocation != null) {
if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) {
return true;
}
dist = currentLocation.distanceTo(lastLocation);
}
final float[] mapDimension = new float[1];
if (map.mapView.getWidth() < map.mapView.getHeight()) {
final double span = map.mapView.getLongitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension);
} else {
final double span = map.mapView.getLatitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension);
}
return dist > (mapDimension[0] * MIN_LOCATION_DELTA);
}
}
private static class DragHandler implements OnMapDragListener {
@NonNull
private final WeakReference<NewMap> mapRef;
DragHandler(@NonNull final NewMap parent) {
mapRef = new WeakReference<>(parent);
}
@Override
public void onDrag() {
final NewMap map = mapRef.get();
if (map != null && NewMap.followMyLocation) {
NewMap.followMyLocation = false;
map.switchMyLocationButton();
}
}
}
public void showSelection(@NonNull final List<GeoitemRef> items) {
if (items.isEmpty()) {
return;
}
if (items.size() == 1) {
showPopup(items.get(0));
return;
}
try {
final ArrayList<GeoitemRef> sorted = new ArrayList<>(items);
Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR);
final LayoutInflater inflater = LayoutInflater.from(this);
final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
final View view = convertView == null ? inflater.inflate(R.layout.cacheslist_item_select, parent, false) : convertView;
final TextView tv = (TextView) view.findViewById(R.id.text);
final GeoitemRef item = getItem(position);
tv.setText(item.getName());
//Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(item.getMarkerId(), 0, 0, 0);
final TextView infoView = (TextView) view.findViewById(R.id.info);
final StringBuilder text = new StringBuilder(item.getItemCode());
if (item.getType() == CoordinatesType.WAYPOINT && StringUtils.isNotEmpty(item.getGeocode())) {
text.append(Formatter.SEPARATOR).append(item.getGeocode());
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
text.append(Formatter.SEPARATOR).append(cache.getName());
}
}
infoView.setText(text.toString());
return view;
}
};
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(res.getString(R.string.map_select_multiple_items))
.setAdapter(adapter, new SelectionClickListener(sorted))
.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
} catch (final NotFoundException e) {
Log.e("NewMap.showSelection", e);
}
}
private class SelectionClickListener implements DialogInterface.OnClickListener {
@NonNull
private final List<GeoitemRef> items;
SelectionClickListener(@NonNull final List<GeoitemRef> items) {
this.items = items;
}
@Override
public void onClick(final DialogInterface dialog, final int which) {
if (which >= 0 && which < items.size()) {
final GeoitemRef item = items.get(which);
showPopup(item);
}
}
}
private void showPopup(final GeoitemRef item) {
if (item == null || StringUtils.isEmpty(item.getGeocode())) {
return;
}
try {
if (item.getType() == CoordinatesType.CACHE) {
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
final RequestDetailsThread requestDetailsThread = new RequestDetailsThread(cache, this);
requestDetailsThread.start();
return;
}
return;
}
if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) {
popupGeocodes.add(item.getGeocode());
WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode());
}
} catch (final NotFoundException e) {
Log.e("NewMap.showPopup", e);
}
}
@Nullable
private Geocache getSingleModeCache() {
if (StringUtils.isNotBlank(mapOptions.geocode)) {
return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
@Nullable
private Geocache getCurrentTargetCache() {
if (StringUtils.isNotBlank(targetGeocode)) {
return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
private void savePrefs() {
Settings.setMapZoom(MapMode.SINGLE, mapView.getMapZoomLevel());
Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter()));
}
private static class RequestDetailsThread extends Thread {
@NonNull
private final Geocache cache;
@NonNull
private final WeakReference<NewMap> map;
RequestDetailsThread(@NonNull final Geocache cache, @NonNull final NewMap map) {
this.cache = cache;
this.map = new WeakReference<>(map);
}
public boolean requestRequired() {
return CacheType.UNKNOWN == cache.getType() || cache.getDifficulty() == 0;
}
@Override
public void run() {
final NewMap map = this.map.get();
if (map == null) {
return;
}
if (requestRequired()) {
try {
/* final SearchResult search = */
GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode()));
} catch (final Exception ex) {
Log.w("Error requesting cache popup info", ex);
ActivityMixin.showToast(map, R.string.err_request_popup_info);
}
}
map.popupGeocodes.add(cache.getGeocode());
CachePopup.startActivityAllowTarget(map, cache.getGeocode());
}
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
private final DisposableHandler handler;
private final Collection<String> geocodes;
private final Set<Integer> listIds;
LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) {
this.handler = handler;
this.geocodes = geocodes;
this.listIds = listIds;
}
public void stopIt() {
handler.dispose();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
for (final String geocode : geocodes) {
try {
if (handler.isDisposed()) {
break;
}
if (!DataStore.isOffline(geocode, null)) {
Geocache.storeCache(null, geocode, listIds, false, handler);
}
} catch (final Exception e) {
Log.e("CGeoMap.LoadDetails.run", e);
} finally {
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
}
// we're done
caches.invalidate(geocodes);
invalidateOptionsMenuCompatible();
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) {
if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) {
final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO);
if (targetInfo != null) {
lastNavTarget = targetInfo.coords;
if (navigationLayer != null) {
navigationLayer.setDestination(targetInfo.coords);
navigationLayer.requestRedraw();
}
if (distanceView != null) {
distanceView.setDestination(targetInfo.coords);
distanceView.setCoordinates(geoDirUpdate.getCurrentLocation());
}
if (StringUtils.isNotBlank(targetInfo.geocode)) {
targetGeocode = targetInfo.geocode;
final Geocache target = getCurrentTargetCache();
targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY);
}
}
}
final List<String> changedGeocodes = new ArrayList<>();
String geocode = popupGeocodes.poll();
while (geocode != null) {
changedGeocodes.add(geocode);
geocode = popupGeocodes.poll();
}
if (caches != null) {
caches.invalidate(changedGeocodes);
}
}
}
private static class ResourceBitmapCacheMonitor {
private static int refCount = 0;
static synchronized void addRef() {
refCount++;
Log.d("ResourceBitmapCacheMonitor.addRef");
}
static synchronized void release() {
if (refCount > 0) {
refCount--;
Log.d("ResourceBitmapCacheMonitor.release");
if (refCount == 0) {
Log.d("ResourceBitmapCacheMonitor.clearResourceBitmaps");
AndroidResourceBitmap.clearResourceBitmaps();
}
}
}
}
}
| Fix #7033, NPE in mapsforge v6
This is rather a mitigation than a fix, as the context when 'caches'
can be null was not reproduced.
| main/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java | Fix #7033, NPE in mapsforge v6 | <ide><path>ain/src/cgeo/geocaching/maps/mapsforge/v6/NewMap.java
<ide> }
<ide> }
<ide>
<del> // we're done
<del> caches.invalidate(geocodes);
<add> // we're done, but map might even have been closed.
<add> if (caches != null) caches.invalidate(geocodes);
<ide> invalidateOptionsMenuCompatible();
<ide> handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
<ide> } |
|
Java | lgpl-2.1 | c76aca83af2e0b94d3be49352cbe425f059c9be2 | 0 | sbliven/biojava-sbliven,emckee2006/biojava,sbliven/biojava-sbliven,biojava/biojava,heuermh/biojava,sbliven/biojava-sbliven,heuermh/biojava,biojava/biojava,emckee2006/biojava,emckee2006/biojava,biojava/biojava,heuermh/biojava | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
/**
*
*/
package org.biojava.nbio.structure.align.ce;
//import static org.junit.Assert.*;
import org.biojava.nbio.structure.*;
import org.biojava.nbio.structure.align.model.AFPChain;
import org.biojava.nbio.structure.align.util.AtomCache;
import org.biojava.nbio.structure.io.PDBParseException;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
/**
* @author Spencer Bliven
*
*/
public class CeCPMainTest {
@Test
public void testFilterDuplicateAFPs() throws Exception {
int[][][] dupAlign = new int[1][2][];
int ca2len = 12;
dupAlign[0][0] = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13 };
dupAlign[0][1] = new int[] { 3, 5, 6, 7, 8, 9,10,11, 0+ca2len, 1+ca2len, 2+ca2len, 3+ca2len, 4+ca2len, 7+ca2len };
Atom[] ca1,ca2;
ca1 = makeDummyCA(dupAlign[0][0].length);
ca2 = makeDummyCA(ca2len);
ca2 = StructureTools.duplicateCA2(ca2);
AFPChain afp = makeDummyAFPChain(dupAlign, ca1, ca2);
CECPParameters params = new CECPParameters();
params.setMinCPLength(0);
// AFPChain newAFP = (AFPChain) filterDuplicateAFPs.invoke(null, afp, new CECalculator(null), ca1, ca2);
AFPChain newAFP = CeCPMain.filterDuplicateAFPs(afp, new CECalculator(null), ca1, ca2, params);
int[][][] align = newAFP.getOptAln();
int[] blkLen = newAFP.getOptLen();
// optimal alignment should be
// 1 2 3 4 5 6 7 | 8 9 10 11 12
// 5 6 7 8 9 10 11 | 0 1 2 3 4
int[][][] expected = new int[][][] {
new int[][] {
new int[] { 1, 2, 3, 4, 5, 6, 7, },
new int[] { 5, 6, 7, 8, 9, 10, 11, },
},
new int[][] {
new int[] { 8, 9, 10, 11, 12, },
new int[] { 0, 1, 2, 3, 4, },
},
};
int[] expectedLen = new int[] { expected[0][0].length, expected[1][0].length };
Assert.assertTrue(Arrays.deepEquals(expected, align));
Assert.assertTrue(Arrays.equals(expectedLen, blkLen));
}
@Test
public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, StructureException {
int[][][] startAln, filteredAln;
int[] filteredLen;
int ca2len;
ca2len = 10;
startAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,},
new int[] { 0, 3, 5, 6, 7, 8, 9, 0+ca2len, 1+ca2len, 2+ca2len, 3+ca2len,},
},
};
Atom[] ca1, ca2;
AFPChain afpChain,result;
ca1 = makeDummyCA(startAln[0][0].length);
ca2 = makeDummyCA(ca2len);
ca2 = StructureTools.duplicateCA2(ca2);
afpChain = makeDummyAFPChain(startAln, ca1, ca2);
// Best block with minCPlen 0-3
filteredAln = new int[][][] {
new int[][] {
new int[] { 1, 2, 3, 4, 5, 6,},
new int[] { 3, 5, 6, 7, 8, 9,},
},
new int[][] {
new int[] { 7, 8, 9,},
new int[] { 0, 1, 2,},
},
};
filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
CECPParameters params = new CECPParameters();
for(int minCPlength=0;minCPlength<4;minCPlength++) {
params.setMinCPLength(minCPlength);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + minCPlength, Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + minCPlength, Arrays.equals(filteredLen, result.getOptLen()));
}
// For minCPlength=4, filtering changes
params.setMinCPLength(4);
filteredAln = new int[][][] {
new int[][] {
new int[] { 2, 3, 4, 5, 6,},
new int[] { 5, 6, 7, 8, 9,},
},
new int[][] {
new int[] { 7, 8, 9,10,},
new int[] { 0, 1, 2, 3,},
},
};
filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// For minCPlength=5, filtering changes
params.setMinCPLength(5);
filteredAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2, 3, 4, 5, 6,},
new int[] { 0, 3, 5, 6, 7, 8, 9,},
},
};
filteredLen = new int[] { filteredAln[0][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
params.setMinCPLength(7);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// Eventually, no alignment!
params.setMinCPLength(8);
filteredAln = new int[0][][];
filteredLen = new int[0];
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
}
@Test
public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, StructureException {
int[][][] startAln, filteredAln;
int ca2len;
// minCPLen == 5
ca2len = 10;
startAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,},
new int[] { 6, 8, 9,10,11,12,13,14,16,17,19,},
},
};
// The longest alignment would include the second 0-3
// However, this leads to a short block
filteredAln = new int[][][] {
new int[][] {
new int[] { 1, 2,},
new int[] { 8, 9,},
},
new int[][] {
new int[] { 3, 4, 5, 6, 7, 8, 9,},
new int[] { 0, 1, 2, 3, 4, 6, 7,},
},
};
int[] filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
Atom[] ca1, ca2;
AFPChain afpChain,result;
ca1 = makeDummyCA(startAln[0][0].length);
ca2 = makeDummyCA(ca2len);
ca2 = StructureTools.duplicateCA2(ca2);
afpChain = makeDummyAFPChain(startAln, ca1, ca2);
CECPParameters params = new CECPParameters();
for(int minCPlength=0;minCPlength<3;minCPlength++) {
params.setMinCPLength(minCPlength);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
}
// For minCPlength=3, filtering changes
params.setMinCPLength(3);
filteredAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2,},
new int[] { 6, 8, 9,},
},
new int[][] {
new int[] { 3, 4, 5, 6, 7,},
new int[] { 0, 1, 2, 3, 4,},
},
};
filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// For minCPlength=4, filtering changes
params.setMinCPLength(5);
filteredAln = new int[][][] {
new int[][] {
new int[] { 3, 4, 5, 6, 7, 8, 9,10,},
new int[] { 0, 1, 2, 3, 4, 6, 7, 9,},
},
};
filteredLen = new int[] { filteredAln[0][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
params.setMinCPLength(8);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// Eventually, no alignment!
params.setMinCPLength(9);
filteredAln = new int[0][][];
filteredLen = new int[0];
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
}
/**
* Creates a minimal AFPChain from the specified alignment and proteins
* @param dupAlign
* @param ca1
* @param ca2
* @return
*/
private AFPChain makeDummyAFPChain(int[][][] dupAlign, Atom[] ca1,Atom[] ca2) {
AFPChain afp = new AFPChain(AFPChain.UNKNOWN_ALGORITHM);
afp.setOptAln(dupAlign);
afp.setOptLength(dupAlign[0][1].length);
afp.setCa1Length(ca1.length);
afp.setCa2Length(ca2.length);
afp.setBlockNum(1);
afp.setOptLen(new int[] {dupAlign[0][1].length});
return afp;
}
@Test
public void testCalculateMinCP() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int[] block;
int ca2len;
block = new int[] { 4,5,6,8,11,12,14,15, };
ca2len = 10;
int minCPlength;
CeCPMain.CPRange cpRange;
minCPlength = 0;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 11, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 8, cpRange.c);
minCPlength = 1;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 8, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 11, cpRange.c);
minCPlength = 2;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 6, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 12, cpRange.c);
minCPlength = 3;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 5, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 14, cpRange.c);
minCPlength = 4;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 4, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 15, cpRange.c);
minCPlength = 5;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, -1, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 20, cpRange.c);
block = new int[] {0,9,10,19};
ca2len = 10;
minCPlength = 0;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 10, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 9, cpRange.c);
minCPlength = 1;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 9, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 10, cpRange.c);
minCPlength = 2;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 0, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 19, cpRange.c);
minCPlength = 3;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, -1, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 20, cpRange.c);
minCPlength = 4;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, -1, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 20, cpRange.c);
}
/**
* Makes dummy CA atoms at 1A intervals
*
* @param len
* @return
* @throws PDBParseException
*/
private Atom[] makeDummyCA(int len) throws PDBParseException {
Atom[] ca1;
Chain chain1 = new ChainImpl();
chain1.setId("A");
chain1.setName("A");
//Some dummy Atoms. Just check they're unique
ca1 = new Atom[len];
for(int i=0;i<len;i++) {
ca1[i] = new AtomImpl();
ca1[i].setName("CA");
ca1[i].setCoords(new double[] { i, 0, 0 });
Group aa = new AminoAcidImpl();
aa.setPDBName("GLY");
aa.setResidueNumber( ResidueNumber.fromString(i+""));
aa.addAtom(ca1[i]);
chain1.addGroup(aa);
}
return ca1;
}
@Test
public void testCECP1() throws IOException, StructureException{
AtomCache cache = new AtomCache();
// since BioJava 6.0.0, there's no PDP provider. The below corresponds to domain "PDP:3A2KAc"
Structure structure1 = cache.getStructure("3A2K.A_234-333");
// since BioJava 6.0.0, there's no RemoteSCOP provider. The below corresponds to domain "d1wy5a2"
Structure structure2 = cache.getStructure("1WY5.A_217-311");
CeCPMain algorithm = new CeCPMain();
Atom[] ca1 = StructureTools.getAtomCAArray(structure1);
Atom[] ca2 = StructureTools.getAtomCAArray(structure2);
AFPChain afpChain = algorithm.align(ca1, ca2);
CECalculator calculator = algorithm.getCECalculator();
// System.out.println(calculator.get);
//StructureAlignmentJmol jmol =
//StructureAlignmentDisplay.display(afpChain, ca1, ca2);
if ( ! (afpChain.getBlockNum() == 1)){
System.out.println(calculator.getLcmp());
System.out.println(afpChain.toFatcat(ca1, ca2));
}
Assert.assertEquals(1, afpChain.getBlockNum());
}
}
| biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
/**
*
*/
package org.biojava.nbio.structure.align.ce;
//import static org.junit.Assert.*;
import org.biojava.nbio.structure.*;
import org.biojava.nbio.structure.align.model.AFPChain;
import org.biojava.nbio.structure.align.util.AtomCache;
import org.biojava.nbio.structure.io.PDBParseException;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Spencer Bliven
*
*/
public class CeCPMainTest {
@Test
public void testFilterDuplicateAFPs() throws Exception {
int[][][] dupAlign = new int[1][2][];
int ca2len = 12;
dupAlign[0][0] = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13 };
dupAlign[0][1] = new int[] { 3, 5, 6, 7, 8, 9,10,11, 0+ca2len, 1+ca2len, 2+ca2len, 3+ca2len, 4+ca2len, 7+ca2len };
Atom[] ca1,ca2;
ca1 = makeDummyCA(dupAlign[0][0].length);
ca2 = makeDummyCA(ca2len);
ca2 = StructureTools.duplicateCA2(ca2);
AFPChain afp = makeDummyAFPChain(dupAlign, ca1, ca2);
CECPParameters params = new CECPParameters();
params.setMinCPLength(0);
// AFPChain newAFP = (AFPChain) filterDuplicateAFPs.invoke(null, afp, new CECalculator(null), ca1, ca2);
AFPChain newAFP = CeCPMain.filterDuplicateAFPs(afp, new CECalculator(null), ca1, ca2, params);
int[][][] align = newAFP.getOptAln();
int[] blkLen = newAFP.getOptLen();
// optimal alignment should be
// 1 2 3 4 5 6 7 | 8 9 10 11 12
// 5 6 7 8 9 10 11 | 0 1 2 3 4
int[][][] expected = new int[][][] {
new int[][] {
new int[] { 1, 2, 3, 4, 5, 6, 7, },
new int[] { 5, 6, 7, 8, 9, 10, 11, },
},
new int[][] {
new int[] { 8, 9, 10, 11, 12, },
new int[] { 0, 1, 2, 3, 4, },
},
};
int[] expectedLen = new int[] { expected[0][0].length, expected[1][0].length };
Assert.assertTrue(Arrays.deepEquals(expected, align));
Assert.assertTrue(Arrays.equals(expectedLen, blkLen));
}
@Test
public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, StructureException {
int[][][] startAln, filteredAln;
int[] filteredLen;
int ca2len;
ca2len = 10;
startAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,},
new int[] { 0, 3, 5, 6, 7, 8, 9, 0+ca2len, 1+ca2len, 2+ca2len, 3+ca2len,},
},
};
Atom[] ca1, ca2;
AFPChain afpChain,result;
ca1 = makeDummyCA(startAln[0][0].length);
ca2 = makeDummyCA(ca2len);
ca2 = StructureTools.duplicateCA2(ca2);
afpChain = makeDummyAFPChain(startAln, ca1, ca2);
// Best block with minCPlen 0-3
filteredAln = new int[][][] {
new int[][] {
new int[] { 1, 2, 3, 4, 5, 6,},
new int[] { 3, 5, 6, 7, 8, 9,},
},
new int[][] {
new int[] { 7, 8, 9,},
new int[] { 0, 1, 2,},
},
};
filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
CECPParameters params = new CECPParameters();
for(int minCPlength=0;minCPlength<4;minCPlength++) {
params.setMinCPLength(minCPlength);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + minCPlength, Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + minCPlength, Arrays.equals(filteredLen, result.getOptLen()));
}
// For minCPlength=4, filtering changes
params.setMinCPLength(4);
filteredAln = new int[][][] {
new int[][] {
new int[] { 2, 3, 4, 5, 6,},
new int[] { 5, 6, 7, 8, 9,},
},
new int[][] {
new int[] { 7, 8, 9,10,},
new int[] { 0, 1, 2, 3,},
},
};
filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// For minCPlength=5, filtering changes
params.setMinCPLength(5);
filteredAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2, 3, 4, 5, 6,},
new int[] { 0, 3, 5, 6, 7, 8, 9,},
},
};
filteredLen = new int[] { filteredAln[0][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
params.setMinCPLength(7);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// Eventually, no alignment!
params.setMinCPLength(8);
filteredAln = new int[0][][];
filteredLen = new int[0];
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
}
@Test
public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, StructureException {
int[][][] startAln, filteredAln;
int ca2len;
// minCPLen == 5
ca2len = 10;
startAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,},
new int[] { 6, 8, 9,10,11,12,13,14,16,17,19,},
},
};
// The longest alignment would include the second 0-3
// However, this leads to a short block
filteredAln = new int[][][] {
new int[][] {
new int[] { 1, 2,},
new int[] { 8, 9,},
},
new int[][] {
new int[] { 3, 4, 5, 6, 7, 8, 9,},
new int[] { 0, 1, 2, 3, 4, 6, 7,},
},
};
int[] filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
Atom[] ca1, ca2;
AFPChain afpChain,result;
ca1 = makeDummyCA(startAln[0][0].length);
ca2 = makeDummyCA(ca2len);
ca2 = StructureTools.duplicateCA2(ca2);
afpChain = makeDummyAFPChain(startAln, ca1, ca2);
CECPParameters params = new CECPParameters();
for(int minCPlength=0;minCPlength<3;minCPlength++) {
params.setMinCPLength(minCPlength);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
}
// For minCPlength=3, filtering changes
params.setMinCPLength(3);
filteredAln = new int[][][] {
new int[][] {
new int[] { 0, 1, 2,},
new int[] { 6, 8, 9,},
},
new int[][] {
new int[] { 3, 4, 5, 6, 7,},
new int[] { 0, 1, 2, 3, 4,},
},
};
filteredLen = new int[] { filteredAln[0][0].length, filteredAln[1][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// For minCPlength=4, filtering changes
params.setMinCPLength(5);
filteredAln = new int[][][] {
new int[][] {
new int[] { 3, 4, 5, 6, 7, 8, 9,10,},
new int[] { 0, 1, 2, 3, 4, 6, 7, 9,},
},
};
filteredLen = new int[] { filteredAln[0][0].length };
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
params.setMinCPLength(8);
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
// Eventually, no alignment!
params.setMinCPLength(9);
filteredAln = new int[0][][];
filteredLen = new int[0];
result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params);
Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln()));
Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen()));
}
/**
* Creates a minimal AFPChain from the specified alignment and proteins
* @param dupAlign
* @param ca1
* @param ca2
* @return
*/
private AFPChain makeDummyAFPChain(int[][][] dupAlign, Atom[] ca1,Atom[] ca2) {
AFPChain afp = new AFPChain(AFPChain.UNKNOWN_ALGORITHM);
afp.setOptAln(dupAlign);
afp.setOptLength(dupAlign[0][1].length);
afp.setCa1Length(ca1.length);
afp.setCa2Length(ca2.length);
afp.setBlockNum(1);
afp.setOptLen(new int[] {dupAlign[0][1].length});
return afp;
}
@Test
public void testCalculateMinCP() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
int[] block;
int ca2len;
block = new int[] { 4,5,6,8,11,12,14,15, };
ca2len = 10;
int minCPlength;
CeCPMain.CPRange cpRange;
minCPlength = 0;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 11, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 8, cpRange.c);
minCPlength = 1;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 8, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 11, cpRange.c);
minCPlength = 2;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 6, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 12, cpRange.c);
minCPlength = 3;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 5, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 14, cpRange.c);
minCPlength = 4;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 4, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 15, cpRange.c);
minCPlength = 5;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, -1, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 20, cpRange.c);
block = new int[] {0,9,10,19};
ca2len = 10;
minCPlength = 0;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 10, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 9, cpRange.c);
minCPlength = 1;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 9, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 10, cpRange.c);
minCPlength = 2;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, 0, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 19, cpRange.c);
minCPlength = 3;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, -1, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 20, cpRange.c);
minCPlength = 4;
cpRange = CeCPMain.calculateMinCP(block, block.length, ca2len, minCPlength);
Assert.assertEquals("Wrong minCPnterm for minCPlen=" + minCPlength, -1, cpRange.n);
Assert.assertEquals("Wrong minCPcterm for minCPlen=" + minCPlength, 20, cpRange.c);
}
/**
* Makes dummy CA atoms at 1A intervals
*
* @param len
* @return
* @throws PDBParseException
*/
private Atom[] makeDummyCA(int len) throws PDBParseException {
Atom[] ca1;
Chain chain1 = new ChainImpl();
chain1.setId("A");
chain1.setName("A");
//Some dummy Atoms. Just check they're unique
ca1 = new Atom[len];
for(int i=0;i<len;i++) {
ca1[i] = new AtomImpl();
ca1[i].setName("CA");
ca1[i].setCoords(new double[] { i, 0, 0 });
Group aa = new AminoAcidImpl();
aa.setPDBName("GLY");
aa.setResidueNumber( ResidueNumber.fromString(i+""));
aa.addAtom(ca1[i]);
chain1.addGroup(aa);
}
return ca1;
}
@Test
public void testCECP1() throws IOException, StructureException{
String pdb1 = "3A2K";
//String name1 = "PDP:3A2KAc"; // A : 234-333
String pdb2 = "1WY5";
//String name2 = "d1wy5a2"; // A : 217-311
AtomCache cache = new AtomCache();
// since BioJava 6.0.0, there's no PDP provider. The below corresponds to domain "PDP:3A2KAc"
List<ResidueRange> ranges = new ArrayList<>();
ranges.add(new ResidueRange("A", new ResidueNumber("A",234, null), new ResidueNumber("A", 333, null)));
SubstructureIdentifier ssi = new SubstructureIdentifier(pdb1, ranges);
Structure structure1 = cache.getStructure(pdb1);
ssi.reduce(structure1);
// since BioJava 6.0.0, there's no RemoteSCOP provider. The below corresponds to domain "d1wy5a2"
ranges = new ArrayList<>();
ranges.add(new ResidueRange("A", new ResidueNumber("A",217, null), new ResidueNumber("A", 311, null)));
ssi = new SubstructureIdentifier(pdb2, ranges);
Structure structure2 = cache.getStructure(pdb2);
ssi.reduce(structure2);
CeCPMain algorithm = new CeCPMain();
Atom[] ca1 = StructureTools.getAtomCAArray(structure1);
Atom[] ca2 = StructureTools.getAtomCAArray(structure2);
AFPChain afpChain = algorithm.align(ca1, ca2);
CECalculator calculator = algorithm.getCECalculator();
// System.out.println(calculator.get);
//StructureAlignmentJmol jmol =
//StructureAlignmentDisplay.display(afpChain, ca1, ca2);
if ( ! (afpChain.getBlockNum() == 1)){
System.out.println(calculator.getLcmp());
System.out.println(afpChain.toFatcat(ca1, ca2));
}
Assert.assertEquals(1, afpChain.getBlockNum());
}
}
| Better way of specifying hard-coded domains
| biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java | Better way of specifying hard-coded domains | <ide><path>iojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java
<ide>
<ide> import java.io.IOException;
<ide> import java.lang.reflect.InvocationTargetException;
<del>import java.util.ArrayList;
<ide> import java.util.Arrays;
<del>import java.util.List;
<ide>
<ide>
<ide> /**
<ide> @Test
<ide> public void testCECP1() throws IOException, StructureException{
<ide>
<del> String pdb1 = "3A2K";
<del> //String name1 = "PDP:3A2KAc"; // A : 234-333
<del> String pdb2 = "1WY5";
<del> //String name2 = "d1wy5a2"; // A : 217-311
<del>
<ide> AtomCache cache = new AtomCache();
<ide>
<ide> // since BioJava 6.0.0, there's no PDP provider. The below corresponds to domain "PDP:3A2KAc"
<del> List<ResidueRange> ranges = new ArrayList<>();
<del> ranges.add(new ResidueRange("A", new ResidueNumber("A",234, null), new ResidueNumber("A", 333, null)));
<del> SubstructureIdentifier ssi = new SubstructureIdentifier(pdb1, ranges);
<del> Structure structure1 = cache.getStructure(pdb1);
<del> ssi.reduce(structure1);
<add> Structure structure1 = cache.getStructure("3A2K.A_234-333");
<ide>
<ide> // since BioJava 6.0.0, there's no RemoteSCOP provider. The below corresponds to domain "d1wy5a2"
<del> ranges = new ArrayList<>();
<del> ranges.add(new ResidueRange("A", new ResidueNumber("A",217, null), new ResidueNumber("A", 311, null)));
<del> ssi = new SubstructureIdentifier(pdb2, ranges);
<del> Structure structure2 = cache.getStructure(pdb2);
<del> ssi.reduce(structure2);
<add> Structure structure2 = cache.getStructure("1WY5.A_217-311");
<ide>
<ide> CeCPMain algorithm = new CeCPMain();
<ide> |
|
Java | apache-2.0 | ef018c0385452635fed17e880d802fa30e623e10 | 0 | epiphany27/SeriesGuide,UweTrottmann/SeriesGuide,UweTrottmann/SeriesGuide,r00t-user/SeriesGuide,0359xiaodong/SeriesGuide,hoanganhx86/SeriesGuide,artemnikitin/SeriesGuide |
package com.battlelancer.seriesguide.util;
import com.battlelancer.seriesguide.Constants;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.getglueapi.GetGlue;
import com.battlelancer.seriesguide.getglueapi.PrepareRequestTokenActivity;
import com.battlelancer.seriesguide.provider.SeriesContract.Episodes;
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences;
import com.battlelancer.seriesguide.ui.ShowInfoActivity;
import com.jakewharton.apibuilder.ApiException;
import com.jakewharton.trakt.ServiceManager;
import com.jakewharton.trakt.TraktException;
import com.jakewharton.trakt.entities.Response;
import com.jakewharton.trakt.enumerations.Rating;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.SupportActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
public class ShareUtils {
public static final String KEY_GETGLUE_COMMENT = "com.battlelancer.seriesguide.getglue.comment";
public static final String KEY_GETGLUE_IMDBID = "com.battlelancer.seriesguide.getglue.imdbid";
protected static final String TAG = "ShareUtils";
public enum ShareMethod {
CHECKIN_GETGLUE(0, R.string.menu_checkin_getglue, R.drawable.ic_getglue),
CHECKIN_TRAKT(1, R.string.menu_checkin_trakt, R.drawable.ic_trakt),
MARKSEEN_TRAKT(2, R.string.menu_markseen_trakt, R.drawable.ic_trakt_seen),
RATE_TRAKT(3, R.string.menu_rate_trakt, R.drawable.trakt_love_large),
OTHER_SERVICES(4, R.string.menu_share_others, R.drawable.ic_action_share);
ShareMethod(int index, int titleRes, int drawableRes) {
this.index = index;
this.titleRes = titleRes;
this.drawableRes = drawableRes;
}
public int index;
public int titleRes;
public int drawableRes;
}
/**
* Share an episode via the given {@link ShareMethod}.
*
* @param activity
* @param shareData - a {@link Bundle} including all
* {@link ShareUtils.ShareItems}
* @param shareMethod the {@link ShareMethod} to use
*/
public static void onShareEpisode(SupportActivity activity, Bundle shareData,
ShareMethod shareMethod) {
final FragmentManager fm = activity.getSupportFragmentManager();
final String imdbId = shareData.getString(ShareUtils.ShareItems.IMDBID);
final String sharestring = shareData.getString(ShareUtils.ShareItems.SHARESTRING);
// save used share method, so we can use it later for the quick share
// button
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.asActivity());
prefs.edit().putInt(SeriesGuidePreferences.KEY_LAST_USED_SHARE_METHOD, shareMethod.index)
.commit();
switch (shareMethod) {
case CHECKIN_GETGLUE: {
// GetGlue check in
if (imdbId.length() != 0) {
showGetGlueDialog(fm, shareData);
} else {
Toast.makeText(activity.asActivity(),
activity.getString(R.string.checkin_impossible), Toast.LENGTH_LONG)
.show();
}
break;
}
case CHECKIN_TRAKT: {
// trakt check in
// DialogFragment.show() will take care of
// adding the fragment
// in a transaction. We also want to remove
// any currently showing
// dialog, so make our own transaction and
// take care of that here.
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
ProgressDialog newFragment = ProgressDialog.newInstance();
// start the trakt check in task, add the
// dialog as listener
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.CHECKIN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData, newFragment).execute();
newFragment.show(ft, "progress-dialog");
break;
}
case MARKSEEN_TRAKT: {
// trakt mark as seen
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.SEEN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData).execute();
break;
}
case RATE_TRAKT: {
// trakt rate
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.RATE_EPISODE.index());
TraktRateDialogFragment newFragment = TraktRateDialogFragment
.newInstance(shareData);
FragmentTransaction ft = fm.beginTransaction();
newFragment.show(ft, "traktratedialog");
break;
}
case OTHER_SERVICES: {
// Android apps
String text = sharestring;
if (imdbId.length() != 0) {
text += " " + ShowInfoActivity.IMDB_TITLE_URL + imdbId;
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(i,
activity.getString(R.string.share_episode)));
break;
}
}
}
public static void showGetGlueDialog(FragmentManager manager, Bundle shareData) {
// Create and show the dialog.
GetGlueDialogFragment newFragment = GetGlueDialogFragment.newInstance(shareData);
FragmentTransaction ft = manager.beginTransaction();
newFragment.show(ft, "getgluedialog");
}
public static class GetGlueDialogFragment extends DialogFragment {
public static GetGlueDialogFragment newInstance(Bundle shareData) {
GetGlueDialogFragment f = new GetGlueDialogFragment();
f.setArguments(shareData);
return f;
}
private EditText input;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String episodestring = getArguments().getString(ShareItems.EPISODESTRING);
final String imdbId = getArguments().getString(ShareItems.IMDBID);
input = new EditText(getActivity());
input.setMinLines(3);
input.setGravity(Gravity.TOP);
input.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(140)
});
if (savedInstanceState != null) {
input.setText(savedInstanceState.getString("inputtext"));
} else {
input.setText(episodestring);
}
return new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.comment))
.setView(input)
.setPositiveButton(R.string.checkin, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onGetGlueCheckIn(getActivity(), input.getText().toString(), imdbId);
}
}).setNegativeButton(android.R.string.cancel, null).create();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("inputtext", input.getText().toString());
}
}
public static void onGetGlueCheckIn(final Activity activity, final String comment,
final String imdbId) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.getApplicationContext());
if (GetGlue.isAuthenticated(prefs)) {
new Thread(new Runnable() {
public void run() {
try {
GetGlue.checkIn(prefs, imdbId, comment, activity);
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity,
activity.getString(R.string.checkinsuccess),
Toast.LENGTH_SHORT).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Success", 0);
} catch (final Exception e) {
Log.e(TAG, "GetGlue Check-In failed");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
activity,
activity.getString(R.string.checkinfailed) + " - "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Failed", 0);
}
}
}).start();
} else {
Intent i = new Intent(activity, PrepareRequestTokenActivity.class);
i.putExtra(ShareUtils.KEY_GETGLUE_IMDBID, imdbId);
i.putExtra(ShareUtils.KEY_GETGLUE_COMMENT, comment);
activity.startActivity(i);
}
}
public interface ShareItems {
String SEASON = "season";
String IMDBID = "imdbId";
String SHARESTRING = "sharestring";
String EPISODESTRING = "episodestring";
String EPISODE = "episode";
String TVDBID = "tvdbid";
String RATING = "rating";
String TRAKTACTION = "traktaction";
}
public static String onCreateShareString(Context context, final Cursor episode) {
String season = episode.getString(episode.getColumnIndexOrThrow(Episodes.SEASON));
String number = episode.getString(episode.getColumnIndexOrThrow(Episodes.NUMBER));
String title = episode.getString(episode.getColumnIndexOrThrow(Episodes.TITLE));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return Utils.getNextEpisodeString(prefs, season, number, title);
}
public static void onAddCalendarEvent(Context context, String title, String description,
long airtime, String runtime) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", title);
intent.putExtra("description", description);
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
Calendar cal = Utils.getAirtimeCalendar(airtime, prefs);
long startTime = cal.getTimeInMillis();
long endTime = startTime + Long.valueOf(runtime) * DateUtils.MINUTE_IN_MILLIS;
intent.putExtra("beginTime", startTime);
intent.putExtra("endTime", endTime);
context.startActivity(intent);
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Success", 0);
} catch (Exception e) {
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Failed", 0);
Toast.makeText(context, context.getString(R.string.addtocalendar_failed),
Toast.LENGTH_SHORT).show();
}
}
public static String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public enum TraktAction {
SEEN_EPISODE(0), RATE_EPISODE(1), CHECKIN_EPISODE(2);
final private int mIndex;
private TraktAction(int index) {
mIndex = index;
}
public int index() {
return mIndex;
}
}
public interface TraktStatus {
String SUCCESS = "success";
String FAILURE = "failure";
}
public static class TraktTask extends AsyncTask<Void, Void, Response> {
private final Context mContext;
private final FragmentManager mManager;
private final Bundle mTraktData;
private OnTaskFinishedListener mListener;
public interface OnTaskFinishedListener {
public void onTaskFinished();
}
/**
* Do the specified TraktAction. traktData should include all required
* parameters.
*
* @param context
* @param manager
* @param traktData
* @param action
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData) {
mContext = context;
mManager = manager;
mTraktData = traktData;
}
/**
* Specify a listener which will be notified once any activity context
* dependent work is completed.
*
* @param context
* @param manager
* @param traktData
* @param listener
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData,
OnTaskFinishedListener listener) {
this(context, manager, traktData);
mListener = listener;
}
@Override
protected Response doInBackground(Void... params) {
if (!isTraktCredentialsValid(mContext)) {
// return null, so onPostExecute displays a credentials dialog
// which later calls us again.
return null;
}
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(mContext, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = mContext.getString(R.string.trakt_decryptfail);
return r;
}
// get some values
final int tvdbid = mTraktData.getInt(ShareItems.TVDBID);
final int season = mTraktData.getInt(ShareItems.SEASON);
final int episode = mTraktData.getInt(ShareItems.EPISODE);
final TraktAction action = TraktAction.values()[mTraktData
.getInt(ShareItems.TRAKTACTION)];
// last chance to abort (return value thrown away)
if (isCancelled()) {
return null;
}
try {
Response r = null;
switch (action) {
case CHECKIN_EPISODE: {
r = manager.showService().checkin(tvdbid).season(season).episode(episode)
.fire();
break;
}
case SEEN_EPISODE: {
manager.showService().episodeSeen(tvdbid).episode(season, episode).fire();
r = new Response();
r.status = TraktStatus.SUCCESS;
r.message = mContext.getString(R.string.trakt_seen);
break;
}
case RATE_EPISODE: {
final Rating rating = Rating.fromValue(mTraktData
.getString(ShareItems.RATING));
r = manager.rateService().episode(tvdbid).season(season).episode(episode)
.rating(rating).fire();
break;
}
}
return r;
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
}
@Override
protected void onPostExecute(Response r) {
if (r != null) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(mContext,
mContext.getString(R.string.trakt_success) + ": " + r.message,
Toast.LENGTH_SHORT).show();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
if (r.wait != 0) {
// looks like a check in is in progress
TraktCancelCheckinDialogFragment newFragment = TraktCancelCheckinDialogFragment
.newInstance(mTraktData, r.wait);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "cancel-checkin-dialog");
} else {
// well, something went wrong
Toast.makeText(mContext,
mContext.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
} else {
// credentials are invalid
TraktCredentialsDialogFragment newFragment = TraktCredentialsDialogFragment
.newInstance(mTraktData);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "traktdialog");
}
// tell a potential listener that our work is done
if (mListener != null) {
mListener.onTaskFinished();
}
}
}
public static class TraktCredentialsDialogFragment extends DialogFragment {
private boolean isForwardingGivenTask;
public static TraktCredentialsDialogFragment newInstance(Bundle traktData) {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.setArguments(traktData);
f.isForwardingGivenTask = true;
return f;
}
public static TraktCredentialsDialogFragment newInstance() {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.isForwardingGivenTask = false;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, null);
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
((EditText) layout.findViewById(R.id.username)).setText(username);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(layout);
builder.setTitle("trakt.tv");
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
((CheckBox) layout.findViewById(R.id.checkNewAccount))
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
builder.setPositiveButton(R.string.save, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String username = ((EditText) layout.findViewById(R.id.username))
.getText().toString();
final String passwordHash = ShareUtils.toSHA1(((EditText) layout
.findViewById(R.id.password)).getText().toString().getBytes());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout
.findViewById(R.id.checkNewAccount)).isChecked();
AsyncTask<String, Void, Response> accountValidatorTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
// SHA of any password is always non-empty
if (username.length() == 0) {
return null;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final ServiceManager manager = new ServiceManager();
manager.setApiKey(getResources().getString(R.string.trakt_apikey));
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService()
.create(username, passwordHash, email).fire();
} else {
// validate existing account
response = manager.accountService().test().fire();
}
} catch (TraktException te) {
response = te.getResponse();
} catch (ApiException ae) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
if (response != null) {
String passwordEncr;
// try to encrypt the password before storing it
try {
passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
} catch (Exception e) {
passwordEncr = "";
}
// prepare writing credentials to settings
Editor editor = prefs.edit();
editor.putString(SeriesGuidePreferences.KEY_TRAKTUSER, username)
.putString(SeriesGuidePreferences.KEY_TRAKTPWD,
passwordEncr);
if (response.getStatus().equalsIgnoreCase("success")
&& passwordEncr.length() != 0 && editor.commit()) {
// all went through
Toast.makeText(context,
response.getStatus() + ": " + response.getMessage(),
Toast.LENGTH_SHORT).show();
// set new auth data for service manager
try {
Utils.getServiceManagerWithAuth(context, true);
} catch (Exception e) {
// we don't care
}
} else {
Toast.makeText(context,
response.getStatus() + ": " + response.getError(),
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context,
context.getString(R.string.trakt_generalerror),
Toast.LENGTH_LONG).show();
}
if (isForwardingGivenTask) {
// relaunch the trakt task which called us
new TraktTask(context, fm, args).execute();
}
}
};
accountValidatorTask.execute();
}
});
builder.setNegativeButton(R.string.dontsave, null);
return builder.create();
}
}
public static class TraktCancelCheckinDialogFragment extends DialogFragment {
private int mWait;
public static TraktCancelCheckinDialogFragment newInstance(Bundle traktData, int wait) {
TraktCancelCheckinDialogFragment f = new TraktCancelCheckinDialogFragment();
f.setArguments(traktData);
f.mWait = wait;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(context.getString(R.string.traktcheckin_inprogress,
DateUtils.formatElapsedTime(mWait)));
builder.setPositiveButton(R.string.traktcheckin_cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AsyncTask<String, Void, Response> cancelCheckinTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(context, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.trakt_decryptfail);
return r;
}
Response response;
try {
response = manager.showService().cancelCheckin().fire();
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
return response;
}
@Override
protected void onPostExecute(Response r) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(
context,
context.getString(R.string.trakt_success) + ": "
+ r.message, Toast.LENGTH_SHORT).show();
// relaunch the trakt task which called us to
// try the check in again
new TraktTask(context, fm, args).execute();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
// well, something went wrong
Toast.makeText(context,
context.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
};
cancelCheckinTask.execute();
}
});
builder.setNegativeButton(R.string.traktcheckin_wait, null);
return builder.create();
}
}
public static class TraktRateDialogFragment extends DialogFragment {
public static TraktRateDialogFragment newInstance(Bundle traktData) {
TraktRateDialogFragment f = new TraktRateDialogFragment();
f.setArguments(traktData);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity();
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_rate_dialog, null);
final Button totallyNinja = (Button) layout.findViewById(R.id.totallyninja);
final Button weakSauce = (Button) layout.findViewById(R.id.weaksauce);
totallyNinja.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Love;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
weakSauce.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Hate;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
builder = new AlertDialog.Builder(context);
builder.setView(layout);
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
}
public static class ProgressDialog extends DialogFragment implements
TraktTask.OnTaskFinishedListener {
public static ProgressDialog newInstance() {
ProgressDialog f = new ProgressDialog();
f.setCancelable(false);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.progress_dialog, container, false);
return v;
}
@Override
public void onTaskFinished() {
if (isVisible()) {
dismiss();
}
}
}
public static boolean isTraktCredentialsValid(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
String password = prefs.getString(SeriesGuidePreferences.KEY_TRAKTPWD, "");
return (!username.equalsIgnoreCase("") && !password.equalsIgnoreCase(""));
}
}
| SeriesGuide/src/com/battlelancer/seriesguide/util/ShareUtils.java |
package com.battlelancer.seriesguide.util;
import com.battlelancer.seriesguide.Constants;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.getglueapi.GetGlue;
import com.battlelancer.seriesguide.getglueapi.PrepareRequestTokenActivity;
import com.battlelancer.seriesguide.provider.SeriesContract.Episodes;
import com.battlelancer.seriesguide.ui.SeriesGuidePreferences;
import com.battlelancer.seriesguide.ui.ShowInfoActivity;
import com.jakewharton.apibuilder.ApiException;
import com.jakewharton.trakt.ServiceManager;
import com.jakewharton.trakt.TraktException;
import com.jakewharton.trakt.entities.Response;
import com.jakewharton.trakt.enumerations.Rating;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.SupportActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
public class ShareUtils {
public static final String KEY_GETGLUE_COMMENT = "com.battlelancer.seriesguide.getglue.comment";
public static final String KEY_GETGLUE_IMDBID = "com.battlelancer.seriesguide.getglue.imdbid";
protected static final String TAG = "ShareUtils";
public enum ShareMethod {
CHECKIN_GETGLUE(0, R.string.menu_checkin_getglue, R.drawable.ic_getglue),
CHECKIN_TRAKT(1, R.string.menu_checkin_trakt, R.drawable.ic_trakt),
MARKSEEN_TRAKT(2, R.string.menu_markseen_trakt, R.drawable.ic_trakt_seen),
RATE_TRAKT(3, R.string.menu_rate_trakt, R.drawable.trakt_love_large),
OTHER_SERVICES(4, R.string.menu_share_others, R.drawable.ic_action_share);
ShareMethod(int index, int titleRes, int drawableRes) {
this.index = index;
this.titleRes = titleRes;
this.drawableRes = drawableRes;
}
public int index;
public int titleRes;
public int drawableRes;
}
/**
* Share an episode via the given {@link ShareMethod}.
*
* @param activity
* @param shareData - a {@link Bundle} including all
* {@link ShareUtils.ShareItems}
* @param shareMethod the {@link ShareMethod} to use
*/
public static void onShareEpisode(SupportActivity activity, Bundle shareData,
ShareMethod shareMethod) {
final FragmentManager fm = activity.getSupportFragmentManager();
final String imdbId = shareData.getString(ShareUtils.ShareItems.IMDBID);
final String sharestring = shareData.getString(ShareUtils.ShareItems.SHARESTRING);
// save used share method, so we can use it later for the quick share
// button
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.asActivity());
prefs.edit().putInt(SeriesGuidePreferences.KEY_LAST_USED_SHARE_METHOD, shareMethod.index)
.commit();
switch (shareMethod) {
case CHECKIN_GETGLUE: {
// GetGlue check in
if (imdbId.length() != 0) {
showGetGlueDialog(fm, shareData);
} else {
Toast.makeText(activity.asActivity(),
activity.getString(R.string.checkin_impossible), Toast.LENGTH_LONG)
.show();
}
break;
}
case CHECKIN_TRAKT: {
// trakt check in
// DialogFragment.show() will take care of
// adding the fragment
// in a transaction. We also want to remove
// any currently showing
// dialog, so make our own transaction and
// take care of that here.
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("progress-dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
ProgressDialog newFragment = ProgressDialog.newInstance();
// start the trakt check in task, add the
// dialog as listener
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.CHECKIN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData, newFragment).execute();
newFragment.show(ft, "progress-dialog");
break;
}
case MARKSEEN_TRAKT: {
// trakt mark as seen
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.SEEN_EPISODE.index());
new TraktTask(activity.asActivity(), fm, shareData).execute();
break;
}
case RATE_TRAKT: {
// trakt rate
shareData.putInt(ShareItems.TRAKTACTION, TraktAction.RATE_EPISODE.index());
TraktRateDialogFragment newFragment = TraktRateDialogFragment
.newInstance(shareData);
FragmentTransaction ft = fm.beginTransaction();
newFragment.show(ft, "traktratedialog");
break;
}
case OTHER_SERVICES: {
// Android apps
String text = sharestring;
if (imdbId.length() != 0) {
text += " " + ShowInfoActivity.IMDB_TITLE_URL + imdbId;
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, text);
activity.startActivity(Intent.createChooser(i,
activity.getString(R.string.share_episode)));
break;
}
}
}
public static void showGetGlueDialog(FragmentManager manager, Bundle shareData) {
// Create and show the dialog.
GetGlueDialogFragment newFragment = GetGlueDialogFragment.newInstance(shareData);
FragmentTransaction ft = manager.beginTransaction();
newFragment.show(ft, "getgluedialog");
}
public static class GetGlueDialogFragment extends DialogFragment {
public static GetGlueDialogFragment newInstance(Bundle shareData) {
GetGlueDialogFragment f = new GetGlueDialogFragment();
f.setArguments(shareData);
return f;
}
private EditText input;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String episodestring = getArguments().getString(ShareItems.EPISODESTRING);
final String imdbId = getArguments().getString(ShareItems.IMDBID);
input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMinLines(3);
input.setGravity(Gravity.TOP);
input.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(140)
});
if (savedInstanceState != null) {
input.setText(savedInstanceState.getString("inputtext"));
} else {
input.setText(episodestring);
}
return new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.comment))
.setView(input)
.setPositiveButton(R.string.checkin, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onGetGlueCheckIn(getActivity(), input.getText().toString(), imdbId);
}
}).setNegativeButton(android.R.string.cancel, null).create();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("inputtext", input.getText().toString());
}
}
public static void onGetGlueCheckIn(final Activity activity, final String comment,
final String imdbId) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity
.getApplicationContext());
if (GetGlue.isAuthenticated(prefs)) {
new Thread(new Runnable() {
public void run() {
try {
GetGlue.checkIn(prefs, imdbId, comment, activity);
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity,
activity.getString(R.string.checkinsuccess),
Toast.LENGTH_SHORT).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Success", 0);
} catch (final Exception e) {
Log.e(TAG, "GetGlue Check-In failed");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(
activity,
activity.getString(R.string.checkinfailed) + " - "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
AnalyticsUtils.getInstance(activity).trackEvent("Sharing", "GetGlue",
"Failed", 0);
}
}
}).start();
} else {
Intent i = new Intent(activity, PrepareRequestTokenActivity.class);
i.putExtra(ShareUtils.KEY_GETGLUE_IMDBID, imdbId);
i.putExtra(ShareUtils.KEY_GETGLUE_COMMENT, comment);
activity.startActivity(i);
}
}
public interface ShareItems {
String SEASON = "season";
String IMDBID = "imdbId";
String SHARESTRING = "sharestring";
String EPISODESTRING = "episodestring";
String EPISODE = "episode";
String TVDBID = "tvdbid";
String RATING = "rating";
String TRAKTACTION = "traktaction";
}
public static String onCreateShareString(Context context, final Cursor episode) {
String season = episode.getString(episode.getColumnIndexOrThrow(Episodes.SEASON));
String number = episode.getString(episode.getColumnIndexOrThrow(Episodes.NUMBER));
String title = episode.getString(episode.getColumnIndexOrThrow(Episodes.TITLE));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return Utils.getNextEpisodeString(prefs, season, number, title);
}
public static void onAddCalendarEvent(Context context, String title, String description,
long airtime, String runtime) {
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", title);
intent.putExtra("description", description);
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
Calendar cal = Utils.getAirtimeCalendar(airtime, prefs);
long startTime = cal.getTimeInMillis();
long endTime = startTime + Long.valueOf(runtime) * DateUtils.MINUTE_IN_MILLIS;
intent.putExtra("beginTime", startTime);
intent.putExtra("endTime", endTime);
context.startActivity(intent);
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Success", 0);
} catch (Exception e) {
AnalyticsUtils.getInstance(context).trackEvent("Sharing", "Calendar", "Failed", 0);
Toast.makeText(context, context.getString(R.string.addtocalendar_failed),
Toast.LENGTH_SHORT).show();
}
}
public static String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return byteArrayToHexString(md.digest(convertme));
}
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public enum TraktAction {
SEEN_EPISODE(0), RATE_EPISODE(1), CHECKIN_EPISODE(2);
final private int mIndex;
private TraktAction(int index) {
mIndex = index;
}
public int index() {
return mIndex;
}
}
public interface TraktStatus {
String SUCCESS = "success";
String FAILURE = "failure";
}
public static class TraktTask extends AsyncTask<Void, Void, Response> {
private final Context mContext;
private final FragmentManager mManager;
private final Bundle mTraktData;
private OnTaskFinishedListener mListener;
public interface OnTaskFinishedListener {
public void onTaskFinished();
}
/**
* Do the specified TraktAction. traktData should include all required
* parameters.
*
* @param context
* @param manager
* @param traktData
* @param action
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData) {
mContext = context;
mManager = manager;
mTraktData = traktData;
}
/**
* Specify a listener which will be notified once any activity context
* dependent work is completed.
*
* @param context
* @param manager
* @param traktData
* @param listener
*/
public TraktTask(Context context, FragmentManager manager, Bundle traktData,
OnTaskFinishedListener listener) {
this(context, manager, traktData);
mListener = listener;
}
@Override
protected Response doInBackground(Void... params) {
if (!isTraktCredentialsValid(mContext)) {
// return null, so onPostExecute displays a credentials dialog
// which later calls us again.
return null;
}
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(mContext, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = mContext.getString(R.string.trakt_decryptfail);
return r;
}
// get some values
final int tvdbid = mTraktData.getInt(ShareItems.TVDBID);
final int season = mTraktData.getInt(ShareItems.SEASON);
final int episode = mTraktData.getInt(ShareItems.EPISODE);
final TraktAction action = TraktAction.values()[mTraktData
.getInt(ShareItems.TRAKTACTION)];
// last chance to abort (return value thrown away)
if (isCancelled()) {
return null;
}
try {
Response r = null;
switch (action) {
case CHECKIN_EPISODE: {
r = manager.showService().checkin(tvdbid).season(season).episode(episode)
.fire();
break;
}
case SEEN_EPISODE: {
manager.showService().episodeSeen(tvdbid).episode(season, episode).fire();
r = new Response();
r.status = TraktStatus.SUCCESS;
r.message = mContext.getString(R.string.trakt_seen);
break;
}
case RATE_EPISODE: {
final Rating rating = Rating.fromValue(mTraktData
.getString(ShareItems.RATING));
r = manager.rateService().episode(tvdbid).season(season).episode(episode)
.rating(rating).fire();
break;
}
}
return r;
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
}
@Override
protected void onPostExecute(Response r) {
if (r != null) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(mContext,
mContext.getString(R.string.trakt_success) + ": " + r.message,
Toast.LENGTH_SHORT).show();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
if (r.wait != 0) {
// looks like a check in is in progress
TraktCancelCheckinDialogFragment newFragment = TraktCancelCheckinDialogFragment
.newInstance(mTraktData, r.wait);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "cancel-checkin-dialog");
} else {
// well, something went wrong
Toast.makeText(mContext,
mContext.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
} else {
// credentials are invalid
TraktCredentialsDialogFragment newFragment = TraktCredentialsDialogFragment
.newInstance(mTraktData);
FragmentTransaction ft = mManager.beginTransaction();
newFragment.show(ft, "traktdialog");
}
// tell a potential listener that our work is done
if (mListener != null) {
mListener.onTaskFinished();
}
}
}
public static class TraktCredentialsDialogFragment extends DialogFragment {
private boolean isForwardingGivenTask;
public static TraktCredentialsDialogFragment newInstance(Bundle traktData) {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.setArguments(traktData);
f.isForwardingGivenTask = true;
return f;
}
public static TraktCredentialsDialogFragment newInstance() {
TraktCredentialsDialogFragment f = new TraktCredentialsDialogFragment();
f.isForwardingGivenTask = false;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
final LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_credentials_dialog, null);
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
// restore the username from settings
final String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
((EditText) layout.findViewById(R.id.username)).setText(username);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(layout);
builder.setTitle("trakt.tv");
final View mailviews = layout.findViewById(R.id.mailviews);
mailviews.setVisibility(View.GONE);
((CheckBox) layout.findViewById(R.id.checkNewAccount))
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mailviews.setVisibility(View.VISIBLE);
} else {
mailviews.setVisibility(View.GONE);
}
}
});
builder.setPositiveButton(R.string.save, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String username = ((EditText) layout.findViewById(R.id.username))
.getText().toString();
final String passwordHash = ShareUtils.toSHA1(((EditText) layout
.findViewById(R.id.password)).getText().toString().getBytes());
final String email = ((EditText) layout.findViewById(R.id.email)).getText()
.toString();
final boolean isNewAccount = ((CheckBox) layout
.findViewById(R.id.checkNewAccount)).isChecked();
AsyncTask<String, Void, Response> accountValidatorTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
// SHA of any password is always non-empty
if (username.length() == 0) {
return null;
}
// use a separate ServiceManager here to avoid
// setting wrong credentials
final ServiceManager manager = new ServiceManager();
manager.setApiKey(getResources().getString(R.string.trakt_apikey));
manager.setAuthentication(username, passwordHash);
Response response = null;
try {
if (isNewAccount) {
// create new account
response = manager.accountService()
.create(username, passwordHash, email).fire();
} else {
// validate existing account
response = manager.accountService().test().fire();
}
} catch (TraktException te) {
response = te.getResponse();
} catch (ApiException ae) {
response = null;
}
return response;
}
@Override
protected void onPostExecute(Response response) {
if (response != null) {
String passwordEncr;
// try to encrypt the password before storing it
try {
passwordEncr = SimpleCrypto.encrypt(passwordHash, context);
} catch (Exception e) {
passwordEncr = "";
}
// prepare writing credentials to settings
Editor editor = prefs.edit();
editor.putString(SeriesGuidePreferences.KEY_TRAKTUSER, username)
.putString(SeriesGuidePreferences.KEY_TRAKTPWD,
passwordEncr);
if (response.getStatus().equalsIgnoreCase("success")
&& passwordEncr.length() != 0 && editor.commit()) {
// all went through
Toast.makeText(context,
response.getStatus() + ": " + response.getMessage(),
Toast.LENGTH_SHORT).show();
// set new auth data for service manager
try {
Utils.getServiceManagerWithAuth(context, true);
} catch (Exception e) {
// we don't care
}
} else {
Toast.makeText(context,
response.getStatus() + ": " + response.getError(),
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context,
context.getString(R.string.trakt_generalerror),
Toast.LENGTH_LONG).show();
}
if (isForwardingGivenTask) {
// relaunch the trakt task which called us
new TraktTask(context, fm, args).execute();
}
}
};
accountValidatorTask.execute();
}
});
builder.setNegativeButton(R.string.dontsave, null);
return builder.create();
}
}
public static class TraktCancelCheckinDialogFragment extends DialogFragment {
private int mWait;
public static TraktCancelCheckinDialogFragment newInstance(Bundle traktData, int wait) {
TraktCancelCheckinDialogFragment f = new TraktCancelCheckinDialogFragment();
f.setArguments(traktData);
f.mWait = wait;
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity().getApplicationContext();
final FragmentManager fm = getSupportFragmentManager();
final Bundle args = getArguments();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(context.getString(R.string.traktcheckin_inprogress,
DateUtils.formatElapsedTime(mWait)));
builder.setPositiveButton(R.string.traktcheckin_cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
AsyncTask<String, Void, Response> cancelCheckinTask = new AsyncTask<String, Void, Response>() {
@Override
protected Response doInBackground(String... params) {
ServiceManager manager;
try {
manager = Utils.getServiceManagerWithAuth(context, false);
} catch (Exception e) {
// password could not be decrypted
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = context.getString(R.string.trakt_decryptfail);
return r;
}
Response response;
try {
response = manager.showService().cancelCheckin().fire();
} catch (TraktException te) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = te.getMessage();
return r;
} catch (ApiException e) {
Response r = new Response();
r.status = TraktStatus.FAILURE;
r.error = e.getMessage();
return r;
}
return response;
}
@Override
protected void onPostExecute(Response r) {
if (r.status.equalsIgnoreCase(TraktStatus.SUCCESS)) {
// all good
Toast.makeText(
context,
context.getString(R.string.trakt_success) + ": "
+ r.message, Toast.LENGTH_SHORT).show();
// relaunch the trakt task which called us to
// try the check in again
new TraktTask(context, fm, args).execute();
} else if (r.status.equalsIgnoreCase(TraktStatus.FAILURE)) {
// well, something went wrong
Toast.makeText(context,
context.getString(R.string.trakt_error) + ": " + r.error,
Toast.LENGTH_LONG).show();
}
}
};
cancelCheckinTask.execute();
}
});
builder.setNegativeButton(R.string.traktcheckin_wait, null);
return builder.create();
}
}
public static class TraktRateDialogFragment extends DialogFragment {
public static TraktRateDialogFragment newInstance(Bundle traktData) {
TraktRateDialogFragment f = new TraktRateDialogFragment();
f.setArguments(traktData);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Context context = getActivity();
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.trakt_rate_dialog, null);
final Button totallyNinja = (Button) layout.findViewById(R.id.totallyninja);
final Button weakSauce = (Button) layout.findViewById(R.id.weaksauce);
totallyNinja.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Love;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
weakSauce.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Rating rating = Rating.Hate;
getArguments().putString(ShareItems.RATING, rating.toString());
new TraktTask(context, getSupportFragmentManager(), getArguments()).execute();
dismiss();
}
});
builder = new AlertDialog.Builder(context);
builder.setView(layout);
builder.setNegativeButton(android.R.string.cancel, null);
return builder.create();
}
}
public static class ProgressDialog extends DialogFragment implements
TraktTask.OnTaskFinishedListener {
public static ProgressDialog newInstance() {
ProgressDialog f = new ProgressDialog();
f.setCancelable(false);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.progress_dialog, container, false);
return v;
}
@Override
public void onTaskFinished() {
if (isVisible()) {
dismiss();
}
}
}
public static boolean isTraktCredentialsValid(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
String username = prefs.getString(SeriesGuidePreferences.KEY_TRAKTUSER, "");
String password = prefs.getString(SeriesGuidePreferences.KEY_TRAKTPWD, "");
return (!username.equalsIgnoreCase("") && !password.equalsIgnoreCase(""));
}
}
| Remove input type flag from GetGlue comment box. Restores multiline
support. | SeriesGuide/src/com/battlelancer/seriesguide/util/ShareUtils.java | Remove input type flag from GetGlue comment box. Restores multiline support. | <ide><path>eriesGuide/src/com/battlelancer/seriesguide/util/ShareUtils.java
<ide> final String imdbId = getArguments().getString(ShareItems.IMDBID);
<ide>
<ide> input = new EditText(getActivity());
<del> input.setInputType(InputType.TYPE_CLASS_TEXT);
<ide> input.setMinLines(3);
<ide> input.setGravity(Gravity.TOP);
<ide> input.setFilters(new InputFilter[] { |
|
Java | apache-2.0 | 0a5efb51610a012344fdf0eec8e387916e0380b8 | 0 | thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck | /*
* Copyright [1999-2013] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* 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) 2004 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ensembl.healthcheck.AssemblyNameInfo;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.SqlTemplate;
import org.ensembl.healthcheck.util.Utils;
/**
* Checks that meta_value contents in the meta table are OK. Only one meta table at a time is done here; checks for the consistency of the
* meta table across species are done in MetaCrossSpecies.
*/
public class MetaValues extends SingleDatabaseTestCase {
private boolean isSangerVega = false;
public MetaValues() {
addToGroup("post_genebuild");
addToGroup("compara-ancestral");
addToGroup("pre-compara-handover");
addToGroup("post-compara-handover");
setTeamResponsible(Team.GENEBUILD);
setSecondTeamResponsible(Team.RELEASE_COORDINATOR);
setDescription("Check that meta_value contents in the meta table are OK");
}
/**
* Checks that meta_value contents in the meta table are OK.
*
* @param dbre
* The database to check.
* @return True if the test passed.
*/
public boolean run(final DatabaseRegistryEntry dbre) {
isSangerVega = dbre.getType() == DatabaseType.SANGER_VEGA;
boolean result = true;
Connection con = dbre.getConnection();
Species species = dbre.getSpecies();
if (species == Species.ANCESTRAL_SEQUENCES) {
// The rest of the tests are not relevant for the ancestral sequences DB
return result;
}
if (!isSangerVega && dbre.getType() != DatabaseType.VEGA) {// do not check for sangervega
result &= checkOverlappingRegions(con);
}
result &= checkAssemblyMapping(con);
result &= checkTaxonomyID(dbre);
result &= checkAssemblyWeb(dbre);
if (dbre.getType() == DatabaseType.CORE) {
result &= checkDates(dbre);
result &= checkGenebuildID(con);
result &= checkGenebuildMethod(dbre);
result &= checkAssemblyAccessionUpdate(dbre);
}
result &= checkCoordSystemTableCases(con);
result &= checkBuildLevel(dbre);
result &= checkSample(dbre);
// ----------------------------------------
//Use an AssemblyNameInfo object to get the assembly information
AssemblyNameInfo assembly = new AssemblyNameInfo(con);
String metaTableAssemblyDefault = assembly.getMetaTableAssemblyDefault();
logger.finest("assembly.default from meta table: " + metaTableAssemblyDefault);
String dbNameAssemblyVersion = assembly.getDBNameAssemblyVersion();
logger.finest("Assembly version from DB name: " + dbNameAssemblyVersion);
String metaTableAssemblyVersion = assembly.getMetaTableAssemblyVersion();
logger.finest("meta table assembly version: " + metaTableAssemblyVersion);
String metaTableAssemblyPrefix = assembly.getMetaTableAssemblyPrefix();
logger.finest("meta table assembly prefix: " + metaTableAssemblyPrefix);
if (metaTableAssemblyVersion == null || metaTableAssemblyDefault == null || metaTableAssemblyPrefix == null || dbNameAssemblyVersion == null) {
ReportManager.problem(this, con, "Cannot get all information from meta table - check for null values");
} else {
// ----------------------------------------
// Check that assembly prefix is valid and corresponds to this species
// Prefix is OK as long as it starts with the valid one
Species dbSpecies = dbre.getSpecies();
String correctPrefix = Species.getAssemblyPrefixForSpecies(dbSpecies);
if (!isSangerVega) {// do not check this for sangervega
if (correctPrefix == null) {
logger.info("Can't get correct assembly prefix for " + dbSpecies.toString());
} else {
if (!metaTableAssemblyPrefix.toUpperCase().startsWith(correctPrefix.toUpperCase())) {
ReportManager.problem(this, con, "Database species is " + dbSpecies + " but assembly prefix " + metaTableAssemblyPrefix + " should have prefix beginning with " + correctPrefix + " There should not be any version number, check Species.java is using the right value");
result = false;
}
}
}
}
// -------------------------------------------
result &= checkRepeatAnalysis(dbre);
// -------------------------------------------
result &= checkForSchemaPatchLineBreaks(dbre);
return result;
} // run
// ---------------------------------------------------------------------
// this HC will check the Meta table contains the assembly.overlapping_regions and
// that it is set to false (so no overlapping regions in the genome)
private boolean checkOverlappingRegions(Connection con) {
boolean result = true;
// check that certain keys exist
String[] metaKeys = { "assembly.overlapping_regions" };
for (int i = 0; i < metaKeys.length; i++) {
String metaKey = metaKeys[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key='" + metaKey + "'");
if (rows == 0) {
result = false;
ReportManager.problem(this, con, "No entry in meta table for " + metaKey + ". It might need to run the misc-scripts/overlapping_regions.pl script");
} else {
String[] metaValue = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='" + metaKey + "'");
if (metaValue[0].equals("1")) {
// there are overlapping regions !! API might behave oddly
ReportManager.problem(this, con, "There are overlapping regions in the database (e.g. two versions of the same chromosomes). The API"
+ " might have unexpected results when trying to map features to that coordinate system.");
result = false;
}
}
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkAssemblyMapping(Connection con) {
boolean result = true;
// Check formatting of assembly.mapping entries; should be of format
// coord_system1{:default}|coord_system2{:default} with optional third
// coordinate system
// and all coord systems should be valid from coord_system
// can also have # instead of | as used in unfinished contigs etc
Pattern assemblyMappingPattern = Pattern.compile("^([a-zA-Z0-9.]+):?([a-zA-Z0-9._-]+)?[\\|#]([a-zA-Z0-9._-]+):?([a-zA-Z0-9._-]+)?([\\|#]([a-zA-Z0-9.]+):?([a-zA-Z0-9._-]+)?)?$");
String[] validCoordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
String[] mappings = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'");
for (int i = 0; i < mappings.length; i++) {
Matcher matcher = assemblyMappingPattern.matcher(mappings[i]);
if (!matcher.matches()) {
result = false;
ReportManager.problem(this, con, "Coordinate system mapping " + mappings[i] + " is not in the correct format");
} else {
// if format is OK, check coord systems are valid
boolean valid = true;
String cs1 = matcher.group(1);
String assembly1 = matcher.group(2);
String cs2 = matcher.group(3);
String assembly2 = matcher.group(4);
String cs3 = matcher.group(6);
String assembly3 = matcher.group(7);
if (!Utils.stringInArray(cs1, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Source co-ordinate system " + cs1 + " is not in the coord_system table");
}
if (!Utils.stringInArray(cs2, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Target co-ordinate system " + cs2 + " is not in the coord_system table");
}
// third coordinate system is optional
if (cs3 != null && !Utils.stringInArray(cs3, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Third co-ordinate system in mapping (" + cs3 + ") is not in the coord_system table");
}
if (valid) {
ReportManager.correct(this, con, "Coordinate system mapping " + mappings[i] + " is OK");
}
result &= valid;
// check that coord_system:version pairs listed here exist in the coord_system table
result &= checkCoordSystemVersionPairs(con, cs1, assembly1, cs2, assembly2, cs3, assembly3);
// check that coord systems are specified in lower-case
result &= checkCoordSystemCase(con, cs1, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs2, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs3, "meta assembly.mapping");
}
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check that coordinate system:assembly pairs in assembly.mappings match what's in the coord system table
*/
private boolean checkCoordSystemVersionPairs(Connection con, String cs1, String assembly1, String cs2, String assembly2, String cs3, String assembly3) {
boolean result = true;
List<String> coordSystemsAndVersions = DBUtils.getColumnValuesList(con, "SELECT CONCAT_WS(':',name,version) FROM coord_system");
result &= checkCoordSystemPairInList(con, cs1, assembly1, coordSystemsAndVersions);
result &= checkCoordSystemPairInList(con, cs2, assembly2, coordSystemsAndVersions);
if (cs3 != null) {
result &= checkCoordSystemPairInList(con, cs3, assembly3, coordSystemsAndVersions);
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check if a particular coordinate system:version pair is in a list. Deal with nulls appropriately.
*/
private boolean checkCoordSystemPairInList(Connection con, String cs, String assembly, List<String> coordSystems) {
boolean result = true;
String toCompare = (assembly != null) ? cs + ":" + assembly : cs;
if (!coordSystems.contains(toCompare)) {
ReportManager.problem(this, con, "Coordinate system name/version " + toCompare + " in assembly.mapping does not appear in coord_system table.");
result = false;
}
return result;
}
// --------------------------------------------------------------------
/**
* @return true if cs is all lower case (or null), false otherwise.
*/
private boolean checkCoordSystemCase(Connection con, String cs, String desc) {
if (cs == null) {
return true;
}
boolean result = true;
if (cs.equals(cs.toLowerCase())) {
ReportManager.correct(this, con, "Co-ordinate system name " + cs + " all lower case in " + desc);
result = true;
} else {
ReportManager.problem(this, con, "Co-ordinate system name " + cs + " is not all lower case in " + desc);
result = false;
}
return result;
}
// --------------------------------------------------------------------
/**
* Check that all coord systems in the coord_system table are lower case.
*/
private boolean checkCoordSystemTableCases(Connection con) {
// TODO - table name in report
boolean result = true;
String[] coordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
for (int i = 0; i < coordSystems.length; i++) {
result &= checkCoordSystemCase(con, coordSystems[i], "coord_system");
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkTaxonomyID(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
Species species = dbre.getSpecies();
String dbTaxonID = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='species.taxonomy_id'");
logger.finest("Taxonomy ID from database: " + dbTaxonID);
if (dbTaxonID.equals(Species.getTaxonomyID(species))) {
ReportManager.correct(this, con, "Taxonomy ID " + dbTaxonID + " is correct for " + species.toString());
} else {
result = false;
ReportManager.problem(this, con, "Taxonomy ID " + dbTaxonID + " in database is not correct - should be " + Species.getTaxonomyID(species) + " for " + species.toString());
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkAssemblyWeb(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
String[] allowedTypes = {"GenBank Assembly ID", "EMBL-Bank WGS Master"};
String[] allowedSources = {"NCBI", "ENA", "DDBJ"};
String WebType = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_type'");
String WebSource = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_source'");
if (WebType.length() > 0) {
if (!Utils.stringInArray(WebType, allowedTypes, true)) {
result = false;
ReportManager.problem(this, con, "Web accession type " + WebType + " is not allowed");
}
}
if (WebSource.length() > 0) {
if (!Utils.stringInArray(WebSource, allowedSources, true)) {
result = false;
ReportManager.problem(this, con, "Web accession source " + WebSource + " is not allowed");
}
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkDates(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] keys = { "genebuild.start_date", "assembly.date", "genebuild.initial_release_date", "genebuild.last_geneset_update" };
String date = "[0-9]{4}-[0-9]{2}";
String[] regexps = { date + "-[a-zA-Z]*", date, date, date };
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
String regexp = regexps[i];
String value = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='" + key + "'");
if (value == null || value.length() == 0) {
ReportManager.problem(this, con, "No " + key + " entry in meta table");
result = false;
}
result &= checkMetaKey(con, key, value, regexp);
if (result) {
result &= checkDateFormat(con, key, value);
}
if (result) {
ReportManager.correct(this, con, key + " is present & in a valid format");
}
}
// some more checks for sanity of dates
int startDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.start_date'").replaceAll("[^0-9]", "")).intValue();
int initialReleaseDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.initial_release_date'").replaceAll("[^0-9]", "")).intValue();
int lastGenesetUpdate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("[^0-9]", "")).intValue();
// check for genebuild.start_date >= genebuild.initial_release_date (not allowed as we cannot release a gene set before
// downloaded the evidence)
if (startDate >= initialReleaseDate) {
result = false;
ReportManager.problem(this, con, "genebuild.start_date is greater than or equal to genebuild.initial_release_date");
}
// check for genebuild.initial_release_date > genebuild.last_geneset_update (not allowed as we cannot update a gene set before
// its initial public release)
if (initialReleaseDate > lastGenesetUpdate) {
result = false;
ReportManager.problem(this, con, "genebuild.initial_release_date is greater than or equal to genebuild.last_geneset_update");
}
// check for current genebuild.last_geneset_update <= previous release genebuild.last_geneset_update
// AND the number of genes or transcripts or exons between the two releases has changed
// If the gene set has changed in any way since the previous release then the date should have been updated.
DatabaseRegistryEntry previous = getEquivalentFromSecondaryServer(dbre);
if (previous == null) {
return result;
}
Connection previousCon = previous.getConnection();
String previousLastGenesetUpdateString = DBUtils.getRowColumnValue(previousCon, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("-", "");
if (previousLastGenesetUpdateString == null || previousLastGenesetUpdateString.length() == 0) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database.");
return false;
}
int previousLastGenesetUpdate;
try {
previousLastGenesetUpdate = Integer.valueOf(previousLastGenesetUpdateString).intValue();
} catch (NumberFormatException e) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database: " + Arrays.toString(e.getStackTrace()));
return false;
}
if (lastGenesetUpdate <= previousLastGenesetUpdate) {
int currentGeneCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM gene");
int currentTranscriptCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM transcript");
int currentExonCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM exon");
int previousGeneCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM gene");
int previousTranscriptCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM transcript");
int previousExonCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM exon");
if (currentGeneCount != previousGeneCount || currentTranscriptCount != previousTranscriptCount || currentExonCount != previousExonCount) {
ReportManager.problem(this, con, "Last geneset update entry is the same or older than the equivalent entry in the previous release and the number of genes, transcripts or exons has changed.");
result = false;
}
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkMetaKey(Connection con, String key, String s, String regexp) {
if (regexp != null) {
if (!s.matches(regexp)) {
ReportManager.problem(this, con, key + " " + s + " is not in correct format - should match " + regexp);
return false;
}
}
return true;
}
// ---------------------------------------------------------------------
private boolean checkDateFormat(Connection con, String key, String s) {
int year = Integer.parseInt(s.substring(0, 4));
if (year < 2003 || year > 2050) {
ReportManager.problem(this, con, "Year part of " + key + " (" + year + ") is incorrect");
return false;
}
int month = Integer.parseInt(s.substring(5, 7));
if (month < 1 || month > 12) {
ReportManager.problem(this, con, "Month part of " + key + " (" + month + ") is incorrect");
return false;
}
return true;
}
// ---------------------------------------------------------------------
private boolean checkGenebuildID(Connection con) {
String gbid = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.id'");
logger.finest("genebuild.id from database: " + gbid);
if (gbid == null || gbid.length() == 0) {
ReportManager.problem(this, con, "No genebuild.id entry in meta table");
return false;
} else if (!gbid.matches("[0-9]+")) {
ReportManager.problem(this, con, "genebuild.id " + gbid + " is not numeric");
return false;
}
ReportManager.correct(this, con, "genebuild.id " + gbid + " is present and numeric");
return true;
}
// ---------------------------------------------------------------------
/**
* Check that at least some sort of genebuild.level-type key is present.
*/
private boolean checkBuildLevel(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] Tables = { "gene", "transcript", "exon", "repeat_feature", "dna_align_feature", "protein_align_feature", "simple_feature", "prediction_transcript", "prediction_exon" };
int exists = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta where meta_key like '%build.level'");
if (exists == 0) {
ReportManager.problem(this, con, "GB: No %build.level entries in the meta table - run ensembl/misc-scripts/meta_levels.pl");
}
int count = 0;
for (int i = 0; i < Tables.length; i++) {
String Table = Tables[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table);
int key = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key = '" + Table + "build.level' ");
int toplevel = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table
+ " t, seq_region_attrib sra, attrib_type at WHERE t.seq_region_id = sra.seq_region_id AND sra.attrib_type_id = at.attrib_type_id AND at.code = 'toplevel' ");
if (rows != 0) {
if (key == 0) {
if (rows == toplevel) {
ReportManager.problem(this, con, "Table " + Table + " should have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
} else {
if (rows != toplevel) {
ReportManager.problem(this, con, "Table " + Table + " has some non toplevel regions, should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
} else {
if (key != 0) {
ReportManager.problem(this, con, "Empty table " + Table + " should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
}
if (count == Tables.length) {
ReportManager.correct(this, con, "Toplevel flags correctly set");
result = true;
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check that the genebuild.method entry exists and has one of the allowed values.
*/
private boolean checkGenebuildMethod(DatabaseRegistryEntry dbre) {
boolean result = true;
String[] allowedMethods = { "full_genebuild", "projection_build", "import", "mixed_strategy_build" };
Connection con = dbre.getConnection();
String method = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.method'");
if (method.equals("")) {
ReportManager.problem(this, con, "No genebuild.method entry present in Meta table");
return false;
}
if (!Utils.stringInArray(method, allowedMethods, true)) {
ReportManager.problem(this, con, "genebuild.method value " + method + " is not in list of allowed methods");
result = false;
} else {
ReportManager.correct(this, con, "genebuild.method " + method + " is valid");
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkAssemblyAccessionUpdate(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String currentAssemblyAccession = DBUtils.getMetaValue(con, "assembly.accession");
String currentAssemblyName = DBUtils.getMetaValue(con, "assembly.name");
if (currentAssemblyAccession.equals("")) {
ReportManager.problem(this, con, "No assembly.accession entry present in Meta table");
return false;
}
if (!currentAssemblyAccession.matches("^GC.*")){
ReportManager.problem(this, con, "Meta key assembly.accession does not start with GC");
return false;
}
if (currentAssemblyName.equals("")) {
ReportManager.problem(this, con, "No assembly.name entry present in Meta table");
return false;
}
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for " + dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is " + sec.getName());
Connection previousCon = sec.getConnection();
String previousAssemblyAccession = DBUtils.getMetaValue(previousCon, "assembly.accession");
String previousAssemblyName = DBUtils.getMetaValue(previousCon, "assembly.name");
long currentAssemblyChecksum = DBUtils.getChecksum(con, "assembly");
long previousAssemblyChecksum = DBUtils.getChecksum(previousCon, "assembly");
boolean assemblyChanged = false;
boolean assemblyTableChanged = false;
boolean assemblyExceptionTableChanged = false;
if (currentAssemblyChecksum != previousAssemblyChecksum) {
assemblyTableChanged = true;
} else {
if (dbre.getSpecies() != Species.HOMO_SAPIENS) {
// compare assembly_exception tables (patches only) from each database
try {
Statement previousStmt = previousCon.createStatement();
Statement currentStmt = con.createStatement();
String sql = "SELECT * FROM assembly_exception WHERE exc_type LIKE ('PATCH_%') ORDER BY assembly_exception_id";
ResultSet previousRS = previousStmt.executeQuery(sql);
ResultSet currentRS = currentStmt.executeQuery(sql);
boolean assExSame = DBUtils.compareResultSets(currentRS, previousRS, this, "", false, false, "assembly_exception", false);
currentRS.close();
previousRS.close();
currentStmt.close();
previousStmt.close();
assemblyExceptionTableChanged = !assExSame;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
assemblyChanged = assemblyTableChanged || assemblyExceptionTableChanged;
if (assemblyChanged == previousAssemblyAccession.equals(currentAssemblyAccession) && previousAssemblyName.equals(currentAssemblyName) ) {
result = false;
String errorMessage = "assembly.accession and assembly.name values need to be updated when "
+ "the assembly table changes or new patches are added to the assembly exception table\n"
+ "previous assembly.accession: " + previousAssemblyAccession + " assembly.name: " + previousAssemblyName
+ " current assembly.accession: " + currentAssemblyAccession + " assembly.name: " + currentAssemblyName + "\n"
+ "assembly table changed:";
if (assemblyTableChanged) {
errorMessage += " yes;";
} else {
errorMessage += " no;";
}
errorMessage += " assembly exception patches changed:";
if (assemblyExceptionTableChanged) {
errorMessage += " yes";
} else {
errorMessage += " no";
}
ReportManager.problem(this, con, errorMessage);
}
if (result) {
ReportManager.correct(this, con, "assembly.accession and assembly.name values are correct");
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check that all meta_values with meta_key 'repeat.analysis' reference analysis.logic_name
* Also check that repeatmask is one of them
*/
private boolean checkRepeatAnalysis(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] repeatAnalyses = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta LEFT JOIN analysis ON meta_value = logic_name WHERE meta_key = 'repeat.analysis' AND analysis_id IS NULL");
if (repeatAnalyses.length > 0) {
result = false;
ReportManager.problem(this, con, "The following values for meta_key repeat.analysis don't have a corresponding logic_name entry in the analysis table: " + Utils.arrayToString(repeatAnalyses,",") );
} else {
ReportManager.correct(this, con, "All values for meta_key repeat.analysis have a corresponding logic_name entry in the analysis table");
}
if (dbre.getType() == DatabaseType.CORE) {
int repeatMask = DBUtils.getRowCount(con, "SELECT count(*) FROM meta WHERE meta_key = 'repeat.analysis' AND (meta_value like 'repeatmask_repbase%' or meta_value = 'repeatmask')");
if (repeatMask == 0) {
result = false;
ReportManager.problem(this, con, "There is no entry in meta for repeatmask repeat.analysis");
} else {
ReportManager.correct(this, con, "Repeatmask is present in meta table for repeat.analysis");
}
}
return result;
}
private boolean checkForSchemaPatchLineBreaks(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "patch";
String sql = "select meta_id from meta where meta_key =? and species_id IS NULL and meta_value like ?";
List<Integer> ids = t.queryForDefaultObjectList(sql, Integer.class, metaKey, "%\n%");
if(!ids.isEmpty()) {
String idsJoined = Utils.listToString(ids, ",");
String usefulSql = "select * from meta where meta_id IN ("+idsJoined+")";
String msg = String.format("The meta ids [%s] had values with linebreaks.\nUSEFUL SQL: %s", idsJoined, usefulSql);
ReportManager.problem(this, dbre.getConnection(), msg);
return false;
}
return true;
}
private boolean checkSample(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "sample.location_text";
String sql = "select meta_value from meta where meta_key = ?";
List<String> value = t.queryForDefaultObjectList(sql, String.class, metaKey);
if (!value.isEmpty()) {
String linkedKey = "sample.location_param";
String linkedSql = "select meta_value from meta where meta_key = ?";
List<String> linkedValue = t.queryForDefaultObjectList(linkedSql, String.class, linkedKey);
if(!linkedValue.equals(value)) {
ReportManager.problem(this, dbre.getConnection(), "Keys " + metaKey + " and " + linkedKey + " do not have same value");
return false;
}
}
return true;
}
} // MetaValues
| src/org/ensembl/healthcheck/testcase/generic/MetaValues.java | /*
* Copyright [1999-2013] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* 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) 2004 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ensembl.healthcheck.AssemblyNameInfo;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.SqlTemplate;
import org.ensembl.healthcheck.util.Utils;
/**
* Checks that meta_value contents in the meta table are OK. Only one meta table at a time is done here; checks for the consistency of the
* meta table across species are done in MetaCrossSpecies.
*/
public class MetaValues extends SingleDatabaseTestCase {
private boolean isSangerVega = false;
public MetaValues() {
addToGroup("post_genebuild");
addToGroup("compara-ancestral");
addToGroup("pre-compara-handover");
addToGroup("post-compara-handover");
setTeamResponsible(Team.GENEBUILD);
setSecondTeamResponsible(Team.RELEASE_COORDINATOR);
setDescription("Check that meta_value contents in the meta table are OK");
}
/**
* Checks that meta_value contents in the meta table are OK.
*
* @param dbre
* The database to check.
* @return True if the test passed.
*/
public boolean run(final DatabaseRegistryEntry dbre) {
isSangerVega = dbre.getType() == DatabaseType.SANGER_VEGA;
boolean result = true;
Connection con = dbre.getConnection();
Species species = dbre.getSpecies();
if (species == Species.ANCESTRAL_SEQUENCES) {
// The rest of the tests are not relevant for the ancestral sequences DB
return result;
}
if (!isSangerVega && dbre.getType() != DatabaseType.VEGA) {// do not check for sangervega
result &= checkOverlappingRegions(con);
}
result &= checkAssemblyMapping(con);
result &= checkTaxonomyID(dbre);
result &= checkAssemblyWeb(dbre);
if (dbre.getType() == DatabaseType.CORE) {
result &= checkDates(dbre);
result &= checkGenebuildID(con);
result &= checkGenebuildMethod(dbre);
result &= checkAssemblyAccessionUpdate(dbre);
}
result &= checkCoordSystemTableCases(con);
result &= checkBuildLevel(dbre);
result &= checkSample(dbre);
// ----------------------------------------
//Use an AssemblyNameInfo object to get the assembly information
AssemblyNameInfo assembly = new AssemblyNameInfo(con);
String metaTableAssemblyDefault = assembly.getMetaTableAssemblyDefault();
logger.finest("assembly.default from meta table: " + metaTableAssemblyDefault);
String dbNameAssemblyVersion = assembly.getDBNameAssemblyVersion();
logger.finest("Assembly version from DB name: " + dbNameAssemblyVersion);
String metaTableAssemblyVersion = assembly.getMetaTableAssemblyVersion();
logger.finest("meta table assembly version: " + metaTableAssemblyVersion);
String metaTableAssemblyPrefix = assembly.getMetaTableAssemblyPrefix();
logger.finest("meta table assembly prefix: " + metaTableAssemblyPrefix);
if (metaTableAssemblyVersion == null || metaTableAssemblyDefault == null || metaTableAssemblyPrefix == null || dbNameAssemblyVersion == null) {
ReportManager.problem(this, con, "Cannot get all information from meta table - check for null values");
} else {
// ----------------------------------------
// Check that assembly prefix is valid and corresponds to this species
// Prefix is OK as long as it starts with the valid one
Species dbSpecies = dbre.getSpecies();
String correctPrefix = Species.getAssemblyPrefixForSpecies(dbSpecies);
if (!isSangerVega) {// do not check this for sangervega
if (correctPrefix == null) {
logger.info("Can't get correct assembly prefix for " + dbSpecies.toString());
} else {
if (!metaTableAssemblyPrefix.toUpperCase().startsWith(correctPrefix.toUpperCase())) {
ReportManager.problem(this, con, "Database species is " + dbSpecies + " but assembly prefix " + metaTableAssemblyPrefix + " should have prefix beginning with " + correctPrefix + " There should not be any version number, check Species.java is using the right value");
result = false;
}
}
}
}
// -------------------------------------------
result &= checkRepeatAnalysis(dbre);
// -------------------------------------------
result &= checkForSchemaPatchLineBreaks(dbre);
return result;
} // run
// ---------------------------------------------------------------------
// this HC will check the Meta table contains the assembly.overlapping_regions and
// that it is set to false (so no overlapping regions in the genome)
private boolean checkOverlappingRegions(Connection con) {
boolean result = true;
// check that certain keys exist
String[] metaKeys = { "assembly.overlapping_regions" };
for (int i = 0; i < metaKeys.length; i++) {
String metaKey = metaKeys[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key='" + metaKey + "'");
if (rows == 0) {
result = false;
ReportManager.problem(this, con, "No entry in meta table for " + metaKey + ". It might need to run the misc-scripts/overlapping_regions.pl script");
} else {
String[] metaValue = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='" + metaKey + "'");
if (metaValue[0].equals("1")) {
// there are overlapping regions !! API might behave oddly
ReportManager.problem(this, con, "There are overlapping regions in the database (e.g. two versions of the same chromosomes). The API"
+ " might have unexpected results when trying to map features to that coordinate system.");
result = false;
}
}
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkAssemblyMapping(Connection con) {
boolean result = true;
// Check formatting of assembly.mapping entries; should be of format
// coord_system1{:default}|coord_system2{:default} with optional third
// coordinate system
// and all coord systems should be valid from coord_system
// can also have # instead of | as used in unfinished contigs etc
Pattern assemblyMappingPattern = Pattern.compile("^([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?[\\|#]([a-zA-Z0-9._]+):?([a-zA-Z0-9._]+)?([\\|#]([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?)?$");
String[] validCoordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
String[] mappings = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'");
for (int i = 0; i < mappings.length; i++) {
Matcher matcher = assemblyMappingPattern.matcher(mappings[i]);
if (!matcher.matches()) {
result = false;
ReportManager.problem(this, con, "Coordinate system mapping " + mappings[i] + " is not in the correct format");
} else {
// if format is OK, check coord systems are valid
boolean valid = true;
String cs1 = matcher.group(1);
String assembly1 = matcher.group(2);
String cs2 = matcher.group(3);
String assembly2 = matcher.group(4);
String cs3 = matcher.group(6);
String assembly3 = matcher.group(7);
if (!Utils.stringInArray(cs1, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Source co-ordinate system " + cs1 + " is not in the coord_system table");
}
if (!Utils.stringInArray(cs2, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Target co-ordinate system " + cs2 + " is not in the coord_system table");
}
// third coordinate system is optional
if (cs3 != null && !Utils.stringInArray(cs3, validCoordSystems, false)) {
valid = false;
ReportManager.problem(this, con, "Third co-ordinate system in mapping (" + cs3 + ") is not in the coord_system table");
}
if (valid) {
ReportManager.correct(this, con, "Coordinate system mapping " + mappings[i] + " is OK");
}
result &= valid;
// check that coord_system:version pairs listed here exist in the coord_system table
result &= checkCoordSystemVersionPairs(con, cs1, assembly1, cs2, assembly2, cs3, assembly3);
// check that coord systems are specified in lower-case
result &= checkCoordSystemCase(con, cs1, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs2, "meta assembly.mapping");
result &= checkCoordSystemCase(con, cs3, "meta assembly.mapping");
}
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check that coordinate system:assembly pairs in assembly.mappings match what's in the coord system table
*/
private boolean checkCoordSystemVersionPairs(Connection con, String cs1, String assembly1, String cs2, String assembly2, String cs3, String assembly3) {
boolean result = true;
List<String> coordSystemsAndVersions = DBUtils.getColumnValuesList(con, "SELECT CONCAT_WS(':',name,version) FROM coord_system");
result &= checkCoordSystemPairInList(con, cs1, assembly1, coordSystemsAndVersions);
result &= checkCoordSystemPairInList(con, cs2, assembly2, coordSystemsAndVersions);
if (cs3 != null) {
result &= checkCoordSystemPairInList(con, cs3, assembly3, coordSystemsAndVersions);
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check if a particular coordinate system:version pair is in a list. Deal with nulls appropriately.
*/
private boolean checkCoordSystemPairInList(Connection con, String cs, String assembly, List<String> coordSystems) {
boolean result = true;
String toCompare = (assembly != null) ? cs + ":" + assembly : cs;
if (!coordSystems.contains(toCompare)) {
ReportManager.problem(this, con, "Coordinate system name/version " + toCompare + " in assembly.mapping does not appear in coord_system table.");
result = false;
}
return result;
}
// --------------------------------------------------------------------
/**
* @return true if cs is all lower case (or null), false otherwise.
*/
private boolean checkCoordSystemCase(Connection con, String cs, String desc) {
if (cs == null) {
return true;
}
boolean result = true;
if (cs.equals(cs.toLowerCase())) {
ReportManager.correct(this, con, "Co-ordinate system name " + cs + " all lower case in " + desc);
result = true;
} else {
ReportManager.problem(this, con, "Co-ordinate system name " + cs + " is not all lower case in " + desc);
result = false;
}
return result;
}
// --------------------------------------------------------------------
/**
* Check that all coord systems in the coord_system table are lower case.
*/
private boolean checkCoordSystemTableCases(Connection con) {
// TODO - table name in report
boolean result = true;
String[] coordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
for (int i = 0; i < coordSystems.length; i++) {
result &= checkCoordSystemCase(con, coordSystems[i], "coord_system");
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkTaxonomyID(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
Species species = dbre.getSpecies();
String dbTaxonID = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='species.taxonomy_id'");
logger.finest("Taxonomy ID from database: " + dbTaxonID);
if (dbTaxonID.equals(Species.getTaxonomyID(species))) {
ReportManager.correct(this, con, "Taxonomy ID " + dbTaxonID + " is correct for " + species.toString());
} else {
result = false;
ReportManager.problem(this, con, "Taxonomy ID " + dbTaxonID + " in database is not correct - should be " + Species.getTaxonomyID(species) + " for " + species.toString());
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkAssemblyWeb(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// Check that the taxonomy ID matches a known one.
// The taxonomy ID-species mapping is held in the Species class.
String[] allowedTypes = {"GenBank Assembly ID", "EMBL-Bank WGS Master"};
String[] allowedSources = {"NCBI", "ENA", "DDBJ"};
String WebType = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_type'");
String WebSource = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.web_accession_source'");
if (WebType.length() > 0) {
if (!Utils.stringInArray(WebType, allowedTypes, true)) {
result = false;
ReportManager.problem(this, con, "Web accession type " + WebType + " is not allowed");
}
}
if (WebSource.length() > 0) {
if (!Utils.stringInArray(WebSource, allowedSources, true)) {
result = false;
ReportManager.problem(this, con, "Web accession source " + WebSource + " is not allowed");
}
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkDates(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] keys = { "genebuild.start_date", "assembly.date", "genebuild.initial_release_date", "genebuild.last_geneset_update" };
String date = "[0-9]{4}-[0-9]{2}";
String[] regexps = { date + "-[a-zA-Z]*", date, date, date };
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
String regexp = regexps[i];
String value = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='" + key + "'");
if (value == null || value.length() == 0) {
ReportManager.problem(this, con, "No " + key + " entry in meta table");
result = false;
}
result &= checkMetaKey(con, key, value, regexp);
if (result) {
result &= checkDateFormat(con, key, value);
}
if (result) {
ReportManager.correct(this, con, key + " is present & in a valid format");
}
}
// some more checks for sanity of dates
int startDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.start_date'").replaceAll("[^0-9]", "")).intValue();
int initialReleaseDate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.initial_release_date'").replaceAll("[^0-9]", "")).intValue();
int lastGenesetUpdate = Integer.valueOf(DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("[^0-9]", "")).intValue();
// check for genebuild.start_date >= genebuild.initial_release_date (not allowed as we cannot release a gene set before
// downloaded the evidence)
if (startDate >= initialReleaseDate) {
result = false;
ReportManager.problem(this, con, "genebuild.start_date is greater than or equal to genebuild.initial_release_date");
}
// check for genebuild.initial_release_date > genebuild.last_geneset_update (not allowed as we cannot update a gene set before
// its initial public release)
if (initialReleaseDate > lastGenesetUpdate) {
result = false;
ReportManager.problem(this, con, "genebuild.initial_release_date is greater than or equal to genebuild.last_geneset_update");
}
// check for current genebuild.last_geneset_update <= previous release genebuild.last_geneset_update
// AND the number of genes or transcripts or exons between the two releases has changed
// If the gene set has changed in any way since the previous release then the date should have been updated.
DatabaseRegistryEntry previous = getEquivalentFromSecondaryServer(dbre);
if (previous == null) {
return result;
}
Connection previousCon = previous.getConnection();
String previousLastGenesetUpdateString = DBUtils.getRowColumnValue(previousCon, "SELECT meta_value FROM meta WHERE meta_key='genebuild.last_geneset_update'").replaceAll("-", "");
if (previousLastGenesetUpdateString == null || previousLastGenesetUpdateString.length() == 0) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database.");
return false;
}
int previousLastGenesetUpdate;
try {
previousLastGenesetUpdate = Integer.valueOf(previousLastGenesetUpdateString).intValue();
} catch (NumberFormatException e) {
ReportManager.problem(this, con, "Problem parsing last geneset update entry from previous database: " + Arrays.toString(e.getStackTrace()));
return false;
}
if (lastGenesetUpdate <= previousLastGenesetUpdate) {
int currentGeneCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM gene");
int currentTranscriptCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM transcript");
int currentExonCount = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM exon");
int previousGeneCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM gene");
int previousTranscriptCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM transcript");
int previousExonCount = DBUtils.getRowCount(previousCon, "SELECT COUNT(*) FROM exon");
if (currentGeneCount != previousGeneCount || currentTranscriptCount != previousTranscriptCount || currentExonCount != previousExonCount) {
ReportManager.problem(this, con, "Last geneset update entry is the same or older than the equivalent entry in the previous release and the number of genes, transcripts or exons has changed.");
result = false;
}
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkMetaKey(Connection con, String key, String s, String regexp) {
if (regexp != null) {
if (!s.matches(regexp)) {
ReportManager.problem(this, con, key + " " + s + " is not in correct format - should match " + regexp);
return false;
}
}
return true;
}
// ---------------------------------------------------------------------
private boolean checkDateFormat(Connection con, String key, String s) {
int year = Integer.parseInt(s.substring(0, 4));
if (year < 2003 || year > 2050) {
ReportManager.problem(this, con, "Year part of " + key + " (" + year + ") is incorrect");
return false;
}
int month = Integer.parseInt(s.substring(5, 7));
if (month < 1 || month > 12) {
ReportManager.problem(this, con, "Month part of " + key + " (" + month + ") is incorrect");
return false;
}
return true;
}
// ---------------------------------------------------------------------
private boolean checkGenebuildID(Connection con) {
String gbid = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.id'");
logger.finest("genebuild.id from database: " + gbid);
if (gbid == null || gbid.length() == 0) {
ReportManager.problem(this, con, "No genebuild.id entry in meta table");
return false;
} else if (!gbid.matches("[0-9]+")) {
ReportManager.problem(this, con, "genebuild.id " + gbid + " is not numeric");
return false;
}
ReportManager.correct(this, con, "genebuild.id " + gbid + " is present and numeric");
return true;
}
// ---------------------------------------------------------------------
/**
* Check that at least some sort of genebuild.level-type key is present.
*/
private boolean checkBuildLevel(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] Tables = { "gene", "transcript", "exon", "repeat_feature", "dna_align_feature", "protein_align_feature", "simple_feature", "prediction_transcript", "prediction_exon" };
int exists = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta where meta_key like '%build.level'");
if (exists == 0) {
ReportManager.problem(this, con, "GB: No %build.level entries in the meta table - run ensembl/misc-scripts/meta_levels.pl");
}
int count = 0;
for (int i = 0; i < Tables.length; i++) {
String Table = Tables[i];
int rows = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table);
int key = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM meta WHERE meta_key = '" + Table + "build.level' ");
int toplevel = DBUtils.getRowCount(con, "SELECT COUNT(*) FROM " + Table
+ " t, seq_region_attrib sra, attrib_type at WHERE t.seq_region_id = sra.seq_region_id AND sra.attrib_type_id = at.attrib_type_id AND at.code = 'toplevel' ");
if (rows != 0) {
if (key == 0) {
if (rows == toplevel) {
ReportManager.problem(this, con, "Table " + Table + " should have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
} else {
if (rows != toplevel) {
ReportManager.problem(this, con, "Table " + Table + " has some non toplevel regions, should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
} else {
if (key != 0) {
ReportManager.problem(this, con, "Empty table " + Table + " should not have a toplevel flag - run ensembl/misc-scripts/meta_levels.pl");
} else {
count++;
}
}
}
if (count == Tables.length) {
ReportManager.correct(this, con, "Toplevel flags correctly set");
result = true;
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check that the genebuild.method entry exists and has one of the allowed values.
*/
private boolean checkGenebuildMethod(DatabaseRegistryEntry dbre) {
boolean result = true;
String[] allowedMethods = { "full_genebuild", "projection_build", "import", "mixed_strategy_build" };
Connection con = dbre.getConnection();
String method = DBUtils.getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='genebuild.method'");
if (method.equals("")) {
ReportManager.problem(this, con, "No genebuild.method entry present in Meta table");
return false;
}
if (!Utils.stringInArray(method, allowedMethods, true)) {
ReportManager.problem(this, con, "genebuild.method value " + method + " is not in list of allowed methods");
result = false;
} else {
ReportManager.correct(this, con, "genebuild.method " + method + " is valid");
}
return result;
}
// ---------------------------------------------------------------------
private boolean checkAssemblyAccessionUpdate(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String currentAssemblyAccession = DBUtils.getMetaValue(con, "assembly.accession");
String currentAssemblyName = DBUtils.getMetaValue(con, "assembly.name");
if (currentAssemblyAccession.equals("")) {
ReportManager.problem(this, con, "No assembly.accession entry present in Meta table");
return false;
}
if (!currentAssemblyAccession.matches("^GC.*")){
ReportManager.problem(this, con, "Meta key assembly.accession does not start with GC");
return false;
}
if (currentAssemblyName.equals("")) {
ReportManager.problem(this, con, "No assembly.name entry present in Meta table");
return false;
}
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for " + dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is " + sec.getName());
Connection previousCon = sec.getConnection();
String previousAssemblyAccession = DBUtils.getMetaValue(previousCon, "assembly.accession");
String previousAssemblyName = DBUtils.getMetaValue(previousCon, "assembly.name");
long currentAssemblyChecksum = DBUtils.getChecksum(con, "assembly");
long previousAssemblyChecksum = DBUtils.getChecksum(previousCon, "assembly");
boolean assemblyChanged = false;
boolean assemblyTableChanged = false;
boolean assemblyExceptionTableChanged = false;
if (currentAssemblyChecksum != previousAssemblyChecksum) {
assemblyTableChanged = true;
} else {
if (dbre.getSpecies() != Species.HOMO_SAPIENS) {
// compare assembly_exception tables (patches only) from each database
try {
Statement previousStmt = previousCon.createStatement();
Statement currentStmt = con.createStatement();
String sql = "SELECT * FROM assembly_exception WHERE exc_type LIKE ('PATCH_%') ORDER BY assembly_exception_id";
ResultSet previousRS = previousStmt.executeQuery(sql);
ResultSet currentRS = currentStmt.executeQuery(sql);
boolean assExSame = DBUtils.compareResultSets(currentRS, previousRS, this, "", false, false, "assembly_exception", false);
currentRS.close();
previousRS.close();
currentStmt.close();
previousStmt.close();
assemblyExceptionTableChanged = !assExSame;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
assemblyChanged = assemblyTableChanged || assemblyExceptionTableChanged;
if (assemblyChanged == previousAssemblyAccession.equals(currentAssemblyAccession) && previousAssemblyName.equals(currentAssemblyName) ) {
result = false;
String errorMessage = "assembly.accession and assembly.name values need to be updated when "
+ "the assembly table changes or new patches are added to the assembly exception table\n"
+ "previous assembly.accession: " + previousAssemblyAccession + " assembly.name: " + previousAssemblyName
+ " current assembly.accession: " + currentAssemblyAccession + " assembly.name: " + currentAssemblyName + "\n"
+ "assembly table changed:";
if (assemblyTableChanged) {
errorMessage += " yes;";
} else {
errorMessage += " no;";
}
errorMessage += " assembly exception patches changed:";
if (assemblyExceptionTableChanged) {
errorMessage += " yes";
} else {
errorMessage += " no";
}
ReportManager.problem(this, con, errorMessage);
}
if (result) {
ReportManager.correct(this, con, "assembly.accession and assembly.name values are correct");
}
return result;
}
// ---------------------------------------------------------------------
/**
* Check that all meta_values with meta_key 'repeat.analysis' reference analysis.logic_name
* Also check that repeatmask is one of them
*/
private boolean checkRepeatAnalysis(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
String[] repeatAnalyses = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta LEFT JOIN analysis ON meta_value = logic_name WHERE meta_key = 'repeat.analysis' AND analysis_id IS NULL");
if (repeatAnalyses.length > 0) {
result = false;
ReportManager.problem(this, con, "The following values for meta_key repeat.analysis don't have a corresponding logic_name entry in the analysis table: " + Utils.arrayToString(repeatAnalyses,",") );
} else {
ReportManager.correct(this, con, "All values for meta_key repeat.analysis have a corresponding logic_name entry in the analysis table");
}
if (dbre.getType() == DatabaseType.CORE) {
int repeatMask = DBUtils.getRowCount(con, "SELECT count(*) FROM meta WHERE meta_key = 'repeat.analysis' AND (meta_value like 'repeatmask_repbase%' or meta_value = 'repeatmask')");
if (repeatMask == 0) {
result = false;
ReportManager.problem(this, con, "There is no entry in meta for repeatmask repeat.analysis");
} else {
ReportManager.correct(this, con, "Repeatmask is present in meta table for repeat.analysis");
}
}
return result;
}
private boolean checkForSchemaPatchLineBreaks(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "patch";
String sql = "select meta_id from meta where meta_key =? and species_id IS NULL and meta_value like ?";
List<Integer> ids = t.queryForDefaultObjectList(sql, Integer.class, metaKey, "%\n%");
if(!ids.isEmpty()) {
String idsJoined = Utils.listToString(ids, ",");
String usefulSql = "select * from meta where meta_id IN ("+idsJoined+")";
String msg = String.format("The meta ids [%s] had values with linebreaks.\nUSEFUL SQL: %s", idsJoined, usefulSql);
ReportManager.problem(this, dbre.getConnection(), msg);
return false;
}
return true;
}
private boolean checkSample(DatabaseRegistryEntry dbre) {
SqlTemplate t = DBUtils.getSqlTemplate(dbre);
String metaKey = "sample.location_text";
String sql = "select meta_value from meta where meta_key = ?";
List<String> value = t.queryForDefaultObjectList(sql, String.class, metaKey);
if (!value.isEmpty()) {
String linkedKey = "sample.location_param";
String linkedSql = "select meta_value from meta where meta_key = ?";
List<String> linkedValue = t.queryForDefaultObjectList(linkedSql, String.class, linkedKey);
if(!linkedValue.equals(value)) {
ReportManager.problem(this, dbre.getConnection(), "Keys " + metaKey + " and " + linkedKey + " do not have same value");
return false;
}
}
return true;
}
} // MetaValues
| adding '-' in the list of allowed caracters for an assembly name
| src/org/ensembl/healthcheck/testcase/generic/MetaValues.java | adding '-' in the list of allowed caracters for an assembly name | <ide><path>rc/org/ensembl/healthcheck/testcase/generic/MetaValues.java
<ide> // and all coord systems should be valid from coord_system
<ide> // can also have # instead of | as used in unfinished contigs etc
<ide>
<del> Pattern assemblyMappingPattern = Pattern.compile("^([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?[\\|#]([a-zA-Z0-9._]+):?([a-zA-Z0-9._]+)?([\\|#]([a-zA-Z0-9.]+):?([a-zA-Z0-9._]+)?)?$");
<add> Pattern assemblyMappingPattern = Pattern.compile("^([a-zA-Z0-9.]+):?([a-zA-Z0-9._-]+)?[\\|#]([a-zA-Z0-9._-]+):?([a-zA-Z0-9._-]+)?([\\|#]([a-zA-Z0-9.]+):?([a-zA-Z0-9._-]+)?)?$");
<ide> String[] validCoordSystems = DBUtils.getColumnValues(con, "SELECT name FROM coord_system");
<ide>
<ide> String[] mappings = DBUtils.getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping'"); |
|
Java | apache-2.0 | 04e00f2612331c237e6e66161251b048c21b8667 | 0 | jranabahu/carbon-governance,wso2/carbon-governance,cnapagoda/carbon-governance,prasa7/carbon-governance,cnapagoda/carbon-governance,daneshk/carbon-governance,jranabahu/carbon-governance,jranabahu/carbon-governance,wso2/carbon-governance,daneshk/carbon-governance,wso2/carbon-governance,cnapagoda/carbon-governance,jranabahu/carbon-governance,cnapagoda/carbon-governance,prasa7/carbon-governance,daneshk/carbon-governance,daneshk/carbon-governance,wso2/carbon-governance,prasa7/carbon-governance,prasa7/carbon-governance | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 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 org.wso2.carbon.governance.rest.api.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.message.Message;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.rest.api.RestApiBasicAuthenticationException;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AuthenticationHandler implements RequestHandler {
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
public static final String AUTHORIZATION_HEADER_NAME = "Authorization";
protected Log log = LogFactory.getLog(AuthenticationHandler.class);
private final static String AUTH_TYPE_BASIC = "Basic";
private final static String AUTH_TYPE_BASIC_REALM_VALUE = " Realm=\"WSO2-Registry\"";
private final static String AUTH_TYPE_OAuth = "Bearer";
private final static String METHOD_GET = "GET";
/**
* Implementation of RequestHandler.handleRequest method.
* This method retrieves userName and password from Basic auth header,
* and tries to authenticate against carbon user store
* <p/>
* Upon successful authentication allows process to proceed to retrieve requested REST resource
* Upon invalid credentials returns a HTTP 401 UNAUTHORIZED response to client
* Upon receiving a userStoreExceptions or IdentityException returns HTTP 500 internal server error to client
*
* @param message
* @param classResourceInfo
* @return Response
*/
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
if (policy != null && AUTH_TYPE_BASIC.equals(policy.getAuthorizationType())) {
return handleBasicAuth(policy, message);
} else if (policy != null) {
return handleOAuth(message);
} else {
return handleAnonymousAcess(message);
}
}
private Response handleAnonymousAcess(Message message) {
String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
if (method != null && METHOD_GET.equals(method)) {
String tenantDomain = getTenantDomain(null, message);
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
carbonContext.setTenantId(getTenantId(tenantDomain));
carbonContext.setTenantDomain(tenantDomain);
return null;
}
return authenticationFail(AUTH_TYPE_BASIC + AUTH_TYPE_BASIC_REALM_VALUE);
}
protected Response handleBasicAuth(AuthorizationPolicy policy, Message message) {
String username = policy.getUserName();
String password = policy.getPassword();
String tenantDomain = getTenantDomain(username , message);
try {
if (authenticate(username, password, tenantDomain)) {
return null;
}
} catch (RestApiBasicAuthenticationException e) {
log.error("Could not authenticate user : " + username + "against carbon userStore", e);
}
return authenticationFail();
}
protected Response handleOAuth(Message message) {
ArrayList<String> headers = ((Map<String, ArrayList>) message.get(Message.PROTOCOL_HEADERS)).get(AUTHORIZATION_HEADER_NAME);
if (headers != null) {
String authHeader = headers.get(0);
if (authHeader.startsWith(AUTH_TYPE_OAuth)) {
return authenticationFail(AUTH_TYPE_OAuth);
}
}
return authenticationFail(AUTH_TYPE_BASIC + AUTH_TYPE_BASIC_REALM_VALUE);
}
/**
* Checks whether a given userName:password combination authenticates correctly against carbon userStore
* Upon successful authentication returns true, false otherwise
*
* @param userName
* @param password
* @return
* @throws RestApiBasicAuthenticationException wraps and throws exceptions occur when trying to authenticate
* the user
*/
private boolean authenticate(String userName, String password, String tenantDomain) throws RestApiBasicAuthenticationException {
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userName);
String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
int tenantId = getTenantId(tenantDomain);
// tenantId == -1, means an invalid tenant.
if (tenantId == -1) {
if (log.isDebugEnabled()) {
log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
}
return false;
}
UserStoreManager userStoreManager = null;
boolean authStatus = false;
try {
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
authStatus = userStoreManager.authenticate(tenantAwareUserName, password);
} catch (UserStoreException e) {
throw new RestApiBasicAuthenticationException(
"User store exception thrown while authenticating user : " + userNameWithTenantDomain, e);
}
if (log.isDebugEnabled()) {
log.debug("Basic authentication request completed. " +
"Username : " + userNameWithTenantDomain +
", Authentication State : " + authStatus);
}
if (authStatus) {
/* Upon successful authentication existing thread local carbon context
* is updated to mimic the authenticated user */
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setUsername(tenantAwareUserName);
carbonContext.setTenantId(tenantId);
carbonContext.setTenantDomain(tenantDomain);
}
return authStatus;
}
private String getTenantDomain(String username, Message message) {
String tenantDomain = null;
// 1. Read "tenant" query parameter from the request URI.
String query = (String) message.get(Message.QUERY_STRING);
if (query != null && !query.isEmpty()) {
int index = query.indexOf("tenant=");
if (index > -1) {
query = query.substring(index + 7);
index = query.indexOf(",");
if (index > 0) {
tenantDomain = query.substring(0, index);
} else {
tenantDomain = query;
}
}
}
// 2. If tenantDomain not found, read "X_TENANT" HTTP header.
if (tenantDomain == null || tenantDomain.isEmpty()) {
Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
if (headers != null && !headers.isEmpty()) {
List<String> headerValues = headers.get("X_TENANT");
if (headerValues != null && !headerValues.isEmpty()) {
tenantDomain = headerValues.get(0);
}
}
}
// 3. If tenantDomain not found, use "username" to resolve the tenant.
if ((tenantDomain == null || tenantDomain.isEmpty()) && username != null) {
tenantDomain = MultitenantUtils.getTenantDomain(username);
}
// 4. If tenantDomain still not found use supper tenant as default option.
if (tenantDomain == null) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
return tenantDomain;
}
private int getTenantId(String tenantDomain) {
RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
TenantManager mgr = realmService.getTenantManager();
try {
return mgr.getTenantId(tenantDomain);
} catch (UserStoreException e) {
log.error("Identity exception thrown while getting tenantID for : " + tenantDomain, e);
}
return 0;
}
private Response authenticationFail() {
return authenticationFail(AUTH_TYPE_BASIC + AUTH_TYPE_BASIC_REALM_VALUE);
}
private Response authenticationFail(String authType) {
//authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
return Response.status(401).header(WWW_AUTHENTICATE, authType).build();
}
} | components/governance/org.wso2.carbon.governance.rest.api/src/main/java/org/wso2/carbon/governance/rest/api/security/AuthenticationHandler.java | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 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 org.wso2.carbon.governance.rest.api.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.message.Message;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.rest.api.RestApiBasicAuthenticationException;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AuthenticationHandler implements RequestHandler {
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
public static final String AUTHORIZATION_HEADER_NAME = "Authorization";
protected Log log = LogFactory.getLog(AuthenticationHandler.class);
private final static String AUTH_TYPE_BASIC = "Basic";
private final static String AUTH_TYPE_BASIC_REALM_VALUE = " Realm=\"WSO2-Registry\"";
private final static String AUTH_TYPE_OAuth = "Bearer";
private final static String METHOD_GET = "GET";
/**
* Implementation of RequestHandler.handleRequest method.
* This method retrieves userName and password from Basic auth header,
* and tries to authenticate against carbon user store
* <p/>
* Upon successful authentication allows process to proceed to retrieve requested REST resource
* Upon invalid credentials returns a HTTP 401 UNAUTHORIZED response to client
* Upon receiving a userStoreExceptions or IdentityException returns HTTP 500 internal server error to client
*
* @param message
* @param classResourceInfo
* @return Response
*/
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
if (policy != null && AUTH_TYPE_BASIC.equals(policy.getAuthorizationType())) {
return handleBasicAuth(policy, message);
} else if (policy != null) {
return handleOAuth(message);
} else {
return handleAnonymousAcess(message);
}
}
private Response handleAnonymousAcess(Message message) {
String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
if (method != null && METHOD_GET.equals(method)) {
String tenantDomain = getTenantDomain(null, message);
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
carbonContext.setTenantId(getTenantId(tenantDomain));
carbonContext.setTenantDomain(tenantDomain);
return null;
}
return authenticationFail(AUTH_TYPE_BASIC + AUTH_TYPE_BASIC_REALM_VALUE);
}
protected Response handleBasicAuth(AuthorizationPolicy policy, Message message) {
String username = policy.getUserName();
String password = policy.getPassword();
String tenantDomain = getTenantDomain(username , message);
try {
if (authenticate(username, password, tenantDomain)) {
return null;
}
} catch (RestApiBasicAuthenticationException e) {
log.error("Could not authenticate user : " + username + "against carbon userStore", e);
}
return authenticationFail();
}
protected Response handleOAuth(Message message) {
ArrayList<String> headers = ((Map<String, ArrayList>) message.get(Message.PROTOCOL_HEADERS)).get(AUTHORIZATION_HEADER_NAME);
if (headers != null) {
String authHeader = headers.get(0);
if (authHeader.startsWith(AUTH_TYPE_OAuth)) {
return authenticationFail(AUTH_TYPE_OAuth);
}
}
return authenticationFail(AUTH_TYPE_BASIC + AUTH_TYPE_BASIC_REALM_VALUE);
}
/**
* Checks whether a given userName:password combination authenticates correctly against carbon userStore
* Upon successful authentication returns true, false otherwise
*
* @param userName
* @param password
* @return
* @throws RestApiBasicAuthenticationException wraps and throws exceptions occur when trying to authenticate
* the user
*/
private boolean authenticate(String userName, String password, String tenantDomain) throws RestApiBasicAuthenticationException {
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(userName);
String userNameWithTenantDomain = tenantAwareUserName + "@" + tenantDomain;
RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
int tenantId = getTenantId(tenantDomain);
// tenantId == -1, means an invalid tenant.
if (tenantId == -1) {
if (log.isDebugEnabled()) {
log.debug("Basic authentication request with an invalid tenant : " + userNameWithTenantDomain);
}
return false;
}
UserStoreManager userStoreManager = null;
boolean authStatus = false;
try {
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
authStatus = userStoreManager.authenticate(tenantAwareUserName, password);
} catch (UserStoreException e) {
throw new RestApiBasicAuthenticationException(
"User store exception thrown while authenticating user : " + userNameWithTenantDomain, e);
}
if (log.isDebugEnabled()) {
log.debug("Basic authentication request completed. " +
"Username : " + userNameWithTenantDomain +
", Authentication State : " + authStatus);
}
if (authStatus) {
/* Upon successful authentication existing thread local carbon context
* is updated to mimic the authenticated user */
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setUsername(userName);
carbonContext.setTenantId(tenantId);
carbonContext.setTenantDomain(tenantDomain);
}
return authStatus;
}
private String getTenantDomain(String username, Message message) {
String tenantDomain = null;
// 1. Read "tenant" query parameter from the request URI.
String query = (String) message.get(Message.QUERY_STRING);
if (query != null && !query.isEmpty()) {
int index = query.indexOf("tenant=");
if (index > -1) {
query = query.substring(index + 7);
index = query.indexOf(",");
if (index > 0) {
tenantDomain = query.substring(0, index);
} else {
tenantDomain = query;
}
}
}
// 2. If tenantDomain not found, read "X_TENANT" HTTP header.
if (tenantDomain == null || tenantDomain.isEmpty()) {
Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
if (headers != null && !headers.isEmpty()) {
List<String> headerValues = headers.get("X_TENANT");
if (headerValues != null && !headerValues.isEmpty()) {
tenantDomain = headerValues.get(0);
}
}
}
// 3. If tenantDomain not found, use "username" to resolve the tenant.
if ((tenantDomain == null || tenantDomain.isEmpty()) && username != null) {
tenantDomain = MultitenantUtils.getTenantDomain(username);
}
// 4. If tenantDomain still not found use supper tenant as default option.
if (tenantDomain == null) {
tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
}
return tenantDomain;
}
private int getTenantId(String tenantDomain) {
RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
TenantManager mgr = realmService.getTenantManager();
try {
return mgr.getTenantId(tenantDomain);
} catch (UserStoreException e) {
log.error("Identity exception thrown while getting tenantID for : " + tenantDomain, e);
}
return 0;
}
private Response authenticationFail() {
return authenticationFail(AUTH_TYPE_BASIC + AUTH_TYPE_BASIC_REALM_VALUE);
}
private Response authenticationFail(String authType) {
//authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate
return Response.status(401).header(WWW_AUTHENTICATE, authType).build();
}
} | REGISTRY-3929 - Fix issue in tenant mode
| components/governance/org.wso2.carbon.governance.rest.api/src/main/java/org/wso2/carbon/governance/rest/api/security/AuthenticationHandler.java | REGISTRY-3929 - Fix issue in tenant mode | <ide><path>omponents/governance/org.wso2.carbon.governance.rest.api/src/main/java/org/wso2/carbon/governance/rest/api/security/AuthenticationHandler.java
<ide> * is updated to mimic the authenticated user */
<ide>
<ide> PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
<del> carbonContext.setUsername(userName);
<add> carbonContext.setUsername(tenantAwareUserName);
<ide> carbonContext.setTenantId(tenantId);
<ide> carbonContext.setTenantDomain(tenantDomain);
<ide> } |
|
Java | bsd-3-clause | 4e933fc42d40594d449566d7463e365cbb410e47 | 0 | chocoteam/choco3,chocoteam/choco3,piyushsh/choco3,cp-profiler/choco3,piyushsh/choco3,PhilAndrew/choco3gwt,piyushsh/choco3,cp-profiler/choco3,cp-profiler/choco3,chocoteam/choco3,Tiger66639/choco3,piyushsh/choco3,PhilAndrew/choco3gwt,cp-profiler/choco3,Tiger66639/choco3,Tiger66639/choco3,chocoteam/choco3,PhilAndrew/choco3gwt,Tiger66639/choco3 | /**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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 solver.variables.view;
import choco.kernel.common.util.iterators.DisposableRangeIterator;
import choco.kernel.common.util.iterators.DisposableValueIterator;
import choco.kernel.common.util.procedure.IntProcedure;
import solver.Cause;
import solver.ICause;
import solver.Solver;
import solver.exception.ContradictionException;
import solver.explanations.Explanation;
import solver.explanations.VariableState;
import solver.variables.AbstractVariable;
import solver.variables.EventType;
import solver.variables.IntVar;
import solver.variables.Variable;
import solver.variables.delta.monitor.IntDeltaMonitor;
import solver.variables.delta.view.ViewDelta;
/**
* declare an IntVar based on X, such |X|
* <p/>
* Based on "Views and Iterators for Generic Constraint Implementations" <br/>
* C. Shulte and G. Tack.<br/>
* Eleventh International Conference on Principles and Practice of Constraint Programming
*
* @author Charles Prud'homme
* @since 09/08/11
*/
public final class SqrView extends View<IntVar> {
protected DisposableValueIterator _viterator;
protected DisposableRangeIterator _riterator;
public SqrView(final IntVar var, Solver solver) {
super("(" + var.getName() + "^2)", var, solver);
}
@Override
public void analyseAndAdapt(int mask) {
super.analyseAndAdapt(mask);
if (!reactOnRemoval && ((modificationEvents & EventType.REMOVE.mask) != 0)) {
var.analyseAndAdapt(mask);
delta = new ViewDelta(new IntDeltaMonitor(var.getDelta()) {
@Override
public void forEach(IntProcedure proc, EventType eventType) throws ContradictionException {
if (EventType.isRemove(eventType.mask)) {
for (int i = frozenFirst; i < frozenLast; i++) {
proc.execute(delta.get(i) * delta.get(i));
}
}
}
});
reactOnRemoval = true;
}
}
@Override
public boolean instantiated() {
if (var.instantiated()) {
return true;
} else {
if (var.getDomainSize() == 2 && Math.abs(var.getLB()) == var.getUB()) {
return true;
}
}
return false;
}
private static int floor_sqrt(int n) {
if (n < 0)
return 0;
return (int) Math.sqrt(n);
}
@Override
public boolean removeValue(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.REMOVE, cause));
if (value < 0) {
return false;
}
int rootV = floor_sqrt(value);
if (rootV * rootV == value) { // is a perfect square ?
int inf = getLB();
int sup = getUB();
EventType evt = EventType.REMOVE;
if (value == inf) {
evt = EventType.INCLOW;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
} else if (value == sup) {
evt = EventType.DECUPP;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
boolean done = var.removeValue(-rootV, this);
done |= var.removeValue(rootV, this);
if (instantiated()) {
evt = EventType.INSTANTIATE;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
if (done) {
notifyMonitors(evt, cause);
}
}
return false;
}
@Override
public boolean removeInterval(int from, int to, ICause cause) throws ContradictionException {
if (from <= getLB()) {
return updateLowerBound(to + 1, cause);
} else if (getUB() <= to) {
return updateUpperBound(from - 1, cause);
} else {
from = floor_sqrt(from);
to = floor_sqrt(to);
boolean done = var.removeInterval(-to, -from, cause);
done |= var.removeInterval(from, to, cause);
if (done) {
notifyMonitors(EventType.REMOVE, cause);
}
return done;
}
}
@Override
public boolean instantiateTo(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.INSTANTIATE, cause));
if (value < 0) {
//TODO: explication?
this.contradiction(cause, EventType.INSTANTIATE, AbstractVariable.MSG_UNKNOWN);
}
int v = floor_sqrt(value);
if (v * v == value) { // is a perfect square ?
boolean done = var.updateLowerBound(-v, this);
done |= var.updateUpperBound(v, this);
EventType evt = EventType.DECUPP;
if (var.hasEnumeratedDomain()) {
done |= var.removeInterval(-v + 1, v - 1, cause);
evt = EventType.INSTANTIATE;
}
if (done) {
notifyMonitors(evt, cause);
}
return done;
} else { //otherwise, impossible value for instantiation
//TODO: explication?
this.contradiction(cause, EventType.INSTANTIATE, AbstractVariable.MSG_UNKNOWN);
}
return false;
}
@Override
public boolean updateLowerBound(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.INCLOW, cause));
if (value <= 0) {
return false;
}
int floorV = floor_sqrt(value);
boolean done = var.removeInterval(-floorV + 1, floorV - 1, this);
if (done) {
EventType evt = EventType.INCLOW;
if(instantiated()){
evt = EventType.INSTANTIATE;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
notifyMonitors(evt, cause);
}
return done;
}
@Override
public boolean updateUpperBound(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.DECUPP, cause));
if (value < 0) {
//TODO: explication?
this.contradiction(cause, EventType.DECUPP, AbstractVariable.MSG_UNKNOWN);
}
int floorV = floor_sqrt(value);
boolean done = var.updateLowerBound(-floorV, this);
done |= var.updateUpperBound(floorV, this);
if (done) {
EventType evt = EventType.DECUPP;
if(instantiated()){
evt = EventType.INSTANTIATE;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
notifyMonitors(evt, cause);
}
return done;
}
@Override
public boolean contains(int value) {
return var.contains(value) || var.contains(-value);
}
@Override
public boolean instantiatedTo(int value) {
return var.instantiatedTo(value) || var.instantiatedTo(-value);
}
@Override
public int getValue() {
return getLB();
}
@Override
public int getLB() {
if (var.contains(0)) {
return 0;
}
int elb = var.getLB();
if (elb > 0) {
return elb * elb;
}
int eub = var.getUB();
if (eub < 0) {
return eub * eub;
}
int l = var.previousValue(0);
int u = var.nextValue(0);
if (-l < u) {
return l * l;
} else {
return u * u;
}
}
@Override
public int getUB() {
int elb = var.getLB();
int eub = var.getUB();
int mm = -elb;
if (elb < 0) {
if (eub > 0 && eub > mm) {
mm = eub;
}
} else {
mm = eub;
}
return mm * mm;
}
@Override
public int nextValue(int v) {
if (v < 0 && var.contains(0)) {
return 0;
}
int floorV = floor_sqrt(v);
int l = var.previousValue(-floorV);
if (l == Integer.MIN_VALUE) {
l = Integer.MAX_VALUE;
} else {
l = Math.abs(l);
}
int u = var.nextValue(floorV);
int min = Math.min(l, Math.abs(u));
if (min == Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return min * min;
}
@Override
public int previousValue(int v) {
if (v < 0) {
return Integer.MIN_VALUE;
}
int floorV = floor_sqrt(v);
if (floorV * floorV != v) {
floorV++;
}
int l = var.nextValue(-floorV);
if (l == Integer.MIN_VALUE) {
l = Integer.MAX_VALUE;
} else {
l = Math.abs(l);
}
int u = var.previousValue(floorV);
int max = Math.max(l, Math.abs(u));
if (max == Integer.MAX_VALUE) {
return Integer.MIN_VALUE;
}
return max * max;
}
@Override
public String toString() {
return "(" + this.var.toString() + "^2) = [" + getLB() + "," + getUB() + "]";
}
@Override
public boolean hasEnumeratedDomain() {
return true;
}
@Override
public int getType() {
return Variable.INTEGER;
}
@Override
public int getDomainSize() {
return var.getDomainSize();
}
@Override
public Explanation explain(VariableState what) {
return var.explain(VariableState.DOM);
}
@Override
public Explanation explain(VariableState what, int val) {
int fl = floor_sqrt(val);
Explanation explanation = new Explanation();
explanation.add(var.explain(what, fl));
explanation.add(var.explain(what, -fl));
return explanation;
}
@Override
public DisposableValueIterator getValueIterator(boolean bottomUp) {
if (_viterator == null || !_viterator.isReusable()) {
_viterator = new DisposableValueIterator() {
DisposableValueIterator u2l;
DisposableValueIterator l2u;
int vl2u;
int vu2l;
@Override
public void bottomUpInit() {
l2u = var.getValueIterator(true);
u2l = var.getValueIterator(false);
super.bottomUpInit();
while (l2u.hasNext()) {
this.vl2u = l2u.next();
if (this.vl2u >= 0) break;
}
while (u2l.hasPrevious()) {
this.vu2l = u2l.previous();
if (this.vu2l <= 0) break;
}
}
@Override
public void topDownInit() {
l2u = var.getValueIterator(true);
u2l = var.getValueIterator(false);
super.topDownInit();
if (l2u.hasNext()) {
this.vl2u = l2u.next();
}
if (u2l.hasPrevious()) {
this.vu2l = u2l.previous();
}
}
@Override
public boolean hasNext() {
return this.vl2u < Integer.MAX_VALUE || this.vu2l > -Integer.MAX_VALUE;
}
@Override
public boolean hasPrevious() {
return this.vl2u <= 0 || this.vu2l >= 0;
}
@Override
public int next() {
int min = this.vl2u < -this.vu2l ? this.vl2u : -this.vu2l;
if (this.vl2u == min) {
if (this.l2u.hasNext()) {
this.vl2u = l2u.next();
} else {
this.vl2u = Integer.MAX_VALUE;
}
}
if (-this.vu2l == min) {
if (this.u2l.hasPrevious()) {
this.vu2l = u2l.previous();
} else {
this.vu2l = -Integer.MAX_VALUE;
}
}
return min * min;
}
@Override
public int previous() {
int max = -this.vl2u > this.vu2l ? -this.vl2u : this.vu2l;
if (-this.vl2u == max && this.l2u.hasNext()) {
this.vl2u = this.l2u.next();
}
if (this.vu2l == max && this.u2l.hasPrevious()) {
this.vu2l = u2l.previous();
}
return max * max;
}
@Override
public void dispose() {
super.dispose();
l2u.dispose();
u2l.dispose();
}
};
}
if (bottomUp) {
_viterator.bottomUpInit();
} else {
_viterator.topDownInit();
}
return _viterator;
}
@Override
public DisposableRangeIterator getRangeIterator(boolean bottomUp) {
if (_riterator == null || !_riterator.isReusable()) {
_riterator = new DisposableRangeIterator() {
DisposableRangeIterator u2l;
DisposableRangeIterator l2u;
int ml2u;
int Ml2u;
int mu2l;
int Mu2l;
int value;
int bound;
@Override
public void bottomUpInit() {
l2u = var.getRangeIterator(true);
u2l = var.getRangeIterator(false);
super.bottomUpInit();
ml2u = Ml2u = mu2l = Mu2l = Integer.MAX_VALUE;
while (l2u.hasNext()) {
if (l2u.min() >= 0) {
ml2u = l2u.min();
Ml2u = l2u.max();
l2u.next();
break;
}
if (l2u.max() >= 0) {
ml2u = 0;
Ml2u = l2u.max();
l2u.next();
break;
}
l2u.next();
}
while (u2l.hasPrevious()) {
if (u2l.max() <= 0) {
Mu2l = -u2l.min();
mu2l = -u2l.max();
u2l.previous();
break;
}
if (u2l.min() <= 0) {
mu2l = 0;
Mu2l = -u2l.min();
u2l.previous();
break;
}
u2l.previous();
}
_next();
}
@Override
public void topDownInit() {
l2u = var.getRangeIterator(true);
u2l = var.getRangeIterator(false);
super.topDownInit();
ml2u = Ml2u = mu2l = Mu2l = Integer.MIN_VALUE;
if (l2u.hasNext()) {
if (l2u.max() <= 0) {
this.ml2u = -l2u.max();
this.Ml2u = -l2u.min();
} else if (l2u.min() <= 0) {
this.ml2u = 0;
this.Ml2u = -l2u.min();
}
l2u.next();
}
if (u2l.hasPrevious()) {
if (u2l.min() >= 0) {
this.mu2l = u2l.min();
this.Mu2l = u2l.max();
} else if (u2l.max() >= 0) {
this.mu2l = 0;
this.Mu2l = u2l.max();
}
u2l.previous();
}
_previous();
}
@Override
public boolean hasNext() {
if (value < bound) {
value++;
}
return value < Integer.MAX_VALUE;
}
@Override
public boolean hasPrevious() {
if (value > bound) {
value--;
}
return value > Integer.MIN_VALUE;
}
@Override
public void next() {
if (value >= bound) {
_next();
}
}
private void _next() {
value = bound = Integer.MAX_VALUE;
// disjoint ranges
if (Ml2u < mu2l - 1) {
value = ml2u - 1; //-1 due to hasNext()
bound = Ml2u;
if (l2u.hasNext()) {
ml2u = l2u.min();
Ml2u = l2u.max();
l2u.next();
} else {
ml2u = Integer.MAX_VALUE;
Ml2u = Integer.MAX_VALUE;
}
} else if (Mu2l < ml2u - 1) {
value = mu2l - 1; //-1 due to hasNext()
bound = Mu2l;
if (u2l.hasPrevious()) {
Mu2l = -u2l.min();
mu2l = -u2l.max();
u2l.previous();
} else {
mu2l = Integer.MAX_VALUE;
Mu2l = Integer.MAX_VALUE;
}
} else {
// we build the current range
if (Ml2u + 1 == mu2l) {
value = ml2u - 1; //-1 due to hasNext()
bound = Mu2l;
} else if (Mu2l + 1 == ml2u) {
value = mu2l - 1; //-1 due to hasNext()
bound = Ml2u;
} else {
value = ml2u < mu2l ? ml2u : mu2l;
bound = Ml2u < Mu2l ? Ml2u : Mu2l;
}
boolean change;
do {
change = false;
if (value < ml2u && ml2u <= bound) {
bound = bound > Ml2u ? bound : Ml2u;
if (l2u.hasNext()) {
ml2u = l2u.min();
Ml2u = l2u.max();
l2u.next();
change = true;
} else {
ml2u = Integer.MAX_VALUE;
Ml2u = Integer.MAX_VALUE;
}
}
if (value < mu2l && mu2l <= bound) {
bound = bound > Mu2l ? bound : Mu2l;
if (u2l.hasPrevious()) {
Mu2l = -u2l.min();
mu2l = -u2l.max();
u2l.previous();
change = true;
} else {
mu2l = Integer.MAX_VALUE;
Mu2l = Integer.MAX_VALUE;
}
}
} while (change);
}
}
@Override
public void previous() {
if (value <= bound) {
_previous();
}
}
private void _previous() {
value = bound = Integer.MIN_VALUE;
// disjoint ranges
if (ml2u > Mu2l + 1) {
bound = ml2u;
value = Ml2u + 1; //+1 due to hasPrevious()
ml2u = Integer.MIN_VALUE;
Ml2u = Integer.MIN_VALUE;
if (l2u.hasNext()) {
//la: grer le 0 et les autres cas
if (l2u.max() <= 0) {
this.ml2u = -l2u.max();
this.Ml2u = -l2u.min();
} else if (l2u.min() <= 0) {
this.ml2u = 0;
this.Ml2u = -l2u.min();
}
l2u.next();
}
} else if (Mu2l + 1 < ml2u) {
bound = mu2l;
value = Mu2l + 1; //+1 due to hasPrevious()
mu2l = Integer.MIN_VALUE;
Mu2l = Integer.MIN_VALUE;
if (u2l.min() >= 0) {
this.mu2l = u2l.min();
this.Mu2l = u2l.max();
} else if (u2l.max() >= 0) {
this.mu2l = 0;
this.Mu2l = u2l.max();
}
} else {
// we build the current range
if (Ml2u + 1 == mu2l) {
bound = ml2u;
value = Mu2l + 1; //+1 due to hasPrevious()
} else if (Mu2l + 1 == ml2u) {
bound = mu2l;
value = Ml2u + 1; //+1 due to hasPrevious()
} else {
bound = ml2u > mu2l ? ml2u : mu2l;
value = (Ml2u > Mu2l ? Ml2u : Mu2l) + 1; //+1 due to hasPrevious()
}
boolean change;
do {
change = false;
if (bound <= Ml2u && Ml2u < value) {
bound = bound < ml2u ? bound : ml2u;
ml2u = Integer.MIN_VALUE;
Ml2u = Integer.MIN_VALUE;
if (l2u.hasNext()) {
if (l2u.max() <= 0) {
this.ml2u = -l2u.max();
this.Ml2u = -l2u.min();
} else if (l2u.min() <= 0) {
this.ml2u = 0;
this.Ml2u = -l2u.min();
}
l2u.next();
change = true;
}
}
if (bound <= mu2l && mu2l < value) {
bound = bound < mu2l ? bound : mu2l;
mu2l = Integer.MIN_VALUE;
Mu2l = Integer.MIN_VALUE;
if (u2l.hasPrevious()) {
if (u2l.min() >= 0) {
this.mu2l = u2l.min();
this.Mu2l = u2l.max();
} else if (u2l.max() >= 0) {
this.mu2l = 0;
this.Mu2l = u2l.max();
}
u2l.previous();
change = true;
}
}
} while (change);
}
}
@Override
public int min() {
return value * value;
}
@Override
public int max() {
return value * value;
}
@Override
public void dispose() {
super.dispose();
l2u.dispose();
u2l.dispose();
}
};
}
if (bottomUp) {
_riterator.bottomUpInit();
} else {
_riterator.topDownInit();
}
return _riterator;
}
@Override
public void transformEvent(EventType evt, ICause cause) throws ContradictionException {
if ((evt.mask & EventType.BOUND.mask) != 0) {
if (instantiated()) { // specific case where DOM_SIZE = 2 and LB = -UB
notifyMonitors(EventType.INSTANTIATE, cause);
} else { // otherwise, we do not know the previous values, so its hard to tell wether it is LB or UB mod
notifyMonitors(EventType.BOUND, cause);
}
} else {
notifyMonitors(evt, cause);
}
}
}
| solver/src/main/java/solver/variables/view/SqrView.java | /**
* Copyright (c) 1999-2011, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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 solver.variables.view;
import choco.kernel.common.util.iterators.DisposableRangeIterator;
import choco.kernel.common.util.iterators.DisposableValueIterator;
import choco.kernel.common.util.procedure.IntProcedure;
import solver.Cause;
import solver.ICause;
import solver.Solver;
import solver.exception.ContradictionException;
import solver.explanations.Explanation;
import solver.explanations.VariableState;
import solver.variables.AbstractVariable;
import solver.variables.EventType;
import solver.variables.IntVar;
import solver.variables.Variable;
import solver.variables.delta.monitor.IntDeltaMonitor;
import solver.variables.delta.view.ViewDelta;
/**
* declare an IntVar based on X, such |X|
* <p/>
* Based on "Views and Iterators for Generic Constraint Implementations" <br/>
* C. Shulte and G. Tack.<br/>
* Eleventh International Conference on Principles and Practice of Constraint Programming
*
* @author Charles Prud'homme
* @since 09/08/11
*/
public final class SqrView extends View<IntVar> {
protected DisposableValueIterator _viterator;
protected DisposableRangeIterator _riterator;
public SqrView(final IntVar var, Solver solver) {
super("(" + var.getName() + "^2)", var, solver);
}
@Override
public void analyseAndAdapt(int mask) {
super.analyseAndAdapt(mask);
if (!reactOnRemoval && ((modificationEvents & EventType.REMOVE.mask) != 0)) {
var.analyseAndAdapt(mask);
delta = new ViewDelta(new IntDeltaMonitor(var.getDelta()) {
@Override
public void forEach(IntProcedure proc, EventType eventType) throws ContradictionException {
if (EventType.isRemove(eventType.mask)) {
for (int i = frozenFirst; i < frozenLast; i++) {
proc.execute(delta.get(i) * delta.get(i));
}
}
}
});
reactOnRemoval = true;
}
}
@Override
public boolean instantiated() {
if (var.instantiated()) {
return true;
} else {
if (var.getDomainSize() == 2 && Math.abs(var.getLB()) == var.getUB()) {
return true;
}
}
return false;
}
private static int floor_sqrt(int n) {
if (n < 0)
return 0;
return (int) Math.sqrt(n);
}
@Override
public boolean removeValue(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.REMOVE, cause));
if (value < 0) {
return false;
}
int rootV = floor_sqrt(value);
if (rootV * rootV == value) { // is a perfect square ?
int inf = getLB();
int sup = getUB();
EventType evt = EventType.REMOVE;
if (value == inf) {
evt = EventType.INCLOW;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
} else if (value == sup) {
evt = EventType.DECUPP;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
boolean done = var.removeValue(-rootV, this);
done |= var.removeValue(rootV, this);
if (instantiated()) {
evt = EventType.INSTANTIATE;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
if (done) {
notifyMonitors(evt, cause);
}
}
return false;
}
@Override
public boolean removeInterval(int from, int to, ICause cause) throws ContradictionException {
if (from <= getLB()) {
return updateLowerBound(to + 1, cause);
} else if (getUB() <= to) {
return updateUpperBound(from - 1, cause);
} else {
from = floor_sqrt(from);
to = floor_sqrt(to);
boolean done = var.removeInterval(-to, -from, cause);
done |= var.removeInterval(from, to, cause);
if (done) {
notifyMonitors(EventType.REMOVE, cause);
}
return done;
}
}
@Override
public boolean instantiateTo(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.INSTANTIATE, cause));
if (value < 0) {
//TODO: explication?
this.contradiction(cause, EventType.INSTANTIATE, AbstractVariable.MSG_UNKNOWN);
}
int v = floor_sqrt(value);
if (v * v == value) { // is a perfect square ?
boolean done = var.updateLowerBound(-v, this);
done |= var.updateUpperBound(v, this);
EventType evt = EventType.DECUPP;
if (var.hasEnumeratedDomain()) {
done |= var.removeInterval(-v + 1, v - 1, cause);
evt = EventType.INSTANTIATE;
}
if (done) {
notifyMonitors(evt, cause);
}
return done;
} else { //otherwise, impossible value for instantiation
//TODO: explication?
this.contradiction(cause, EventType.INSTANTIATE, AbstractVariable.MSG_UNKNOWN);
}
return false;
}
@Override
public boolean updateLowerBound(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.INCLOW, cause));
if (value <= 0) {
return false;
}
int floorV = floor_sqrt(value);
boolean done = var.removeInterval(-floorV + 1, floorV - 1, this);
if (done) {
EventType evt = EventType.INCLOW;
if(instantiated()){
evt = EventType.INSTANTIATE;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
notifyMonitors(evt, cause);
}
return done;
}
@Override
public boolean updateUpperBound(int value, ICause cause) throws ContradictionException {
records.forEach(beforeModification.set(this, EventType.DECUPP, cause));
if (value < 0) {
//TODO: explication?
this.contradiction(cause, EventType.DECUPP, AbstractVariable.MSG_UNKNOWN);
}
int floorV = floor_sqrt(value);
boolean done = var.updateLowerBound(-floorV, this);
done |= var.updateUpperBound(floorV, this);
if (done) {
EventType evt = EventType.DECUPP;
if(instantiated()){
evt = EventType.INSTANTIATE;
if (cause.reactOnPromotion()) {
cause = Cause.Null;
}
}
notifyMonitors(evt, cause);
}
return done;
}
@Override
public boolean contains(int value) {
return var.contains(value) || var.contains(-value);
}
@Override
public boolean instantiatedTo(int value) {
return var.instantiatedTo(value) || var.instantiatedTo(-value);
}
@Override
public int getValue() {
int v = var.getLB();
return v * v;
}
@Override
public int getLB() {
if (var.contains(0)) {
return 0;
}
int elb = var.getLB();
if (elb > 0) {
return elb * elb;
}
int eub = var.getUB();
if (eub < 0) {
return eub * eub;
}
int l = var.previousValue(0);
int u = var.nextValue(0);
if (-l < u) {
return l * l;
} else {
return u * u;
}
}
@Override
public int getUB() {
int elb = var.getLB();
int eub = var.getUB();
int mm = -elb;
if (elb < 0) {
if (eub > 0 && eub > mm) {
mm = eub;
}
} else {
mm = eub;
}
return mm * mm;
}
@Override
public int nextValue(int v) {
if (v < 0 && var.contains(0)) {
return 0;
}
int floorV = floor_sqrt(v);
int l = var.previousValue(-floorV);
if (l == Integer.MIN_VALUE) {
l = Integer.MAX_VALUE;
} else {
l = Math.abs(l);
}
int u = var.nextValue(floorV);
int min = Math.min(l, Math.abs(u));
if (min == Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return min * min;
}
@Override
public int previousValue(int v) {
if (v < 0) {
return Integer.MIN_VALUE;
}
int floorV = floor_sqrt(v);
if (floorV * floorV != v) {
floorV++;
}
int l = var.nextValue(-floorV);
if (l == Integer.MIN_VALUE) {
l = Integer.MAX_VALUE;
} else {
l = Math.abs(l);
}
int u = var.previousValue(floorV);
int max = Math.max(l, Math.abs(u));
if (max == Integer.MAX_VALUE) {
return Integer.MIN_VALUE;
}
return max * max;
}
@Override
public String toString() {
return "(" + this.var.toString() + "^2) = [" + getLB() + "," + getUB() + "]";
}
@Override
public boolean hasEnumeratedDomain() {
return true;
}
@Override
public int getType() {
return Variable.INTEGER;
}
@Override
public int getDomainSize() {
return var.getDomainSize();
}
@Override
public Explanation explain(VariableState what) {
return var.explain(VariableState.DOM);
}
@Override
public Explanation explain(VariableState what, int val) {
int fl = floor_sqrt(val);
Explanation explanation = new Explanation();
explanation.add(var.explain(what, fl));
explanation.add(var.explain(what, -fl));
return explanation;
}
@Override
public DisposableValueIterator getValueIterator(boolean bottomUp) {
if (_viterator == null || !_viterator.isReusable()) {
_viterator = new DisposableValueIterator() {
DisposableValueIterator u2l;
DisposableValueIterator l2u;
int vl2u;
int vu2l;
@Override
public void bottomUpInit() {
l2u = var.getValueIterator(true);
u2l = var.getValueIterator(false);
super.bottomUpInit();
while (l2u.hasNext()) {
this.vl2u = l2u.next();
if (this.vl2u >= 0) break;
}
while (u2l.hasPrevious()) {
this.vu2l = u2l.previous();
if (this.vu2l <= 0) break;
}
}
@Override
public void topDownInit() {
l2u = var.getValueIterator(true);
u2l = var.getValueIterator(false);
super.topDownInit();
if (l2u.hasNext()) {
this.vl2u = l2u.next();
}
if (u2l.hasPrevious()) {
this.vu2l = u2l.previous();
}
}
@Override
public boolean hasNext() {
return this.vl2u < Integer.MAX_VALUE || this.vu2l > -Integer.MAX_VALUE;
}
@Override
public boolean hasPrevious() {
return this.vl2u <= 0 || this.vu2l >= 0;
}
@Override
public int next() {
int min = this.vl2u < -this.vu2l ? this.vl2u : -this.vu2l;
if (this.vl2u == min) {
if (this.l2u.hasNext()) {
this.vl2u = l2u.next();
} else {
this.vl2u = Integer.MAX_VALUE;
}
}
if (-this.vu2l == min) {
if (this.u2l.hasPrevious()) {
this.vu2l = u2l.previous();
} else {
this.vu2l = -Integer.MAX_VALUE;
}
}
return min * min;
}
@Override
public int previous() {
int max = -this.vl2u > this.vu2l ? -this.vl2u : this.vu2l;
if (-this.vl2u == max && this.l2u.hasNext()) {
this.vl2u = this.l2u.next();
}
if (this.vu2l == max && this.u2l.hasPrevious()) {
this.vu2l = u2l.previous();
}
return max * max;
}
@Override
public void dispose() {
super.dispose();
l2u.dispose();
u2l.dispose();
}
};
}
if (bottomUp) {
_viterator.bottomUpInit();
} else {
_viterator.topDownInit();
}
return _viterator;
}
@Override
public DisposableRangeIterator getRangeIterator(boolean bottomUp) {
if (_riterator == null || !_riterator.isReusable()) {
_riterator = new DisposableRangeIterator() {
DisposableRangeIterator u2l;
DisposableRangeIterator l2u;
int ml2u;
int Ml2u;
int mu2l;
int Mu2l;
int value;
int bound;
@Override
public void bottomUpInit() {
l2u = var.getRangeIterator(true);
u2l = var.getRangeIterator(false);
super.bottomUpInit();
ml2u = Ml2u = mu2l = Mu2l = Integer.MAX_VALUE;
while (l2u.hasNext()) {
if (l2u.min() >= 0) {
ml2u = l2u.min();
Ml2u = l2u.max();
l2u.next();
break;
}
if (l2u.max() >= 0) {
ml2u = 0;
Ml2u = l2u.max();
l2u.next();
break;
}
l2u.next();
}
while (u2l.hasPrevious()) {
if (u2l.max() <= 0) {
Mu2l = -u2l.min();
mu2l = -u2l.max();
u2l.previous();
break;
}
if (u2l.min() <= 0) {
mu2l = 0;
Mu2l = -u2l.min();
u2l.previous();
break;
}
u2l.previous();
}
_next();
}
@Override
public void topDownInit() {
l2u = var.getRangeIterator(true);
u2l = var.getRangeIterator(false);
super.topDownInit();
ml2u = Ml2u = mu2l = Mu2l = Integer.MIN_VALUE;
if (l2u.hasNext()) {
if (l2u.max() <= 0) {
this.ml2u = -l2u.max();
this.Ml2u = -l2u.min();
} else if (l2u.min() <= 0) {
this.ml2u = 0;
this.Ml2u = -l2u.min();
}
l2u.next();
}
if (u2l.hasPrevious()) {
if (u2l.min() >= 0) {
this.mu2l = u2l.min();
this.Mu2l = u2l.max();
} else if (u2l.max() >= 0) {
this.mu2l = 0;
this.Mu2l = u2l.max();
}
u2l.previous();
}
_previous();
}
@Override
public boolean hasNext() {
if (value < bound) {
value++;
}
return value < Integer.MAX_VALUE;
}
@Override
public boolean hasPrevious() {
if (value > bound) {
value--;
}
return value > Integer.MIN_VALUE;
}
@Override
public void next() {
if (value >= bound) {
_next();
}
}
private void _next() {
value = bound = Integer.MAX_VALUE;
// disjoint ranges
if (Ml2u < mu2l - 1) {
value = ml2u - 1; //-1 due to hasNext()
bound = Ml2u;
if (l2u.hasNext()) {
ml2u = l2u.min();
Ml2u = l2u.max();
l2u.next();
} else {
ml2u = Integer.MAX_VALUE;
Ml2u = Integer.MAX_VALUE;
}
} else if (Mu2l < ml2u - 1) {
value = mu2l - 1; //-1 due to hasNext()
bound = Mu2l;
if (u2l.hasPrevious()) {
Mu2l = -u2l.min();
mu2l = -u2l.max();
u2l.previous();
} else {
mu2l = Integer.MAX_VALUE;
Mu2l = Integer.MAX_VALUE;
}
} else {
// we build the current range
if (Ml2u + 1 == mu2l) {
value = ml2u - 1; //-1 due to hasNext()
bound = Mu2l;
} else if (Mu2l + 1 == ml2u) {
value = mu2l - 1; //-1 due to hasNext()
bound = Ml2u;
} else {
value = ml2u < mu2l ? ml2u : mu2l;
bound = Ml2u < Mu2l ? Ml2u : Mu2l;
}
boolean change;
do {
change = false;
if (value < ml2u && ml2u <= bound) {
bound = bound > Ml2u ? bound : Ml2u;
if (l2u.hasNext()) {
ml2u = l2u.min();
Ml2u = l2u.max();
l2u.next();
change = true;
} else {
ml2u = Integer.MAX_VALUE;
Ml2u = Integer.MAX_VALUE;
}
}
if (value < mu2l && mu2l <= bound) {
bound = bound > Mu2l ? bound : Mu2l;
if (u2l.hasPrevious()) {
Mu2l = -u2l.min();
mu2l = -u2l.max();
u2l.previous();
change = true;
} else {
mu2l = Integer.MAX_VALUE;
Mu2l = Integer.MAX_VALUE;
}
}
} while (change);
}
}
@Override
public void previous() {
if (value <= bound) {
_previous();
}
}
private void _previous() {
value = bound = Integer.MIN_VALUE;
// disjoint ranges
if (ml2u > Mu2l + 1) {
bound = ml2u;
value = Ml2u + 1; //+1 due to hasPrevious()
ml2u = Integer.MIN_VALUE;
Ml2u = Integer.MIN_VALUE;
if (l2u.hasNext()) {
//la: grer le 0 et les autres cas
if (l2u.max() <= 0) {
this.ml2u = -l2u.max();
this.Ml2u = -l2u.min();
} else if (l2u.min() <= 0) {
this.ml2u = 0;
this.Ml2u = -l2u.min();
}
l2u.next();
}
} else if (Mu2l + 1 < ml2u) {
bound = mu2l;
value = Mu2l + 1; //+1 due to hasPrevious()
mu2l = Integer.MIN_VALUE;
Mu2l = Integer.MIN_VALUE;
if (u2l.min() >= 0) {
this.mu2l = u2l.min();
this.Mu2l = u2l.max();
} else if (u2l.max() >= 0) {
this.mu2l = 0;
this.Mu2l = u2l.max();
}
} else {
// we build the current range
if (Ml2u + 1 == mu2l) {
bound = ml2u;
value = Mu2l + 1; //+1 due to hasPrevious()
} else if (Mu2l + 1 == ml2u) {
bound = mu2l;
value = Ml2u + 1; //+1 due to hasPrevious()
} else {
bound = ml2u > mu2l ? ml2u : mu2l;
value = (Ml2u > Mu2l ? Ml2u : Mu2l) + 1; //+1 due to hasPrevious()
}
boolean change;
do {
change = false;
if (bound <= Ml2u && Ml2u < value) {
bound = bound < ml2u ? bound : ml2u;
ml2u = Integer.MIN_VALUE;
Ml2u = Integer.MIN_VALUE;
if (l2u.hasNext()) {
if (l2u.max() <= 0) {
this.ml2u = -l2u.max();
this.Ml2u = -l2u.min();
} else if (l2u.min() <= 0) {
this.ml2u = 0;
this.Ml2u = -l2u.min();
}
l2u.next();
change = true;
}
}
if (bound <= mu2l && mu2l < value) {
bound = bound < mu2l ? bound : mu2l;
mu2l = Integer.MIN_VALUE;
Mu2l = Integer.MIN_VALUE;
if (u2l.hasPrevious()) {
if (u2l.min() >= 0) {
this.mu2l = u2l.min();
this.Mu2l = u2l.max();
} else if (u2l.max() >= 0) {
this.mu2l = 0;
this.Mu2l = u2l.max();
}
u2l.previous();
change = true;
}
}
} while (change);
}
}
@Override
public int min() {
return value * value;
}
@Override
public int max() {
return value * value;
}
@Override
public void dispose() {
super.dispose();
l2u.dispose();
u2l.dispose();
}
};
}
if (bottomUp) {
_riterator.bottomUpInit();
} else {
_riterator.topDownInit();
}
return _riterator;
}
@Override
public void transformEvent(EventType evt, ICause cause) throws ContradictionException {
if ((evt.mask & EventType.BOUND.mask) != 0) {
if (instantiated()) { // specific case where DOM_SIZE = 2 and LB = -UB
notifyMonitors(EventType.INSTANTIATE, cause);
} else { // otherwise, we do not know the previous values, so its hard to tell wether it is LB or UB mod
notifyMonitors(EventType.BOUND, cause);
}
} else {
notifyMonitors(evt, cause);
}
}
}
| issue#26: JGF comment
| solver/src/main/java/solver/variables/view/SqrView.java | issue#26: JGF comment | <ide><path>olver/src/main/java/solver/variables/view/SqrView.java
<ide>
<ide> @Override
<ide> public int getValue() {
<del> int v = var.getLB();
<del> return v * v;
<add> return getLB();
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | e47e1bfac5df12e863d851593988982752cc7d75 | 0 | DougFirErickson/libSBOLj,SynBioDex/libSBOLj | package org.sbolstandard.core2;
import static org.sbolstandard.core2.URIcompliance.createCompliantURI;
import static org.sbolstandard.core2.URIcompliance.isChildURIcompliant;
import static org.sbolstandard.core2.URIcompliance.isURIcompliant;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author Zhen Zhang
* @author Tramy Nguyen
* @author Nicholas Roehner
* @author Matthew Pocock
* @author Goksel Misirli
* @author Chris Myers
* @version 2.0-beta
*/
public class ModuleDefinition extends TopLevel {
private Set<URI> roles;
private HashMap<URI, Module> modules;
private HashMap<URI, Interaction> interactions;
private HashMap<URI, FunctionalComponent> functionalComponents;
private Set<URI> models;
ModuleDefinition(URI identity) {
super(identity);
this.roles = new HashSet<>();
this.modules = new HashMap<>();
this.interactions = new HashMap<>();
this.functionalComponents = new HashMap<>();
this.models = new HashSet<>();
}
private ModuleDefinition(ModuleDefinition moduleDefinition) {
super(moduleDefinition);
this.roles = new HashSet<>();
this.modules = new HashMap<>();
this.interactions = new HashMap<>();
this.functionalComponents = new HashMap<>();
this.models = new HashSet<>();
for (URI role : moduleDefinition.getRoles()) {
this.addRole(role);
}
for (Module subModule : moduleDefinition.getModules()) {
this.addModule(subModule.deepCopy());
}
for (Interaction interaction : moduleDefinition.getInteractions()) {
this.addInteraction(interaction.deepCopy());
}
for (FunctionalComponent component : moduleDefinition.getFunctionalComponents()) {
this.addFunctionalComponent(component.deepCopy());
}
this.setModels(moduleDefinition.getModelURIs());
}
/**
* Adds the specified role URI to this ModuleDefinition's set of role URIs.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @param roleURI
* @return {@code true} if this set did not already contain the specified role.
* @throws SBOLException if the associated SBOLDocument is not compliant
*/
public boolean addRole(URI roleURI) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
return roles.add(roleURI);
}
/**
* Removes the specified role reference from the set of role references.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @param roleURI
* @return {@code true} if the matching role reference is removed successfully, {@code false} otherwise.
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public boolean removeRole(URI roleURI) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
return roles.remove(roleURI);
}
/**
* Clears the existing set of role references first, then adds the specified
* set of the role references to this ModuleDefinition object.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @param roles
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public void setRoles(Set<URI> roles) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
clearRoles();
if (roles == null)
return;
for (URI role : roles) {
addRole(role);
}
}
/**
* Returns the set of role instances owned by this ModuleDefinition object.
* @return the set of role instances owned by this ModuleDefinition object.
*/
public Set<URI> getRoles() {
Set<URI> result = new HashSet<>();
result.addAll(roles);
return result;
}
/**
* Checks if the given role URI is included in this ModuleDefinition
* object's set of reference role URIs.
* @param roleURI
* @return {@code true} if this set contains the specified URI.
*/
public boolean containsRole(URI roleURI) {
return roles.contains(roleURI);
}
/**
* Removes all entries of this ModuleDefinition object's set of role URIs.
* The set will be empty after this call returns.
*/
public void clearRoles() {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
roles.clear();
}
/**
* Calls the ModuleInstantiation constructor to create a new instance using
* the specified parameters,
* then adds to the list of ModuleInstantiation instances owned by this
* ModuleDefinition object.
*
* @param identity
* @param moduleDefinitionURI
* @return a Module instance
*/
Module createModule(URI identity, URI moduleDefinitionURI) {
Module module = new Module(identity, moduleDefinitionURI);
addModule(module);
return module;
}
/**
* Creates a child Module instance for this ModuleDefinition object with the
* specified arguments, and then adds to this ModuleDefinition's list of Module instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance
* is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* This method creates a compliant Module URI with the default URI prefix
* for this SBOLDocument instance, and the given {@code displayId} and {@code version}.
* It then calls {@link #createModule(String, URI)} with this component
* definition URI.
*
* @param displayId
* @param moduleId
* @param version
* @return a Module instance
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public Module createModule(String displayId, String moduleId, String version) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
URI module = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
TopLevel.MODULE_DEFINITION, moduleId, version, sbolDocument.isTypesInURIs());
return createModule(displayId, module);
}
/**
* Creates a child Module instance for this ModuleDefinition object with the
* specified arguments, and then adds to this ModuleDefinition's list of Module instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* If the SBOLDocument instance already completely specifies all URIs and
* the given {@code moduleDefinitionURI} is not found in them, then an
* {@link IllegalArgumentException} is thrown.
* <p>
* This method creates a compliant Module URI with the default URI prefix
* for this SBOLDocument instance, the given {@code displayId}, and this
* ModuleDefinition object's version.
*
* @param displayId
* @param moduleDefinitionURI
* @return a Module instance
* @throws SBOLException if the associated SBOLDocument is not compliant.
*
* @throws IllegalArgumentException if the associated SBOLDocument instance already completely specifies all URIs and the given {@code definitionURI}
is not found in them.
*/
public Module createModule(String displayId, URI moduleDefinitionURI) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getModuleDefinition(moduleDefinitionURI) == null) {
throw new IllegalArgumentException("Module definition '" + moduleDefinitionURI
+ "' does not exist.");
}
}
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
URI newModuleURI = createCompliantURI(URIprefix, displayId, version);
Module m = createModule(newModuleURI, moduleDefinitionURI);
m.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
m.setDisplayId(displayId);
m.setVersion(version);
return m;
}
/**
* Adds the given {@code module} argument to this ModuleDefinition's list of
* Module instances, and then associates it with the SBOLDocument instance that also contains
* this ModuleDefinition object.
* @param module
*/
void addModule(Module module) {
addChildSafely(module, modules, "module", functionalComponents, interactions);
module.setSBOLDocument(this.sbolDocument);
module.setModuleDefinition(this);
}
/**
* Removes the specified Module instance from the list of Module instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @param module
* @return {@code true} if the matching Module instance is removed successfully, {@code false} otherwise.
* @throws SBOLException if the associated SBOLDocument is not compliant.
*
*/
public boolean removeModule(Module module) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
return removeChildSafely(module, modules);
}
/**
* Returns the Module instance matching the given displayId from the list of
* Module instances.
*
* @return the matching Module instance if present, or <code>null</code> if
* not present.
*/
public Module getModule(String displayId) {
return modules.get(createCompliantURI(this.getPersistentIdentity().toString(), displayId,
this.getVersion()));
}
/**
* Returns the instance matching the given URI from the list of Module instances.
*
*
* @return the matching Module instance if present, or <code>null</code> if
* not present.
*/
public Module getModule(URI moduleURI) {
return modules.get(moduleURI);
}
/**
*
* Returns the set of Module instances owned by this ModuleDefinition object.
*
* @return the set of Module instances owned by this ModuleDefinition object.
*
*/
public Set<Module> getModules() {
return new HashSet<>(modules.values());
}
/**
* Removes all entries of this ModuleDefinition object's list of Module
* objects.
* The set will be empty after this call returns.
*/
public void clearModules() {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
Object[] valueSetArray = modules.values().toArray();
for (Object module : valueSetArray) {
removeModule((Module) module);
}
}
/**
* Clears the existing set of Module instances first, then adds the given
* set of the Module instances to this ModuleDefinition object.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @param modules
* @throws SBOLException if the associated SBOLDocument is not compliant.
*
*/
void setModules(List<Module> modules) {
clearModules();
if (modules == null)
return;
for (Module module : modules) {
addModule(module);
}
}
/**
* Calls the Interaction constructor to create a new instance using the
* given parameters, then adds to the list of Interaction instances owned by this
* ModuleDefinition object.
*
* @return the created Interaction instance.
*/
Interaction createInteraction(URI identity, Set<URI> type) {
Interaction interaction = new Interaction(identity, type);
addInteraction(interaction);
return interaction;
}
/**
* Creates a child Interaction object for this ModuleDefinition object with
* the given arguments, and then adds to this ModuleDefinition's list of Interaction instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* This method creates a compliant Interaction URI with the default URI
* prefix for this SBOLDocument instance, the given {@code displayId}, and this
* ModuleDefinition object's version.
*
* @param displayId
* @param types
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public Interaction createInteraction(String displayId, Set<URI> types) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
URI newInteractionURI = createCompliantURI(URIprefix, displayId, version);
Interaction i = createInteraction(newInteractionURI, types);
i.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
i.setDisplayId(displayId);
i.setVersion(version);
return i;
}
/**
* Adds the given Interaction instance to the list of Interaction instances.
*/
void addInteraction(Interaction interaction) {
addChildSafely(interaction, interactions, "interaction", functionalComponents, modules);
interaction.setSBOLDocument(this.sbolDocument);
interaction.setModuleDefinition(this);
}
/**
* Removes the given Interaction instance from the list of Interaction
* instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @return {@code true} if the matching Interaction instance is removed successfully, {@code false} otherwise.
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public boolean removeInteraction(Interaction interaction) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
return removeChildSafely(interaction, interactions);
}
/**
* Returns the instance matching the given Interaction displayId from the
* list of Interaction instances.
*
* @return the matching instance if present, or <code>null</code> if not
* present.
*/
public Interaction getInteraction(String displayId) {
return interactions.get(createCompliantURI(this.getPersistentIdentity().toString(),
displayId, this.getVersion()));
}
/**
*
* Returns the instance matching the given Interaction URI from the list of
* Interaction instances.
*
* @return the matching instance if present, or <code>null</code> if not
* present.
*/
public Interaction getInteraction(URI interactionURI) {
return interactions.get(interactionURI);
}
/**
* Returns the set of interaction instances owned by this ModuleDefinition
* object.
*
* @return the set of interaction instances owned by this ModuleDefinition
* object.
*/
public Set<Interaction> getInteractions() {
return new HashSet<>(interactions.values());
}
/**
* Removes all entries of this ModuleDefinition object's list of Instance
* objects.
*
* The list will be empty after this call returns.
*/
public void clearInteractions() {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
Object[] valueSetArray = interactions.values().toArray();
for (Object interaction : valueSetArray) {
removeInteraction((Interaction) interaction);
}
}
/**
* Clears the existing list of interaction instances, then appends all of
* the elements in the given collection to the end of this list.
*/
void setInteractions(
List<Interaction> interactions) {
clearInteractions();
if (interactions == null)
return;
for (Interaction interaction : interactions) {
addInteraction(interaction);
}
}
/**
* @param identity
* @param access
* @param definitionURI
* @param direction
* @return a FunctionalComponent instance.
*/
FunctionalComponent createFunctionalComponent(URI identity, AccessType access,
URI definitionURI, DirectionType direction) {
FunctionalComponent functionalComponent =
new FunctionalComponent(identity, access, definitionURI, direction);
addFunctionalComponent(functionalComponent);
return functionalComponent;
}
/**
* Creates a child FunctionalComponent instance for this ModuleDefinition
* object with the given arguments, and then adds to this ModuleDefinition's list of FunctionalComponent
* instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance
* is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* This method creates a compliant FunctionalComponent URI with the default
* URI prefix for this SBOLDocument instance, and the given {@code definition} and {@code version}.
* It then calls {@link #createFunctionalComponent(String, AccessType, URI,DirectionType)}
* with this component definition URI.
*
* @param displayId
* @param access
* @param definition
* @param version
* @param direction
* @return a FunctionalComponent instance
* @throws SBOLException if the associated SBOLDocument is not compliant
*/
public FunctionalComponent createFunctionalComponent(String displayId, AccessType access,
String definition, String version, DirectionType direction) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
URI definitionURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
TopLevel.COMPONENT_DEFINITION, definition, version, sbolDocument.isTypesInURIs());
return createFunctionalComponent(displayId, access, definitionURI, direction);
}
/**
* Creates a child FunctionalComponent instance for this ModuleDefinition
* object with the given arguments, and then adds to this ModuleDefinition's list of FunctionalComponent
* instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* If the SBOLDocument instance already completely specifies all URIs and
* the given {@code fcURI} is not found in them, then an {@link IllegalArgumentException} is thrown.
* <p>
* This method creates a compliant FunctionalComponent URI with the default
* URI prefix for this SBOLDocument instance, the given {@code displayId}, and this
* ModuleDefinition object's version.
*
* @param displayId
* @param access
* @param fcURI
* @param direction
* @return a FunctionalComponent instance
* @throws SBOLException if the associated SBOLDocument is not compliant.
* @throws IllegalArgumentException if the associated SBOLDocument instance already completely
specifies all URIs and the given {@code definitionURI} is not found in them.
*/
public FunctionalComponent createFunctionalComponent(String displayId, AccessType access,
URI fcURI, DirectionType direction) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getComponentDefinition(fcURI) == null) {
throw new IllegalArgumentException("Component '" + fcURI
+ "' does not exist.");
}
}
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
URI functionalComponentURI = createCompliantURI(URIprefix, displayId, version);
FunctionalComponent fc = createFunctionalComponent(functionalComponentURI, access,
fcURI, direction);
fc.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
fc.setDisplayId(displayId);
fc.setVersion(version);
return fc;
}
/**
* Adds the given instance to the list of components.
*/
void addFunctionalComponent(FunctionalComponent functionalComponent) {
addChildSafely(functionalComponent, functionalComponents, "functionalComponent",
interactions, modules);
functionalComponent.setSBOLDocument(this.sbolDocument);
}
/**
* Removes the given FunctionalComponent instance from the list of
* FunctionalComponent instances.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* Before removing the given FunctionalComponent instance, this method
* checks if it is referenced by any children and grandchildren instances of this ModuleDefinition object.
*
* @return {@code true} if the matching FunctionalComponent instance is removed successfully,
* {@code false} otherwise.
* @throws SBOLException if the associated SBOLDocument is not compliant.
* @throws SBOLException the given FunctionalComponent instance is referenced.
*/
public boolean removeFunctionalComponent(FunctionalComponent functionalComponent) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
for (Interaction i : interactions.values()) {
for (Participation p : i.getParticipations()) {
if (p.getParticipantURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
for (FunctionalComponent c : functionalComponents.values()) {
for (MapsTo mt : c.getMapsTos()) {
if (mt.getLocalURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
for (Module m : modules.values()) {
for (MapsTo mt : m.getMapsTos()) {
if (mt.getLocalURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
if (sbolDocument != null) {
for (ModuleDefinition md : sbolDocument.getModuleDefinitions()) {
for (Module m : md.getModules()) {
for (MapsTo mt : m.getMapsTos()) {
if (mt.getRemoteURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove "
+ functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
}
}
return removeChildSafely(functionalComponent, functionalComponents);
}
/**
* Returns the instance matching the given displayId from the list of FunctionalComponent instances.
*
* @return the matching instance if present, or {@code null} if not present.
*/
public FunctionalComponent getFunctionalComponent(String displayId) {
return functionalComponents.get(createCompliantURI(this.getPersistentIdentity().toString(),
displayId, this.getVersion()));
}
/**
* Returns the instance matching the given FunctionalComponent URI from the
* list of FunctionalComponent instances.
*
* @return the matching FunctionalComponent instance if present, or
* {@code null} if not present.
*/
public FunctionalComponent getFunctionalComponent(URI componentURI) {
return functionalComponents.get(componentURI);
}
/**
* Returns the set of FunctionalComponent instances owned by this
* ModuleDefinition object.
*
* @return the set of FunctionalComponent instances owned by this
* ModuleDefinition object.
*/
public Set<FunctionalComponent> getFunctionalComponents() {
return new HashSet<>(functionalComponents.values());
}
/**
* Removes all entries of this ModuleDefinition object's list of
* FunctionalComponent objects.
* The list will be empty after this call returns.
*/
public void clearFunctionalComponents() {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
Object[] valueSetArray = functionalComponents.values().toArray();
for (Object functionalComponent : valueSetArray) {
removeFunctionalComponent((FunctionalComponent) functionalComponent);
}
}
/**
* Clears the existing list of FunctionalComponent instances, then appends
* all of the elements in the given collection to the end of this list.
*/
void setFunctionalComponents(
List<FunctionalComponent> components) {
clearFunctionalComponents();
if (components == null)
return;
for (FunctionalComponent component : components) {
addFunctionalComponent(component);
}
}
/**
* Adds the URI of the given Model instance to this ComponentDefinition's
* set of reference Model URIs.
* <p>
* If this ComponentDefinition object belongs to an SBOLDocument instance,
* then the SBOLDcouement instance
* is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* If the SBOLDocument instance already completely specifies all its
* reference URIs and the given model's URI
* is not found in them, then an {@link IllegalArgumentException} is thrown.
*
* @param model
* @throws SBOLException
* if the associated SBOLDocument is not compliant
* @throws IllegalArgumentException
* if the associated SBOLDocument instance already completely specifies all URIs
* and the given Model instance's URI is not found in them.
* @return {@code true} if this set did not already contain the given Model
* instance URI.
*/
public void addModel(Model model) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getModel(model.getIdentity()) == null) {
throw new IllegalArgumentException("Model '" + model.getIdentity()
+ "' does not exist.");
}
}
this.addModel(model.getIdentity());
}
/**
*
* Creates a compliant model URI and then adds it to this ModuleDefinition
* object's set of reference model URIs. The model argument specifies the reference
* Model's display ID, and the version argument specifies its version.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed be edited.
*
* @param model
* @param version
* @throws SBOLException if the associated SBOLDocument is not compliant
*/
public void addModel(String model, String version) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
URI modelURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
TopLevel.MODEL, model, version, sbolDocument.isTypesInURIs());
addModel(modelURI);
}
/**
* Adds the given Model URI to this ModuleDefinition's set of reference
* Model URIs.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance
* is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
* <p>
* If the SBOLDocument instance already completely specifies all its
* reference URIs and the given {@code modelURI}
* is not found in them, then an {@link IllegalArgumentException} is thrown.
*
* @param modelURI
* @throws SBOLException if the associated SBOLDocument is not compliant
* @throws IllegalArgumentException if the associated SBOLDocument instance already completely
* specifies all URIs and the given {@code modelURI} is not found in them.
*/
public void addModel(URI modelURI) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getModel(modelURI) == null) {
throw new IllegalArgumentException("Model '" + modelURI + "' does not exist.");
}
}
models.add(modelURI);
}
/**
* Removes the given Model reference from the set of Model references.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance
* is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @return {@code true} if the matching Model reference is removed successfully,
* {@code false} otherwise.
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public boolean removeModel(URI modelURI) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
return models.remove(modelURI);
}
/**
* Clears the existing set of Model references first, then adds the given
* set of the Model references to this ModuleDefinition object.
* <p>
* If this ModuleDefinition object belongs to an SBOLDocument instance, then
* the SBOLDcouement instance
* is checked for compliance first. Only a compliant SBOLDocument instance
* is allowed to be edited.
*
* @param models
* @throws SBOLException if the associated SBOLDocument is not compliant.
*/
public void setModels(Set<URI> models) {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
clearModels();
if (models == null)
return;
for (URI model : models) {
addModel(model);
}
}
/**
* Returns the set of Model URIs referenced by this ModuleDefinition's object.
*
* @return the set of Model URIs referenced by this ModuleDefinition's object.
*
*/
public Set<URI> getModelURIs() {
Set<URI> result = new HashSet<>();
result.addAll(models);
return result;
}
/**
* Returns the set of Model instances referenced by this ModuleDefinition object.
*
* @return the set of Model instances referenced by this ModuleDefinition object
*/
public Set<Model> getModels() {
Set<Model> result = new HashSet<>();
for (URI modelURI : models) {
Model model = sbolDocument.getModel(modelURI);
result.add(model);
}
return result;
}
/**
* Checks if the given model URI is included in this ModuleDefinition
* object's set of reference Model URIs.
*
* @param modelURI
* @return {@code true} if this set contains the given URI.
*/
public boolean containsModel(URI modelURI) {
return models.contains(modelURI);
}
/**
* Removes all entries of this ModuleDefinition object's set of reference
* Model URIs.
* The set will be empty after this call returns.
*/
public void clearModels() {
if (sbolDocument != null)
sbolDocument.checkReadOnly();
models.clear();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((functionalComponents == null) ? 0 : functionalComponents.hashCode());
result = prime * result + ((interactions == null) ? 0 : interactions.hashCode());
result = prime * result + ((models == null) ? 0 : models.hashCode());
result = prime * result + ((roles == null) ? 0 : roles.hashCode());
result = prime * result + ((modules == null) ? 0 : modules.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ModuleDefinition other = (ModuleDefinition) obj;
if (functionalComponents == null) {
if (other.functionalComponents != null)
return false;
} else if (!functionalComponents.equals(other.functionalComponents))
return false;
if (interactions == null) {
if (other.interactions != null)
return false;
} else if (!interactions.equals(other.interactions))
return false;
if (models == null) {
if (other.models != null)
return false;
} else if (!models.equals(other.models))
return false;
if (roles == null) {
if (other.roles != null)
return false;
} else if (!roles.equals(other.roles))
return false;
if (modules == null) {
if (other.modules != null)
return false;
} else if (!modules.equals(other.modules))
return false;
return true;
}
@Override
protected ModuleDefinition deepCopy() {
return new ModuleDefinition(this);
}
// /**
// * @param newDisplayId
// * @return
// */
// public ModuleDefinition copy(String newDisplayId) {
// ModuleDefinition cloned = (ModuleDefinition) super.copy(newDisplayId);
// cloned.updateCompliantURI(newDisplayId);
// return cloned;
// }
//
//
// /* (non-Javadoc)
// * @see
// org.sbolstandard.core2.abstract_classes.TopLevel#updateDisplayId(java.lang.String)
// */
// protected void updateCompliantURI(String newDisplayId) {
// super.updateCompliantURI(newDisplayId);
// if (isTopLevelURIcompliant(this.getIdentity())) {
// // TODO Change all of its children's displayIds in their URIs.
// }
// }
//
// /**
// * Get a deep copy of the object first, and set its major version to the
// given value, and minor version to "0".
// * @param newVersion
// * @return the copied {@link ComponentDefinition} instance with the given
// major version.
// */
// public ModuleDefinition newVersion(String newVersion) {
// ModuleDefinition cloned = (ModuleDefinition)
// super.newVersion(newVersion);
// cloned.updateVersion(newVersion);
// return cloned;
// }
//
// /* (non-Javadoc)
// * @see
// org.sbolstandard.core2.abstract_classes.TopLevel#updateVersion(java.lang.String)
// */
// protected void updateVersion(String newVersion) {
// super.updateVersion(newVersion);
// if (isTopLevelURIcompliant(this.getIdentity())) {
// // TODO Change all of its children's versions in their URIs.
// }
// }
// /**
// *
// * Check if the given key exists in any hash maps in this class other than
// * the one with the given keySet. This method
// *
// * constructs a set of key sets for other hash maps first, and then checks
// * if the key exists.
// *
// * @return <code>true</code> if the given key exists in other hash maps.
// */
// private boolean keyExistsInOtherMaps(Set<URI> keySet, URI key) {
// Set<Set<URI>> complementSet = new HashSet<>();
// complementSet.add(functionalComponents.keySet());
// complementSet.add(interactions.keySet());
// complementSet.remove(keySet);
// for (Set<URI> otherKeySet : complementSet) {
// if (otherKeySet.contains(key)) {
// return true;
// }
// }
// return false;
// }
/*
* (non-Javadoc)
*
* @see
* org.sbolstandard.core2.abstract_classes.TopLevel#copy(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
ModuleDefinition copy(String URIprefix, String displayId, String version) {
ModuleDefinition cloned = this.deepCopy();
cloned.setWasDerivedFrom(this.getIdentity());
cloned.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
cloned.setDisplayId(displayId);
cloned.setVersion(version);
URI newIdentity = createCompliantURI(URIprefix, displayId, version);
cloned.setIdentity(newIdentity);
int count = 0;
for (FunctionalComponent component : cloned.getFunctionalComponents()) {
if (!component.isSetDisplayId())
component.setDisplayId("functionalComponent" + ++count);
component.updateCompliantURI(cloned.getPersistentIdentity().toString(),
component.getDisplayId(), version);
cloned.removeChildSafely(component, cloned.functionalComponents);
cloned.addFunctionalComponent(component);
}
count = 0;
for (Module module : cloned.getModules()) {
if (!module.isSetDisplayId())
module.setDisplayId("module" + ++count);
module.updateCompliantURI(cloned.getPersistentIdentity().toString(),
module.getDisplayId(), version);
cloned.removeChildSafely(module, cloned.modules);
cloned.addModule(module);
}
count = 0;
for (Interaction interaction : cloned.getInteractions()) {
if (!interaction.isSetDisplayId())
interaction.setDisplayId("interaction" + ++count);
interaction.updateCompliantURI(cloned.getPersistentIdentity().toString(),
interaction.getDisplayId(), version);
cloned.removeChildSafely(interaction, cloned.interactions);
cloned.addInteraction(interaction);
}
return cloned;
}
/*
* (non-Javadoc)
*
* @see
* org.sbolstandard.core2.abstract_classes.TopLevel#updateCompliantURI(java
* .lang.String, java.lang.String, java.lang.String)
*/
protected boolean checkDescendantsURIcompliance() {
// codereview: spaghetti
if (!isURIcompliant(this.getIdentity(), 0)) { // ComponentDefinition to
// be copied has
// non-compliant URI.
return false;
}
boolean allDescendantsCompliant = true;
if (!this.getModules().isEmpty()) {
for (Module module : this.getModules()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(this.getIdentity(), module.getIdentity());
if (!allDescendantsCompliant) { // Current sequence constraint
// has non-compliant URI.
return allDescendantsCompliant;
}
if (!module.getMapsTos().isEmpty()) {
// Check compliance of Module's children
for (MapsTo mapsTo : module.getMapsTos()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(module.getIdentity(), mapsTo.getIdentity());
if (!allDescendantsCompliant) { // Current mapsTo has
// non-compliant URI.
return allDescendantsCompliant;
}
}
}
}
}
if (!this.getFunctionalComponents().isEmpty()) {
for (FunctionalComponent functionalComponent : this.getFunctionalComponents()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(this.getIdentity(), functionalComponent.getIdentity());
if (!allDescendantsCompliant) { // Current component has
// non-compliant URI.
return allDescendantsCompliant;
}
if (!functionalComponent.getMapsTos().isEmpty()) {
// Check compliance of Component's children
for (MapsTo mapsTo : functionalComponent.getMapsTos()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(functionalComponent.getIdentity(),
mapsTo.getIdentity());
if (!allDescendantsCompliant) { // Current mapsTo has
// non-compliant URI.
return allDescendantsCompliant;
}
}
}
}
}
if (!this.getInteractions().isEmpty()) {
for (Interaction interaction : this.getInteractions()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(this.getIdentity(), interaction.getIdentity());
if (!allDescendantsCompliant) { // Current interaction has
// non-compliant URI.
return allDescendantsCompliant;
}
for (Participation participation : interaction.getParticipations()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(interaction.getIdentity(), participation.getIdentity());
if (!allDescendantsCompliant) { // Current participation has
// non-compliant URI.
return allDescendantsCompliant;
}
}
}
}
// All descendants of this ComponentDefinition object have compliant
// URIs.
return allDescendantsCompliant;
}
protected boolean isComplete() {
if (sbolDocument == null)
return false;
for (URI modelURI : models) {
if (sbolDocument.getModel(modelURI) == null)
return false;
}
for (FunctionalComponent functionalComponent : getFunctionalComponents()) {
if (functionalComponent.getDefinition() == null)
return false;
}
for (Module module : getModules()) {
if (module.getDefinition() == null)
return false;
}
return true;
}
}
| core2/src/main/java/org/sbolstandard/core2/ModuleDefinition.java | package org.sbolstandard.core2;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.sbolstandard.core2.URIcompliance.*;
/**
* @author Zhen Zhang
* @author Tramy Nguyen
* @author Nicholas Roehner
* @author Matthew Pocock
* @author Goksel Misirli
* @author Chris Myers
* @version 2.0-beta
*/
public class ModuleDefinition extends TopLevel {
private Set<URI> roles;
private HashMap<URI, Module> modules;
private HashMap<URI, Interaction> interactions;
private HashMap<URI, FunctionalComponent> functionalComponents;
private Set<URI> models;
ModuleDefinition(URI identity) {
super(identity);
this.roles = new HashSet<>();
this.modules = new HashMap<>();
this.interactions = new HashMap<>();
this.functionalComponents = new HashMap<>();
this.models = new HashSet<>();
}
private ModuleDefinition(ModuleDefinition moduleDefinition) {
super(moduleDefinition);
this.roles = new HashSet<>();
this.modules = new HashMap<>();
this.interactions = new HashMap<>();
this.functionalComponents = new HashMap<>();
this.models = new HashSet<>();
for (URI role : moduleDefinition.getRoles()) {
this.addRole(role);
}
for (Module subModule : moduleDefinition.getModules()) {
this.addModule(subModule.deepCopy());
}
for (Interaction interaction : moduleDefinition.getInteractions()) {
this.addInteraction(interaction.deepCopy());
}
for (FunctionalComponent component : moduleDefinition.getFunctionalComponents()) {
this.addFunctionalComponent(component.deepCopy());
}
this.setModels(moduleDefinition.getModelURIs());
}
/**
* Adds the specified element to the set <code>roles</code> if it is not already present.
* @return <code>true</code> if this set did not already contain the specified element.
*/
public boolean addRole(URI roleURI) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
return roles.add(roleURI);
}
/**
* Removes the specified element from the set <code>roles</code> if it is present.
* @return <code>true</code> if this set contained the specified element
*/
public boolean removeRole(URI roleURI) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
return roles.remove(roleURI);
}
/**
* Sets the field variable <code>roles</code> to the specified element.
*/
public void setRoles(Set<URI> roles) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
clearRoles();
if (roles==null) return;
for (URI role : roles) {
addRole(role);
}
}
/**
* Returns the field variable <code>roles</code>.
*/
public Set<URI> getRoles() {
Set<URI> result = new HashSet<>();
result.addAll(roles);
return result;
}
/**
* Returns true if the set <code>roles</code> contains the specified element.
* @return <code>true</code> if this set contains the specified element.
*/
public boolean containsRole(URI rolesURI) {
return roles.contains(rolesURI);
}
/**
* Removes all entries of the list of <code>roles</code> instances owned by this instance.
* The list will be empty after this call returns.
*/
public void clearRoles() {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
roles.clear();
}
// /**
// * Test if field variable <code>subModules</code> is set.
// * @return <code>true</code> if it is not an empty list.
// */
// public boolean isSetSubModules() {
// if (subModules.isEmpty())
// return false;
// else
// return true;
// }
/**
* Calls the ModuleInstantiation constructor to create a new instance using the specified parameters,
* then adds to the list of ModuleInstantiation instances owned by this instance.
* @return the created ModuleInstantiation instance.
*/
Module createModule(URI identity, URI moduleDefinitionURI) {
Module subModule = new Module(identity, moduleDefinitionURI);
addModule(subModule);
return subModule;
}
public Module createModule(String displayId, String moduleDefinitionId, String version) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
URI moduleDefinition = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
TopLevel.MODULE_DEFINITION, moduleDefinitionId, version, sbolDocument.isTypesInURIs());
return createModule(displayId,moduleDefinition);
}
public Module createModule(String displayId, URI moduleDefinitionURI) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getModuleDefinition(moduleDefinitionURI)==null) {
throw new IllegalArgumentException("Module definition '" + moduleDefinitionURI + "' does not exist.");
}
}
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
URI newModuleURI = createCompliantURI(URIprefix, displayId, version);
Module m = createModule(newModuleURI, moduleDefinitionURI);
m.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
m.setDisplayId(displayId);
m.setVersion(version);
return m;
}
/**
* Adds the specified instance to the list of subModules.
*/
void addModule(Module module) {
addChildSafely(module, modules, "module", functionalComponents, interactions);
module.setSBOLDocument(this.sbolDocument);
module.setModuleDefinition(this);
}
/**
* Removes the instance matching the specified URI from the list of subModules if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public boolean removeModule(Module module) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
return removeChildSafely(module,modules);
}
/**
* Returns the instance matching the specified displayId from the list of modules, if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public Module getModule(String displayId) {
return modules.get(createCompliantURI(this.getPersistentIdentity().toString(),displayId,this.getVersion()));
}
/**
* Returns the instance matching the specified URI from the list of modules, if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public Module getModule(URI moduleURI) {
return modules.get(moduleURI);
}
/**
* Returns the list of subModule instances owned by this instance.
* @return the list of subModule instances owned by this instance.
*/
public Set<Module> getModules() {
return new HashSet<>(modules.values());
}
/**
* Removes all entries of the list of modules owned by this instance. The list will be empty after this call returns.
*/
public void clearModules() {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
Object[] valueSetArray = modules.values().toArray();
for (Object module : valueSetArray) {
removeModule((Module)module);
}
}
/**
* Clears the existing list of subModule instances, then appends all of the elements in the specified collection to the end of this list.
*/
void setModules(List<Module> modules) {
clearModules();
if (modules==null) return;
for (Module module : modules) {
addModule(module);
}
}
// /**
// * Test if field variable <code>interactions</code> is set.
// * @return <code>true</code> if it is not an empty list.
// */
// public boolean isSetInteractions() {
// if (interactions.isEmpty())
// return false;
// else
// return true;
// }
/**
* Calls the Interaction constructor to create a new instance using the specified parameters,
* then adds to the list of Interaction instances owned by this instance.
* @return the created Interaction instance.
*/
Interaction createInteraction(URI identity, Set<URI> type) {
Interaction interaction = new Interaction(identity, type);
addInteraction(interaction);
return interaction;
}
public Interaction createInteraction(String displayId, Set<URI> type) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
URI newInteractionURI = createCompliantURI(URIprefix, displayId, version);
Interaction i = createInteraction(newInteractionURI, type);
i.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
i.setDisplayId(displayId);
i.setVersion(version);
return i;
}
/**
* Adds the specified instance to the list of interactions.
*/
void addInteraction(Interaction interaction) {
addChildSafely(interaction, interactions, "interaction", functionalComponents, modules);
interaction.setSBOLDocument(this.sbolDocument);
interaction.setModuleDefinition(this);
}
/**
* Removes the instance matching the specified URI from the list of interactions if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public boolean removeInteraction(Interaction interaction) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
return removeChildSafely(interaction,interactions);
}
/**
* Returns the instance matching the specified displayId from the list of interactions, if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public Interaction getInteraction(String displayId) {
return interactions.get(createCompliantURI(this.getPersistentIdentity().toString(),displayId,this.getVersion()));
}
/**
* Returns the instance matching the specified URI from the list of interactions, if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public Interaction getInteraction(URI interactionURI) {
return interactions.get(interactionURI);
}
/**
* Returns the list of interaction instances owned by this instance.
* @return the list of interaction instances owned by this instance.
*/
public Set<Interaction> getInteractions() {
return new HashSet<>(interactions.values());
}
/**
* Removes all entries of the list of interactions owned by this instance. The list will be empty after this call returns.
*/
public void clearInteractions() {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
Object[] valueSetArray = interactions.values().toArray();
for (Object interaction : valueSetArray) {
removeInteraction((Interaction)interaction);
}
}
/**
* Clears the existing list of interaction instances, then appends all of the elements in the specified collection to the end of this list.
*/
void setInteractions(
List<Interaction> interactions) {
clearInteractions();
if (interactions==null) return;
for (Interaction interaction : interactions) {
addInteraction(interaction);
}
}
// /**
// * Test if field variable <code>functionalInstantiations</code> is set.
// * @return <code>true</code> if it is not an empty list.
// */
// public boolean isSetComponents() {
// if (components.isEmpty())
// return false;
// else
// return true;
// }
/**
* Calls the FunctionalInstantiation constructor to create a new instance using the specified parameters,
* then adds to the list of FunctionalInstantiation instances owned by this instance.
* @return the created {@link FunctionalComponent} instance.
*/
FunctionalComponent createFunctionalComponent(URI identity, AccessType access,
URI definitionURI, DirectionType direction) {
FunctionalComponent functionalComponent =
new FunctionalComponent(identity, access, definitionURI, direction);
addFunctionalComponent(functionalComponent);
return functionalComponent;
}
public FunctionalComponent createFunctionalComponent(String displayId, AccessType access,
String definition, String version, DirectionType direction) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
URI definitionURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
TopLevel.COMPONENT_DEFINITION, definition, version, sbolDocument.isTypesInURIs());
return createFunctionalComponent(displayId,access,definitionURI,direction);
}
public FunctionalComponent createFunctionalComponent(String displayId, AccessType access,
URI definitionURI, DirectionType direction) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getComponentDefinition(definitionURI)==null) {
throw new IllegalArgumentException("Component definition '" + definitionURI + "' does not exist.");
}
}
String URIprefix = this.getPersistentIdentity().toString();
String version = this.getVersion();
URI functionalComponentURI = createCompliantURI(URIprefix, displayId, version);
FunctionalComponent fc = createFunctionalComponent(functionalComponentURI, access, definitionURI, direction);
fc.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
fc.setDisplayId(displayId);
fc.setVersion(version);
return fc;
}
/**
* Adds the specified instance to the list of components.
*/
void addFunctionalComponent(FunctionalComponent functionalComponent) {
addChildSafely(functionalComponent, functionalComponents, "functionalComponent", interactions, modules);
functionalComponent.setSBOLDocument(this.sbolDocument);
}
/**
* Removes the instance matching the specified URI from the list of functionalInstantiations if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public boolean removeFunctionalComponent(FunctionalComponent functionalComponent) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
for (Interaction i : interactions.values()) {
for (Participation p : i.getParticipations()) {
if (p.getParticipantURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
for (FunctionalComponent c : functionalComponents.values()) {
for (MapsTo mt : c.getMapsTos()) {
if (mt.getLocalURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
for (Module m : modules.values()) {
for (MapsTo mt : m.getMapsTos()) {
if (mt.getLocalURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
if (sbolDocument!=null) {
for (ModuleDefinition md : sbolDocument.getModuleDefinitions()) {
for (Module m : md.getModules()) {
for (MapsTo mt : m.getMapsTos()) {
if (mt.getRemoteURI().equals(functionalComponent.getIdentity())) {
throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
" since it is in use.");
}
}
}
}
}
return removeChildSafely(functionalComponent,functionalComponents);
}
/**
* Returns the instance matching the specified displayId from the list of functional instantiations, if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public FunctionalComponent getFunctionalComponent(String displayId) {
return functionalComponents.get(createCompliantURI(this.getPersistentIdentity().toString(),displayId,this.getVersion()));
}
/**
* Returns the instance matching the specified URI from the list of functional instantiations, if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public FunctionalComponent getFunctionalComponent(URI componentURI) {
return functionalComponents.get(componentURI);
}
/**
* Returns the list of functionalInstantiation instances owned by this instance.
* @return the list of functionalInstantiation instances owned by this instance.
*/
public Set<FunctionalComponent> getFunctionalComponents() {
return new HashSet<>(functionalComponents.values());
}
/**
* Removes all entries of the list of functional components owned by this instance. The list will be empty after this call returns.
*/
public void clearFunctionalComponents() {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
Object[] valueSetArray = functionalComponents.values().toArray();
for (Object functionalComponent : valueSetArray) {
removeFunctionalComponent((FunctionalComponent)functionalComponent);
}
}
/**
* Clears the existing list of functionalInstantiation instances, then appends all of the elements in the specified collection to the end of this list.
*/
void setFunctionalComponents(
List<FunctionalComponent> components) {
clearFunctionalComponents();
if (components==null) return;
for (FunctionalComponent component : components) {
addFunctionalComponent(component);
}
}
// /**
// * Set optional field variable <code>subModules</code> to an empty list.
// */
// public void unsetModuleInstantiations() {
// subModules.clear();
// }
//
// /**
// * Set optional field variable <code>interactions</code> to an empty list.
// */
// public void unsetInteractions() {
// interactions.clear();
// }
//
// /**
// * Set optional field variable <code>functionalInstantiations</code> to an empty list.
// */
// public void unsetFunctionalInstantiations() {
// functionalInstantiations.clear();
// }
// /**
// * Test if field variable <code>models</code> is set.
// * @return <code>true</code> if it is not an empty list.
// */
// public boolean isSetModels() {
// if (models.isEmpty())
// return false;
// else
// return true;
// }
public void addModel(String model,String version) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
URI modelURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
TopLevel.MODEL, model, version, sbolDocument.isTypesInURIs());
addModel(modelURI);
}
/**
* Adds the specified instance to the list of models.
*/
public void addModel(URI modelURI) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
if (sbolDocument != null && sbolDocument.isComplete()) {
if (sbolDocument.getModel(modelURI)==null) {
throw new IllegalArgumentException("Model '" + modelURI + "' does not exist.");
}
}
models.add(modelURI);
}
/**
* Removes the instance matching the specified URI from the list of models if present.
* @return the matching instance if present, or <code>null</code> if not present.
*/
public boolean removeModel(URI modelURI) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
return models.remove(modelURI);
}
/**
* Clears the existing list of model instances, then appends all of the elements in the specified collection to the end of this list.
*/
public void setModels(Set<URI> models) {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
clearModels();
if (models==null) return;
for (URI model : models) {
addModel(model);
}
}
/**
* Returns the set of model URIs referenced by this instance.
* @return the set of model URIs referenced by this instance
*/
public Set<URI> getModelURIs() {
Set<URI> result = new HashSet<>();
result.addAll(models);
return result;
}
/**
* Returns the set of models referenced by this instance.
* @return the set of models referenced by this instance
*/
public Set<Model> getModels() {
Set<Model> result = new HashSet<>();
for (URI modelURI : models) {
Model model = sbolDocument.getModel(modelURI);
result.add(model);
}
return result;
}
/**
* Returns true if the set <code>models</code> contains the specified element.
* @return <code>true</code> if this set contains the specified element.
*/
public boolean containsModel(URI modelURI) {
return models.contains(modelURI);
}
/**
* Removes all entries of the list of model instances owned by this instance.
* The list will be empty after this call returns.
*/
public void clearModels() {
if (sbolDocument!=null) sbolDocument.checkReadOnly();
models.clear();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((functionalComponents == null) ? 0 : functionalComponents.hashCode());
result = prime * result + ((interactions == null) ? 0 : interactions.hashCode());
result = prime * result + ((models == null) ? 0 : models.hashCode());
result = prime * result + ((roles == null) ? 0 : roles.hashCode());
result = prime * result + ((modules == null) ? 0 : modules.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ModuleDefinition other = (ModuleDefinition) obj;
if (functionalComponents == null) {
if (other.functionalComponents != null)
return false;
} else if (!functionalComponents.equals(other.functionalComponents))
return false;
if (interactions == null) {
if (other.interactions != null)
return false;
} else if (!interactions.equals(other.interactions))
return false;
if (models == null) {
if (other.models != null)
return false;
} else if (!models.equals(other.models))
return false;
if (roles == null) {
if (other.roles != null)
return false;
} else if (!roles.equals(other.roles))
return false;
if (modules == null) {
if (other.modules != null)
return false;
} else if (!modules.equals(other.modules))
return false;
return true;
}
@Override
protected ModuleDefinition deepCopy() {
return new ModuleDefinition(this);
}
// /**
// * @param newDisplayId
// * @return
// */
// public ModuleDefinition copy(String newDisplayId) {
// ModuleDefinition cloned = (ModuleDefinition) super.copy(newDisplayId);
// cloned.updateCompliantURI(newDisplayId);
// return cloned;
// }
//
//
// /* (non-Javadoc)
// * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateDisplayId(java.lang.String)
// */
// protected void updateCompliantURI(String newDisplayId) {
// super.updateCompliantURI(newDisplayId);
// if (isTopLevelURIcompliant(this.getIdentity())) {
// // TODO Change all of its children's displayIds in their URIs.
// }
// }
//
// /**
// * Get a deep copy of the object first, and set its major version to the specified value, and minor version to "0".
// * @param newVersion
// * @return the copied {@link ComponentDefinition} instance with the specified major version.
// */
// public ModuleDefinition newVersion(String newVersion) {
// ModuleDefinition cloned = (ModuleDefinition) super.newVersion(newVersion);
// cloned.updateVersion(newVersion);
// return cloned;
// }
//
// /* (non-Javadoc)
// * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateVersion(java.lang.String)
// */
// protected void updateVersion(String newVersion) {
// super.updateVersion(newVersion);
// if (isTopLevelURIcompliant(this.getIdentity())) {
// // TODO Change all of its children's versions in their URIs.
// }
// }
/**
* Check if the specified key exists in any hash maps in this class other than the one with the specified keySet. This method
* constructs a set of key sets for other hash maps first, and then checks if the key exists.
* @return <code>true</code> if the specified key exists in other hash maps.
*/
// private boolean keyExistsInOtherMaps(Set<URI> keySet, URI key) {
// Set<Set<URI>> complementSet = new HashSet<>();
// complementSet.add(functionalComponents.keySet());
// complementSet.add(interactions.keySet());
// complementSet.remove(keySet);
// for (Set<URI> otherKeySet : complementSet) {
// if (otherKeySet.contains(key)) {
// return true;
// }
// }
// return false;
// }
/* (non-Javadoc)
* @see org.sbolstandard.core2.abstract_classes.TopLevel#copy(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
ModuleDefinition copy(String URIprefix, String displayId, String version) {
ModuleDefinition cloned = this.deepCopy();
cloned.setWasDerivedFrom(this.getIdentity());
cloned.setPersistentIdentity(createCompliantURI(URIprefix,displayId,""));
cloned.setDisplayId(displayId);
cloned.setVersion(version);
URI newIdentity = createCompliantURI(URIprefix,displayId,version);
cloned.setIdentity(newIdentity);
int count = 0;
for (FunctionalComponent component : cloned.getFunctionalComponents()) {
if (!component.isSetDisplayId()) component.setDisplayId("functionalComponent"+ ++count);
component.updateCompliantURI(cloned.getPersistentIdentity().toString(),
component.getDisplayId(),version);
cloned.removeChildSafely(component, cloned.functionalComponents);
cloned.addFunctionalComponent(component);
}
count = 0;
for (Module module : cloned.getModules()) {
if (!module.isSetDisplayId()) module.setDisplayId("module"+ ++count);
module.updateCompliantURI(cloned.getPersistentIdentity().toString(),
module.getDisplayId(),version);
cloned.removeChildSafely(module, cloned.modules);
cloned.addModule(module);
}
count = 0;
for (Interaction interaction : cloned.getInteractions()) {
if (!interaction.isSetDisplayId()) interaction.setDisplayId("interaction"+ ++count);
interaction.updateCompliantURI(cloned.getPersistentIdentity().toString(),
interaction.getDisplayId(),version);
cloned.removeChildSafely(interaction, cloned.interactions);
cloned.addInteraction(interaction);
}
return cloned;
}
/* (non-Javadoc)
* @see org.sbolstandard.core2.abstract_classes.TopLevel#updateCompliantURI(java.lang.String, java.lang.String, java.lang.String)
*/
protected boolean checkDescendantsURIcompliance() {
// codereview: spaghetti
if (!isURIcompliant(this.getIdentity(), 0)) { // ComponentDefinition to be copied has non-compliant URI.
return false;
}
boolean allDescendantsCompliant = true;
if (!this.getModules().isEmpty()) {
for (Module module : this.getModules()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(this.getIdentity(), module.getIdentity());
if (!allDescendantsCompliant) { // Current sequence constraint has non-compliant URI.
return allDescendantsCompliant;
}
if (!module.getMapsTos().isEmpty()) {
// Check compliance of Module's children
for (MapsTo mapsTo : module.getMapsTos()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(module.getIdentity(), mapsTo.getIdentity());
if (!allDescendantsCompliant) { // Current mapsTo has non-compliant URI.
return allDescendantsCompliant;
}
}
}
}
}
if (!this.getFunctionalComponents().isEmpty()) {
for (FunctionalComponent functionalComponent : this.getFunctionalComponents()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(this.getIdentity(), functionalComponent.getIdentity());
if (!allDescendantsCompliant) { // Current component has non-compliant URI.
return allDescendantsCompliant;
}
if (!functionalComponent.getMapsTos().isEmpty()) {
// Check compliance of Component's children
for (MapsTo mapsTo : functionalComponent.getMapsTos()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(functionalComponent.getIdentity(), mapsTo.getIdentity());
if (!allDescendantsCompliant) { // Current mapsTo has non-compliant URI.
return allDescendantsCompliant;
}
}
}
}
}
if (!this.getInteractions().isEmpty()) {
for (Interaction interaction : this.getInteractions()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(this.getIdentity(), interaction.getIdentity());
if (!allDescendantsCompliant) { // Current interaction has non-compliant URI.
return allDescendantsCompliant;
}
for (Participation participation : interaction.getParticipations()) {
allDescendantsCompliant = allDescendantsCompliant
&& isChildURIcompliant(interaction.getIdentity(), participation.getIdentity());
if (!allDescendantsCompliant) { // Current participation has non-compliant URI.
return allDescendantsCompliant;
}
}
}
}
// All descendants of this ComponentDefinition object have compliant URIs.
return allDescendantsCompliant;
}
protected boolean isComplete() {
if (sbolDocument==null) return false;
for (URI modelURI : models) {
if (sbolDocument.getModel(modelURI)==null) return false;
}
for (FunctionalComponent functionalComponent : getFunctionalComponents()) {
if (functionalComponent.getDefinition()==null) return false;
}
for (Module module : getModules()) {
if (module.getDefinition()==null) return false;
}
return true;
}
}
| Revised methods' comments in ModuleDefinition. Added the addModel(Model)
method. | core2/src/main/java/org/sbolstandard/core2/ModuleDefinition.java | Revised methods' comments in ModuleDefinition. Added the addModel(Model) method. | <ide><path>ore2/src/main/java/org/sbolstandard/core2/ModuleDefinition.java
<ide> package org.sbolstandard.core2;
<ide>
<add>import static org.sbolstandard.core2.URIcompliance.createCompliantURI;
<add>import static org.sbolstandard.core2.URIcompliance.isChildURIcompliant;
<add>import static org.sbolstandard.core2.URIcompliance.isURIcompliant;
<add>
<ide> import java.net.URI;
<del>import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide>
<del>import static org.sbolstandard.core2.URIcompliance.*;
<del>
<ide> /**
<add> *
<ide> * @author Zhen Zhang
<ide> * @author Tramy Nguyen
<ide> * @author Nicholas Roehner
<ide> */
<ide>
<ide> public class ModuleDefinition extends TopLevel {
<del>
<del> private Set<URI> roles;
<del> private HashMap<URI, Module> modules;
<del> private HashMap<URI, Interaction> interactions;
<del> private HashMap<URI, FunctionalComponent> functionalComponents;
<del> private Set<URI> models;
<del>
<add>
<add> private Set<URI> roles;
<add> private HashMap<URI, Module> modules;
<add> private HashMap<URI, Interaction> interactions;
<add> private HashMap<URI, FunctionalComponent> functionalComponents;
<add> private Set<URI> models;
<add>
<ide> ModuleDefinition(URI identity) {
<ide> super(identity);
<ide> this.roles = new HashSet<>();
<ide> this.functionalComponents = new HashMap<>();
<ide> this.models = new HashSet<>();
<ide> }
<del>
<add>
<ide> private ModuleDefinition(ModuleDefinition moduleDefinition) {
<ide> super(moduleDefinition);
<ide> this.roles = new HashSet<>();
<ide> this.models = new HashSet<>();
<ide> for (URI role : moduleDefinition.getRoles()) {
<ide> this.addRole(role);
<del> }
<add> }
<ide> for (Module subModule : moduleDefinition.getModules()) {
<ide> this.addModule(subModule.deepCopy());
<ide> }
<ide> this.setModels(moduleDefinition.getModelURIs());
<ide> }
<ide>
<del>
<del> /**
<del> * Adds the specified element to the set <code>roles</code> if it is not already present.
<del> * @return <code>true</code> if this set did not already contain the specified element.
<add> /**
<add> * Adds the specified role URI to this ModuleDefinition's set of role URIs.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @param roleURI
<add> * @return {@code true} if this set did not already contain the specified role.
<add> * @throws SBOLException if the associated SBOLDocument is not compliant
<ide> */
<ide> public boolean addRole(URI roleURI) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> return roles.add(roleURI);
<ide> }
<del>
<del> /**
<del> * Removes the specified element from the set <code>roles</code> if it is present.
<del> * @return <code>true</code> if this set contained the specified element
<add>
<add> /**
<add> * Removes the specified role reference from the set of role references.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @param roleURI
<add> * @return {@code true} if the matching role reference is removed successfully, {@code false} otherwise.
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<ide> */
<ide> public boolean removeRole(URI roleURI) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> return roles.remove(roleURI);
<ide> }
<del>
<del> /**
<del> * Sets the field variable <code>roles</code> to the specified element.
<add>
<add> /**
<add> * Clears the existing set of role references first, then adds the specified
<add> * set of the role references to this ModuleDefinition object.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @param roles
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<ide> */
<ide> public void setRoles(Set<URI> roles) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> clearRoles();
<del> if (roles==null) return;
<add> if (roles == null)
<add> return;
<ide> for (URI role : roles) {
<ide> addRole(role);
<ide> }
<ide> }
<del>
<del> /**
<del> * Returns the field variable <code>roles</code>.
<add>
<add> /**
<add> * Returns the set of role instances owned by this ModuleDefinition object.
<add> * @return the set of role instances owned by this ModuleDefinition object.
<ide> */
<ide> public Set<URI> getRoles() {
<ide> Set<URI> result = new HashSet<>();
<ide> result.addAll(roles);
<ide> return result;
<ide> }
<del>
<del> /**
<del> * Returns true if the set <code>roles</code> contains the specified element.
<del> * @return <code>true</code> if this set contains the specified element.
<del> */
<del> public boolean containsRole(URI rolesURI) {
<del> return roles.contains(rolesURI);
<del> }
<del>
<del> /**
<del> * Removes all entries of the list of <code>roles</code> instances owned by this instance.
<del> * The list will be empty after this call returns.
<add>
<add> /**
<add> * Checks if the given role URI is included in this ModuleDefinition
<add> * object's set of reference role URIs.
<add> * @param roleURI
<add> * @return {@code true} if this set contains the specified URI.
<add> */
<add> public boolean containsRole(URI roleURI) {
<add> return roles.contains(roleURI);
<add> }
<add>
<add> /**
<add> * Removes all entries of this ModuleDefinition object's set of role URIs.
<add> * The set will be empty after this call returns.
<ide> */
<ide> public void clearRoles() {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> roles.clear();
<ide> }
<del>
<del>// /**
<del>// * Test if field variable <code>subModules</code> is set.
<del>// * @return <code>true</code> if it is not an empty list.
<del>// */
<del>// public boolean isSetSubModules() {
<del>// if (subModules.isEmpty())
<del>// return false;
<del>// else
<del>// return true;
<del>// }
<del>
<del> /**
<del> * Calls the ModuleInstantiation constructor to create a new instance using the specified parameters,
<del> * then adds to the list of ModuleInstantiation instances owned by this instance.
<del> * @return the created ModuleInstantiation instance.
<add>
<add> /**
<add> * Calls the ModuleInstantiation constructor to create a new instance using
<add> * the specified parameters,
<add> * then adds to the list of ModuleInstantiation instances owned by this
<add> * ModuleDefinition object.
<add> *
<add> * @param identity
<add> * @param moduleDefinitionURI
<add> * @return a Module instance
<ide> */
<ide> Module createModule(URI identity, URI moduleDefinitionURI) {
<del> Module subModule = new Module(identity, moduleDefinitionURI);
<del> addModule(subModule);
<del> return subModule;
<del> }
<del>
<del> public Module createModule(String displayId, String moduleDefinitionId, String version) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<del> URI moduleDefinition = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
<del> TopLevel.MODULE_DEFINITION, moduleDefinitionId, version, sbolDocument.isTypesInURIs());
<del> return createModule(displayId,moduleDefinition);
<del> }
<del>
<add> Module module = new Module(identity, moduleDefinitionURI);
<add> addModule(module);
<add> return module;
<add> }
<add>
<add> /**
<add> * Creates a child Module instance for this ModuleDefinition object with the
<add> * specified arguments, and then adds to this ModuleDefinition's list of Module instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance
<add> * is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * This method creates a compliant Module URI with the default URI prefix
<add> * for this SBOLDocument instance, and the given {@code displayId} and {@code version}.
<add> * It then calls {@link #createModule(String, URI)} with this component
<add> * definition URI.
<add> *
<add> * @param displayId
<add> * @param moduleId
<add> * @param version
<add> * @return a Module instance
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> */
<add> public Module createModule(String displayId, String moduleId, String version) {
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<add> URI module = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
<add> TopLevel.MODULE_DEFINITION, moduleId, version, sbolDocument.isTypesInURIs());
<add> return createModule(displayId, module);
<add> }
<add>
<add> /**
<add> * Creates a child Module instance for this ModuleDefinition object with the
<add> * specified arguments, and then adds to this ModuleDefinition's list of Module instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * If the SBOLDocument instance already completely specifies all URIs and
<add> * the given {@code moduleDefinitionURI} is not found in them, then an
<add> * {@link IllegalArgumentException} is thrown.
<add> * <p>
<add> * This method creates a compliant Module URI with the default URI prefix
<add> * for this SBOLDocument instance, the given {@code displayId}, and this
<add> * ModuleDefinition object's version.
<add> *
<add> * @param displayId
<add> * @param moduleDefinitionURI
<add> * @return a Module instance
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> *
<add> * @throws IllegalArgumentException if the associated SBOLDocument instance already completely specifies all URIs and the given {@code definitionURI}
<add> is not found in them.
<add> */
<ide> public Module createModule(String displayId, URI moduleDefinitionURI) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> if (sbolDocument != null && sbolDocument.isComplete()) {
<del> if (sbolDocument.getModuleDefinition(moduleDefinitionURI)==null) {
<del> throw new IllegalArgumentException("Module definition '" + moduleDefinitionURI + "' does not exist.");
<add> if (sbolDocument.getModuleDefinition(moduleDefinitionURI) == null) {
<add> throw new IllegalArgumentException("Module definition '" + moduleDefinitionURI
<add> + "' does not exist.");
<ide> }
<ide> }
<ide> String URIprefix = this.getPersistentIdentity().toString();
<ide> m.setVersion(version);
<ide> return m;
<ide> }
<del>
<del>
<del> /**
<del> * Adds the specified instance to the list of subModules.
<add>
<add> /**
<add> * Adds the given {@code module} argument to this ModuleDefinition's list of
<add> * Module instances, and then associates it with the SBOLDocument instance that also contains
<add> * this ModuleDefinition object.
<add> * @param module
<ide> */
<ide> void addModule(Module module) {
<ide> addChildSafely(module, modules, "module", functionalComponents, interactions);
<ide> module.setSBOLDocument(this.sbolDocument);
<ide> module.setModuleDefinition(this);
<ide> }
<del>
<del> /**
<del> * Removes the instance matching the specified URI from the list of subModules if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<del> */
<add>
<add> /**
<add> * Removes the specified Module instance from the list of Module instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @param module
<add> * @return {@code true} if the matching Module instance is removed successfully, {@code false} otherwise.
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> *
<add> */
<add>
<ide> public boolean removeModule(Module module) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<del> return removeChildSafely(module,modules);
<del> }
<del>
<del> /**
<del> * Returns the instance matching the specified displayId from the list of modules, if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<add> return removeChildSafely(module, modules);
<add> }
<add>
<add> /**
<add> * Returns the Module instance matching the given displayId from the list of
<add> * Module instances.
<add> *
<add> * @return the matching Module instance if present, or <code>null</code> if
<add> * not present.
<ide> */
<ide> public Module getModule(String displayId) {
<del> return modules.get(createCompliantURI(this.getPersistentIdentity().toString(),displayId,this.getVersion()));
<del> }
<del>
<del> /**
<del> * Returns the instance matching the specified URI from the list of modules, if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add> return modules.get(createCompliantURI(this.getPersistentIdentity().toString(), displayId,
<add> this.getVersion()));
<add> }
<add>
<add> /**
<add> * Returns the instance matching the given URI from the list of Module instances.
<add> *
<add> *
<add> * @return the matching Module instance if present, or <code>null</code> if
<add> * not present.
<ide> */
<ide> public Module getModule(URI moduleURI) {
<ide> return modules.get(moduleURI);
<ide> }
<del>
<del> /**
<del> * Returns the list of subModule instances owned by this instance.
<del> * @return the list of subModule instances owned by this instance.
<add>
<add> /**
<add> *
<add> * Returns the set of Module instances owned by this ModuleDefinition object.
<add> *
<add> * @return the set of Module instances owned by this ModuleDefinition object.
<add> *
<ide> */
<ide> public Set<Module> getModules() {
<ide> return new HashSet<>(modules.values());
<ide> }
<del>
<del> /**
<del> * Removes all entries of the list of modules owned by this instance. The list will be empty after this call returns.
<add>
<add> /**
<add> * Removes all entries of this ModuleDefinition object's list of Module
<add> * objects.
<add> * The set will be empty after this call returns.
<ide> */
<ide> public void clearModules() {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> Object[] valueSetArray = modules.values().toArray();
<ide> for (Object module : valueSetArray) {
<del> removeModule((Module)module);
<del> }
<del> }
<del>
<del> /**
<del> * Clears the existing list of subModule instances, then appends all of the elements in the specified collection to the end of this list.
<add> removeModule((Module) module);
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Clears the existing set of Module instances first, then adds the given
<add> * set of the Module instances to this ModuleDefinition object.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @param modules
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> *
<ide> */
<ide> void setModules(List<Module> modules) {
<ide> clearModules();
<del> if (modules==null) return;
<add> if (modules == null)
<add> return;
<ide> for (Module module : modules) {
<ide> addModule(module);
<ide> }
<ide> }
<ide>
<del>// /**
<del>// * Test if field variable <code>interactions</code> is set.
<del>// * @return <code>true</code> if it is not an empty list.
<del>// */
<del>// public boolean isSetInteractions() {
<del>// if (interactions.isEmpty())
<del>// return false;
<del>// else
<del>// return true;
<del>// }
<del>
<del> /**
<del> * Calls the Interaction constructor to create a new instance using the specified parameters,
<del> * then adds to the list of Interaction instances owned by this instance.
<del> * @return the created Interaction instance.
<add> /**
<add> * Calls the Interaction constructor to create a new instance using the
<add> * given parameters, then adds to the list of Interaction instances owned by this
<add> * ModuleDefinition object.
<add> *
<add> * @return the created Interaction instance.
<ide> */
<ide> Interaction createInteraction(URI identity, Set<URI> type) {
<ide> Interaction interaction = new Interaction(identity, type);
<ide> addInteraction(interaction);
<ide> return interaction;
<ide> }
<del>
<del> public Interaction createInteraction(String displayId, Set<URI> type) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add>
<add> /**
<add> * Creates a child Interaction object for this ModuleDefinition object with
<add> * the given arguments, and then adds to this ModuleDefinition's list of Interaction instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * This method creates a compliant Interaction URI with the default URI
<add> * prefix for this SBOLDocument instance, the given {@code displayId}, and this
<add> * ModuleDefinition object's version.
<add> *
<add> * @param displayId
<add> * @param types
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> */
<add> public Interaction createInteraction(String displayId, Set<URI> types) {
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> String URIprefix = this.getPersistentIdentity().toString();
<ide> String version = this.getVersion();
<ide> URI newInteractionURI = createCompliantURI(URIprefix, displayId, version);
<del> Interaction i = createInteraction(newInteractionURI, type);
<add> Interaction i = createInteraction(newInteractionURI, types);
<ide> i.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
<ide> i.setDisplayId(displayId);
<ide> i.setVersion(version);
<ide> return i;
<ide> }
<del>
<del>
<del> /**
<del> * Adds the specified instance to the list of interactions.
<add>
<add> /**
<add> * Adds the given Interaction instance to the list of Interaction instances.
<ide> */
<ide> void addInteraction(Interaction interaction) {
<ide> addChildSafely(interaction, interactions, "interaction", functionalComponents, modules);
<ide> interaction.setSBOLDocument(this.sbolDocument);
<del> interaction.setModuleDefinition(this);
<del> }
<del>
<del> /**
<del> * Removes the instance matching the specified URI from the list of interactions if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add> interaction.setModuleDefinition(this);
<add> }
<add>
<add> /**
<add> * Removes the given Interaction instance from the list of Interaction
<add> * instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @return {@code true} if the matching Interaction instance is removed successfully, {@code false} otherwise.
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<ide> */
<ide> public boolean removeInteraction(Interaction interaction) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<del> return removeChildSafely(interaction,interactions);
<del> }
<del>
<del> /**
<del> * Returns the instance matching the specified displayId from the list of interactions, if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<del> */
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<add> return removeChildSafely(interaction, interactions);
<add> }
<add>
<add> /**
<add> * Returns the instance matching the given Interaction displayId from the
<add> * list of Interaction instances.
<add> *
<add> * @return the matching instance if present, or <code>null</code> if not
<add> * present.
<add> */
<add>
<ide> public Interaction getInteraction(String displayId) {
<del> return interactions.get(createCompliantURI(this.getPersistentIdentity().toString(),displayId,this.getVersion()));
<del> }
<del>
<del> /**
<del> * Returns the instance matching the specified URI from the list of interactions, if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add> return interactions.get(createCompliantURI(this.getPersistentIdentity().toString(),
<add> displayId, this.getVersion()));
<add> }
<add>
<add> /**
<add> *
<add> * Returns the instance matching the given Interaction URI from the list of
<add> * Interaction instances.
<add> *
<add> * @return the matching instance if present, or <code>null</code> if not
<add> * present.
<ide> */
<ide> public Interaction getInteraction(URI interactionURI) {
<ide> return interactions.get(interactionURI);
<ide> }
<del>
<del> /**
<del> * Returns the list of interaction instances owned by this instance.
<del> * @return the list of interaction instances owned by this instance.
<add>
<add> /**
<add> * Returns the set of interaction instances owned by this ModuleDefinition
<add> * object.
<add> *
<add> * @return the set of interaction instances owned by this ModuleDefinition
<add> * object.
<ide> */
<ide> public Set<Interaction> getInteractions() {
<ide> return new HashSet<>(interactions.values());
<ide> }
<del>
<del> /**
<del> * Removes all entries of the list of interactions owned by this instance. The list will be empty after this call returns.
<add>
<add> /**
<add> * Removes all entries of this ModuleDefinition object's list of Instance
<add> * objects.
<add> *
<add> * The list will be empty after this call returns.
<ide> */
<ide> public void clearInteractions() {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> Object[] valueSetArray = interactions.values().toArray();
<ide> for (Object interaction : valueSetArray) {
<del> removeInteraction((Interaction)interaction);
<del> }
<del> }
<del>
<del> /**
<del> * Clears the existing list of interaction instances, then appends all of the elements in the specified collection to the end of this list.
<add> removeInteraction((Interaction) interaction);
<add> }
<add> }
<add>
<add> /**
<add> * Clears the existing list of interaction instances, then appends all of
<add> * the elements in the given collection to the end of this list.
<ide> */
<ide> void setInteractions(
<del> List<Interaction> interactions) {
<del> clearInteractions();
<del> if (interactions==null) return;
<add> List<Interaction> interactions) {
<add> clearInteractions();
<add> if (interactions == null)
<add> return;
<ide> for (Interaction interaction : interactions) {
<ide> addInteraction(interaction);
<ide> }
<ide> }
<del>
<del>// /**
<del>// * Test if field variable <code>functionalInstantiations</code> is set.
<del>// * @return <code>true</code> if it is not an empty list.
<del>// */
<del>// public boolean isSetComponents() {
<del>// if (components.isEmpty())
<del>// return false;
<del>// else
<del>// return true;
<del>// }
<del>
<del> /**
<del> * Calls the FunctionalInstantiation constructor to create a new instance using the specified parameters,
<del> * then adds to the list of FunctionalInstantiation instances owned by this instance.
<del> * @return the created {@link FunctionalComponent} instance.
<del> */
<del> FunctionalComponent createFunctionalComponent(URI identity, AccessType access,
<add>
<add> /**
<add> * @param identity
<add> * @param access
<add> * @param definitionURI
<add> * @param direction
<add> * @return a FunctionalComponent instance.
<add> */
<add>
<add> FunctionalComponent createFunctionalComponent(URI identity, AccessType access,
<ide> URI definitionURI, DirectionType direction) {
<del> FunctionalComponent functionalComponent =
<add> FunctionalComponent functionalComponent =
<ide> new FunctionalComponent(identity, access, definitionURI, direction);
<ide> addFunctionalComponent(functionalComponent);
<ide> return functionalComponent;
<ide> }
<del>
<add>
<add> /**
<add> * Creates a child FunctionalComponent instance for this ModuleDefinition
<add> * object with the given arguments, and then adds to this ModuleDefinition's list of FunctionalComponent
<add> * instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance
<add> * is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * This method creates a compliant FunctionalComponent URI with the default
<add> * URI prefix for this SBOLDocument instance, and the given {@code definition} and {@code version}.
<add> * It then calls {@link #createFunctionalComponent(String, AccessType, URI,DirectionType)}
<add> * with this component definition URI.
<add> *
<add> * @param displayId
<add> * @param access
<add> * @param definition
<add> * @param version
<add> * @param direction
<add> * @return a FunctionalComponent instance
<add> * @throws SBOLException if the associated SBOLDocument is not compliant
<add> */
<ide> public FunctionalComponent createFunctionalComponent(String displayId, AccessType access,
<ide> String definition, String version, DirectionType direction) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<del> URI definitionURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<add> URI definitionURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
<ide> TopLevel.COMPONENT_DEFINITION, definition, version, sbolDocument.isTypesInURIs());
<del> return createFunctionalComponent(displayId,access,definitionURI,direction);
<del> }
<del>
<add> return createFunctionalComponent(displayId, access, definitionURI, direction);
<add> }
<add>
<add> /**
<add> * Creates a child FunctionalComponent instance for this ModuleDefinition
<add> * object with the given arguments, and then adds to this ModuleDefinition's list of FunctionalComponent
<add> * instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * If the SBOLDocument instance already completely specifies all URIs and
<add> * the given {@code fcURI} is not found in them, then an {@link IllegalArgumentException} is thrown.
<add> * <p>
<add> * This method creates a compliant FunctionalComponent URI with the default
<add> * URI prefix for this SBOLDocument instance, the given {@code displayId}, and this
<add> * ModuleDefinition object's version.
<add> *
<add> * @param displayId
<add> * @param access
<add> * @param fcURI
<add> * @param direction
<add> * @return a FunctionalComponent instance
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> * @throws IllegalArgumentException if the associated SBOLDocument instance already completely
<add> specifies all URIs and the given {@code definitionURI} is not found in them.
<add> */
<ide> public FunctionalComponent createFunctionalComponent(String displayId, AccessType access,
<del> URI definitionURI, DirectionType direction) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> URI fcURI, DirectionType direction) {
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> if (sbolDocument != null && sbolDocument.isComplete()) {
<del> if (sbolDocument.getComponentDefinition(definitionURI)==null) {
<del> throw new IllegalArgumentException("Component definition '" + definitionURI + "' does not exist.");
<add> if (sbolDocument.getComponentDefinition(fcURI) == null) {
<add> throw new IllegalArgumentException("Component '" + fcURI
<add> + "' does not exist.");
<ide> }
<ide> }
<ide> String URIprefix = this.getPersistentIdentity().toString();
<ide> String version = this.getVersion();
<ide> URI functionalComponentURI = createCompliantURI(URIprefix, displayId, version);
<del> FunctionalComponent fc = createFunctionalComponent(functionalComponentURI, access, definitionURI, direction);
<add> FunctionalComponent fc = createFunctionalComponent(functionalComponentURI, access,
<add> fcURI, direction);
<ide> fc.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
<ide> fc.setDisplayId(displayId);
<ide> fc.setVersion(version);
<ide> return fc;
<ide> }
<del>
<del> /**
<del> * Adds the specified instance to the list of components.
<add>
<add> /**
<add> * Adds the given instance to the list of components.
<ide> */
<ide> void addFunctionalComponent(FunctionalComponent functionalComponent) {
<del> addChildSafely(functionalComponent, functionalComponents, "functionalComponent", interactions, modules);
<add> addChildSafely(functionalComponent, functionalComponents, "functionalComponent",
<add> interactions, modules);
<ide> functionalComponent.setSBOLDocument(this.sbolDocument);
<ide> }
<del>
<del> /**
<del> * Removes the instance matching the specified URI from the list of functionalInstantiations if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add>
<add> /**
<add> * Removes the given FunctionalComponent instance from the list of
<add> * FunctionalComponent instances.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * Before removing the given FunctionalComponent instance, this method
<add> * checks if it is referenced by any children and grandchildren instances of this ModuleDefinition object.
<add> *
<add> * @return {@code true} if the matching FunctionalComponent instance is removed successfully,
<add> * {@code false} otherwise.
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<add> * @throws SBOLException the given FunctionalComponent instance is referenced.
<ide> */
<ide> public boolean removeFunctionalComponent(FunctionalComponent functionalComponent) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> for (Interaction i : interactions.values()) {
<ide> for (Participation p : i.getParticipations()) {
<ide> if (p.getParticipantURI().equals(functionalComponent.getIdentity())) {
<del> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<del> " since it is in use.");
<add> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<add> " since it is in use.");
<ide> }
<ide> }
<ide> }
<ide> for (FunctionalComponent c : functionalComponents.values()) {
<ide> for (MapsTo mt : c.getMapsTos()) {
<ide> if (mt.getLocalURI().equals(functionalComponent.getIdentity())) {
<del> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<del> " since it is in use.");
<add> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<add> " since it is in use.");
<ide> }
<ide> }
<del>
<ide> }
<ide> for (Module m : modules.values()) {
<ide> for (MapsTo mt : m.getMapsTos()) {
<ide> if (mt.getLocalURI().equals(functionalComponent.getIdentity())) {
<del> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<del> " since it is in use.");
<add> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<add> " since it is in use.");
<ide> }
<ide> }
<del>
<del> }
<del> if (sbolDocument!=null) {
<add> }
<add> if (sbolDocument != null) {
<ide> for (ModuleDefinition md : sbolDocument.getModuleDefinitions()) {
<ide> for (Module m : md.getModules()) {
<ide> for (MapsTo mt : m.getMapsTos()) {
<ide> if (mt.getRemoteURI().equals(functionalComponent.getIdentity())) {
<del> throw new SBOLException("Cannot remove " + functionalComponent.getIdentity() +
<add> throw new SBOLException("Cannot remove "
<add> + functionalComponent.getIdentity() +
<ide> " since it is in use.");
<ide> }
<del> }
<add> }
<ide> }
<ide> }
<ide> }
<del> return removeChildSafely(functionalComponent,functionalComponents);
<del> }
<del>
<del> /**
<del> * Returns the instance matching the specified displayId from the list of functional instantiations, if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add> return removeChildSafely(functionalComponent, functionalComponents);
<add> }
<add>
<add> /**
<add> * Returns the instance matching the given displayId from the list of FunctionalComponent instances.
<add> *
<add> * @return the matching instance if present, or {@code null} if not present.
<ide> */
<ide> public FunctionalComponent getFunctionalComponent(String displayId) {
<del> return functionalComponents.get(createCompliantURI(this.getPersistentIdentity().toString(),displayId,this.getVersion()));
<del> }
<del>
<del> /**
<del> * Returns the instance matching the specified URI from the list of functional instantiations, if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add> return functionalComponents.get(createCompliantURI(this.getPersistentIdentity().toString(),
<add> displayId, this.getVersion()));
<add> }
<add>
<add> /**
<add> * Returns the instance matching the given FunctionalComponent URI from the
<add> * list of FunctionalComponent instances.
<add> *
<add> * @return the matching FunctionalComponent instance if present, or
<add> * {@code null} if not present.
<ide> */
<ide> public FunctionalComponent getFunctionalComponent(URI componentURI) {
<ide> return functionalComponents.get(componentURI);
<ide> }
<del>
<del> /**
<del> * Returns the list of functionalInstantiation instances owned by this instance.
<del> * @return the list of functionalInstantiation instances owned by this instance.
<add>
<add> /**
<add> * Returns the set of FunctionalComponent instances owned by this
<add> * ModuleDefinition object.
<add> *
<add> * @return the set of FunctionalComponent instances owned by this
<add> * ModuleDefinition object.
<ide> */
<ide> public Set<FunctionalComponent> getFunctionalComponents() {
<ide> return new HashSet<>(functionalComponents.values());
<ide> }
<del>
<del> /**
<del> * Removes all entries of the list of functional components owned by this instance. The list will be empty after this call returns.
<add>
<add> /**
<add> * Removes all entries of this ModuleDefinition object's list of
<add> * FunctionalComponent objects.
<add> * The list will be empty after this call returns.
<ide> */
<ide> public void clearFunctionalComponents() {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> Object[] valueSetArray = functionalComponents.values().toArray();
<ide> for (Object functionalComponent : valueSetArray) {
<del> removeFunctionalComponent((FunctionalComponent)functionalComponent);
<del> }
<del> }
<del>
<del> /**
<del> * Clears the existing list of functionalInstantiation instances, then appends all of the elements in the specified collection to the end of this list.
<add> removeFunctionalComponent((FunctionalComponent) functionalComponent);
<add> }
<add> }
<add>
<add> /**
<add> * Clears the existing list of FunctionalComponent instances, then appends
<add> * all of the elements in the given collection to the end of this list.
<ide> */
<ide> void setFunctionalComponents(
<del> List<FunctionalComponent> components) {
<del> clearFunctionalComponents();
<del> if (components==null) return;
<add> List<FunctionalComponent> components) {
<add> clearFunctionalComponents();
<add> if (components == null)
<add> return;
<ide> for (FunctionalComponent component : components) {
<ide> addFunctionalComponent(component);
<ide> }
<ide> }
<del>
<del>// /**
<del>// * Set optional field variable <code>subModules</code> to an empty list.
<del>// */
<del>// public void unsetModuleInstantiations() {
<del>// subModules.clear();
<del>// }
<del>//
<del>// /**
<del>// * Set optional field variable <code>interactions</code> to an empty list.
<del>// */
<del>// public void unsetInteractions() {
<del>// interactions.clear();
<del>// }
<del>//
<del>// /**
<del>// * Set optional field variable <code>functionalInstantiations</code> to an empty list.
<del>// */
<del>// public void unsetFunctionalInstantiations() {
<del>// functionalInstantiations.clear();
<del>// }
<del>
<del>// /**
<del>// * Test if field variable <code>models</code> is set.
<del>// * @return <code>true</code> if it is not an empty list.
<del>// */
<del>// public boolean isSetModels() {
<del>// if (models.isEmpty())
<del>// return false;
<del>// else
<del>// return true;
<del>// }
<del>
<del> public void addModel(String model,String version) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<del> URI modelURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
<del> TopLevel.MODEL, model, version, sbolDocument.isTypesInURIs());
<add>
<add> /**
<add> * Adds the URI of the given Model instance to this ComponentDefinition's
<add> * set of reference Model URIs.
<add> * <p>
<add> * If this ComponentDefinition object belongs to an SBOLDocument instance,
<add> * then the SBOLDcouement instance
<add> * is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * If the SBOLDocument instance already completely specifies all its
<add> * reference URIs and the given model's URI
<add> * is not found in them, then an {@link IllegalArgumentException} is thrown.
<add> *
<add> * @param model
<add> * @throws SBOLException
<add> * if the associated SBOLDocument is not compliant
<add> * @throws IllegalArgumentException
<add> * if the associated SBOLDocument instance already completely specifies all URIs
<add> * and the given Model instance's URI is not found in them.
<add> * @return {@code true} if this set did not already contain the given Model
<add> * instance URI.
<add> */
<add>
<add> public void addModel(Model model) {
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<add> if (sbolDocument != null && sbolDocument.isComplete()) {
<add> if (sbolDocument.getModel(model.getIdentity()) == null) {
<add> throw new IllegalArgumentException("Model '" + model.getIdentity()
<add> + "' does not exist.");
<add> }
<add> }
<add> this.addModel(model.getIdentity());
<add> }
<add>
<add> /**
<add> *
<add> * Creates a compliant model URI and then adds it to this ModuleDefinition
<add> * object's set of reference model URIs. The model argument specifies the reference
<add> * Model's display ID, and the version argument specifies its version.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed be edited.
<add> *
<add> * @param model
<add> * @param version
<add> * @throws SBOLException if the associated SBOLDocument is not compliant
<add> */
<add> public void addModel(String model, String version) {
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<add> URI modelURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(),
<add> TopLevel.MODEL, model, version, sbolDocument.isTypesInURIs());
<ide> addModel(modelURI);
<ide> }
<del>
<del> /**
<del> * Adds the specified instance to the list of models.
<add>
<add> /**
<add> * Adds the given Model URI to this ModuleDefinition's set of reference
<add> * Model URIs.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance
<add> * is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> * <p>
<add> * If the SBOLDocument instance already completely specifies all its
<add> * reference URIs and the given {@code modelURI}
<add> * is not found in them, then an {@link IllegalArgumentException} is thrown.
<add> *
<add> * @param modelURI
<add> * @throws SBOLException if the associated SBOLDocument is not compliant
<add> * @throws IllegalArgumentException if the associated SBOLDocument instance already completely
<add> * specifies all URIs and the given {@code modelURI} is not found in them.
<ide> */
<ide> public void addModel(URI modelURI) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> if (sbolDocument != null && sbolDocument.isComplete()) {
<del> if (sbolDocument.getModel(modelURI)==null) {
<add> if (sbolDocument.getModel(modelURI) == null) {
<ide> throw new IllegalArgumentException("Model '" + modelURI + "' does not exist.");
<ide> }
<ide> }
<ide> models.add(modelURI);
<ide> }
<del>
<del> /**
<del> * Removes the instance matching the specified URI from the list of models if present.
<del> * @return the matching instance if present, or <code>null</code> if not present.
<add>
<add> /**
<add> * Removes the given Model reference from the set of Model references.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance
<add> * is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @return {@code true} if the matching Model reference is removed successfully,
<add> * {@code false} otherwise.
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<ide> */
<ide> public boolean removeModel(URI modelURI) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> return models.remove(modelURI);
<ide> }
<del>
<del> /**
<del> * Clears the existing list of model instances, then appends all of the elements in the specified collection to the end of this list.
<add>
<add> /**
<add> * Clears the existing set of Model references first, then adds the given
<add> * set of the Model references to this ModuleDefinition object.
<add> * <p>
<add> * If this ModuleDefinition object belongs to an SBOLDocument instance, then
<add> * the SBOLDcouement instance
<add> * is checked for compliance first. Only a compliant SBOLDocument instance
<add> * is allowed to be edited.
<add> *
<add> * @param models
<add> * @throws SBOLException if the associated SBOLDocument is not compliant.
<ide> */
<ide> public void setModels(Set<URI> models) {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> clearModels();
<del> if (models==null) return;
<add> if (models == null)
<add> return;
<ide> for (URI model : models) {
<ide> addModel(model);
<ide> }
<ide> }
<del>
<del> /**
<del> * Returns the set of model URIs referenced by this instance.
<del> * @return the set of model URIs referenced by this instance
<add>
<add> /**
<add> * Returns the set of Model URIs referenced by this ModuleDefinition's object.
<add> *
<add> * @return the set of Model URIs referenced by this ModuleDefinition's object.
<add> *
<ide> */
<ide> public Set<URI> getModelURIs() {
<ide> Set<URI> result = new HashSet<>();
<ide> result.addAll(models);
<ide> return result;
<ide> }
<del>
<del> /**
<del> * Returns the set of models referenced by this instance.
<del> * @return the set of models referenced by this instance
<add>
<add> /**
<add> * Returns the set of Model instances referenced by this ModuleDefinition object.
<add> *
<add> * @return the set of Model instances referenced by this ModuleDefinition object
<ide> */
<ide> public Set<Model> getModels() {
<ide> Set<Model> result = new HashSet<>();
<ide> }
<ide> return result;
<ide> }
<del>
<del> /**
<del> * Returns true if the set <code>models</code> contains the specified element.
<del> * @return <code>true</code> if this set contains the specified element.
<add>
<add> /**
<add> * Checks if the given model URI is included in this ModuleDefinition
<add> * object's set of reference Model URIs.
<add> *
<add> * @param modelURI
<add> * @return {@code true} if this set contains the given URI.
<ide> */
<ide> public boolean containsModel(URI modelURI) {
<ide> return models.contains(modelURI);
<ide> }
<ide>
<ide> /**
<del> * Removes all entries of the list of model instances owned by this instance.
<del> * The list will be empty after this call returns.
<add> * Removes all entries of this ModuleDefinition object's set of reference
<add> * Model URIs.
<add> * The set will be empty after this call returns.
<ide> */
<ide> public void clearModels() {
<del> if (sbolDocument!=null) sbolDocument.checkReadOnly();
<add> if (sbolDocument != null)
<add> sbolDocument.checkReadOnly();
<ide> models.clear();
<del> }
<add> }
<ide>
<ide> @Override
<ide> public int hashCode() {
<ide> final int prime = 31;
<ide> int result = super.hashCode();
<del> result = prime * result + ((functionalComponents == null) ? 0 : functionalComponents.hashCode());
<add> result = prime * result
<add> + ((functionalComponents == null) ? 0 : functionalComponents.hashCode());
<ide> result = prime * result + ((interactions == null) ? 0 : interactions.hashCode());
<ide> result = prime * result + ((models == null) ? 0 : models.hashCode());
<ide> result = prime * result + ((roles == null) ? 0 : roles.hashCode());
<ide> result = prime * result + ((modules == null) ? 0 : modules.hashCode());
<ide> return result;
<ide> }
<del>
<ide>
<ide> @Override
<ide> public boolean equals(Object obj) {
<ide> return true;
<ide> }
<ide>
<del>
<ide> @Override
<ide> protected ModuleDefinition deepCopy() {
<ide> return new ModuleDefinition(this);
<ide> }
<del>
<add>
<add> // /**
<add>
<add> // * @param newDisplayId
<add>
<add> // * @return
<add>
<add> // */
<add>
<add> // public ModuleDefinition copy(String newDisplayId) {
<add>
<add> // ModuleDefinition cloned = (ModuleDefinition) super.copy(newDisplayId);
<add>
<add> // cloned.updateCompliantURI(newDisplayId);
<add>
<add> // return cloned;
<add>
<add> // }
<add>
<add> //
<add>
<add> //
<add>
<add> // /* (non-Javadoc)
<add>
<add> // * @see
<add> // org.sbolstandard.core2.abstract_classes.TopLevel#updateDisplayId(java.lang.String)
<add>
<add> // */
<add>
<add> // protected void updateCompliantURI(String newDisplayId) {
<add>
<add> // super.updateCompliantURI(newDisplayId);
<add>
<add> // if (isTopLevelURIcompliant(this.getIdentity())) {
<add>
<add> // // TODO Change all of its children's displayIds in their URIs.
<add>
<add> // }
<add>
<add> // }
<add>
<add> //
<add>
<add> // /**
<add>
<add> // * Get a deep copy of the object first, and set its major version to the
<add> // given value, and minor version to "0".
<add>
<add> // * @param newVersion
<add>
<add> // * @return the copied {@link ComponentDefinition} instance with the given
<add> // major version.
<add>
<add> // */
<add>
<add> // public ModuleDefinition newVersion(String newVersion) {
<add>
<add> // ModuleDefinition cloned = (ModuleDefinition)
<add> // super.newVersion(newVersion);
<add>
<add> // cloned.updateVersion(newVersion);
<add>
<add> // return cloned;
<add>
<add> // }
<add>
<add> //
<add>
<add> // /* (non-Javadoc)
<add>
<add> // * @see
<add> // org.sbolstandard.core2.abstract_classes.TopLevel#updateVersion(java.lang.String)
<add>
<add> // */
<add>
<add> // protected void updateVersion(String newVersion) {
<add>
<add> // super.updateVersion(newVersion);
<add>
<add> // if (isTopLevelURIcompliant(this.getIdentity())) {
<add>
<add> // // TODO Change all of its children's versions in their URIs.
<add>
<add> // }
<add>
<add> // }
<add>
<ide> // /**
<del>// * @param newDisplayId
<del>// * @return
<add>// *
<add>// * Check if the given key exists in any hash maps in this class other than
<add>// * the one with the given keySet. This method
<add>// *
<add>// * constructs a set of key sets for other hash maps first, and then checks
<add>// * if the key exists.
<add>// *
<add>// * @return <code>true</code> if the given key exists in other hash maps.
<ide> // */
<del>// public ModuleDefinition copy(String newDisplayId) {
<del>// ModuleDefinition cloned = (ModuleDefinition) super.copy(newDisplayId);
<del>// cloned.updateCompliantURI(newDisplayId);
<del>// return cloned;
<del>// }
<del>//
<del>//
<del>// /* (non-Javadoc)
<del>// * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateDisplayId(java.lang.String)
<del>// */
<del>// protected void updateCompliantURI(String newDisplayId) {
<del>// super.updateCompliantURI(newDisplayId);
<del>// if (isTopLevelURIcompliant(this.getIdentity())) {
<del>// // TODO Change all of its children's displayIds in their URIs.
<del>// }
<del>// }
<del>//
<del>// /**
<del>// * Get a deep copy of the object first, and set its major version to the specified value, and minor version to "0".
<del>// * @param newVersion
<del>// * @return the copied {@link ComponentDefinition} instance with the specified major version.
<del>// */
<del>// public ModuleDefinition newVersion(String newVersion) {
<del>// ModuleDefinition cloned = (ModuleDefinition) super.newVersion(newVersion);
<del>// cloned.updateVersion(newVersion);
<del>// return cloned;
<del>// }
<del>//
<del>// /* (non-Javadoc)
<del>// * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateVersion(java.lang.String)
<del>// */
<del>// protected void updateVersion(String newVersion) {
<del>// super.updateVersion(newVersion);
<del>// if (isTopLevelURIcompliant(this.getIdentity())) {
<del>// // TODO Change all of its children's versions in their URIs.
<del>// }
<del>// }
<del>
<del> /**
<del> * Check if the specified key exists in any hash maps in this class other than the one with the specified keySet. This method
<del> * constructs a set of key sets for other hash maps first, and then checks if the key exists.
<del> * @return <code>true</code> if the specified key exists in other hash maps.
<del> */
<del>// private boolean keyExistsInOtherMaps(Set<URI> keySet, URI key) {
<del>// Set<Set<URI>> complementSet = new HashSet<>();
<del>// complementSet.add(functionalComponents.keySet());
<del>// complementSet.add(interactions.keySet());
<del>// complementSet.remove(keySet);
<del>// for (Set<URI> otherKeySet : complementSet) {
<del>// if (otherKeySet.contains(key)) {
<del>// return true;
<del>// }
<del>// }
<del>// return false;
<del>// }
<del>
<del> /* (non-Javadoc)
<del> * @see org.sbolstandard.core2.abstract_classes.TopLevel#copy(java.lang.String, java.lang.String, java.lang.String)
<del> */
<add>
<add> // private boolean keyExistsInOtherMaps(Set<URI> keySet, URI key) {
<add>
<add> // Set<Set<URI>> complementSet = new HashSet<>();
<add>
<add> // complementSet.add(functionalComponents.keySet());
<add>
<add> // complementSet.add(interactions.keySet());
<add>
<add> // complementSet.remove(keySet);
<add>
<add> // for (Set<URI> otherKeySet : complementSet) {
<add>
<add> // if (otherKeySet.contains(key)) {
<add>
<add> // return true;
<add>
<add> // }
<add>
<add> // }
<add>
<add> // return false;
<add>
<add> // }
<add>
<add> /*
<add> * (non-Javadoc)
<add> *
<add> * @see
<add> * org.sbolstandard.core2.abstract_classes.TopLevel#copy(java.lang.String,
<add> * java.lang.String, java.lang.String)
<add> */
<add>
<ide> @Override
<ide> ModuleDefinition copy(String URIprefix, String displayId, String version) {
<ide> ModuleDefinition cloned = this.deepCopy();
<ide> cloned.setWasDerivedFrom(this.getIdentity());
<del> cloned.setPersistentIdentity(createCompliantURI(URIprefix,displayId,""));
<add> cloned.setPersistentIdentity(createCompliantURI(URIprefix, displayId, ""));
<ide> cloned.setDisplayId(displayId);
<ide> cloned.setVersion(version);
<del> URI newIdentity = createCompliantURI(URIprefix,displayId,version);
<add> URI newIdentity = createCompliantURI(URIprefix, displayId, version);
<ide> cloned.setIdentity(newIdentity);
<ide> int count = 0;
<ide> for (FunctionalComponent component : cloned.getFunctionalComponents()) {
<del> if (!component.isSetDisplayId()) component.setDisplayId("functionalComponent"+ ++count);
<del> component.updateCompliantURI(cloned.getPersistentIdentity().toString(),
<del> component.getDisplayId(),version);
<add> if (!component.isSetDisplayId())
<add> component.setDisplayId("functionalComponent" + ++count);
<add> component.updateCompliantURI(cloned.getPersistentIdentity().toString(),
<add> component.getDisplayId(), version);
<ide> cloned.removeChildSafely(component, cloned.functionalComponents);
<ide> cloned.addFunctionalComponent(component);
<ide> }
<ide> count = 0;
<ide> for (Module module : cloned.getModules()) {
<del> if (!module.isSetDisplayId()) module.setDisplayId("module"+ ++count);
<del> module.updateCompliantURI(cloned.getPersistentIdentity().toString(),
<del> module.getDisplayId(),version);
<add> if (!module.isSetDisplayId())
<add> module.setDisplayId("module" + ++count);
<add> module.updateCompliantURI(cloned.getPersistentIdentity().toString(),
<add> module.getDisplayId(), version);
<ide> cloned.removeChildSafely(module, cloned.modules);
<ide> cloned.addModule(module);
<ide> }
<ide> count = 0;
<ide> for (Interaction interaction : cloned.getInteractions()) {
<del> if (!interaction.isSetDisplayId()) interaction.setDisplayId("interaction"+ ++count);
<del> interaction.updateCompliantURI(cloned.getPersistentIdentity().toString(),
<del> interaction.getDisplayId(),version);
<add> if (!interaction.isSetDisplayId())
<add> interaction.setDisplayId("interaction" + ++count);
<add> interaction.updateCompliantURI(cloned.getPersistentIdentity().toString(),
<add> interaction.getDisplayId(), version);
<ide> cloned.removeChildSafely(interaction, cloned.interactions);
<ide> cloned.addInteraction(interaction);
<ide> }
<ide> return cloned;
<ide> }
<ide>
<del> /* (non-Javadoc)
<del> * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateCompliantURI(java.lang.String, java.lang.String, java.lang.String)
<del> */
<add> /*
<add> * (non-Javadoc)
<add> *
<add> * @see
<add> * org.sbolstandard.core2.abstract_classes.TopLevel#updateCompliantURI(java
<add> * .lang.String, java.lang.String, java.lang.String)
<add> */
<add>
<ide> protected boolean checkDescendantsURIcompliance() {
<ide> // codereview: spaghetti
<del> if (!isURIcompliant(this.getIdentity(), 0)) { // ComponentDefinition to be copied has non-compliant URI.
<add> if (!isURIcompliant(this.getIdentity(), 0)) { // ComponentDefinition to
<add> // be copied has
<add> // non-compliant URI.
<ide> return false;
<ide> }
<ide> boolean allDescendantsCompliant = true;
<ide> if (!this.getModules().isEmpty()) {
<ide> for (Module module : this.getModules()) {
<del> allDescendantsCompliant = allDescendantsCompliant
<del> && isChildURIcompliant(this.getIdentity(), module.getIdentity());
<del> if (!allDescendantsCompliant) { // Current sequence constraint has non-compliant URI.
<add> allDescendantsCompliant = allDescendantsCompliant
<add> && isChildURIcompliant(this.getIdentity(), module.getIdentity());
<add> if (!allDescendantsCompliant) { // Current sequence constraint
<add> // has non-compliant URI.
<ide> return allDescendantsCompliant;
<ide> }
<ide> if (!module.getMapsTos().isEmpty()) {
<ide> // Check compliance of Module's children
<ide> for (MapsTo mapsTo : module.getMapsTos()) {
<del> allDescendantsCompliant = allDescendantsCompliant
<del> && isChildURIcompliant(module.getIdentity(), mapsTo.getIdentity());
<del> if (!allDescendantsCompliant) { // Current mapsTo has non-compliant URI.
<add> allDescendantsCompliant = allDescendantsCompliant
<add> && isChildURIcompliant(module.getIdentity(), mapsTo.getIdentity());
<add> if (!allDescendantsCompliant) { // Current mapsTo has
<add> // non-compliant URI.
<ide> return allDescendantsCompliant;
<ide> }
<del> }
<add> }
<ide> }
<ide> }
<ide> }
<ide> if (!this.getFunctionalComponents().isEmpty()) {
<ide> for (FunctionalComponent functionalComponent : this.getFunctionalComponents()) {
<del> allDescendantsCompliant = allDescendantsCompliant
<del> && isChildURIcompliant(this.getIdentity(), functionalComponent.getIdentity());
<del> if (!allDescendantsCompliant) { // Current component has non-compliant URI.
<add> allDescendantsCompliant = allDescendantsCompliant
<add> && isChildURIcompliant(this.getIdentity(), functionalComponent.getIdentity());
<add> if (!allDescendantsCompliant) { // Current component has
<add> // non-compliant URI.
<ide> return allDescendantsCompliant;
<ide> }
<ide> if (!functionalComponent.getMapsTos().isEmpty()) {
<ide> // Check compliance of Component's children
<ide> for (MapsTo mapsTo : functionalComponent.getMapsTos()) {
<del> allDescendantsCompliant = allDescendantsCompliant
<del> && isChildURIcompliant(functionalComponent.getIdentity(), mapsTo.getIdentity());
<del> if (!allDescendantsCompliant) { // Current mapsTo has non-compliant URI.
<add> allDescendantsCompliant = allDescendantsCompliant
<add> && isChildURIcompliant(functionalComponent.getIdentity(),
<add> mapsTo.getIdentity());
<add> if (!allDescendantsCompliant) { // Current mapsTo has
<add> // non-compliant URI.
<ide> return allDescendantsCompliant;
<ide> }
<del> }
<add> }
<ide> }
<ide> }
<ide> }
<ide> if (!this.getInteractions().isEmpty()) {
<ide> for (Interaction interaction : this.getInteractions()) {
<del> allDescendantsCompliant = allDescendantsCompliant
<del> && isChildURIcompliant(this.getIdentity(), interaction.getIdentity());
<del> if (!allDescendantsCompliant) { // Current interaction has non-compliant URI.
<add> allDescendantsCompliant = allDescendantsCompliant
<add> && isChildURIcompliant(this.getIdentity(), interaction.getIdentity());
<add> if (!allDescendantsCompliant) { // Current interaction has
<add> // non-compliant URI.
<ide> return allDescendantsCompliant;
<ide> }
<ide> for (Participation participation : interaction.getParticipations()) {
<del> allDescendantsCompliant = allDescendantsCompliant
<del> && isChildURIcompliant(interaction.getIdentity(), participation.getIdentity());
<del> if (!allDescendantsCompliant) { // Current participation has non-compliant URI.
<add> allDescendantsCompliant = allDescendantsCompliant
<add> && isChildURIcompliant(interaction.getIdentity(), participation.getIdentity());
<add> if (!allDescendantsCompliant) { // Current participation has
<add> // non-compliant URI.
<ide> return allDescendantsCompliant;
<ide> }
<ide> }
<ide> }
<ide> }
<del> // All descendants of this ComponentDefinition object have compliant URIs.
<del> return allDescendantsCompliant;
<del> }
<del>
<add> // All descendants of this ComponentDefinition object have compliant
<add> // URIs.
<add> return allDescendantsCompliant;
<add> }
<add>
<ide> protected boolean isComplete() {
<del> if (sbolDocument==null) return false;
<add> if (sbolDocument == null)
<add> return false;
<ide> for (URI modelURI : models) {
<del> if (sbolDocument.getModel(modelURI)==null) return false;
<add> if (sbolDocument.getModel(modelURI) == null)
<add> return false;
<ide> }
<ide> for (FunctionalComponent functionalComponent : getFunctionalComponents()) {
<del> if (functionalComponent.getDefinition()==null) return false;
<add> if (functionalComponent.getDefinition() == null)
<add> return false;
<ide> }
<ide> for (Module module : getModules()) {
<del> if (module.getDefinition()==null) return false;
<add> if (module.getDefinition() == null)
<add> return false;
<ide> }
<ide> return true;
<ide> }
<del>
<ide> } |
|
Java | agpl-3.0 | f4981db02b36ef15e2727142ec6fd2979d08b244 | 0 | quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,bhutchinson/kfs,kkronenb/kfs,smith750/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,bhutchinson/kfs,smith750/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,smith750/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,kuali/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs | /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.sys.context;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.batch.BatchSpringContext;
import org.kuali.kfs.sys.batch.Job;
import org.kuali.kfs.sys.batch.Step;
import org.kuali.rice.kns.service.DateTimeService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiModuleService;
import org.kuali.rice.kns.service.ModuleService;
import org.kuali.rice.kns.service.ParameterService;
public class BatchStepRunner {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BatchStepRunner.class);
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("ERROR: You must pass the name of the step to run on the command line.");
System.exit(8);
}
try {
Log4jConfigurer.configureLogging(false);
SpringContext.initializeBatchApplicationContext();
String[] stepNames;
if (args[0].indexOf(",") > 0) {
stepNames = StringUtils.split(args[0], ",");
}
else {
stepNames = new String[] { args[0] };
}
ParameterService parameterService = SpringContext.getBean(ParameterService.class);
DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
String jobName = args.length >= 2 ? args[1] : KFSConstants.BATCH_STEP_RUNNER_JOB_NAME;
Date jobRunDate = dateTimeService.getCurrentDate();
LOG.info("Executing job: " + jobName + " steps: " + Arrays.toString(stepNames));
for (int i = 0; i < stepNames.length; ++i) {
Step step = BatchSpringContext.getStep(stepNames[i]);
if ( step != null ) {
ModuleService module = SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService( step.getClass() );
Appender ndcAppender = null;
String nestedDiagnosticContext =
StringUtils.substringAfter( module.getModuleConfiguration().getNamespaceCode(), "-").toLowerCase()
+ File.separator + step.getName()
+ "-" + dateTimeService.toDateTimeStringForFilename(dateTimeService.getCurrentDate());
boolean ndcSet = false;;
try {
ndcAppender = new FileAppender(Logger.getRootLogger().getAppender("LogFile").getLayout(), getLogFileName(nestedDiagnosticContext));
ndcAppender.addFilter(new NDCFilter(nestedDiagnosticContext));
Logger.getRootLogger().addAppender(ndcAppender);
NDC.push(nestedDiagnosticContext);
ndcSet = true;
} catch (Exception ex) {
LOG.warn("Could not initialize custom logging for step: " + step.getName(), ex);
}
try {
if (!Job.runStep(parameterService, jobName, i, step, jobRunDate) ) {
System.exit(4);
}
} catch ( RuntimeException ex ) {
throw ex;
} finally {
if ( ndcSet ) {
ndcAppender.close();
Logger.getRootLogger().removeAppender(ndcAppender);
NDC.pop();
}
}
} else {
throw new IllegalArgumentException( "Unable to find step: " + stepNames[i] );
}
}
LOG.info("Finished executing job: " + jobName + " steps: " + Arrays.toString(stepNames));
System.exit(0);
}
catch (Throwable t) {
System.err.println("ERROR: Exception caught: ");
t.printStackTrace(System.err);
System.exit(8);
}
}
protected static String getLogFileName(String nestedDiagnosticContext) {
return SpringContext.getBean( KualiConfigurationService.class ).getPropertyString(KFSConstants.REPORTS_DIRECTORY_KEY)
+ File.separator
+ nestedDiagnosticContext + ".log";
}
}
| work/src/org/kuali/kfs/sys/context/BatchStepRunner.java | /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.sys.context;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.batch.BatchSpringContext;
import org.kuali.kfs.sys.batch.Job;
import org.kuali.kfs.sys.batch.Step;
import org.kuali.rice.kns.service.DateTimeService;
import org.kuali.rice.kns.service.KualiConfigurationService;
import org.kuali.rice.kns.service.KualiModuleService;
import org.kuali.rice.kns.service.ModuleService;
import org.kuali.rice.kns.service.ParameterService;
public class BatchStepRunner {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BatchStepRunner.class);
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("ERROR: You must pass the name of the step to run on the command line.");
System.exit(8);
}
try {
Log4jConfigurer.configureLogging(false);
SpringContext.initializeBatchApplicationContext();
String[] stepNames;
if (args[0].indexOf(",") > 0) {
stepNames = StringUtils.split(args[0], ",");
}
else {
stepNames = new String[] { args[0] };
}
ParameterService parameterService = SpringContext.getBean(ParameterService.class);
DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
String jobName = args.length >= 2 ? args[1] : KFSConstants.BATCH_STEP_RUNNER_JOB_NAME;
Date jobRunDate = dateTimeService.getCurrentDate();
LOG.info("Executing job: " + jobName + " steps: " + Arrays.toString(stepNames));
Map<String, Step> steps = SpringContext.getBeansOfType(Step.class);
for (String stepName : steps.keySet()) {
System.out.println("Step name: " + stepName + " class: " + steps.get(stepName).getClass().getName());
}
for (int i = 0; i < stepNames.length; ++i) {
Step step = BatchSpringContext.getStep(stepNames[i]);
if ( step != null ) {
ModuleService module = SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService( step.getClass() );
Appender ndcAppender = null;
String nestedDiagnosticContext =
StringUtils.substringAfter( module.getModuleConfiguration().getNamespaceCode(), "-").toLowerCase()
+ File.separator + step.getName()
+ "-" + dateTimeService.toDateTimeStringForFilename(dateTimeService.getCurrentDate());
boolean ndcSet = false;;
try {
ndcAppender = new FileAppender(Logger.getRootLogger().getAppender("LogFile").getLayout(), getLogFileName(nestedDiagnosticContext));
ndcAppender.addFilter(new NDCFilter(nestedDiagnosticContext));
Logger.getRootLogger().addAppender(ndcAppender);
NDC.push(nestedDiagnosticContext);
ndcSet = true;
} catch (Exception ex) {
LOG.warn("Could not initialize custom logging for step: " + step.getName(), ex);
}
try {
if (!Job.runStep(parameterService, jobName, i, step, jobRunDate) ) {
System.exit(4);
}
} catch ( RuntimeException ex ) {
throw ex;
} finally {
if ( ndcSet ) {
ndcAppender.close();
Logger.getRootLogger().removeAppender(ndcAppender);
NDC.pop();
}
}
} else {
throw new IllegalArgumentException( "Unable to find step: " + stepNames[i] );
}
}
LOG.info("Finished executing job: " + jobName + " steps: " + Arrays.toString(stepNames));
System.exit(0);
}
catch (Throwable t) {
System.err.println("ERROR: Exception caught: ");
t.printStackTrace(System.err);
System.exit(8);
}
}
protected static String getLogFileName(String nestedDiagnosticContext) {
return SpringContext.getBean( KualiConfigurationService.class ).getPropertyString(KFSConstants.REPORTS_DIRECTORY_KEY)
+ File.separator
+ nestedDiagnosticContext + ".log";
}
}
| remove testing code
| work/src/org/kuali/kfs/sys/context/BatchStepRunner.java | remove testing code | <ide><path>ork/src/org/kuali/kfs/sys/context/BatchStepRunner.java
<ide> import java.io.IOException;
<ide> import java.util.Arrays;
<ide> import java.util.Date;
<del>import java.util.Map;
<ide>
<ide> import org.apache.commons.lang.StringUtils;
<ide> import org.apache.log4j.Appender;
<ide> String jobName = args.length >= 2 ? args[1] : KFSConstants.BATCH_STEP_RUNNER_JOB_NAME;
<ide> Date jobRunDate = dateTimeService.getCurrentDate();
<ide> LOG.info("Executing job: " + jobName + " steps: " + Arrays.toString(stepNames));
<del> Map<String, Step> steps = SpringContext.getBeansOfType(Step.class);
<del> for (String stepName : steps.keySet()) {
<del> System.out.println("Step name: " + stepName + " class: " + steps.get(stepName).getClass().getName());
<del> }
<ide> for (int i = 0; i < stepNames.length; ++i) {
<ide> Step step = BatchSpringContext.getStep(stepNames[i]);
<ide> if ( step != null ) { |
|
Java | apache-2.0 | f74a7ebcc93794b1e3ca60a618caeebcd255c679 | 0 | codehaus/mvel,codehaus/mvel | package org.mvel.util;
import org.mvel.*;
import static org.mvel.DataConversion.canConvert;
import static org.mvel.DataConversion.convert;
import static org.mvel.ExpressionParser.eval;
import org.mvel.integration.VariableResolverFactory;
import org.mvel.optimizers.ExecutableStatement;
import org.mvel.optimizers.impl.refl.ConstructorAccessor;
import org.mvel.optimizers.impl.refl.ReflectiveAccessor;
import static java.lang.Character.isWhitespace;
import static java.lang.Class.forName;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class ParseTools {
public static String[] parseMethodOrConstructor(char[] parm) {
int start = -1;
for (int i = 0; i < parm.length; i++) {
if (parm[i] == '(') {
start = ++i;
break;
}
}
if (start != -1) {
for (int i = parm.length - 1; i > 0; i--) {
if (parm[i] == ')') {
return parseParameterList(parm, start, i - start);
}
}
}
return null;
}
public static String[] parseParameterList(char[] parm, int offset, int length) {
List<String> list = new LinkedList<String>();
if (length == -1) length = parm.length;
int adepth = 0;
int start = offset;
int i = offset;
int end = i + length;
for (; i < end; i++) {
switch (parm[i]) {
case'[':
case'{':
if (adepth++ == 0) start = i;
continue;
case']':
case'}':
if (--adepth == 0) {
list.add(new String(parm, start, i - start + 1));
while (isWhitespace(parm[i])) i++;
start = i + 1;
}
continue;
case'\'':
int rStart = i;
while (++i < end && parm[i] != '\'') {
if (parm[i] == '\\') handleEscapeSequence(parm[++i]);
}
if (i == end || parm[i] != '\'') {
throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm, offset, length));
}
continue;
case'"':
rStart = i;
while (++i < end && parm[i] != '"') {
if (parm[i] == '\\') handleEscapeSequence(parm[++i]);
}
if (i == end || parm[i] != '\'') {
throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm, offset, length));
}
continue;
case',':
if (adepth != 0) continue;
if (i > start) {
while (isWhitespace(parm[start])) start++;
list.add(new String(parm, start, i - start));
}
while (isWhitespace(parm[i])) i++;
start = i + 1;
}
}
if (start < length && i > start) {
String s = new String(parm, start, i - start).trim();
if (s.length() > 0)
list.add(s);
}
else if (list.size() == 0) {
String s = new String(parm, start, length).trim();
if (s.length() > 0)
list.add(s);
}
return list.toArray(new String[list.size()]);
}
private static Map<String, Map<Integer, Method>> RESOLVED_METH_CACHE =
new WeakHashMap<String, Map<Integer, Method>>(10);
public static Method getBestCanadidate(Object[] arguments, String method, Method[] methods) {
Class[] parmTypes;
Method bestCandidate = null;
int bestScore = 0;
int score = 0;
Class[] targetParms = new Class[arguments.length];
for (int i = 0; i < arguments.length; i++)
targetParms[i] = arguments[i] != null ? arguments[i].getClass() : Object.class;
Integer hash = createClassSignatureHash(targetParms);
if (RESOLVED_METH_CACHE.containsKey(method) && RESOLVED_METH_CACHE.get(method).containsKey(hash))
return RESOLVED_METH_CACHE.get(method).get(hash);
for (Method meth : methods) {
if (method.equals(meth.getName())) {
if ((parmTypes = meth.getParameterTypes()).length != arguments.length) continue;
else if (arguments.length == 0 && parmTypes.length == 0) return meth;
for (int i = 0; i < arguments.length; i++) {
if (parmTypes[i].isPrimitive() && boxPrimitive(parmTypes[i]) == targetParms[i]) score += 3;
else if (parmTypes[i] == targetParms[i]) score += 4;
else if (parmTypes[i].isAssignableFrom(targetParms[i])) score += 2;
else if (canConvert(parmTypes[i], targetParms[i])) score += 1;
else {
score = 0;
break;
}
}
if (score != 0 && score > bestScore) {
bestCandidate = meth;
bestScore = score;
}
score = 0;
}
}
if (bestCandidate != null) {
if (!RESOLVED_METH_CACHE.containsKey(method))
RESOLVED_METH_CACHE.put(method, new WeakHashMap<Integer, Method>());
RESOLVED_METH_CACHE.get(method).put(hash, bestCandidate);
}
return bestCandidate;
}
private static Map<Class, Map<Integer, Constructor>> RESOLVED_CONST_CACHE = new WeakHashMap<Class, Map<Integer, Constructor>>(10);
private static Map<Constructor, Class[]> CONSTRUCTOR_PARMS_CACHE = new WeakHashMap<Constructor, Class[]>(10);
private static Class[] getConstructors(Constructor cns) {
if (CONSTRUCTOR_PARMS_CACHE.containsKey(cns))
return CONSTRUCTOR_PARMS_CACHE.get(cns);
else {
Class[] c = cns.getParameterTypes();
CONSTRUCTOR_PARMS_CACHE.put(cns, c);
return c;
}
}
public static Constructor getBestConstructorCanadidate(Object[] arguments, Class cls) {
Class[] parmTypes;
Constructor bestCandidate = null;
int bestScore = 0;
int score = 0;
Class[] targetParms = new Class[arguments.length];
for (int i = 0; i < arguments.length; i++)
targetParms[i] = arguments[i] != null ? arguments[i].getClass() : Object.class;
Integer hash = createClassSignatureHash(targetParms);
if (RESOLVED_CONST_CACHE.containsKey(cls) && RESOLVED_CONST_CACHE.get(cls).containsKey(hash))
return RESOLVED_CONST_CACHE.get(cls).get(hash);
for (Constructor construct : getConstructors(cls)) {
if ((parmTypes = getConstructors(construct)).length != arguments.length) continue;
else if (arguments.length == 0 && parmTypes.length == 0) return construct;
for (int i = 0; i < arguments.length; i++) {
if (parmTypes[i].isPrimitive() && boxPrimitive(parmTypes[i]) == targetParms[i]) score += 3;
else if (parmTypes[i] == targetParms[i]) score += 4;
else if (parmTypes[i].isAssignableFrom(targetParms[i])) score += 2;
else if (canConvert(parmTypes[i], targetParms[i])) score += 1;
else {
score = 0;
break;
}
}
if (score != 0 && score > bestScore) {
bestCandidate = construct;
bestScore = score;
}
score = 0;
}
if (bestCandidate != null) {
if (!RESOLVED_CONST_CACHE.containsKey(cls))
RESOLVED_CONST_CACHE.put(cls, new WeakHashMap<Integer, Constructor>());
RESOLVED_CONST_CACHE.get(cls).put(hash, bestCandidate);
}
return bestCandidate;
}
private static Map<String, Class> CLASS_RESOLVER_CACHE = new WeakHashMap<String, Class>(10);
private static Map<Class, Constructor[]> CLASS_CONSTRUCTOR_CACHE = new WeakHashMap<Class, Constructor[]>(10);
private static Class createClass(String className) throws ClassNotFoundException {
if (CLASS_RESOLVER_CACHE.containsKey(className))
return CLASS_RESOLVER_CACHE.get(className);
else {
Class cls = Class.forName(className);
CLASS_RESOLVER_CACHE.put(className, cls);
return cls;
}
}
private static Constructor[] getConstructors(Class cls) {
if (CLASS_CONSTRUCTOR_CACHE.containsKey(cls))
return CLASS_CONSTRUCTOR_CACHE.get(cls);
else {
Constructor[] cns = cls.getConstructors();
CLASS_CONSTRUCTOR_CACHE.put(cls, cns);
return cns;
}
}
public static Object constructObject(String expression, Object ctx, VariableResolverFactory vrf)
throws InstantiationException, IllegalAccessException, InvocationTargetException,
ClassNotFoundException {
String[] constructorParms = parseMethodOrConstructor(expression.toCharArray());
if (constructorParms != null) {
Class cls = Token.LITERALS.containsKey(expression = expression.substring(0, expression.indexOf('('))) ?
((Class) Token.LITERALS.get(expression)) : createClass(expression);
Object[] parms = new Object[constructorParms.length];
for (int i = 0; i < constructorParms.length; i++) {
parms[i] = (eval(constructorParms[i], ctx, vrf));
}
Constructor cns = getBestConstructorCanadidate(parms, cls);
if (cns == null)
throw new CompileException("unable to find constructor for: " + cls.getName());
for (int i = 0; i < parms.length; i++) {
//noinspection unchecked
parms[i] = convert(parms[i], cns.getParameterTypes()[i]);
}
return cns.newInstance(parms);
}
else {
return forName(expression).newInstance();
}
}
public static AccessorNode compileConstructor(String expression, Object ctx, VariableResolverFactory vars) throws
InstantiationException, IllegalAccessException, InvocationTargetException,
ClassNotFoundException, NoSuchMethodException {
String[] cnsRes = captureContructorAndResidual(expression);
String[] constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray());
if (constructorParms != null) {
Class cls = Token.LITERALS.containsKey(expression = expression.substring(0, expression.indexOf('('))) ?
((Class) Token.LITERALS.get(expression)) : createClass(expression);
ExecutableStatement[] cStmts = new ExecutableStatement[constructorParms.length];
for (int i = 0; i < constructorParms.length; i++) {
cStmts[i] = (ExecutableStatement) ExpressionParser.compileExpression(constructorParms[i]);
}
Object[] parms = new Object[constructorParms.length];
for (int i = 0; i < constructorParms.length; i++) {
parms[i] = cStmts[i].getValue(ctx, vars);
}
Constructor cns = getBestConstructorCanadidate(parms, cls);
if (cns == null)
throw new CompileException("unable to find constructor for: " + cls.getName());
for (int i = 0; i < parms.length; i++) {
//noinspection unchecked
parms[i] = convert(parms[i], cns.getParameterTypes()[i]);
}
AccessorNode ca = new ConstructorAccessor(cns, cStmts);
if (cnsRes.length > 1) {
ReflectiveAccessor compiledAccessor
= new ReflectiveAccessor(cnsRes[1].toCharArray(), cns.newInstance(parms), ctx, vars);
compiledAccessor.setRootNode(ca);
compiledAccessor.compileGetChain();
ca = compiledAccessor.getRootNode();
}
return ca;
}
else {
Constructor cns = Class.forName(expression).getConstructor();
AccessorNode ca = new ConstructorAccessor(cns, null);
if (cnsRes.length > 1) {
ReflectiveAccessor compiledAccessor
= new ReflectiveAccessor(cnsRes[1].toCharArray(), cns.newInstance(), ctx, vars);
compiledAccessor.setRootNode(ca);
compiledAccessor.compileGetChain();
ca = compiledAccessor.getRootNode();
}
return ca;
}
}
public static String[] captureContructorAndResidual
(String
token) {
char[] cs = token.toCharArray();
int depth = 0;
for (int i = 0; i < cs.length; i++) {
switch (cs[i]) {
case'(':
depth++;
continue;
case')':
if (1 == depth--) {
return new String[]{new String(cs, 0, ++i), new String(cs, i, cs.length - i)};
}
}
}
return new String[]{token};
}
public static Class boxPrimitive
(Class
cls) {
if (cls == int.class) {
return Integer.class;
}
else if (cls == int[].class) {
return Integer[].class;
}
else if (cls == long.class) {
return Long.class;
}
else if (cls == long[].class) {
return Long[].class;
}
else if (cls == short.class) {
return Short.class;
}
else if (cls == short[].class) {
return Short[].class;
}
else if (cls == double.class) {
return Double.class;
}
else if (cls == double[].class) {
return Double[].class;
}
else if (cls == float.class) {
return Float.class;
}
else if (cls == float[].class) {
return Float[].class;
}
else if (cls == boolean.class) {
return Boolean.class;
}
else if (cls == boolean[].class) {
return Boolean[].class;
}
else if (cls == byte.class) {
return Byte.class;
}
else if (cls == byte[].class) {
return Byte[].class;
}
return null;
}
public static boolean containsCheck
(Object
compareTo, Object
compareTest) {
if (compareTo == null)
return false;
else if (compareTo instanceof String)
return ((String) compareTo).contains(String.valueOf(compareTest));
else if (compareTo instanceof Collection)
return ((Collection) compareTo).contains(compareTest);
else if (compareTo instanceof Map)
return ((Map) compareTo).containsKey(compareTest);
else if (compareTo.getClass().isArray()) {
for (Object o : ((Object[]) compareTo)) {
if (compareTest == null && o == null) return true;
else if (o != null && o.equals(compareTest)) return true;
}
}
return false;
}
public static int createClassSignatureHash
(Class[] sig) {
int hash = 0;
for (Class cls : sig) {
if (cls != null) hash += cls.hashCode();
}
return hash + sig.length;
}
public static char handleEscapeSequence
(
char escapedChar) {
switch (escapedChar) {
case'\\':
return '\\';
case't':
return '\t';
case'r':
return '\r';
case'\'':
return '\'';
case'"':
return '"';
default:
throw new ParseException("illegal escape sequence: " + escapedChar);
}
}
public static void main
(String[] args) {
for (Package p : Package.getPackages()) {
System.out.println(p);
}
}
public static boolean debug
(String
str) {
System.out.println(str);
return true;
}
public static boolean debug
(Throwable
t) {
t.printStackTrace();
return true;
}
public static Object valueOnly(Object o) {
return (o instanceof Token) ? ((Token) o).getValue() : o;
}
}
| src/main/java/org/mvel/util/ParseTools.java | package org.mvel.util;
import org.mvel.*;
import static org.mvel.DataConversion.canConvert;
import static org.mvel.DataConversion.convert;
import static org.mvel.ExpressionParser.eval;
import org.mvel.integration.VariableResolverFactory;
import org.mvel.optimizers.ExecutableStatement;
import org.mvel.optimizers.impl.refl.ConstructorAccessor;
import org.mvel.optimizers.impl.refl.ReflectiveAccessor;
import static java.lang.Character.isWhitespace;
import static java.lang.Class.forName;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class ParseTools {
public static String[] parseMethodOrConstructor(char[] parm) {
int start = -1;
for (int i = 0; i < parm.length; i++) {
if (parm[i] == '(') {
start = ++i;
break;
}
}
if (start != -1) {
for (int i = parm.length - 1; i > 0; i--) {
if (parm[i] == ')') {
return parseParameterList(parm, start, i - start);
}
}
}
return null;
}
public static String[] parseParameterList(char[] parm, int offset, int length) {
List<String> list = new LinkedList<String>();
if (length == -1) length = parm.length;
int adepth = 0;
int start = offset;
int i = offset;
int end = i + length;
for (; i < end; i++) {
switch (parm[i]) {
case'[':
case'{':
if (adepth++ == 0) start = i;
continue;
case']':
case'}':
if (--adepth == 0) {
list.add(new String(parm, start, i - start + 1));
while (isWhitespace(parm[i])) i++;
start = i + 1;
}
continue;
case'\'':
int rStart = i;
while (++i < end && parm[i] != '\'') {
if (parm[i] == '\\') handleEscapeSequence(parm[++i]);
}
if (i == end || parm[i] != '\'') {
throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm));
}
continue;
case'"':
rStart = i;
while (++i < end && parm[i] != '"') {
if (parm[i] == '\\') handleEscapeSequence(parm[++i]);
}
if (i == end || parm[i] != '\'') {
throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm));
}
continue;
case',':
if (adepth != 0) continue;
if (i > start) {
while (isWhitespace(parm[start])) start++;
list.add(new String(parm, start, i - start));
}
while (isWhitespace(parm[i])) i++;
start = i + 1;
}
}
if (start < length && i > start) {
String s = new String(parm, start, i - start).trim();
if (s.length() > 0)
list.add(s);
}
else if (list.size() == 0) {
String s = new String(parm, start, length).trim();
if (s.length() > 0)
list.add(s);
}
return list.toArray(new String[list.size()]);
}
private static Map<String, Map<Integer, Method>> RESOLVED_METH_CACHE =
new WeakHashMap<String, Map<Integer, Method>>(10);
public static Method getBestCanadidate(Object[] arguments, String method, Method[] methods) {
Class[] parmTypes;
Method bestCandidate = null;
int bestScore = 0;
int score = 0;
Class[] targetParms = new Class[arguments.length];
for (int i = 0; i < arguments.length; i++)
targetParms[i] = arguments[i] != null ? arguments[i].getClass() : Object.class;
Integer hash = createClassSignatureHash(targetParms);
if (RESOLVED_METH_CACHE.containsKey(method) && RESOLVED_METH_CACHE.get(method).containsKey(hash))
return RESOLVED_METH_CACHE.get(method).get(hash);
for (Method meth : methods) {
if (method.equals(meth.getName())) {
if ((parmTypes = meth.getParameterTypes()).length != arguments.length) continue;
else if (arguments.length == 0 && parmTypes.length == 0) return meth;
for (int i = 0; i < arguments.length; i++) {
if (parmTypes[i].isPrimitive() && boxPrimitive(parmTypes[i]) == targetParms[i]) score += 3;
else if (parmTypes[i] == targetParms[i]) score += 4;
else if (parmTypes[i].isAssignableFrom(targetParms[i])) score += 2;
else if (canConvert(parmTypes[i], targetParms[i])) score += 1;
else {
score = 0;
break;
}
}
if (score != 0 && score > bestScore) {
bestCandidate = meth;
bestScore = score;
}
score = 0;
}
}
if (bestCandidate != null) {
if (!RESOLVED_METH_CACHE.containsKey(method))
RESOLVED_METH_CACHE.put(method, new WeakHashMap<Integer, Method>());
RESOLVED_METH_CACHE.get(method).put(hash, bestCandidate);
}
return bestCandidate;
}
private static Map<Class, Map<Integer, Constructor>> RESOLVED_CONST_CACHE = new WeakHashMap<Class, Map<Integer, Constructor>>(10);
private static Map<Constructor, Class[]> CONSTRUCTOR_PARMS_CACHE = new WeakHashMap<Constructor, Class[]>(10);
private static Class[] getConstructors(Constructor cns) {
if (CONSTRUCTOR_PARMS_CACHE.containsKey(cns))
return CONSTRUCTOR_PARMS_CACHE.get(cns);
else {
Class[] c = cns.getParameterTypes();
CONSTRUCTOR_PARMS_CACHE.put(cns, c);
return c;
}
}
public static Constructor getBestConstructorCanadidate(Object[] arguments, Class cls) {
Class[] parmTypes;
Constructor bestCandidate = null;
int bestScore = 0;
int score = 0;
Class[] targetParms = new Class[arguments.length];
for (int i = 0; i < arguments.length; i++)
targetParms[i] = arguments[i] != null ? arguments[i].getClass() : Object.class;
Integer hash = createClassSignatureHash(targetParms);
if (RESOLVED_CONST_CACHE.containsKey(cls) && RESOLVED_CONST_CACHE.get(cls).containsKey(hash))
return RESOLVED_CONST_CACHE.get(cls).get(hash);
for (Constructor construct : getConstructors(cls)) {
if ((parmTypes = getConstructors(construct)).length != arguments.length) continue;
else if (arguments.length == 0 && parmTypes.length == 0) return construct;
for (int i = 0; i < arguments.length; i++) {
if (parmTypes[i].isPrimitive() && boxPrimitive(parmTypes[i]) == targetParms[i]) score += 3;
else if (parmTypes[i] == targetParms[i]) score += 4;
else if (parmTypes[i].isAssignableFrom(targetParms[i])) score += 2;
else if (canConvert(parmTypes[i], targetParms[i])) score += 1;
else {
score = 0;
break;
}
}
if (score != 0 && score > bestScore) {
bestCandidate = construct;
bestScore = score;
}
score = 0;
}
if (bestCandidate != null) {
if (!RESOLVED_CONST_CACHE.containsKey(cls))
RESOLVED_CONST_CACHE.put(cls, new WeakHashMap<Integer, Constructor>());
RESOLVED_CONST_CACHE.get(cls).put(hash, bestCandidate);
}
return bestCandidate;
}
private static Map<String, Class> CLASS_RESOLVER_CACHE = new WeakHashMap<String, Class>(10);
private static Map<Class, Constructor[]> CLASS_CONSTRUCTOR_CACHE = new WeakHashMap<Class, Constructor[]>(10);
private static Class createClass(String className) throws ClassNotFoundException {
if (CLASS_RESOLVER_CACHE.containsKey(className))
return CLASS_RESOLVER_CACHE.get(className);
else {
Class cls = Class.forName(className);
CLASS_RESOLVER_CACHE.put(className, cls);
return cls;
}
}
private static Constructor[] getConstructors(Class cls) {
if (CLASS_CONSTRUCTOR_CACHE.containsKey(cls))
return CLASS_CONSTRUCTOR_CACHE.get(cls);
else {
Constructor[] cns = cls.getConstructors();
CLASS_CONSTRUCTOR_CACHE.put(cls, cns);
return cns;
}
}
public static Object constructObject(String expression, Object ctx, VariableResolverFactory vrf)
throws InstantiationException, IllegalAccessException, InvocationTargetException,
ClassNotFoundException {
String[] constructorParms = parseMethodOrConstructor(expression.toCharArray());
if (constructorParms != null) {
Class cls = Token.LITERALS.containsKey(expression = expression.substring(0, expression.indexOf('('))) ?
((Class) Token.LITERALS.get(expression)) : createClass(expression);
Object[] parms = new Object[constructorParms.length];
for (int i = 0; i < constructorParms.length; i++) {
parms[i] = (eval(constructorParms[i], ctx, vrf));
}
Constructor cns = getBestConstructorCanadidate(parms, cls);
if (cns == null)
throw new CompileException("unable to find constructor for: " + cls.getName());
for (int i = 0; i < parms.length; i++) {
//noinspection unchecked
parms[i] = convert(parms[i], cns.getParameterTypes()[i]);
}
return cns.newInstance(parms);
}
else {
return forName(expression).newInstance();
}
}
public static AccessorNode compileConstructor(String expression, Object ctx, VariableResolverFactory vars) throws
InstantiationException, IllegalAccessException, InvocationTargetException,
ClassNotFoundException, NoSuchMethodException {
String[] cnsRes = captureContructorAndResidual(expression);
String[] constructorParms = parseMethodOrConstructor(cnsRes[0].toCharArray());
if (constructorParms != null) {
Class cls = Token.LITERALS.containsKey(expression = expression.substring(0, expression.indexOf('('))) ?
((Class) Token.LITERALS.get(expression)) : createClass(expression);
ExecutableStatement[] cStmts = new ExecutableStatement[constructorParms.length];
for (int i = 0; i < constructorParms.length; i++) {
cStmts[i] = (ExecutableStatement) ExpressionParser.compileExpression(constructorParms[i]);
}
Object[] parms = new Object[constructorParms.length];
for (int i = 0; i < constructorParms.length; i++) {
parms[i] = cStmts[i].getValue(ctx, vars);
}
Constructor cns = getBestConstructorCanadidate(parms, cls);
if (cns == null)
throw new CompileException("unable to find constructor for: " + cls.getName());
for (int i = 0; i < parms.length; i++) {
//noinspection unchecked
parms[i] = convert(parms[i], cns.getParameterTypes()[i]);
}
AccessorNode ca = new ConstructorAccessor(cns, cStmts);
if (cnsRes.length > 1) {
ReflectiveAccessor compiledAccessor
= new ReflectiveAccessor(cnsRes[1].toCharArray(), cns.newInstance(parms), ctx, vars);
compiledAccessor.setRootNode(ca);
compiledAccessor.compileGetChain();
ca = compiledAccessor.getRootNode();
}
return ca;
}
else {
Constructor cns = Class.forName(expression).getConstructor();
AccessorNode ca = new ConstructorAccessor(cns, null);
if (cnsRes.length > 1) {
ReflectiveAccessor compiledAccessor
= new ReflectiveAccessor(cnsRes[1].toCharArray(), cns.newInstance(), ctx, vars);
compiledAccessor.setRootNode(ca);
compiledAccessor.compileGetChain();
ca = compiledAccessor.getRootNode();
}
return ca;
}
}
public static String[] captureContructorAndResidual
(String
token) {
char[] cs = token.toCharArray();
int depth = 0;
for (int i = 0; i < cs.length; i++) {
switch (cs[i]) {
case'(':
depth++;
continue;
case')':
if (1 == depth--) {
return new String[]{new String(cs, 0, ++i), new String(cs, i, cs.length - i)};
}
}
}
return new String[]{token};
}
public static Class boxPrimitive
(Class
cls) {
if (cls == int.class) {
return Integer.class;
}
else if (cls == int[].class) {
return Integer[].class;
}
else if (cls == long.class) {
return Long.class;
}
else if (cls == long[].class) {
return Long[].class;
}
else if (cls == short.class) {
return Short.class;
}
else if (cls == short[].class) {
return Short[].class;
}
else if (cls == double.class) {
return Double.class;
}
else if (cls == double[].class) {
return Double[].class;
}
else if (cls == float.class) {
return Float.class;
}
else if (cls == float[].class) {
return Float[].class;
}
else if (cls == boolean.class) {
return Boolean.class;
}
else if (cls == boolean[].class) {
return Boolean[].class;
}
else if (cls == byte.class) {
return Byte.class;
}
else if (cls == byte[].class) {
return Byte[].class;
}
return null;
}
public static boolean containsCheck
(Object
compareTo, Object
compareTest) {
if (compareTo == null)
return false;
else if (compareTo instanceof String)
return ((String) compareTo).contains(String.valueOf(compareTest));
else if (compareTo instanceof Collection)
return ((Collection) compareTo).contains(compareTest);
else if (compareTo instanceof Map)
return ((Map) compareTo).containsKey(compareTest);
else if (compareTo.getClass().isArray()) {
for (Object o : ((Object[]) compareTo)) {
if (compareTest == null && o == null) return true;
else if (o != null && o.equals(compareTest)) return true;
}
}
return false;
}
public static int createClassSignatureHash
(Class[] sig) {
int hash = 0;
for (Class cls : sig) {
if (cls != null) hash += cls.hashCode();
}
return hash + sig.length;
}
public static char handleEscapeSequence
(
char escapedChar) {
switch (escapedChar) {
case'\\':
return '\\';
case't':
return '\t';
case'r':
return '\r';
case'\'':
return '\'';
case'"':
return '"';
default:
throw new ParseException("illegal escape sequence: " + escapedChar);
}
}
public static void main
(String[] args) {
for (Package p : Package.getPackages()) {
System.out.println(p);
}
}
public static boolean debug
(String
str) {
System.out.println(str);
return true;
}
public static boolean debug
(Throwable
t) {
t.printStackTrace();
return true;
}
public static Object valueOnly(Object o) {
return (o instanceof Token) ? ((Token) o).getValue() : o;
}
}
| JIT Integrated | src/main/java/org/mvel/util/ParseTools.java | JIT Integrated | <ide><path>rc/main/java/org/mvel/util/ParseTools.java
<ide> return null;
<ide> }
<ide>
<add>
<ide> public static String[] parseParameterList(char[] parm, int offset, int length) {
<ide> List<String> list = new LinkedList<String>();
<ide>
<ide> }
<ide>
<ide> if (i == end || parm[i] != '\'') {
<del> throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm));
<add> throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm, offset, length));
<ide> }
<ide> continue;
<ide>
<ide> }
<ide>
<ide> if (i == end || parm[i] != '\'') {
<del> throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm));
<add> throw new CompileException("unterminated literal starting at index " + rStart + ": " + new String(parm, offset, length));
<ide> }
<ide> continue;
<ide> |
|
Java | apache-2.0 | ab35a7ec2808788ff063445e6598e50201fd114b | 0 | arpost/eurekaclinical-user-webapp,eurekaclinical/eurekaclinical-user-webapp | /*-
* #%L
* Eureka! Clinical User Webapp
* %%
* Copyright (C) 2016 Emory University
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.eurekaclinical.user.webapp.config;
import java.net.URI;
import org.eurekaclinical.standardapis.props.CasEurekaClinicalProperties;
/**
*
* @author miaoai
*/
public class UserWebappProperties extends CasEurekaClinicalProperties {
public UserWebappProperties() {
super("/etc/ec-user");
}
public String getUserServiceUrl() {
return this.getValue("eurekaclinical.userservice.url");
}
public String getEurekaWebappUrl() {
return this.getValue("eureka.webapp.url");
}
public String getEurekaServicesUrl() {
return this.getValue("eureka.services.url");
}
public boolean isEphiProhibited() {
return Boolean.parseBoolean(getValue("eurekaclinical.userwebapp.ephiprohibited"));
}
public boolean isDemoMode() {
return Boolean.parseBoolean(getValue("eurekaclinical.userwebapp.demomode"));
}
@Override
public String getProxyCallbackServer() {
return this.getValue("eurekaclinical.userwebapp.callbackserver");
}
public boolean isOAuthRegistrationEnabled() {
return isGoogleOAuthRegistrationEnabled() || isGitHubOAuthRegistrationEnabled() || isGlobusOAuthRegistrationEnabled();
}
public boolean isGoogleOAuthRegistrationEnabled() {
return getGoogleOAuthKey() != null && getGoogleOAuthSecret() != null;
}
public boolean isGitHubOAuthRegistrationEnabled() {
return getGitHubOAuthKey() != null && getGitHubOAuthSecret() != null;
}
public boolean isGlobusOAuthRegistrationEnabled() {
return getGlobusOAuthKey() != null && getGlobusOAuthSecret() != null;
}
public boolean isLocalAccountRegistrationEnabled() {
return Boolean.parseBoolean(getValue("eurekaclinical.userwebapp.localregistrationenabled"));
}
public boolean isRegistrationEnabled() {
return isLocalAccountRegistrationEnabled() || isOAuthRegistrationEnabled();
}
public String getGitHubOAuthKey() {
return getValue("eurekaclinical.userwebapp.githuboauthkey");
}
public String getGitHubOAuthSecret() {
return getValue("eurekaclinical.userwebapp.githuboauthsecret");
}
public String getGlobusOAuthKey() {
return getValue("eurekaclinical.userwebapp.globusoauthkey");
}
public String getGlobusOAuthSecret() {
return getValue("eurekaclinical.userwebapp.globusoauthsecret");
}
public String getGoogleOAuthKey() {
return getValue("eurekaclinical.userwebapp.googleoauthkey");
}
public String getGoogleOAuthSecret() {
return getValue("eurekaclinical.userwebapp.googleoauthsecret");
}
public URI getURI() {
String url = getValue("eurekaclinical.userwebapp.url");
if (!url.endsWith("/")) {
return URI.create(url + "/");
} else {
return URI.create(url);
}
}
@Override
public String getUrl() {
return getURI().toString();
}
}
| src/main/java/org/eurekaclinical/user/webapp/config/UserWebappProperties.java | /*-
* #%L
* Eureka! Clinical User Webapp
* %%
* Copyright (C) 2016 Emory University
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.eurekaclinical.user.webapp.config;
import java.net.URI;
import org.eurekaclinical.standardapis.props.CasEurekaClinicalProperties;
/**
*
* @author miaoai
*/
public class UserWebappProperties extends CasEurekaClinicalProperties {
public UserWebappProperties() {
super("/etc/ec-user");
}
public String getUserServiceUrl() {
return this.getValue("eurekaclinical.userservice.url");
}
public String getEurekaWebappUrl() {
return this.getValue("eureka.webapp.url");
}
public String getEurekaServicesUrl() {
return this.getValue("eureka.services.url");
}
public boolean isEphiProhibited() {
return Boolean.parseBoolean(getValue("eurekaclinical.userwebapp.ephiprohibited"));
}
public boolean isDemoMode() {
return Boolean.parseBoolean(getValue("eurekaclinical.userwebapp.demomode"));
}
@Override
public String getProxyCallbackServer() {
return this.getValue("eurekaclinical.userwebapp.callbackserver");
}
public boolean isOAuthRegistrationEnabled() {
return isGoogleOAuthRegistrationEnabled() || isGitHubOAuthRegistrationEnabled() || isGlobusOAuthRegistrationEnabled();
}
public boolean isGoogleOAuthRegistrationEnabled() {
return getGoogleOAuthKey() != null && getGoogleOAuthSecret() != null;
}
public boolean isGitHubOAuthRegistrationEnabled() {
return getGitHubOAuthKey() != null && getGitHubOAuthSecret() != null;
}
public boolean isGlobusOAuthRegistrationEnabled() {
return getGlobusOAuthKey() != null && getGlobusOAuthSecret() != null;
}
public boolean isLocalAccountRegistrationEnabled() {
return Boolean.parseBoolean(getValue("eurekaclinical.userwebapp.localregistrationenabled"));
}
public boolean isRegistrationEnabled() {
return isLocalAccountRegistrationEnabled() || isOAuthRegistrationEnabled();
}
public String getGitHubOAuthKey() {
return getValue("eurekaclinical.userwebapp.githuboauthkey");
}
public String getGitHubOAuthSecret() {
return getValue("eurekaclinical.userwebapp.githuboauthsecret");
}
public String getGlobusOAuthKey() {
return getValue("eurekaclinical.userwebapp.globusoauthkey");
}
public String getGlobusOAuthSecret() {
return getValue("eurekaclinical.userwebapp.globusoauthsecret");
}
public String getGoogleOAuthKey() {
return getValue("eurekaclinical.userwebapp.googleoauthkey");
}
public String getGoogleOAuthSecret() {
return getValue("eurekaclinical.userwebapp.googleoauthsecret");
}
public URI getURI() {
return URI.create(getValue("eurekaclinical.userwebapp.url"));
}
@Override
public String getUrl() {
return getURI().toString();
}
}
| Use UriBuilder instead.
| src/main/java/org/eurekaclinical/user/webapp/config/UserWebappProperties.java | Use UriBuilder instead. | <ide><path>rc/main/java/org/eurekaclinical/user/webapp/config/UserWebappProperties.java
<ide> public String getGoogleOAuthSecret() {
<ide> return getValue("eurekaclinical.userwebapp.googleoauthsecret");
<ide> }
<del>
<add>
<ide> public URI getURI() {
<del> return URI.create(getValue("eurekaclinical.userwebapp.url"));
<add> String url = getValue("eurekaclinical.userwebapp.url");
<add> if (!url.endsWith("/")) {
<add> return URI.create(url + "/");
<add> } else {
<add> return URI.create(url);
<add> }
<ide> }
<del>
<add>
<ide> @Override
<ide> public String getUrl() {
<ide> return getURI().toString();
<ide> }
<del>
<add>
<ide> } |
|
JavaScript | mit | 5945d763c37a78f564d0fbac3555af351290470e | 0 | NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2,NAPWebProductionEditTeam/MagTool2 | /* globals magazineBuilder */
(function(window, $, app) {
function NewElement() {
// If a slug exists, add the new element after the slug, else add it to the top of the page
var addToDom = function($element) {
var $selectable = app.Page.getContent();
console.log("ADDING " + $element + " TO DOM");
var $slug = app.Slug.findSlug();
if ($slug.length) {
console.log("Placing after slug");
$slug.after($element);
} else {
console.log("placing at top of page");
$element.prependTo(app.Page.getContent());
}
app.ContentEditor.deselect($selectable);
app.ContentEditor.select($element);
};
// Create New Text Element
this.newText = function() {
console.log("Creating text element");
addToDom('<div class="span-12 textAlignCenter draggable resizable push-down-18 push-right-18">TEXT ELEMENT</div>');
};
// Create New Image Element
this.newImage = function() {
console.log("Creating image element");
var $imageElement = '<div class="span-9 textAlignCenter draggable resizable push-down-18 push-right-18"><img src="" data-img-src@2x="" alt="" title="" height="200" width="200"></div>';
addToDom($imageElement);
};
// Create New CTA Element
this.newCTA = function() {
console.log("Creating CTA element");
var $ctaElement = '<div class="draggable resizable editable textAlignCenter span-11 btnShopThe pull-up-1-a push-right-37-c"><a data-magtool="ntk" href="${CtaLinkXML[\'ntk\'].@url}">SHOP THE SELECTION</a></div>';
addToDom($ctaElement);
};
}
app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
| src/js/Application/NewElement.js | /* globals magazineBuilder */
(function(window, $, app) {
function NewElement() {
// If a slug exists, add the new element after the slug, else add it to the top of the page
var addToDom = function($element) {
console.log("ADDING " + $element + " TO DOM");
var $slug = app.Slug.findSlug();
if ($slug.length) {
console.log("Placing after slug");
$slug.after($element);
} else {
console.log("placing at top of page");
$element.prependTo(app.Page.getContent());
}
};
// Create New Text Element
this.newText = function() {
console.log("Creating text element");
addToDom('<div class="span-12 textAlignCenter draggable resizable push-down-18 push-right-18">TEXT ELEMENT</div>');
};
// Create New Image Element
this.newImage = function() {
console.log("Creating image element");
var $imageElement = '<div class="span-9 textAlignCenter draggable resizable push-down-18 push-right-18"><img src="" data-img-src@2x="" alt="" title="" height="200" width="200"></div>';
addToDom($imageElement);
};
// Create New CTA Element
this.newCTA = function() {
console.log("Creating CTA element");
var $ctaElement = '<div class="draggable resizable editable textAlignCenter span-11 btnShopThe pull-up-1-a push-right-37-c"><a data-magtool="ntk" href="${CtaLinkXML[\'ntk\'].@url}">SHOP THE SELECTION</a></div>';
addToDom($ctaElement);
};
}
app.modules.NewElement = NewElement;
})(window, jQuery, MagTool);
| sdfsf
| src/js/Application/NewElement.js | sdfsf | <ide><path>rc/js/Application/NewElement.js
<ide>
<ide> // If a slug exists, add the new element after the slug, else add it to the top of the page
<ide> var addToDom = function($element) {
<add> var $selectable = app.Page.getContent();
<ide> console.log("ADDING " + $element + " TO DOM");
<ide> var $slug = app.Slug.findSlug();
<ide>
<ide> console.log("placing at top of page");
<ide> $element.prependTo(app.Page.getContent());
<ide> }
<add>
<add> app.ContentEditor.deselect($selectable);
<add> app.ContentEditor.select($element);
<ide> };
<ide>
<ide> // Create New Text Element |
|
Java | bsd-3-clause | f0b4c293fb155cde5922409fc02f4d931762f5c5 | 0 | Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo,Caleydo/caleydo | package org.caleydo.core.view.opengl.canvas.remote;
import gleem.linalg.Rotf;
import gleem.linalg.Vec3f;
import gleem.linalg.Vec4f;
import gleem.linalg.open.Transform;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import org.caleydo.core.command.ECommandType;
import org.caleydo.core.command.view.opengl.CmdCreateGLEventListener;
import org.caleydo.core.command.view.opengl.CmdCreateGLPathway;
import org.caleydo.core.data.IUniqueObject;
import org.caleydo.core.data.collection.ESetType;
import org.caleydo.core.data.collection.ISet;
import org.caleydo.core.data.graph.ICaleydoGraphItem;
import org.caleydo.core.data.graph.pathway.core.PathwayGraph;
import org.caleydo.core.data.graph.pathway.item.vertex.PathwayVertexGraphItem;
import org.caleydo.core.data.mapping.EIDType;
import org.caleydo.core.data.mapping.EMappingType;
import org.caleydo.core.data.selection.DeltaEventContainer;
import org.caleydo.core.data.selection.ESelectionType;
import org.caleydo.core.data.selection.EVAOperation;
import org.caleydo.core.data.selection.ISelectionDelta;
import org.caleydo.core.manager.IViewManager;
import org.caleydo.core.manager.event.EMediatorType;
import org.caleydo.core.manager.event.IDListEventContainer;
import org.caleydo.core.manager.event.IEventContainer;
import org.caleydo.core.manager.event.IMediatorReceiver;
import org.caleydo.core.manager.event.IMediatorSender;
import org.caleydo.core.manager.general.GeneralManager;
import org.caleydo.core.manager.id.EManagedObjectType;
import org.caleydo.core.manager.picking.EPickingMode;
import org.caleydo.core.manager.picking.EPickingType;
import org.caleydo.core.manager.picking.Pick;
import org.caleydo.core.util.system.SystemTime;
import org.caleydo.core.util.system.Time;
import org.caleydo.core.view.opengl.camera.EProjectionMode;
import org.caleydo.core.view.opengl.camera.IViewFrustum;
import org.caleydo.core.view.opengl.canvas.AGLEventListener;
import org.caleydo.core.view.opengl.canvas.EDetailLevel;
import org.caleydo.core.view.opengl.canvas.cell.GLCell;
import org.caleydo.core.view.opengl.canvas.glyph.gridview.GLGlyph;
import org.caleydo.core.view.opengl.canvas.panel.GLSelectionPanel;
import org.caleydo.core.view.opengl.canvas.pathway.GLPathway;
import org.caleydo.core.view.opengl.canvas.remote.bucket.BucketMouseWheelListener;
import org.caleydo.core.view.opengl.canvas.remote.bucket.GLConnectionLineRendererBucket;
import org.caleydo.core.view.opengl.canvas.remote.jukebox.GLConnectionLineRendererJukebox;
import org.caleydo.core.view.opengl.canvas.storagebased.AStorageBasedView;
import org.caleydo.core.view.opengl.canvas.storagebased.heatmap.GLHeatMap;
import org.caleydo.core.view.opengl.canvas.storagebased.parcoords.GLParallelCoordinates;
import org.caleydo.core.view.opengl.miniview.GLColorMappingBarMiniView;
import org.caleydo.core.view.opengl.mouse.PickingJoglMouseListener;
import org.caleydo.core.view.opengl.renderstyle.layout.ARemoteViewLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.BucketLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.JukeboxLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.ListLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.ARemoteViewLayoutRenderStyle.LayoutMode;
import org.caleydo.core.view.opengl.util.drag.GLDragAndDrop;
import org.caleydo.core.view.opengl.util.hierarchy.RemoteElementManager;
import org.caleydo.core.view.opengl.util.hierarchy.RemoteLevel;
import org.caleydo.core.view.opengl.util.hierarchy.RemoteLevelElement;
import org.caleydo.core.view.opengl.util.slerp.SlerpAction;
import org.caleydo.core.view.opengl.util.slerp.SlerpMod;
import org.caleydo.core.view.opengl.util.texture.EIconTextures;
import org.caleydo.core.view.opengl.util.texture.GLOffScreenTextureRenderer;
import org.caleydo.util.graph.EGraphItemHierarchy;
import org.caleydo.util.graph.EGraphItemProperty;
import org.caleydo.util.graph.IGraphItem;
import com.sun.opengl.util.j2d.TextRenderer;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureCoords;
/**
* Abstract class that is able to remotely rendering views. Subclasses implement
* the positioning of the views (bucket, jukebox, etc.).
*
* @author Marc Streit
* @author Alexander Lex
*/
public class GLRemoteRendering
extends AGLEventListener
implements IMediatorReceiver, IMediatorSender, IGLCanvasRemoteRendering
{
private ARemoteViewLayoutRenderStyle.LayoutMode layoutMode;
private static final int SLERP_RANGE = 1000;
private static final int SLERP_SPEED = 1400;
// private GenericSelectionManager selectionManager;
private int iMouseOverObjectID = -1;
private RemoteLevel focusLevel;
private RemoteLevel stackLevel;
private RemoteLevel poolLevel;
private RemoteLevel transitionLevel;
private RemoteLevel spawnLevel;
private RemoteLevel selectionLevel;
private ArrayList<SlerpAction> arSlerpActions;
private Time time;
/**
* Slerp factor: 0 = source; 1 = destination
*/
private int iSlerpFactor = 0;
protected AGLConnectionLineRenderer glConnectionLineRenderer;
private int iNavigationMouseOverViewID_left = -1;
private int iNavigationMouseOverViewID_right = -1;
private int iNavigationMouseOverViewID_out = -1;
private int iNavigationMouseOverViewID_in = -1;
private int iNavigationMouseOverViewID_lock = -1;
private boolean bEnableNavigationOverlay = false;
private ArrayList<Integer> iAlUninitializedPathwayIDs;
private TextRenderer textRenderer;
private GLDragAndDrop dragAndDrop;
private ARemoteViewLayoutRenderStyle layoutRenderStyle;
private BucketMouseWheelListener bucketMouseWheelListener;
private GLColorMappingBarMiniView colorMappingBarMiniView;
private ArrayList<Integer> iAlContainedViewIDs;
/**
* The current view in which the user is performing actions.
*/
private int iActiveViewID = -1;
// private int iGLDisplayList;
private GLSelectionPanel glSelectionPanel;
private ISelectionDelta lastSelectionDelta;
/**
* Used for dragging views to the pool area.
*/
private int iPoolLevelCommonID = -1;
private GLOffScreenTextureRenderer glOffScreenRenderer;
private boolean bUpdateOffScreenTextures = true;
private boolean bEnableConnectinLines = true;
/**
* Constructor.
*/
public GLRemoteRendering(final int iGLCanvasID, final String sLabel,
final IViewFrustum viewFrustum,
final ARemoteViewLayoutRenderStyle.LayoutMode layoutMode)
{
super(iGLCanvasID, sLabel, viewFrustum, true);
viewType = EManagedObjectType.GL_REMOTE_RENDERING;
this.layoutMode = layoutMode;
// if (generalManager.isWiiModeActive())
// {
glOffScreenRenderer = new GLOffScreenTextureRenderer();
// }
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
layoutRenderStyle = new BucketLayoutRenderStyle(viewFrustum);
super.renderStyle = layoutRenderStyle;
bucketMouseWheelListener = new BucketMouseWheelListener(this,
(BucketLayoutRenderStyle) layoutRenderStyle);
// Unregister standard mouse wheel listener
parentGLCanvas.removeMouseWheelListener(pickingTriggerMouseAdapter);
// Register specialized bucket mouse wheel listener
parentGLCanvas.addMouseWheelListener(bucketMouseWheelListener);
// parentGLCanvas.addMouseListener(bucketMouseWheelListener);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX))
{
layoutRenderStyle = new JukeboxLayoutRenderStyle(viewFrustum);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.LIST))
{
layoutRenderStyle = new ListLayoutRenderStyle(viewFrustum);
}
focusLevel = layoutRenderStyle.initFocusLevel();
if (GeneralManager.get().isWiiModeActive()
&& layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
stackLevel = ((BucketLayoutRenderStyle) layoutRenderStyle).initStackLevelWii();
}
else
{
stackLevel = layoutRenderStyle.initStackLevel(bucketMouseWheelListener
.isZoomedIn());
}
poolLevel = layoutRenderStyle.initPoolLevel(bucketMouseWheelListener.isZoomedIn(), -1);
selectionLevel = layoutRenderStyle.initMemoLevel();
transitionLevel = layoutRenderStyle.initTransitionLevel();
spawnLevel = layoutRenderStyle.initSpawnLevel();
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
glConnectionLineRenderer = new GLConnectionLineRendererBucket(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX))
{
glConnectionLineRenderer = new GLConnectionLineRendererJukebox(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.LIST))
{
glConnectionLineRenderer = null;
}
pickingTriggerMouseAdapter.addGLCanvas(this);
arSlerpActions = new ArrayList<SlerpAction>();
iAlUninitializedPathwayIDs = new ArrayList<Integer>();
createEventMediator();
dragAndDrop = new GLDragAndDrop();
textRenderer = new TextRenderer(new Font("Arial", Font.PLAIN, 24), false);
// trashCan = new TrashCan();
// TODO: the genome mapper should be stored centralized instead of newly
// created
colorMappingBarMiniView = new GLColorMappingBarMiniView(viewFrustum);
// Create selection panel
CmdCreateGLEventListener cmdCreateGLView = (CmdCreateGLEventListener) generalManager
.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_PANEL_SELECTION);
cmdCreateGLView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, 0.8f, 0, 4, -20, 20,
null, -1);
cmdCreateGLView.doCommand();
glSelectionPanel = (GLSelectionPanel) cmdCreateGLView.getCreatedObject();
// Registration to event system
generalManager.getEventPublisher().addSender(EMediatorType.SELECTION_MEDIATOR,
(IMediatorSender) this);
generalManager.getEventPublisher().addReceiver(EMediatorType.SELECTION_MEDIATOR,
(IMediatorReceiver) this);
generalManager.getEventPublisher().addSender(EMediatorType.VIEW_SELECTION, this);
iPoolLevelCommonID = generalManager.getIDManager().createID(
EManagedObjectType.REMOTE_LEVEL_ELEMENT);
}
@Override
public void initLocal(final GL gl)
{
// iGLDisplayList = gl.glGenLists(1);
init(gl);
}
@Override
public void initRemote(final GL gl, final int iRemoteViewID,
final PickingJoglMouseListener pickingTriggerMouseAdapter,
final IGLCanvasRemoteRendering remoteRenderingGLCanvas)
{
throw new IllegalStateException("Not implemented to be rendered remote");
}
@Override
public void init(final GL gl)
{
gl.glClearColor(0.5f, 0.5f, 0.5f, 1f);
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.init(gl);
// iconTextureManager = new GLIconTextureManager(gl);
time = new SystemTime();
((SystemTime) time).rebase();
initializeContainedViews(gl);
selectionLevel.getElementByPositionIndex(0).setContainedElementID(
glSelectionPanel.getID());
// selectionLevel.setElementVisibilityById(true,
// glSelectionPanel.getID());
glSelectionPanel.initRemote(gl, getID(), pickingTriggerMouseAdapter,
remoteRenderingGLCanvas);
colorMappingBarMiniView.setWidth(layoutRenderStyle.getColorBarWidth());
colorMappingBarMiniView.setHeight(layoutRenderStyle.getColorBarHeight());
glOffScreenRenderer.init(gl);
}
@Override
public synchronized void displayLocal(final GL gl)
{
if ((pickingTriggerMouseAdapter.wasRightMouseButtonPressed() && !bucketMouseWheelListener
.isZoomedIn())
&& !(layoutRenderStyle instanceof ListLayoutRenderStyle))
{
bEnableNavigationOverlay = !bEnableNavigationOverlay;
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.enableRendering(!bEnableNavigationOverlay);
}
pickingManager.handlePicking(iUniqueID, gl, true);
// if (bIsDisplayListDirtyLocal)
// {
// buildDisplayList(gl);
// bIsDisplayListDirtyLocal = false;
// }
display(gl);
if (eBusyModeState != EBusyModeState.OFF)
renderBusyMode(gl);
if (pickingTriggerMouseAdapter.getPickedPoint() != null)
dragAndDrop.setCurrentMousePos(gl, pickingTriggerMouseAdapter.getPickedPoint());
if (dragAndDrop.isDragActionRunning())
{
dragAndDrop.renderDragThumbnailTexture(gl);
}
if (pickingTriggerMouseAdapter.wasMouseReleased() && dragAndDrop.isDragActionRunning())
{
int iDraggedObjectId = dragAndDrop.getDraggedObjectedId();
// System.out.println("over: " +iExternalID);
// System.out.println("dragged: " +iDraggedObjectId);
// Prevent user from dragging element onto selection level
if (!RemoteElementManager.get().hasItem(iMouseOverObjectID)
|| !selectionLevel.containsElement(RemoteElementManager.get().getItem(
iMouseOverObjectID)))
{
RemoteLevelElement mouseOverElement = null;
// Check if a drag and drop action is performed onto the pool
// level
if (iMouseOverObjectID == iPoolLevelCommonID)
{
mouseOverElement = poolLevel.getNextFree();
}
else if (mouseOverElement == null && iMouseOverObjectID != iDraggedObjectId)
{
mouseOverElement = RemoteElementManager.get().getItem(iMouseOverObjectID);
}
if (mouseOverElement != null)
{
RemoteLevelElement originElement = RemoteElementManager.get().getItem(
iDraggedObjectId);
int iMouseOverElementID = mouseOverElement.getContainedElementID();
int iOriginElementID = originElement.getContainedElementID();
mouseOverElement.setContainedElementID(iOriginElementID);
originElement.setContainedElementID(iMouseOverElementID);
IViewManager viewGLCanvasManager = generalManager.getViewGLCanvasManager();
AGLEventListener originView = viewGLCanvasManager
.getGLEventListener(iOriginElementID);
if (originView != null)
originView.setRemoteLevelElement(mouseOverElement);
AGLEventListener mouseOverView = viewGLCanvasManager
.getGLEventListener(iMouseOverElementID);
if (mouseOverView != null)
mouseOverView.setRemoteLevelElement(originElement);
updateViewDetailLevels(originElement);
updateViewDetailLevels(mouseOverElement);
if (mouseOverElement.getContainedElementID() != -1)
{
if (poolLevel.containsElement(originElement)
&& (stackLevel.containsElement(mouseOverElement) || focusLevel
.containsElement(mouseOverElement)))
{
generalManager.getViewGLCanvasManager().getGLEventListener(
mouseOverElement.getContainedElementID())
.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
if (poolLevel.containsElement(mouseOverElement)
&& (stackLevel.containsElement(originElement) || focusLevel
.containsElement(originElement)))
{
generalManager.getViewGLCanvasManager().getGLEventListener(
mouseOverElement.getContainedElementID())
.broadcastElements(EVAOperation.REMOVE_ELEMENT);
}
}
}
}
dragAndDrop.stopDragAction();
bUpdateOffScreenTextures = true;
}
checkForHits(gl);
pickingTriggerMouseAdapter.resetEvents();
// gl.glCallList(iGLDisplayListIndexLocal);
}
@Override
public synchronized void displayRemote(final GL gl)
{
display(gl);
}
@Override
public synchronized void display(final GL gl)
{
time.update();
layoutRenderStyle.initPoolLevel(false, iMouseOverObjectID);
// layoutRenderStyle.initStackLevel(false);
// layoutRenderStyle.initMemoLevel();
if (GeneralManager.get().isWiiModeActive()
&& layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
((BucketLayoutRenderStyle) layoutRenderStyle).initFocusLevelWii();
((BucketLayoutRenderStyle) layoutRenderStyle).initStackLevelWii();
}
doSlerpActions(gl);
initializeNewPathways(gl);
if (!generalManager.isWiiModeActive())
{
renderRemoteLevel(gl, focusLevel);
renderRemoteLevel(gl, stackLevel);
}
else
{
if (bUpdateOffScreenTextures)
updateOffScreenTextures(gl);
renderRemoteLevel(gl, focusLevel);
glOffScreenRenderer.renderRubberBucket(gl, stackLevel,
(BucketLayoutRenderStyle) layoutRenderStyle, this);
}
// If user zooms to the bucket bottom all but the under
// focus layer is _not_ rendered.
if (bucketMouseWheelListener == null || !bucketMouseWheelListener.isZoomedIn())
{
// comment here for connection lines
if (glConnectionLineRenderer != null && bEnableConnectinLines)
glConnectionLineRenderer.render(gl);
renderPoolAndMemoLayerBackground(gl);
renderRemoteLevel(gl, transitionLevel);
renderRemoteLevel(gl, spawnLevel);
renderRemoteLevel(gl, poolLevel);
renderRemoteLevel(gl, selectionLevel);
}
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
bucketMouseWheelListener.render();
}
// colorMappingBarMiniView.render(gl,
// layoutRenderStyle.getColorBarXPos(),
// layoutRenderStyle.getColorBarYPos(), 4);
renderHandles(gl);
// gl.glCallList(iGLDisplayList);
}
public synchronized void setInitialContainedViews(
ArrayList<Integer> iAlInitialContainedViewIDs)
{
iAlContainedViewIDs = iAlInitialContainedViewIDs;
}
private void initializeContainedViews(final GL gl)
{
if (iAlContainedViewIDs == null)
return;
for (int iContainedViewID : iAlContainedViewIDs)
{
AGLEventListener tmpGLEventListener = generalManager.getViewGLCanvasManager()
.getGLEventListener(iContainedViewID);
// Ignore pathway views upon startup
// because they will be activated when pathway loader thread has
// finished
if (tmpGLEventListener == this || tmpGLEventListener instanceof GLPathway)
{
continue;
}
int iViewID = (tmpGLEventListener).getID();
if (focusLevel.hasFreePosition())
{
RemoteLevelElement element = focusLevel.getNextFree();
element.setContainedElementID(iViewID);
tmpGLEventListener.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
tmpGLEventListener.broadcastElements(EVAOperation.APPEND_UNIQUE);
tmpGLEventListener.setDetailLevel(EDetailLevel.MEDIUM);
tmpGLEventListener.setRemoteLevelElement(element);
// generalManager.getGUIBridge().setActiveGLSubView(this,
// tmpGLEventListener);
}
else if (stackLevel.hasFreePosition()
&& !(layoutRenderStyle instanceof ListLayoutRenderStyle))
{
RemoteLevelElement element = stackLevel.getNextFree();
element.setContainedElementID(iViewID);
tmpGLEventListener.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
tmpGLEventListener.broadcastElements(EVAOperation.APPEND_UNIQUE);
tmpGLEventListener.setDetailLevel(EDetailLevel.LOW);
tmpGLEventListener.setRemoteLevelElement(element);
}
else if (poolLevel.hasFreePosition())
{
RemoteLevelElement element = poolLevel.getNextFree();
element.setContainedElementID(iViewID);
tmpGLEventListener.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
tmpGLEventListener.setDetailLevel(EDetailLevel.VERY_LOW);
tmpGLEventListener.setRemoteLevelElement(element);
}
// pickingTriggerMouseAdapter.addGLCanvas(tmpGLEventListener);
pickingManager.getPickingID(iUniqueID, EPickingType.VIEW_SELECTION, iViewID);
generalManager.getEventPublisher().addSender(EMediatorType.SELECTION_MEDIATOR,
(IMediatorSender) tmpGLEventListener);
generalManager.getEventPublisher().addReceiver(EMediatorType.SELECTION_MEDIATOR,
(IMediatorReceiver) tmpGLEventListener);
}
}
public void renderBucketWall(final GL gl, boolean bRenderBorder, RemoteLevelElement element)
{
// Highlight potential view drop destination
if (dragAndDrop.isDragActionRunning() && element.getID() == iMouseOverObjectID)
{
gl.glLineWidth(5);
gl.glColor4f(0.2f, 0.2f, 0.2f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 0, 0.01f);
gl.glVertex3f(0, 8, 0.01f);
gl.glVertex3f(8, 8, 0.01f);
gl.glVertex3f(8, 0, 0.01f);
gl.glEnd();
}
if (arSlerpActions.isEmpty())
gl.glColor4f(1f, 1f, 1f, 1.0f); // normal mode
else
gl.glColor4f(1f, 1f, 1f, 0.3f);
if (!iAlUninitializedPathwayIDs.isEmpty())
gl.glColor4f(1f, 1f, 1f, 0.3f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(0, 0, -0.03f);
gl.glVertex3f(0, 8, -0.03f);
gl.glVertex3f(8, 8, -0.03f);
gl.glVertex3f(8, 0, -0.03f);
gl.glEnd();
if (!bRenderBorder)
return;
gl.glColor4f(0.4f, 0.4f, 0.4f, 1f);
gl.glLineWidth(1f);
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(0, 0, -0.02f);
// gl.glVertex3f(0, 8, -0.02f);
// gl.glVertex3f(8, 8, -0.02f);
// gl.glVertex3f(8, 0, -0.02f);
// gl.glEnd();
}
private void renderRemoteLevel(final GL gl, final RemoteLevel level)
{
for (RemoteLevelElement element : level.getAllElements())
{
renderRemoteLevelElement(gl, element, level);
if (!(layoutRenderStyle instanceof ListLayoutRenderStyle))
renderEmptyBucketWall(gl, element, level);
}
}
private void renderRemoteLevelElement(final GL gl, RemoteLevelElement element,
RemoteLevel level)
{
// // Check if view is visible
// if (!level.getElementVisibilityById(iViewID))
// return;
if (element.getContainedElementID() == -1)
return;
int iViewID = element.getContainedElementID();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, element.getID()));
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.VIEW_SELECTION,
iViewID));
AGLEventListener glEventListener = (generalManager.getViewGLCanvasManager()
.getGLEventListener(iViewID));
if (glEventListener == null)
throw new IllegalStateException("Cannot render canvas object which is null!");
gl.glPushMatrix();
Transform transform = element.getTransform();
Vec3f translation = transform.getTranslation();
Rotf rot = transform.getRotation();
Vec3f scale = transform.getScale();
Vec3f axis = new Vec3f();
float fAngle = rot.get(axis);
gl.glTranslatef(translation.x(), translation.y(), translation.z());
gl.glRotatef(Vec3f.convertRadiant2Grad(fAngle), axis.x(), axis.y(), axis.z());
gl.glScalef(scale.x(), scale.y(), scale.z());
if (level == poolLevel)
{
String sRenderText = glEventListener.getShortInfo();
// Limit pathway name in length
int iMaxChars;
if (layoutRenderStyle instanceof ListLayoutRenderStyle)
iMaxChars = 80;
else
iMaxChars = 20;
if (sRenderText.length() > iMaxChars && scale.x() < 0.03f)
sRenderText = sRenderText.subSequence(0, iMaxChars - 3) + "...";
if (element.getID() == iMouseOverObjectID)
textRenderer.setColor(1, 1, 1, 1);
else
textRenderer.setColor(0, 0, 0, 1);
if (glEventListener.getNumberOfSelections(ESelectionType.MOUSE_OVER) > 0)
{
textRenderer.setColor(1, 0, 0, 1);
// sRenderText =
// glEventListener.getNumberOfSelections(ESelectionType.MOUSE_OVER)
// + " - " + sRenderText;
}
else if (glEventListener.getNumberOfSelections(ESelectionType.SELECTION) > 0)
{
textRenderer.setColor(0, 1, 0, 1);
// sRenderText =
// glEventListener.getNumberOfSelections(ESelectionType.SELECTION)
// + " - " + sRenderText;
}
float fTextScalingFactor = 0.09f;
float fTextXPosition = 0f;
if (element.getID() == iMouseOverObjectID)
{
renderPoolSelection(gl, translation.x() - 0.4f / fAspectRatio, translation.y()
* scale.y() + 5.2f,
(float) textRenderer.getBounds(sRenderText).getWidth() * 0.06f + 23, 6f,
element); // 1.8f -> pool focus scaling
gl.glTranslatef(0.8f, 1.3f, 0);
fTextScalingFactor = 0.075f;
fTextXPosition = 12f;
}
else
{
// Render view background frame
Texture tempTexture = iconTextureManager.getIconTexture(gl,
EIconTextures.POOL_VIEW_BACKGROUND);
tempTexture.enable();
tempTexture.bind();
float fFrameWidth = 9.5f;
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glColor4f(1, 1, 1, 0.75f);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(-0.7f, -0.6f + fFrameWidth, -0.01f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(-0.7f + fFrameWidth, -0.6f + fFrameWidth, -0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(-0.7f + fFrameWidth, -0.6f, -0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(-0.7f, -0.6f, -0.01f);
gl.glEnd();
tempTexture.disable();
fTextXPosition = 9.5f;
}
textRenderer.begin3DRendering();
textRenderer.draw3D(sRenderText, fTextXPosition, 3, 0, fTextScalingFactor);
textRenderer.end3DRendering();
}
// Prevent rendering of view textures when simple list view
// if ((layoutRenderStyle instanceof ListLayoutRenderStyle
// && (layer == poolLayer || layer == stackLayer)))
// {
// gl.glPopMatrix();
// return;
// }
if (level != selectionLevel && level != poolLevel)
{
if (level.equals(focusLevel))
renderBucketWall(gl, false, element);
else
renderBucketWall(gl, true, element);
}
if (!bEnableNavigationOverlay || !level.equals(stackLevel))
{
glEventListener.displayRemote(gl);
}
else
{
renderNavigationOverlay(gl, element.getID());
}
gl.glPopMatrix();
gl.glPopName();
gl.glPopName();
}
private void renderEmptyBucketWall(final GL gl, RemoteLevelElement element,
RemoteLevel level)
{
gl.glPushMatrix();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, element.getID()));
Transform transform = element.getTransform();
Vec3f translation = transform.getTranslation();
Rotf rot = transform.getRotation();
Vec3f scale = transform.getScale();
Vec3f axis = new Vec3f();
float fAngle = rot.get(axis);
gl.glTranslatef(translation.x(), translation.y(), translation.z());
gl.glScalef(scale.x(), scale.y(), scale.z());
gl.glRotatef(Vec3f.convertRadiant2Grad(fAngle), axis.x(), axis.y(), axis.z());
if (!level.equals(transitionLevel) && !level.equals(spawnLevel)
&& !level.equals(poolLevel) && !level.equals(selectionLevel))
{
renderBucketWall(gl, true, element);
}
gl.glPopName();
gl.glPopMatrix();
}
private void renderHandles(final GL gl)
{
float fZoomedInScalingFactor = 0.4f;
// Bucket stack top
RemoteLevelElement element = stackLevel.getElementByPositionIndex(0);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(-2, 0, 4.02f);
renderNavigationHandleBar(gl, element, 4, 0.075f, false, 1);
gl.glTranslatef(2, 0, -4.02f);
}
else
{
gl.glTranslatef(-2 - 4 * fZoomedInScalingFactor, 0, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(2 + 4 * fZoomedInScalingFactor, 0, -0.02f);
}
}
// Bucket stack bottom
element = stackLevel.getElementByPositionIndex(2);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(-2, 0, 4.02f);
gl.glRotatef(180, 1, 0, 0);
renderNavigationHandleBar(gl, element, 4, 0.075f, true, 1);
gl.glRotatef(-180, 1, 0, 0);
gl.glTranslatef(2, 0, -4.02f);
}
else
{
gl.glTranslatef(-2 - 4 * fZoomedInScalingFactor, -4 + 4
* fZoomedInScalingFactor, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(2 + 4 * fZoomedInScalingFactor, +4 - 4
* fZoomedInScalingFactor, -0.02f);
}
}
// Bucket stack left
element = stackLevel.getElementByPositionIndex(1);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(-2f / fAspectRatio + 2 + 0.8f, -2, 4.02f);
gl.glRotatef(90, 0, 0, 1);
renderNavigationHandleBar(gl, element, 4, 0.075f, false, 1);
gl.glRotatef(-90, 0, 0, 1);
gl.glTranslatef(2f / fAspectRatio - 2 - 0.8f, 2, -4.02f);
}
else
{
gl.glTranslatef(2, 0, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(-2, 0, -0.02f);
}
}
// Bucket stack right
element = stackLevel.getElementByPositionIndex(3);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(2f / fAspectRatio - 0.8f - 2, 2, 4.02f);
gl.glRotatef(-90, 0, 0, 1);
renderNavigationHandleBar(gl, element, 4, 0.075f, false, 1);
gl.glRotatef(90, 0, 0, 1);
gl.glTranslatef(-2f / fAspectRatio + 0.8f + 2, -2, -4.02f);
}
else
{
gl.glTranslatef(2, -4 + 4 * fZoomedInScalingFactor, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(-2, +4 - 4 * fZoomedInScalingFactor, -0.02f);
}
}
// Bucket center
element = focusLevel.getElementByPositionIndex(0);
if (element.getContainedElementID() != -1)
{
float fYCorrection = 0f;
if (!bucketMouseWheelListener.isZoomedIn())
fYCorrection = 0f;
else
fYCorrection = 0.1f;
Transform transform = element.getTransform();
Vec3f translation = transform.getTranslation();
gl.glTranslatef(translation.x(), translation.y() - 2 * 0.075f + fYCorrection,
translation.z() + 0.001f);
gl.glScalef(2, 2, 2);
renderNavigationHandleBar(gl, element, 2, 0.075f, false, 2);
gl.glScalef(1 / 2f, 1 / 2f, 1 / 2f);
gl.glTranslatef(-translation.x(), -translation.y() + 2 * 0.075f - fYCorrection,
-translation.z() - 0.001f);
}
}
private void renderNavigationHandleBar(final GL gl, RemoteLevelElement element,
float fHandleWidth, float fHandleHeight, boolean bUpsideDown, float fScalingFactor)
{
// Render icons
gl.glTranslatef(0, 2 + fHandleHeight, 0);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_DRAG_ICON_SELECTION,
EIconTextures.NAVIGATION_DRAG_VIEW, fHandleHeight, fHandleHeight);
gl.glTranslatef(fHandleWidth - 2 * fHandleHeight, 0, 0);
if (bUpsideDown)
{
gl.glRotatef(180, 1, 0, 0);
gl.glTranslatef(0, fHandleHeight, 0);
}
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_LOCK_ICON_SELECTION,
EIconTextures.NAVIGATION_LOCK_VIEW, fHandleHeight, fHandleHeight);
if (bUpsideDown)
{
gl.glTranslatef(0, -fHandleHeight, 0);
gl.glRotatef(-180, 1, 0, 0);
}
gl.glTranslatef(fHandleHeight, 0, 0);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_REMOVE_ICON_SELECTION,
EIconTextures.NAVIGATION_REMOVE_VIEW, fHandleHeight, fHandleHeight);
gl.glTranslatef(-fHandleWidth + fHandleHeight, -2 - fHandleHeight, 0);
// Render background (also draggable)
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.BUCKET_DRAG_ICON_SELECTION, element.getID()));
gl.glColor3f(0.25f, 0.25f, 0.25f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(0 + fHandleHeight, 2 + fHandleHeight, 0);
gl.glVertex3f(fHandleWidth - 2 * fHandleHeight, 2 + fHandleHeight, 0);
gl.glVertex3f(fHandleWidth - 2 * fHandleHeight, 2, 0);
gl.glVertex3f(0 + fHandleHeight, 2, 0);
gl.glEnd();
gl.glPopName();
// Render view information
String sText = generalManager.getViewGLCanvasManager().getGLEventListener(
element.getContainedElementID()).getShortInfo();
int iMaxChars = 50;
if (sText.length() > iMaxChars)
sText = sText.subSequence(0, iMaxChars - 3) + "...";
float fTextScalingFactor = 0.0027f;
if (bUpsideDown)
{
gl.glRotatef(180, 1, 0, 0);
gl.glTranslatef(0, -4 - fHandleHeight, 0);
}
textRenderer.setColor(0.7f, 0.7f, 0.7f, 1);
textRenderer.begin3DRendering();
textRenderer.draw3D(sText, 2 / fScalingFactor
- (float) textRenderer.getBounds(sText).getWidth() / 2f * fTextScalingFactor,
2.02f, 0, fTextScalingFactor);
textRenderer.end3DRendering();
if (bUpsideDown)
{
gl.glTranslatef(0, 4 + fHandleHeight, 0);
gl.glRotatef(-180, 1, 0, 0);
}
}
private void renderSingleHandle(final GL gl, int iRemoteLevelElementID,
EPickingType ePickingType, EIconTextures eIconTexture, float fWidth, float fHeight)
{
gl.glPushName(pickingManager.getPickingID(iUniqueID, ePickingType,
iRemoteLevelElementID));
Texture tempTexture = iconTextureManager.getIconTexture(gl, eIconTexture);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(0, -fHeight, 0f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(0, 0, 0f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fWidth, 0, 0f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fWidth, -fHeight, 0f);
gl.glEnd();
tempTexture.disable();
gl.glPopName();
}
private void renderNavigationOverlay(final GL gl, final int iRemoteLevelElementID)
{
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.enableRendering(false);
RemoteLevelElement remoteLevelElement = RemoteElementManager.get().getItem(
iRemoteLevelElementID);
EPickingType leftWallPickingType = null;
EPickingType rightWallPickingType = null;
EPickingType topWallPickingType = null;
EPickingType bottomWallPickingType = null;
Vec4f tmpColor_out = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_in = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_left = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_right = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_lock = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// Assign view symbol
Texture textureViewSymbol;
AGLEventListener view = generalManager.getViewGLCanvasManager().getGLEventListener(
remoteLevelElement.getContainedElementID());
if (view instanceof GLHeatMap)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.HEAT_MAP_SYMBOL);
}
else if (view instanceof GLParallelCoordinates)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.PAR_COORDS_SYMBOL);
}
else if (view instanceof GLPathway)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.PATHWAY_SYMBOL);
}
else if (view instanceof GLGlyph)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.GLYPH_SYMBOL);
}
else if (view instanceof GLCell)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.GLYPH_SYMBOL);
}
else
{
throw new IllegalStateException("Unknown view that has no symbol assigned.");
}
Texture textureMoveLeft = null;
Texture textureMoveRight = null;
Texture textureMoveOut = null;
Texture textureMoveIn = null;
TextureCoords texCoords = textureViewSymbol.getImageTexCoords();
if (iNavigationMouseOverViewID_lock == iRemoteLevelElementID)
tmpColor_lock.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
if (layoutMode.equals(LayoutMode.JUKEBOX))
{
topWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_LEFT);
}
else
{
if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 0) // top
{
topWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
else if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 2) // bottom
{
topWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
else if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 1) // left
{
topWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
else if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 3) // right
{
topWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
// else if
// (underInteractionLayer.getPositionIndexByElementID(iViewID) == 0)
// // center
// {
// topWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
// bottomWallPickingType =
// EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
// leftWallPickingType =
// EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
// rightWallPickingType =
// EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
//
// if (iNavigationMouseOverViewID_out == iViewID)
// tmpColor_out.set(1, 0.3f, 0.3f, 0.9f);
// else if (iNavigationMouseOverViewID_in == iViewID)
// tmpColor_in.set(1, 0.3f, 0.3f, 0.9f);
// else if (iNavigationMouseOverViewID_left == iViewID)
// tmpColor_left.set(1, 0.3f, 0.3f, 0.9f);
// else if (iNavigationMouseOverViewID_right == iViewID)
// tmpColor_right.set(1, 0.3f, 0.3f, 0.9f);
//
// textureMoveIn =
// iconTextureManager.getIconTexture(EIconTextures.ARROW_LEFT);
// textureMoveOut =
// iconTextureManager.getIconTexture(EIconTextures.ARROW_DOWN);
// textureMoveLeft = iconTextureManager
// .getIconTexture(EIconTextures.ARROW_DOWN);
// textureMoveRight = iconTextureManager
// .getIconTexture(EIconTextures.ARROW_LEFT);
// }
}
// else if (underInteractionLayer.containsElement(iViewID))
// {
// topWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
// bottomWallPickingType =
// EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
// leftWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
// rightWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
// }
gl.glLineWidth(1);
float fNavigationZValue = 0f;
// CENTER - NAVIGATION: VIEW IDENTIFICATION ICON
// gl.glPushName(pickingManager.getPickingID(iUniqueID,
// EPickingType.BUCKET_LOCK_ICON_SELECTION, iViewID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_lock.x(), tmpColor_lock.y(), tmpColor_lock.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(2.66f, 2.66f, 0.02f);
// gl.glVertex3f(2.66f, 5.33f, 0.02f);
// gl.glVertex3f(5.33f, 5.33f, 0.02f);
// gl.glVertex3f(5.33f, 2.66f, 0.02f);
// gl.glEnd();
textureViewSymbol.enable();
textureViewSymbol.bind();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glEnd();
textureViewSymbol.disable();
// gl.glPopName();
// BOTTOM - NAVIGATION: MOVE IN
gl.glPushName(pickingManager.getPickingID(iUniqueID, bottomWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 0, fNavigationZValue);
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glVertex3f(8, 0, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_in.x(), tmpColor_in.y(), tmpColor_in.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(0.05f, 0.05f, 0.02f);
// gl.glVertex3f(2.66f, 2.66f, 0.02f);
// gl.glVertex3f(5.33f, 2.66f, 0.02f);
// gl.glVertex3f(7.95f, 0.02f, 0.02f);
// gl.glEnd();
textureMoveIn.enable();
textureMoveIn.bind();
// texCoords = textureMoveIn.getImageTexCoords();
// gl.glColor4f(1,0.3f,0.3f,0.9f);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(2.66f, 0.05f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(5.33f, 0.05f, fNavigationZValue);
gl.glEnd();
textureMoveIn.disable();
gl.glPopName();
// RIGHT - NAVIGATION: MOVE RIGHT
gl.glPushName(pickingManager.getPickingID(iUniqueID, rightWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(8, 0, fNavigationZValue);
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glVertex3f(8, 8, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_right.x(), tmpColor_right.y(), tmpColor_right.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(7.95f, 0.05f, 0.02f);
// gl.glVertex3f(5.33f, 2.66f, 0.02f);
// gl.glVertex3f(5.33f, 5.33f, 0.02f);
// gl.glVertex3f(7.95f, 7.95f, 0.02f);
// gl.glEnd();
textureMoveRight.enable();
textureMoveRight.bind();
// gl.glColor4f(0,1,0,1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(7.95f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(7.95f, 5.33f, fNavigationZValue);
gl.glEnd();
textureMoveRight.disable();
gl.glPopName();
// LEFT - NAVIGATION: MOVE LEFT
gl.glPushName(pickingManager.getPickingID(iUniqueID, leftWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 0, fNavigationZValue);
gl.glVertex3f(0, 8, fNavigationZValue);
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_left.x(), tmpColor_left.y(), tmpColor_left.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(0.05f, 0.05f, fNavigationZValue);
// gl.glVertex3f(0.05f, 7.95f, fNavigationZValue);
// gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
// gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
// gl.glEnd();
textureMoveLeft.enable();
textureMoveLeft.bind();
// gl.glColor4f(0,1,0,1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(0.05f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.05f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glEnd();
textureMoveLeft.disable();
gl.glPopName();
// TOP - NAVIGATION: MOVE OUT
gl.glPushName(pickingManager.getPickingID(iUniqueID, topWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 8, fNavigationZValue);
gl.glVertex3f(8, 8, fNavigationZValue);
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_out.x(), tmpColor_out.y(), tmpColor_out.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(0.05f, 7.95f, 0.02f);
// gl.glVertex3f(7.95f, 7.95f, 0.02f);
// gl.glVertex3f(5.33f, 5.33f, 0.02f);
// gl.glVertex3f(2.66f, 5.33f, 0.02f);
// gl.glEnd();
textureMoveOut.enable();
textureMoveOut.bind();
// gl.glColor4f(0,1,0,1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(2.66f, 7.95f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(5.33f, 7.95f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glEnd();
textureMoveOut.disable();
gl.glPopName();
}
private void renderPoolSelection(final GL gl, float fXOrigin, float fYOrigin,
float fWidth, float fHeight, RemoteLevelElement element)
{
float fPanelSideWidth = 11f;
gl.glColor3f(0.25f, 0.25f, 0.25f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth, fYOrigin - fHeight
/ 2f + fHeight, 0f);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth + fWidth, fYOrigin
- fHeight / 2f + fHeight, 0f);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth + fWidth, fYOrigin
- fHeight / 2f, 0f);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth, fYOrigin - fHeight
/ 2f, 0f);
gl.glEnd();
Texture tempTexture = iconTextureManager.getIconTexture(gl,
EIconTextures.POOL_VIEW_BACKGROUND_SELECTION);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glColor4f(1, 1, 1, 0.75f);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(fXOrigin + (2) / fAspectRatio + fPanelSideWidth, fYOrigin - fHeight,
-0.01f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(fXOrigin + (2) / fAspectRatio + fPanelSideWidth, fYOrigin + fHeight,
-0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fXOrigin + 2f / fAspectRatio, fYOrigin + fHeight, -0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fXOrigin + 2f / fAspectRatio, fYOrigin - fHeight, -0.01f);
gl.glEnd();
tempTexture.disable();
gl.glPopName();
gl.glPopName();
int fHandleScaleFactor = 18;
gl.glTranslatef(fXOrigin + 2.5f / fAspectRatio,
fYOrigin - fHeight / 2f + fHeight - 1f, 1.8f);
gl.glScalef(fHandleScaleFactor, fHandleScaleFactor, fHandleScaleFactor);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_DRAG_ICON_SELECTION,
EIconTextures.POOL_DRAG_VIEW, 0.1f, 0.1f);
gl.glTranslatef(0, -0.2f, 0);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_REMOVE_ICON_SELECTION,
EIconTextures.POOL_REMOVE_VIEW, 0.1f, 0.1f);
gl.glTranslatef(0, 0.2f, 0);
gl.glScalef(1f / fHandleScaleFactor, 1f / fHandleScaleFactor, 1f / fHandleScaleFactor);
gl.glTranslatef(-fXOrigin - 2.5f / fAspectRatio, -fYOrigin + fHeight / 2f - fHeight
+ 1f, -1.8f);
// gl.glColor3f(0.25f, 0.25f, 0.25f);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(fXOrigin + 3f, fYOrigin - fHeight / 2f + fHeight -
// 2.5f, 0f);
// gl.glVertex3f(fXOrigin + 5.1f, fYOrigin - fHeight / 2f + fHeight -
// 2.5f, 0f);
// gl.glVertex3f(fXOrigin + 5.1f, fYOrigin- fHeight / 2f + 1.5f, 0f);
// gl.glVertex3f(fXOrigin + 3f, fYOrigin- fHeight / 2f + 1.5f , 0f);
// gl.glEnd();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, element.getID()));
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.VIEW_SELECTION,
element.getID()));
}
private void doSlerpActions(final GL gl)
{
if (arSlerpActions.isEmpty())
return;
SlerpAction tmpSlerpAction = arSlerpActions.get(0);
if (iSlerpFactor == 0)
{
tmpSlerpAction.start();
// System.out.println("Start slerp action " +tmpSlerpAction);
}
if (iSlerpFactor < SLERP_RANGE)
{
// Makes animation rendering speed independent
iSlerpFactor += SLERP_SPEED * time.deltaT();
if (iSlerpFactor > SLERP_RANGE)
iSlerpFactor = SLERP_RANGE;
}
slerpView(gl, tmpSlerpAction);
}
private void slerpView(final GL gl, SlerpAction slerpAction)
{
int iViewID = slerpAction.getElementId();
SlerpMod slerpMod = new SlerpMod();
if ((iSlerpFactor == 0))
{
slerpMod.playSlerpSound();
}
Transform transform = slerpMod.interpolate(slerpAction.getOriginRemoteLevelElement()
.getTransform(),
slerpAction.getDestinationRemoteLevelElement().getTransform(),
(float) iSlerpFactor / SLERP_RANGE);
gl.glPushMatrix();
slerpMod.applySlerp(gl, transform);
(generalManager.getViewGLCanvasManager().getGLEventListener(iViewID))
.displayRemote(gl);
gl.glPopMatrix();
// Check if slerp action is finished
if (iSlerpFactor >= SLERP_RANGE)
{
arSlerpActions.remove(slerpAction);
iSlerpFactor = 0;
slerpAction.finished();
RemoteLevelElement destinationElement = slerpAction
.getDestinationRemoteLevelElement();
updateViewDetailLevels(destinationElement);
}
// After last slerp action is done the line connections are turned on
// again
if (arSlerpActions.isEmpty())
{
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.enableRendering(true);
generalManager.getViewGLCanvasManager().getInfoAreaManager().enable(
!bEnableNavigationOverlay);
}
}
private void updateViewDetailLevels(RemoteLevelElement element)
{
RemoteLevel destinationLevel = element.getRemoteLevel();
if (element.getContainedElementID() == -1)
return;
AGLEventListener glActiveSubView = GeneralManager.get().getViewGLCanvasManager()
.getGLEventListener(element.getContainedElementID());
glActiveSubView.setRemoteLevelElement(element);
// Update detail level of moved view when slerp action is finished;
if (destinationLevel == focusLevel)
{
if (bucketMouseWheelListener.isZoomedIn()
|| layoutRenderStyle instanceof ListLayoutRenderStyle)
glActiveSubView.setDetailLevel(EDetailLevel.HIGH);
else
glActiveSubView.setDetailLevel(EDetailLevel.MEDIUM);
// if (glActiveSubView instanceof GLPathway)
// {
// ((GLPathway) glActiveSubView).enableTitleRendering(true);
// ((GLPathway) glActiveSubView).setAlignment(SWT.CENTER,
// SWT.BOTTOM);
// }
// generalManager.getGUIBridge().setActiveGLSubView(this,
// glActiveSubView);
}
else if (destinationLevel == stackLevel)
{
glActiveSubView.setDetailLevel(EDetailLevel.LOW);
// if (glActiveSubView instanceof GLPathway)
// {
// ((GLPathway) glActiveSubView).enableTitleRendering(true);
//
// int iStackPos = stackLevel.getPositionIndexByElementID(element);
// switch (iStackPos)
// {
// case 0:
// ((GLPathway) glActiveSubView).setAlignment(SWT.CENTER, SWT.TOP);
// break;
// case 1:
// ((GLPathway) glActiveSubView).setAlignment(SWT.LEFT, SWT.BOTTOM);
// break;
// case 2:
// ((GLPathway) glActiveSubView).setAlignment(SWT.CENTER,
// SWT.BOTTOM);
// break;
// case 3:
// ((GLPathway) glActiveSubView).setAlignment(SWT.RIGHT,
// SWT.BOTTOM);
// break;
// default:
// break;
// }
// }
}
else if (destinationLevel == poolLevel || destinationLevel == selectionLevel)
{
glActiveSubView.setDetailLevel(EDetailLevel.VERY_LOW);
// if (glActiveSubView instanceof GLPathway)
// {
// ((GLPathway) glActiveSubView).enableTitleRendering(false);
// }
}
compactPoolLevel();
}
private void loadViewToFocusLevel(final int iRemoteLevelElementID)
{
RemoteLevelElement element = RemoteElementManager.get().getItem(iRemoteLevelElementID);
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
return;
arSlerpActions.clear();
int iViewID = element.getContainedElementID();
if (iViewID == -1)
return;
// Only broadcast elements if view is moved from pool to bucket
if (poolLevel.containsElement(element))
{
generalManager.getViewGLCanvasManager().getGLEventListener(iViewID)
.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
// if (layoutRenderStyle instanceof ListLayoutRenderStyle)
// {
// // Slerp selected view to under interaction transition position
// SlerpAction slerpActionTransition = new
// SlerpAction(iRemoteLevelElementID, poolLevel,
// transitionLevel);
// arSlerpActions.add(slerpActionTransition);
//
// // Check if focus has a free spot
// if (focusLevel.getElementByPositionIndex(0).getContainedElementID()
// != -1)
// {
// // Slerp under interaction view to free spot in pool
// SlerpAction reverseSlerpAction = new SlerpAction(focusLevel
// .getElementIDByPositionIndex(0), focusLevel, poolLevel);
// arSlerpActions.add(reverseSlerpAction);
// }
//
// // Slerp selected view from transition position to under interaction
// // position
// SlerpAction slerpAction = new SlerpAction(iViewID, transitionLevel,
// focusLevel);
// arSlerpActions.add(slerpAction);
// }
// else
{
// Check if view is already loaded in the stack layer
if (stackLevel.containsElement(element))
{
// Slerp selected view to transition position
SlerpAction slerpActionTransition = new SlerpAction(element, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
// Check if focus level is free
if (!focusLevel.hasFreePosition())
{
// Slerp focus view to free spot in stack
SlerpAction reverseSlerpAction = new SlerpAction(focusLevel
.getElementByPositionIndex(0).getContainedElementID(), focusLevel
.getElementByPositionIndex(0), element);
arSlerpActions.add(reverseSlerpAction);
}
// Slerp selected view from transition position to focus
// position
SlerpAction slerpAction = new SlerpAction(element.getContainedElementID(),
transitionLevel.getElementByPositionIndex(0), focusLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpAction);
}
else
{
// Slerp selected view to transition position
SlerpAction slerpActionTransition = new SlerpAction(element, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
RemoteLevelElement freeStackElement = null;
if (!stackLevel.hasFreePosition())
{
int iReplacePosition = 1;
// // Determine non locked stack position for view movement
// to pool
// for (int iTmpReplacePosition = 0; iTmpReplacePosition <
// stackLevel.getCapacity(); iTmpReplacePosition++)
// {
// if
// (stackLevel.getElementByPositionIndex(iTmpReplacePosition).isLocked())
// continue;
//
// iReplacePosition = iTmpReplacePosition + 1; // +1 to
// start with left view for outsourcing
//
// if (iReplacePosition == 4)
// iReplacePosition = 0;
//
// break;
// }
//
// if (iReplacePosition == -1)
// throw new
// IllegalStateException("All views in stack are locked!");
freeStackElement = stackLevel.getElementByPositionIndex(iReplacePosition);
// Slerp view from stack to pool
SlerpAction reverseSlerpAction = new SlerpAction(freeStackElement,
poolLevel.getNextFree());
arSlerpActions.add(reverseSlerpAction);
// Unregister all elements of the view that is moved out
generalManager.getViewGLCanvasManager().getGLEventListener(
freeStackElement.getContainedElementID()).broadcastElements(
EVAOperation.REMOVE_ELEMENT);
}
else
{
freeStackElement = stackLevel.getNextFree();
}
if (!focusLevel.hasFreePosition())
{
// Slerp focus view to free spot in stack
SlerpAction reverseSlerpAction2 = new SlerpAction(focusLevel
.getElementByPositionIndex(0), freeStackElement);
arSlerpActions.add(reverseSlerpAction2);
}
// Slerp selected view from transition position to focus
// position
SlerpAction slerpAction = new SlerpAction(iViewID, transitionLevel
.getElementByPositionIndex(0), focusLevel.getElementByPositionIndex(0));
arSlerpActions.add(slerpAction);
}
}
iSlerpFactor = 0;
}
@SuppressWarnings("unchecked")
@Override
public void handleExternalEvent(IUniqueObject eventTrigger, IEventContainer eventContainer)
{
switch (eventContainer.getEventType())
{
// pathway loading based on gene id
case LOAD_PATHWAY_BY_GENE:
// take care here, if we ever use non integer ids this has to be
// cast to raw type first to determine the actual id data types
IDListEventContainer<Integer> idContainer = (IDListEventContainer<Integer>) eventContainer;
if (idContainer.getIDType() == EIDType.REFSEQ_MRNA_INT)
{
int iGraphItemID = 0;
Integer iDavidID = -1;
ArrayList<ICaleydoGraphItem> alPathwayVertexGraphItem = new ArrayList<ICaleydoGraphItem>();
for (Integer iRefSeqID : idContainer.getIDs())
{
iDavidID = idMappingManager.getID(EMappingType.REFSEQ_MRNA_INT_2_DAVID, iRefSeqID);
if (iDavidID == null || iDavidID == -1)
throw new IllegalStateException("Cannot resolve RefSeq ID to David ID.");
iGraphItemID = generalManager.getPathwayItemManager()
.getPathwayVertexGraphItemIdByDavidId(iDavidID);
if (iGraphItemID == -1)
continue;
PathwayVertexGraphItem tmpPathwayVertexGraphItem = ((PathwayVertexGraphItem) generalManager
.getPathwayItemManager().getItem(iGraphItemID));
if (tmpPathwayVertexGraphItem == null)
continue;
alPathwayVertexGraphItem.add(tmpPathwayVertexGraphItem);
}
if (!alPathwayVertexGraphItem.isEmpty())
{
loadDependentPathways(alPathwayVertexGraphItem);
}
}
else
{
throw new IllegalStateException("Not Implemented");
}
break;
// Handle incoming pathways
case LOAD_PATHWAY_BY_PATHWAY_ID:
IDListEventContainer<Integer> pathwayIDContainer = (IDListEventContainer<Integer>) eventContainer;
for (Integer iPathwayID : pathwayIDContainer.getIDs())
{
addPathwayView(iPathwayID);
}
break;
case SELECTION_UPDATE:
lastSelectionDelta = ((DeltaEventContainer<ISelectionDelta>) eventContainer)
.getSelectionDelta();
}
bUpdateOffScreenTextures = true;
}
/**
* Add pathway view. Also used when serialized pathways are loaded.
*
* @param iPathwayIDToLoad
*/
public synchronized void addPathwayView(final int iPathwayIDToLoad)
{
iAlUninitializedPathwayIDs.add(iPathwayIDToLoad);
}
public synchronized void loadDependentPathways(final List<ICaleydoGraphItem> alVertex)
{
// Remove pathways from stacked layer view
// poolLayer.removeAllElements();
Iterator<ICaleydoGraphItem> iterPathwayGraphItem = alVertex.iterator();
Iterator<IGraphItem> iterIdenticalPathwayGraphItemRep = null;
IGraphItem pathwayGraphItem;
int iPathwayID = 0;
while (iterPathwayGraphItem.hasNext())
{
pathwayGraphItem = iterPathwayGraphItem.next();
if (pathwayGraphItem == null)
{
// generalManager.logMsg(
// this.getClass().getSimpleName() + " (" + iUniqueID
// + "): pathway graph item is null. ",
// LoggerType.VERBOSE);
continue;
}
iterIdenticalPathwayGraphItemRep = pathwayGraphItem.getAllItemsByProp(
EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterIdenticalPathwayGraphItemRep.hasNext())
{
iPathwayID = ((PathwayGraph) iterIdenticalPathwayGraphItemRep.next()
.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT).toArray()[0])
.getId();
// Only add pathway if it is not loaded yet
if (!generalManager.getPathwayManager().isPathwayVisible(iPathwayID))
iAlUninitializedPathwayIDs.add(iPathwayID);
}
}
if (iAlUninitializedPathwayIDs.isEmpty())
return;
// Disable picking until pathways are loaded
pickingManager.enablePicking(false);
// Zoom out of the bucket when loading pathways
if (bucketMouseWheelListener.isZoomedIn())
bucketMouseWheelListener.triggerZoom(false);
// Turn on busy mode
for (AGLEventListener tmpGLEventListener : GeneralManager.get()
.getViewGLCanvasManager().getAllGLEventListeners())
{
if (!tmpGLEventListener.isRenderedRemote())
tmpGLEventListener.enableBusyMode(true);
}
// iSlerpFactor = 0;
}
@Override
protected void handleEvents(EPickingType pickingType, EPickingMode pickingMode,
int iExternalID, Pick pick)
{
switch (pickingType)
{
case BUCKET_DRAG_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
if (!dragAndDrop.isDragActionRunning())
{
// System.out.println("Start drag!");
dragAndDrop.startDragAction(iExternalID);
}
iMouseOverObjectID = iExternalID;
compactPoolLevel();
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.BUCKET_DRAG_ICON_SELECTION);
pickingManager.flushHits(iUniqueID, EPickingType.REMOTE_LEVEL_ELEMENT);
break;
case BUCKET_REMOVE_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
RemoteLevelElement element = RemoteElementManager.get().getItem(
iExternalID);
AGLEventListener glEventListener = ((AGLEventListener) generalManager
.getViewGLCanvasManager().getGLEventListener(
element.getContainedElementID()));
// Unregister all elements of the view that is removed
glEventListener.broadcastElements(EVAOperation.REMOVE_ELEMENT);
removeView(glEventListener);
element.setContainedElementID(-1);
if (element.getRemoteLevel() == poolLevel)
compactPoolLevel();
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.BUCKET_REMOVE_ICON_SELECTION);
break;
case BUCKET_LOCK_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
RemoteLevelElement element = RemoteElementManager.get().getItem(
iExternalID);
// Toggle lock flag
element.lock(!element.isLocked());
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.BUCKET_LOCK_ICON_SELECTION);
break;
case REMOTE_LEVEL_ELEMENT:
switch (pickingMode)
{
case MOUSE_OVER:
case DRAGGED:
iMouseOverObjectID = iExternalID;
break;
case CLICKED:
// Do not handle click if element is dragged
if (dragAndDrop.isDragActionRunning())
break;
// Check if view is contained in pool level
for (RemoteLevelElement element : poolLevel.getAllElements())
{
if (element.getID() == iExternalID)
{
loadViewToFocusLevel(iExternalID);
break;
}
}
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.REMOTE_LEVEL_ELEMENT);
break;
case VIEW_SELECTION:
switch (pickingMode)
{
case MOUSE_OVER:
// generalManager.getViewGLCanvasManager().getInfoAreaManager()
// .setDataAboutView(iExternalID);
// Prevent update flood when moving mouse over view
if (iActiveViewID == iExternalID)
break;
iActiveViewID = iExternalID;
setDisplayListDirty();
// TODO
// generalManager.getEventPublisher().triggerEvent(
// EMediatorType.VIEW_SELECTION,
// generalManager.getViewGLCanvasManager().getGLEventListener(
// iExternalID), );
break;
case CLICKED:
// generalManager.getViewGLCanvasManager().getInfoAreaManager()
// .setDataAboutView(iExternalID);
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.VIEW_SELECTION);
break;
// case BUCKET_LOCK_ICON_SELECTION:
// switch (pickingMode)
// {
// case CLICKED:
//
// break;
//
// case MOUSE_OVER:
//
// iNavigationMouseOverViewID_lock = iExternalID;
// iNavigationMouseOverViewID_left = -1;
// iNavigationMouseOverViewID_right = -1;
// iNavigationMouseOverViewID_out = -1;
// iNavigationMouseOverViewID_in = -1;
//
// break;
// }
//
// pickingManager.flushHits(iUniqueID,
// EPickingType.BUCKET_LOCK_ICON_SELECTION);
//
// break;
case BUCKET_MOVE_IN_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
loadViewToFocusLevel(iExternalID);
bEnableNavigationOverlay = false;
// glConnectionLineRenderer.enableRendering(true);
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = -1;
iNavigationMouseOverViewID_right = -1;
iNavigationMouseOverViewID_out = -1;
iNavigationMouseOverViewID_in = iExternalID;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager
.flushHits(iUniqueID, EPickingType.BUCKET_MOVE_IN_ICON_SELECTION);
break;
case BUCKET_MOVE_OUT_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
break;
// glConnectionLineRenderer.enableRendering(true);
arSlerpActions.clear();
RemoteLevelElement element = RemoteElementManager.get().getItem(
iExternalID);
SlerpAction slerpActionTransition = new SlerpAction(element, poolLevel
.getNextFree());
arSlerpActions.add(slerpActionTransition);
bEnableNavigationOverlay = false;
// Unregister all elements of the view that is moved out
generalManager.getViewGLCanvasManager().getGLEventListener(
element.getContainedElementID()).broadcastElements(
EVAOperation.REMOVE_ELEMENT);
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = -1;
iNavigationMouseOverViewID_right = -1;
iNavigationMouseOverViewID_out = iExternalID;
iNavigationMouseOverViewID_in = -1;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager.flushHits(iUniqueID,
EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION);
break;
case BUCKET_MOVE_LEFT_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
break;
// glConnectionLineRenderer.enableRendering(true);
arSlerpActions.clear();
RemoteLevelElement selectedElement = RemoteElementManager.get()
.getItem(iExternalID);
int iDestinationPosIndex = stackLevel
.getPositionIndexByElementID(selectedElement);
if (iDestinationPosIndex == 3)
iDestinationPosIndex = 0;
else
iDestinationPosIndex++;
// Check if destination position in stack is free
if (stackLevel.getElementByPositionIndex(iDestinationPosIndex)
.getContainedElementID() == -1)
{
SlerpAction slerpAction = new SlerpAction(selectedElement,
stackLevel.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpAction);
}
else
{
SlerpAction slerpActionTransition = new SlerpAction(
selectedElement, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
SlerpAction slerpAction = new SlerpAction(stackLevel
.getElementByPositionIndex(iDestinationPosIndex),
selectedElement);
arSlerpActions.add(slerpAction);
SlerpAction slerpActionTransitionReverse = new SlerpAction(
selectedElement.getContainedElementID(), transitionLevel
.getElementByPositionIndex(0), stackLevel
.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpActionTransitionReverse);
}
bEnableNavigationOverlay = false;
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = iExternalID;
iNavigationMouseOverViewID_right = -1;
iNavigationMouseOverViewID_out = -1;
iNavigationMouseOverViewID_in = -1;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager.flushHits(iUniqueID,
EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION);
break;
case BUCKET_MOVE_RIGHT_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
break;
// glConnectionLineRenderer.enableRendering(true);
arSlerpActions.clear();
RemoteLevelElement selectedElement = RemoteElementManager.get()
.getItem(iExternalID);
int iDestinationPosIndex = stackLevel
.getPositionIndexByElementID(selectedElement);
if (iDestinationPosIndex == 0)
iDestinationPosIndex = 3;
else
iDestinationPosIndex--;
// Check if destination position in stack is free
if (stackLevel.getElementByPositionIndex(iDestinationPosIndex)
.getContainedElementID() == -1)
{
SlerpAction slerpAction = new SlerpAction(selectedElement,
stackLevel.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpAction);
}
else
{
SlerpAction slerpActionTransition = new SlerpAction(
selectedElement, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
SlerpAction slerpAction = new SlerpAction(stackLevel
.getElementByPositionIndex(iDestinationPosIndex),
selectedElement);
arSlerpActions.add(slerpAction);
SlerpAction slerpActionTransitionReverse = new SlerpAction(
selectedElement.getContainedElementID(), transitionLevel
.getElementByPositionIndex(0), stackLevel
.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpActionTransitionReverse);
}
bEnableNavigationOverlay = false;
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = -1;
iNavigationMouseOverViewID_right = iExternalID;
iNavigationMouseOverViewID_out = -1;
iNavigationMouseOverViewID_in = -1;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager.flushHits(iUniqueID,
EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION);
break;
// case MEMO_PAD_SELECTION:
// switch (pickingMode)
// {
// case CLICKED:
//
// break;
//
// case DRAGGED:
//
// int iDraggedObjectId = dragAndDrop.getDraggedObjectedId();
//
// if (iExternalID == TRASH_CAN_PICKING_ID)
// {
// if (iDraggedObjectId != -1)
// {
// // if
// // (memoLayer.containsElement(iDraggedObjectId))
// // {
// memoLayer.removeElement(iDraggedObjectId);
// // dragAndDrop.stopDragAction();
// // break;
// // }
//
// underInteractionLayer.removeElement(iDraggedObjectId);
// stackLayer.removeElement(iDraggedObjectId);
// poolLayer.removeElement(iDraggedObjectId);
// }
// }
// else if (iExternalID == MEMO_PAD_PICKING_ID)
// {
// if (iDraggedObjectId != -1)
// {
// if (!memoLayer.containsElement(iDraggedObjectId))
// {
// memoLayer.addElement(iDraggedObjectId);
// memoLayer.setElementVisibilityById(true, iDraggedObjectId);
// }
// }
// }
//
// dragAndDrop.stopDragAction();
//
// break;
// }
//
// pickingManager.flushHits(iUniqueID,
// EPickingType.MEMO_PAD_SELECTION);
// break;
}
}
@Override
public String getShortInfo()
{
return "Bucket / Jukebox";
}
@Override
public String getDetailedInfo()
{
StringBuffer sInfoText = new StringBuffer();
sInfoText.append("Bucket / Jukebox");
return sInfoText.toString();
}
private void createEventMediator()
{
generalManager.getEventPublisher().addSender(EMediatorType.SELECTION_MEDIATOR,
(IMediatorSender) this);
generalManager.getEventPublisher().addReceiver(EMediatorType.SELECTION_MEDIATOR,
(IMediatorReceiver) this);
}
public synchronized void toggleLayoutMode()
{
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
layoutMode = ARemoteViewLayoutRenderStyle.LayoutMode.LIST;
// layoutMode = ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX;
else
layoutMode = ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET;
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
layoutRenderStyle = new BucketLayoutRenderStyle(viewFrustum, layoutRenderStyle);
bucketMouseWheelListener = new BucketMouseWheelListener(this,
(BucketLayoutRenderStyle) layoutRenderStyle);
// Unregister standard mouse wheel listener
parentGLCanvas.removeMouseWheelListener(pickingTriggerMouseAdapter);
// Register specialized bucket mouse wheel listener
parentGLCanvas.addMouseWheelListener(bucketMouseWheelListener);
glConnectionLineRenderer = new GLConnectionLineRendererBucket(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX))
{
layoutRenderStyle = new JukeboxLayoutRenderStyle(viewFrustum, layoutRenderStyle);
// Unregister bucket wheel listener
parentGLCanvas.removeMouseWheelListener(bucketMouseWheelListener);
// Register standard mouse wheel listener
parentGLCanvas.addMouseWheelListener(pickingTriggerMouseAdapter);
glConnectionLineRenderer = new GLConnectionLineRendererJukebox(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.LIST))
{
layoutRenderStyle = new ListLayoutRenderStyle(viewFrustum, layoutRenderStyle);
glConnectionLineRenderer = null;
// // Copy views from stack to pool
// for (Integer iElementID : stackLevel.getElementList())
// {
// if (iElementID == -1)
// continue;
//
// poolLevel.addElement(iElementID);
// // poolLevel.setElementVisibilityById(true, iElementID);
// }
// stackLevel.clear();
}
focusLevel = layoutRenderStyle.initFocusLevel();
stackLevel = layoutRenderStyle.initStackLevel(bucketMouseWheelListener.isZoomedIn());
poolLevel = layoutRenderStyle.initPoolLevel(bucketMouseWheelListener.isZoomedIn(), -1);
selectionLevel = layoutRenderStyle.initMemoLevel();
transitionLevel = layoutRenderStyle.initTransitionLevel();
spawnLevel = layoutRenderStyle.initSpawnLevel();
viewFrustum.setProjectionMode(layoutRenderStyle.getProjectionMode());
// Trigger reshape to apply new projection mode
// Is there a better way to achieve this? :)
parentGLCanvas.setSize(parentGLCanvas.getWidth(), parentGLCanvas.getHeight());
}
public synchronized void toggleConnectionLines()
{
bEnableConnectinLines = !bEnableConnectinLines;
}
/**
* Unregister view from event system. Remove view from GL render loop.
*/
public void removeView(AGLEventListener glEventListener)
{
glEventListener.destroy();
}
public synchronized void clearAll()
{
enableBusyMode(false);
pickingManager.enablePicking(true);
iAlUninitializedPathwayIDs.clear();
arSlerpActions.clear();
generalManager.getPathwayManager().resetPathwayVisiblityState();
clearRemoteLevel(focusLevel);
clearRemoteLevel(stackLevel);
clearRemoteLevel(poolLevel);
generalManager.getViewGLCanvasManager().getConnectedElementRepresentationManager().clearAll();
}
private void clearRemoteLevel(RemoteLevel remoteLevel)
{
int iViewID;
IViewManager viewManager = generalManager.getViewGLCanvasManager();
AGLEventListener glEventListener = null;
for (RemoteLevelElement element : remoteLevel.getAllElements())
{
iViewID = element.getContainedElementID();
if (iViewID == -1)
continue;
glEventListener = viewManager.getGLEventListener(iViewID);
if (glEventListener instanceof GLHeatMap
|| glEventListener instanceof GLParallelCoordinates)
{
// Remove all elements from heatmap and parallel coordinates
((AStorageBasedView) glEventListener).resetView();
if (!glEventListener.isRenderedRemote())
glEventListener.enableBusyMode(false);
}
else
{
removeView(glEventListener);
element.setContainedElementID(-1);
}
}
}
// @Override
// public synchronized RemoteLevel getHierarchyLayerByGLEventListenerId(
// final int iGLEventListenerId)
// {
// if (focusLevel.containsElement(iGLEventListenerId))
// return focusLevel;
// else if (stackLevel.containsElement(iGLEventListenerId))
// return stackLevel;
// else if (poolLevel.containsElement(iGLEventListenerId))
// return poolLevel;
// else if (transitionLevel.containsElement(iGLEventListenerId))
// return transitionLevel;
// else if (spawnLevel.containsElement(iGLEventListenerId))
// return spawnLevel;
// else if (selectionLevel.containsElement(iGLEventListenerId))
// return selectionLevel;
//
// generalManager.getLogger().log(Level.WARNING,
// "GL Event Listener " + iGLEventListenerId +
// " is not contained in any layer!");
//
// return null;
// }
@Override
public RemoteLevel getFocusLevel()
{
return focusLevel;
}
@Override
public BucketMouseWheelListener getBucketMouseWheelListener()
{
return bucketMouseWheelListener;
}
@Override
public synchronized void reshape(GLAutoDrawable drawable, int x, int y, int width,
int height)
{
super.reshape(drawable, x, y, width, height);
// Update aspect ratio and reinitialize stack and focus layer
layoutRenderStyle.setAspectRatio(fAspectRatio);
layoutRenderStyle.initFocusLevel();
layoutRenderStyle.initStackLevel(bucketMouseWheelListener.isZoomedIn());
layoutRenderStyle.initPoolLevel(bucketMouseWheelListener.isZoomedIn(),
iMouseOverObjectID);
layoutRenderStyle.initMemoLevel();
}
protected void renderPoolAndMemoLayerBackground(final GL gl)
{
// Pool layer background
float fWidth = 0.8f;
float fXCorrection = 0.07f; // Detach pool level from stack
if (layoutMode.equals(LayoutMode.BUCKET))
{
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, iPoolLevelCommonID));
gl.glColor4f(0.85f, 0.85f, 0.85f, 1f);
gl.glLineWidth(1);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, -2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, -2, 4);
gl.glEnd();
if (dragAndDrop.isDragActionRunning() && iMouseOverObjectID == iPoolLevelCommonID)
{
gl.glLineWidth(5);
gl.glColor4f(0.2f, 0.2f, 0.2f, 1);
}
else
{
gl.glLineWidth(1);
gl.glColor4f(0.4f, 0.4f, 0.4f, 1);
}
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, -2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, -2, 4);
gl.glEnd();
gl.glPopName();
// // Render memo pad background
// gl.glColor4f(0.85f, 0.85f, 0.85f, 1f);
// gl.glLineWidth(1);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(2 / fAspectRatio, -2, 4);
// gl.glVertex3f(2 / fAspectRatio, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, -2, 4);
// gl.glEnd();
//
// gl.glColor4f(0.4f, 0.4f, 0.4f, 1);
// gl.glLineWidth(1);
// gl.glBegin(GL.GL_LINE_LOOP);
// gl.glVertex3f(2 / fAspectRatio, -2, 4);
// gl.glVertex3f(2 / fAspectRatio, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, -2, 4);
// gl.glEnd();
}
// Render caption
if (textRenderer == null)
return;
String sTmp = "POOL AREA";
textRenderer.begin3DRendering();
textRenderer.setColor(0.6f, 0.6f, 0.6f, 1.0f);
textRenderer.draw3D(sTmp, (-1.9f - fXCorrection) / fAspectRatio, -1.97f, 4.001f,
0.003f);
textRenderer.end3DRendering();
}
public synchronized void enableGeneMapping(final boolean bEnableMapping)
{
for (GLEventListener tmpGLEventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (tmpGLEventListener instanceof GLPathway)
{
((GLPathway) tmpGLEventListener).enableGeneMapping(bEnableMapping);
}
}
}
public synchronized void enablePathwayTextures(final boolean bEnablePathwayTexture)
{
for (GLEventListener tmpGLEventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (tmpGLEventListener instanceof GLPathway)
{
((GLPathway) tmpGLEventListener).enablePathwayTextures(bEnablePathwayTexture);
}
}
}
public synchronized void enableNeighborhood(final boolean bEnableNeighborhood)
{
for (GLEventListener tmpGLEventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (tmpGLEventListener instanceof GLPathway)
{
((GLPathway) tmpGLEventListener).enableNeighborhood(bEnableNeighborhood);
}
}
}
@Override
public void triggerEvent(EMediatorType eMediatorType, IEventContainer eventContainer)
{
generalManager.getEventPublisher().triggerEvent(eMediatorType, this, eventContainer);
}
@Override
public synchronized void broadcastElements(EVAOperation type)
{
throw new IllegalStateException("Not Implemented");
}
private synchronized void initializeNewPathways(final GL gl)
{
// Init newly created pathways
// FIXME: this specialization to pathways in the bucket is not good!
if (!iAlUninitializedPathwayIDs.isEmpty() && arSlerpActions.isEmpty())
{
int iTmpPathwayID = iAlUninitializedPathwayIDs.get(0);
// Check if pathway is already loaded in bucket
if (!generalManager.getPathwayManager().isPathwayVisible(iTmpPathwayID))
{
ArrayList<Integer> iAlSetIDs = new ArrayList<Integer>();
for (ISet tmpSet : alSets)
{
if (tmpSet.getSetType() != ESetType.GENE_EXPRESSION_DATA)
continue;
iAlSetIDs.add(tmpSet.getID());
}
// Create Pathway3D view
CmdCreateGLPathway cmdPathway = (CmdCreateGLPathway) generalManager
.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_PATHWAY_3D);
cmdPathway.setAttributes(iTmpPathwayID, iAlSetIDs,
EProjectionMode.ORTHOGRAPHIC, -4, 4, 4, -4, -20, 20);
cmdPathway.doCommand();
GLPathway glPathway = (GLPathway) cmdPathway.getCreatedObject();
int iGeneratedViewID = glPathway.getID();
GeneralManager.get().getEventPublisher().addSender(
EMediatorType.SELECTION_MEDIATOR, (IMediatorSender) glPathway);
GeneralManager.get().getEventPublisher().addReceiver(
EMediatorType.SELECTION_MEDIATOR, (IMediatorReceiver) glPathway);
iAlContainedViewIDs.add(iGeneratedViewID);
// Trigger last delta to new pathways
if (lastSelectionDelta != null)
triggerEvent(EMediatorType.SELECTION_MEDIATOR,
new DeltaEventContainer<ISelectionDelta>(lastSelectionDelta));
if (focusLevel.hasFreePosition())
{
spawnLevel.getElementByPositionIndex(0).setContainedElementID(
iGeneratedViewID);
SlerpAction slerpActionTransition = new SlerpAction(spawnLevel
.getElementByPositionIndex(0), focusLevel.getNextFree());
arSlerpActions.add(slerpActionTransition);
glPathway.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
glPathway.setDetailLevel(EDetailLevel.MEDIUM);
// Trigger initial gene propagation
glPathway.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
else if (stackLevel.hasFreePosition()
&& !(layoutRenderStyle instanceof ListLayoutRenderStyle))
{
spawnLevel.getElementByPositionIndex(0).setContainedElementID(
iGeneratedViewID);
SlerpAction slerpActionTransition = new SlerpAction(spawnLevel
.getElementByPositionIndex(0), stackLevel.getNextFree());
arSlerpActions.add(slerpActionTransition);
glPathway.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
glPathway.setDetailLevel(EDetailLevel.LOW);
// Trigger initial gene propagation
glPathway.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
else if (poolLevel.hasFreePosition())
{
spawnLevel.getElementByPositionIndex(0).setContainedElementID(
iGeneratedViewID);
SlerpAction slerpActionTransition = new SlerpAction(spawnLevel
.getElementByPositionIndex(0), poolLevel.getNextFree());
arSlerpActions.add(slerpActionTransition);
glPathway.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
glPathway.setDetailLevel(EDetailLevel.VERY_LOW);
}
else
{
generalManager.getLogger().log(Level.SEVERE,
"No empty space left to add new pathway!");
iAlUninitializedPathwayIDs.clear();
for (AGLEventListener eventListener : generalManager
.getViewGLCanvasManager().getAllGLEventListeners())
{
if (!eventListener.isRenderedRemote())
eventListener.enableBusyMode(false);
}
// Enable picking after all pathways are loaded
generalManager.getViewGLCanvasManager().getPickingManager().enablePicking(
true);
return;
}
}
else
{
generalManager.getLogger().log(Level.WARNING,
"Pathway with ID: " + iTmpPathwayID + " is already loaded in Bucket.");
}
iAlUninitializedPathwayIDs.remove(0);
if (iAlUninitializedPathwayIDs.isEmpty())
{
// Enable picking after all pathways are loaded
generalManager.getViewGLCanvasManager().getPickingManager()
.enablePicking(true);
for (AGLEventListener eventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (!eventListener.isRenderedRemote())
eventListener.enableBusyMode(false);
}
}
}
}
@Override
public void enableBusyMode(boolean busyMode)
{
super.enableBusyMode(busyMode);
if (eBusyModeState == EBusyModeState.ON)
{
// parentGLCanvas.removeMouseListener(pickingTriggerMouseAdapter);
parentGLCanvas.removeMouseWheelListener(bucketMouseWheelListener);
}
else
{
// parentGLCanvas.addMouseListener(pickingTriggerMouseAdapter);
parentGLCanvas.addMouseWheelListener(bucketMouseWheelListener);
}
}
@Override
public int getNumberOfSelections(ESelectionType eSelectionType)
{
return 0;
}
private void compactPoolLevel()
{
RemoteLevelElement element;
RemoteLevelElement elementInner;
for (int iIndex = 0; iIndex < poolLevel.getCapacity(); iIndex++)
{
element = poolLevel.getElementByPositionIndex(iIndex);
if (element.isFree())
{
// Search for next element to put it in the free position
for (int iInnerIndex = iIndex + 1; iInnerIndex < poolLevel.getCapacity(); iInnerIndex++)
{
elementInner = poolLevel.getElementByPositionIndex(iInnerIndex);
if (elementInner.isFree())
continue;
element.setContainedElementID(elementInner.getContainedElementID());
elementInner.setContainedElementID(-1);
break;
}
}
}
}
public ArrayList<Integer> getRemoteRenderedViews()
{
return iAlContainedViewIDs;
}
private void updateOffScreenTextures(final GL gl)
{
bUpdateOffScreenTextures = false;
gl.glPushMatrix();
int iViewWidth = parentGLCanvas.getWidth();
int iViewHeight = parentGLCanvas.getHeight();
if (stackLevel.getElementByPositionIndex(0).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(0)
.getContainedElementID(), 0, iViewWidth, iViewHeight);
}
if (stackLevel.getElementByPositionIndex(1).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(1)
.getContainedElementID(), 1, iViewWidth, iViewHeight);
}
if (stackLevel.getElementByPositionIndex(2).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(2)
.getContainedElementID(), 2, iViewWidth, iViewHeight);
}
if (stackLevel.getElementByPositionIndex(3).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(3)
.getContainedElementID(), 3, iViewWidth, iViewHeight);
}
gl.glPopMatrix();
}
}
| org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/remote/GLRemoteRendering.java | package org.caleydo.core.view.opengl.canvas.remote;
import gleem.linalg.Rotf;
import gleem.linalg.Vec3f;
import gleem.linalg.Vec4f;
import gleem.linalg.open.Transform;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import org.caleydo.core.command.ECommandType;
import org.caleydo.core.command.view.opengl.CmdCreateGLEventListener;
import org.caleydo.core.command.view.opengl.CmdCreateGLPathway;
import org.caleydo.core.data.IUniqueObject;
import org.caleydo.core.data.collection.ESetType;
import org.caleydo.core.data.collection.ISet;
import org.caleydo.core.data.graph.ICaleydoGraphItem;
import org.caleydo.core.data.graph.pathway.core.PathwayGraph;
import org.caleydo.core.data.graph.pathway.item.vertex.PathwayVertexGraphItem;
import org.caleydo.core.data.mapping.EIDType;
import org.caleydo.core.data.selection.DeltaEventContainer;
import org.caleydo.core.data.selection.ESelectionType;
import org.caleydo.core.data.selection.EVAOperation;
import org.caleydo.core.data.selection.ISelectionDelta;
import org.caleydo.core.manager.IViewManager;
import org.caleydo.core.manager.event.EMediatorType;
import org.caleydo.core.manager.event.IDListEventContainer;
import org.caleydo.core.manager.event.IEventContainer;
import org.caleydo.core.manager.event.IMediatorReceiver;
import org.caleydo.core.manager.event.IMediatorSender;
import org.caleydo.core.manager.general.GeneralManager;
import org.caleydo.core.manager.id.EManagedObjectType;
import org.caleydo.core.manager.picking.EPickingMode;
import org.caleydo.core.manager.picking.EPickingType;
import org.caleydo.core.manager.picking.Pick;
import org.caleydo.core.util.system.SystemTime;
import org.caleydo.core.util.system.Time;
import org.caleydo.core.view.opengl.camera.EProjectionMode;
import org.caleydo.core.view.opengl.camera.IViewFrustum;
import org.caleydo.core.view.opengl.canvas.AGLEventListener;
import org.caleydo.core.view.opengl.canvas.EDetailLevel;
import org.caleydo.core.view.opengl.canvas.cell.GLCell;
import org.caleydo.core.view.opengl.canvas.glyph.gridview.GLGlyph;
import org.caleydo.core.view.opengl.canvas.panel.GLSelectionPanel;
import org.caleydo.core.view.opengl.canvas.pathway.GLPathway;
import org.caleydo.core.view.opengl.canvas.remote.bucket.BucketMouseWheelListener;
import org.caleydo.core.view.opengl.canvas.remote.bucket.GLConnectionLineRendererBucket;
import org.caleydo.core.view.opengl.canvas.remote.jukebox.GLConnectionLineRendererJukebox;
import org.caleydo.core.view.opengl.canvas.storagebased.AStorageBasedView;
import org.caleydo.core.view.opengl.canvas.storagebased.heatmap.GLHeatMap;
import org.caleydo.core.view.opengl.canvas.storagebased.parcoords.GLParallelCoordinates;
import org.caleydo.core.view.opengl.miniview.GLColorMappingBarMiniView;
import org.caleydo.core.view.opengl.mouse.PickingJoglMouseListener;
import org.caleydo.core.view.opengl.renderstyle.layout.ARemoteViewLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.BucketLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.JukeboxLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.ListLayoutRenderStyle;
import org.caleydo.core.view.opengl.renderstyle.layout.ARemoteViewLayoutRenderStyle.LayoutMode;
import org.caleydo.core.view.opengl.util.drag.GLDragAndDrop;
import org.caleydo.core.view.opengl.util.hierarchy.RemoteElementManager;
import org.caleydo.core.view.opengl.util.hierarchy.RemoteLevel;
import org.caleydo.core.view.opengl.util.hierarchy.RemoteLevelElement;
import org.caleydo.core.view.opengl.util.slerp.SlerpAction;
import org.caleydo.core.view.opengl.util.slerp.SlerpMod;
import org.caleydo.core.view.opengl.util.texture.EIconTextures;
import org.caleydo.core.view.opengl.util.texture.GLOffScreenTextureRenderer;
import org.caleydo.util.graph.EGraphItemHierarchy;
import org.caleydo.util.graph.EGraphItemProperty;
import org.caleydo.util.graph.IGraphItem;
import com.sun.opengl.util.j2d.TextRenderer;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureCoords;
/**
* Abstract class that is able to remotely rendering views. Subclasses implement
* the positioning of the views (bucket, jukebox, etc.).
*
* @author Marc Streit
* @author Alexander Lex
*/
public class GLRemoteRendering
extends AGLEventListener
implements IMediatorReceiver, IMediatorSender, IGLCanvasRemoteRendering
{
private ARemoteViewLayoutRenderStyle.LayoutMode layoutMode;
private static final int SLERP_RANGE = 1000;
private static final int SLERP_SPEED = 1400;
// private GenericSelectionManager selectionManager;
private int iMouseOverObjectID = -1;
private RemoteLevel focusLevel;
private RemoteLevel stackLevel;
private RemoteLevel poolLevel;
private RemoteLevel transitionLevel;
private RemoteLevel spawnLevel;
private RemoteLevel selectionLevel;
private ArrayList<SlerpAction> arSlerpActions;
private Time time;
/**
* Slerp factor: 0 = source; 1 = destination
*/
private int iSlerpFactor = 0;
protected AGLConnectionLineRenderer glConnectionLineRenderer;
private int iNavigationMouseOverViewID_left = -1;
private int iNavigationMouseOverViewID_right = -1;
private int iNavigationMouseOverViewID_out = -1;
private int iNavigationMouseOverViewID_in = -1;
private int iNavigationMouseOverViewID_lock = -1;
private boolean bEnableNavigationOverlay = false;
private ArrayList<Integer> iAlUninitializedPathwayIDs;
private TextRenderer textRenderer;
private GLDragAndDrop dragAndDrop;
private ARemoteViewLayoutRenderStyle layoutRenderStyle;
private BucketMouseWheelListener bucketMouseWheelListener;
private GLColorMappingBarMiniView colorMappingBarMiniView;
private ArrayList<Integer> iAlContainedViewIDs;
/**
* The current view in which the user is performing actions.
*/
private int iActiveViewID = -1;
// private int iGLDisplayList;
private GLSelectionPanel glSelectionPanel;
private ISelectionDelta lastSelectionDelta;
/**
* Used for dragging views to the pool area.
*/
private int iPoolLevelCommonID = -1;
private GLOffScreenTextureRenderer glOffScreenRenderer;
private boolean bUpdateOffScreenTextures = true;
private boolean bEnableConnectinLines = true;
/**
* Constructor.
*/
public GLRemoteRendering(final int iGLCanvasID, final String sLabel,
final IViewFrustum viewFrustum,
final ARemoteViewLayoutRenderStyle.LayoutMode layoutMode)
{
super(iGLCanvasID, sLabel, viewFrustum, true);
viewType = EManagedObjectType.GL_REMOTE_RENDERING;
this.layoutMode = layoutMode;
// if (generalManager.isWiiModeActive())
// {
glOffScreenRenderer = new GLOffScreenTextureRenderer();
// }
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
layoutRenderStyle = new BucketLayoutRenderStyle(viewFrustum);
super.renderStyle = layoutRenderStyle;
bucketMouseWheelListener = new BucketMouseWheelListener(this,
(BucketLayoutRenderStyle) layoutRenderStyle);
// Unregister standard mouse wheel listener
parentGLCanvas.removeMouseWheelListener(pickingTriggerMouseAdapter);
// Register specialized bucket mouse wheel listener
parentGLCanvas.addMouseWheelListener(bucketMouseWheelListener);
// parentGLCanvas.addMouseListener(bucketMouseWheelListener);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX))
{
layoutRenderStyle = new JukeboxLayoutRenderStyle(viewFrustum);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.LIST))
{
layoutRenderStyle = new ListLayoutRenderStyle(viewFrustum);
}
focusLevel = layoutRenderStyle.initFocusLevel();
if (GeneralManager.get().isWiiModeActive()
&& layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
stackLevel = ((BucketLayoutRenderStyle) layoutRenderStyle).initStackLevelWii();
}
else
{
stackLevel = layoutRenderStyle.initStackLevel(bucketMouseWheelListener
.isZoomedIn());
}
poolLevel = layoutRenderStyle.initPoolLevel(bucketMouseWheelListener.isZoomedIn(), -1);
selectionLevel = layoutRenderStyle.initMemoLevel();
transitionLevel = layoutRenderStyle.initTransitionLevel();
spawnLevel = layoutRenderStyle.initSpawnLevel();
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
glConnectionLineRenderer = new GLConnectionLineRendererBucket(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX))
{
glConnectionLineRenderer = new GLConnectionLineRendererJukebox(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.LIST))
{
glConnectionLineRenderer = null;
}
pickingTriggerMouseAdapter.addGLCanvas(this);
arSlerpActions = new ArrayList<SlerpAction>();
iAlUninitializedPathwayIDs = new ArrayList<Integer>();
createEventMediator();
dragAndDrop = new GLDragAndDrop();
textRenderer = new TextRenderer(new Font("Arial", Font.PLAIN, 24), false);
// trashCan = new TrashCan();
// TODO: the genome mapper should be stored centralized instead of newly
// created
colorMappingBarMiniView = new GLColorMappingBarMiniView(viewFrustum);
// Create selection panel
CmdCreateGLEventListener cmdCreateGLView = (CmdCreateGLEventListener) generalManager
.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_PANEL_SELECTION);
cmdCreateGLView.setAttributes(EProjectionMode.ORTHOGRAPHIC, 0, 0.8f, 0, 4, -20, 20,
null, -1);
cmdCreateGLView.doCommand();
glSelectionPanel = (GLSelectionPanel) cmdCreateGLView.getCreatedObject();
// Registration to event system
generalManager.getEventPublisher().addSender(EMediatorType.SELECTION_MEDIATOR,
(IMediatorSender) this);
generalManager.getEventPublisher().addReceiver(EMediatorType.SELECTION_MEDIATOR,
(IMediatorReceiver) this);
generalManager.getEventPublisher().addSender(EMediatorType.VIEW_SELECTION, this);
iPoolLevelCommonID = generalManager.getIDManager().createID(
EManagedObjectType.REMOTE_LEVEL_ELEMENT);
}
@Override
public void initLocal(final GL gl)
{
// iGLDisplayList = gl.glGenLists(1);
init(gl);
}
@Override
public void initRemote(final GL gl, final int iRemoteViewID,
final PickingJoglMouseListener pickingTriggerMouseAdapter,
final IGLCanvasRemoteRendering remoteRenderingGLCanvas)
{
throw new IllegalStateException("Not implemented to be rendered remote");
}
@Override
public void init(final GL gl)
{
gl.glClearColor(0.5f, 0.5f, 0.5f, 1f);
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.init(gl);
// iconTextureManager = new GLIconTextureManager(gl);
time = new SystemTime();
((SystemTime) time).rebase();
initializeContainedViews(gl);
selectionLevel.getElementByPositionIndex(0).setContainedElementID(
glSelectionPanel.getID());
// selectionLevel.setElementVisibilityById(true,
// glSelectionPanel.getID());
glSelectionPanel.initRemote(gl, getID(), pickingTriggerMouseAdapter,
remoteRenderingGLCanvas);
colorMappingBarMiniView.setWidth(layoutRenderStyle.getColorBarWidth());
colorMappingBarMiniView.setHeight(layoutRenderStyle.getColorBarHeight());
glOffScreenRenderer.init(gl);
}
@Override
public synchronized void displayLocal(final GL gl)
{
if ((pickingTriggerMouseAdapter.wasRightMouseButtonPressed() && !bucketMouseWheelListener
.isZoomedIn())
&& !(layoutRenderStyle instanceof ListLayoutRenderStyle))
{
bEnableNavigationOverlay = !bEnableNavigationOverlay;
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.enableRendering(!bEnableNavigationOverlay);
}
pickingManager.handlePicking(iUniqueID, gl, true);
// if (bIsDisplayListDirtyLocal)
// {
// buildDisplayList(gl);
// bIsDisplayListDirtyLocal = false;
// }
display(gl);
if (eBusyModeState != EBusyModeState.OFF)
renderBusyMode(gl);
if (pickingTriggerMouseAdapter.getPickedPoint() != null)
dragAndDrop.setCurrentMousePos(gl, pickingTriggerMouseAdapter.getPickedPoint());
if (dragAndDrop.isDragActionRunning())
{
dragAndDrop.renderDragThumbnailTexture(gl);
}
if (pickingTriggerMouseAdapter.wasMouseReleased() && dragAndDrop.isDragActionRunning())
{
int iDraggedObjectId = dragAndDrop.getDraggedObjectedId();
// System.out.println("over: " +iExternalID);
// System.out.println("dragged: " +iDraggedObjectId);
// Prevent user from dragging element onto selection level
if (!RemoteElementManager.get().hasItem(iMouseOverObjectID)
|| !selectionLevel.containsElement(RemoteElementManager.get().getItem(
iMouseOverObjectID)))
{
RemoteLevelElement mouseOverElement = null;
// Check if a drag and drop action is performed onto the pool
// level
if (iMouseOverObjectID == iPoolLevelCommonID)
{
mouseOverElement = poolLevel.getNextFree();
}
else if (mouseOverElement == null && iMouseOverObjectID != iDraggedObjectId)
{
mouseOverElement = RemoteElementManager.get().getItem(iMouseOverObjectID);
}
if (mouseOverElement != null)
{
RemoteLevelElement originElement = RemoteElementManager.get().getItem(
iDraggedObjectId);
int iMouseOverElementID = mouseOverElement.getContainedElementID();
int iOriginElementID = originElement.getContainedElementID();
mouseOverElement.setContainedElementID(iOriginElementID);
originElement.setContainedElementID(iMouseOverElementID);
IViewManager viewGLCanvasManager = generalManager.getViewGLCanvasManager();
AGLEventListener originView = viewGLCanvasManager
.getGLEventListener(iOriginElementID);
if (originView != null)
originView.setRemoteLevelElement(mouseOverElement);
AGLEventListener mouseOverView = viewGLCanvasManager
.getGLEventListener(iMouseOverElementID);
if (mouseOverView != null)
mouseOverView.setRemoteLevelElement(originElement);
updateViewDetailLevels(originElement);
updateViewDetailLevels(mouseOverElement);
if (mouseOverElement.getContainedElementID() != -1)
{
if (poolLevel.containsElement(originElement)
&& (stackLevel.containsElement(mouseOverElement) || focusLevel
.containsElement(mouseOverElement)))
{
generalManager.getViewGLCanvasManager().getGLEventListener(
mouseOverElement.getContainedElementID())
.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
if (poolLevel.containsElement(mouseOverElement)
&& (stackLevel.containsElement(originElement) || focusLevel
.containsElement(originElement)))
{
generalManager.getViewGLCanvasManager().getGLEventListener(
mouseOverElement.getContainedElementID())
.broadcastElements(EVAOperation.REMOVE_ELEMENT);
}
}
}
}
dragAndDrop.stopDragAction();
bUpdateOffScreenTextures = true;
}
checkForHits(gl);
pickingTriggerMouseAdapter.resetEvents();
// gl.glCallList(iGLDisplayListIndexLocal);
}
@Override
public synchronized void displayRemote(final GL gl)
{
display(gl);
}
@Override
public synchronized void display(final GL gl)
{
time.update();
layoutRenderStyle.initPoolLevel(false, iMouseOverObjectID);
// layoutRenderStyle.initStackLevel(false);
// layoutRenderStyle.initMemoLevel();
if (GeneralManager.get().isWiiModeActive()
&& layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
((BucketLayoutRenderStyle) layoutRenderStyle).initFocusLevelWii();
((BucketLayoutRenderStyle) layoutRenderStyle).initStackLevelWii();
}
doSlerpActions(gl);
initializeNewPathways(gl);
if (!generalManager.isWiiModeActive())
{
renderRemoteLevel(gl, focusLevel);
renderRemoteLevel(gl, stackLevel);
}
else
{
if (bUpdateOffScreenTextures)
updateOffScreenTextures(gl);
renderRemoteLevel(gl, focusLevel);
glOffScreenRenderer.renderRubberBucket(gl, stackLevel,
(BucketLayoutRenderStyle) layoutRenderStyle, this);
}
// If user zooms to the bucket bottom all but the under
// focus layer is _not_ rendered.
if (bucketMouseWheelListener == null || !bucketMouseWheelListener.isZoomedIn())
{
// comment here for connection lines
if (glConnectionLineRenderer != null && bEnableConnectinLines)
glConnectionLineRenderer.render(gl);
renderPoolAndMemoLayerBackground(gl);
renderRemoteLevel(gl, transitionLevel);
renderRemoteLevel(gl, spawnLevel);
renderRemoteLevel(gl, poolLevel);
renderRemoteLevel(gl, selectionLevel);
}
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
bucketMouseWheelListener.render();
}
// colorMappingBarMiniView.render(gl,
// layoutRenderStyle.getColorBarXPos(),
// layoutRenderStyle.getColorBarYPos(), 4);
renderHandles(gl);
// gl.glCallList(iGLDisplayList);
}
public synchronized void setInitialContainedViews(
ArrayList<Integer> iAlInitialContainedViewIDs)
{
iAlContainedViewIDs = iAlInitialContainedViewIDs;
}
private void initializeContainedViews(final GL gl)
{
if (iAlContainedViewIDs == null)
return;
for (int iContainedViewID : iAlContainedViewIDs)
{
AGLEventListener tmpGLEventListener = generalManager.getViewGLCanvasManager()
.getGLEventListener(iContainedViewID);
// Ignore pathway views upon startup
// because they will be activated when pathway loader thread has
// finished
if (tmpGLEventListener == this || tmpGLEventListener instanceof GLPathway)
{
continue;
}
int iViewID = (tmpGLEventListener).getID();
if (focusLevel.hasFreePosition())
{
RemoteLevelElement element = focusLevel.getNextFree();
element.setContainedElementID(iViewID);
tmpGLEventListener.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
tmpGLEventListener.broadcastElements(EVAOperation.APPEND_UNIQUE);
tmpGLEventListener.setDetailLevel(EDetailLevel.MEDIUM);
tmpGLEventListener.setRemoteLevelElement(element);
// generalManager.getGUIBridge().setActiveGLSubView(this,
// tmpGLEventListener);
}
else if (stackLevel.hasFreePosition()
&& !(layoutRenderStyle instanceof ListLayoutRenderStyle))
{
RemoteLevelElement element = stackLevel.getNextFree();
element.setContainedElementID(iViewID);
tmpGLEventListener.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
tmpGLEventListener.broadcastElements(EVAOperation.APPEND_UNIQUE);
tmpGLEventListener.setDetailLevel(EDetailLevel.LOW);
tmpGLEventListener.setRemoteLevelElement(element);
}
else if (poolLevel.hasFreePosition())
{
RemoteLevelElement element = poolLevel.getNextFree();
element.setContainedElementID(iViewID);
tmpGLEventListener.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
tmpGLEventListener.setDetailLevel(EDetailLevel.VERY_LOW);
tmpGLEventListener.setRemoteLevelElement(element);
}
// pickingTriggerMouseAdapter.addGLCanvas(tmpGLEventListener);
pickingManager.getPickingID(iUniqueID, EPickingType.VIEW_SELECTION, iViewID);
generalManager.getEventPublisher().addSender(EMediatorType.SELECTION_MEDIATOR,
(IMediatorSender) tmpGLEventListener);
generalManager.getEventPublisher().addReceiver(EMediatorType.SELECTION_MEDIATOR,
(IMediatorReceiver) tmpGLEventListener);
}
}
public void renderBucketWall(final GL gl, boolean bRenderBorder, RemoteLevelElement element)
{
// Highlight potential view drop destination
if (dragAndDrop.isDragActionRunning() && element.getID() == iMouseOverObjectID)
{
gl.glLineWidth(5);
gl.glColor4f(0.2f, 0.2f, 0.2f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 0, 0.01f);
gl.glVertex3f(0, 8, 0.01f);
gl.glVertex3f(8, 8, 0.01f);
gl.glVertex3f(8, 0, 0.01f);
gl.glEnd();
}
if (arSlerpActions.isEmpty())
gl.glColor4f(1f, 1f, 1f, 1.0f); // normal mode
else
gl.glColor4f(1f, 1f, 1f, 0.3f);
if (!iAlUninitializedPathwayIDs.isEmpty())
gl.glColor4f(1f, 1f, 1f, 0.3f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(0, 0, -0.03f);
gl.glVertex3f(0, 8, -0.03f);
gl.glVertex3f(8, 8, -0.03f);
gl.glVertex3f(8, 0, -0.03f);
gl.glEnd();
if (!bRenderBorder)
return;
gl.glColor4f(0.4f, 0.4f, 0.4f, 1f);
gl.glLineWidth(1f);
// gl.glBegin(GL.GL_LINES);
// gl.glVertex3f(0, 0, -0.02f);
// gl.glVertex3f(0, 8, -0.02f);
// gl.glVertex3f(8, 8, -0.02f);
// gl.glVertex3f(8, 0, -0.02f);
// gl.glEnd();
}
private void renderRemoteLevel(final GL gl, final RemoteLevel level)
{
for (RemoteLevelElement element : level.getAllElements())
{
renderRemoteLevelElement(gl, element, level);
if (!(layoutRenderStyle instanceof ListLayoutRenderStyle))
renderEmptyBucketWall(gl, element, level);
}
}
private void renderRemoteLevelElement(final GL gl, RemoteLevelElement element,
RemoteLevel level)
{
// // Check if view is visible
// if (!level.getElementVisibilityById(iViewID))
// return;
if (element.getContainedElementID() == -1)
return;
int iViewID = element.getContainedElementID();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, element.getID()));
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.VIEW_SELECTION,
iViewID));
AGLEventListener glEventListener = (generalManager.getViewGLCanvasManager()
.getGLEventListener(iViewID));
if (glEventListener == null)
throw new IllegalStateException("Cannot render canvas object which is null!");
gl.glPushMatrix();
Transform transform = element.getTransform();
Vec3f translation = transform.getTranslation();
Rotf rot = transform.getRotation();
Vec3f scale = transform.getScale();
Vec3f axis = new Vec3f();
float fAngle = rot.get(axis);
gl.glTranslatef(translation.x(), translation.y(), translation.z());
gl.glRotatef(Vec3f.convertRadiant2Grad(fAngle), axis.x(), axis.y(), axis.z());
gl.glScalef(scale.x(), scale.y(), scale.z());
if (level == poolLevel)
{
String sRenderText = glEventListener.getShortInfo();
// Limit pathway name in length
int iMaxChars;
if (layoutRenderStyle instanceof ListLayoutRenderStyle)
iMaxChars = 80;
else
iMaxChars = 20;
if (sRenderText.length() > iMaxChars && scale.x() < 0.03f)
sRenderText = sRenderText.subSequence(0, iMaxChars - 3) + "...";
if (element.getID() == iMouseOverObjectID)
textRenderer.setColor(1, 1, 1, 1);
else
textRenderer.setColor(0, 0, 0, 1);
if (glEventListener.getNumberOfSelections(ESelectionType.MOUSE_OVER) > 0)
{
textRenderer.setColor(1, 0, 0, 1);
// sRenderText =
// glEventListener.getNumberOfSelections(ESelectionType.MOUSE_OVER)
// + " - " + sRenderText;
}
else if (glEventListener.getNumberOfSelections(ESelectionType.SELECTION) > 0)
{
textRenderer.setColor(0, 1, 0, 1);
// sRenderText =
// glEventListener.getNumberOfSelections(ESelectionType.SELECTION)
// + " - " + sRenderText;
}
float fTextScalingFactor = 0.09f;
float fTextXPosition = 0f;
if (element.getID() == iMouseOverObjectID)
{
renderPoolSelection(gl, translation.x() - 0.4f / fAspectRatio, translation.y()
* scale.y() + 5.2f,
(float) textRenderer.getBounds(sRenderText).getWidth() * 0.06f + 23, 6f,
element); // 1.8f -> pool focus scaling
gl.glTranslatef(0.8f, 1.3f, 0);
fTextScalingFactor = 0.075f;
fTextXPosition = 12f;
}
else
{
// Render view background frame
Texture tempTexture = iconTextureManager.getIconTexture(gl,
EIconTextures.POOL_VIEW_BACKGROUND);
tempTexture.enable();
tempTexture.bind();
float fFrameWidth = 9.5f;
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glColor4f(1, 1, 1, 0.75f);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(-0.7f, -0.6f + fFrameWidth, -0.01f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(-0.7f + fFrameWidth, -0.6f + fFrameWidth, -0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(-0.7f + fFrameWidth, -0.6f, -0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(-0.7f, -0.6f, -0.01f);
gl.glEnd();
tempTexture.disable();
fTextXPosition = 9.5f;
}
textRenderer.begin3DRendering();
textRenderer.draw3D(sRenderText, fTextXPosition, 3, 0, fTextScalingFactor);
textRenderer.end3DRendering();
}
// Prevent rendering of view textures when simple list view
// if ((layoutRenderStyle instanceof ListLayoutRenderStyle
// && (layer == poolLayer || layer == stackLayer)))
// {
// gl.glPopMatrix();
// return;
// }
if (level != selectionLevel && level != poolLevel)
{
if (level.equals(focusLevel))
renderBucketWall(gl, false, element);
else
renderBucketWall(gl, true, element);
}
if (!bEnableNavigationOverlay || !level.equals(stackLevel))
{
glEventListener.displayRemote(gl);
}
else
{
renderNavigationOverlay(gl, element.getID());
}
gl.glPopMatrix();
gl.glPopName();
gl.glPopName();
}
private void renderEmptyBucketWall(final GL gl, RemoteLevelElement element,
RemoteLevel level)
{
gl.glPushMatrix();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, element.getID()));
Transform transform = element.getTransform();
Vec3f translation = transform.getTranslation();
Rotf rot = transform.getRotation();
Vec3f scale = transform.getScale();
Vec3f axis = new Vec3f();
float fAngle = rot.get(axis);
gl.glTranslatef(translation.x(), translation.y(), translation.z());
gl.glScalef(scale.x(), scale.y(), scale.z());
gl.glRotatef(Vec3f.convertRadiant2Grad(fAngle), axis.x(), axis.y(), axis.z());
if (!level.equals(transitionLevel) && !level.equals(spawnLevel)
&& !level.equals(poolLevel) && !level.equals(selectionLevel))
{
renderBucketWall(gl, true, element);
}
gl.glPopName();
gl.glPopMatrix();
}
private void renderHandles(final GL gl)
{
float fZoomedInScalingFactor = 0.4f;
// Bucket stack top
RemoteLevelElement element = stackLevel.getElementByPositionIndex(0);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(-2, 0, 4.02f);
renderNavigationHandleBar(gl, element, 4, 0.075f, false, 1);
gl.glTranslatef(2, 0, -4.02f);
}
else
{
gl.glTranslatef(-2 - 4 * fZoomedInScalingFactor, 0, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(2 + 4 * fZoomedInScalingFactor, 0, -0.02f);
}
}
// Bucket stack bottom
element = stackLevel.getElementByPositionIndex(2);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(-2, 0, 4.02f);
gl.glRotatef(180, 1, 0, 0);
renderNavigationHandleBar(gl, element, 4, 0.075f, true, 1);
gl.glRotatef(-180, 1, 0, 0);
gl.glTranslatef(2, 0, -4.02f);
}
else
{
gl.glTranslatef(-2 - 4 * fZoomedInScalingFactor, -4 + 4
* fZoomedInScalingFactor, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(2 + 4 * fZoomedInScalingFactor, +4 - 4
* fZoomedInScalingFactor, -0.02f);
}
}
// Bucket stack left
element = stackLevel.getElementByPositionIndex(1);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(-2f / fAspectRatio + 2 + 0.8f, -2, 4.02f);
gl.glRotatef(90, 0, 0, 1);
renderNavigationHandleBar(gl, element, 4, 0.075f, false, 1);
gl.glRotatef(-90, 0, 0, 1);
gl.glTranslatef(2f / fAspectRatio - 2 - 0.8f, 2, -4.02f);
}
else
{
gl.glTranslatef(2, 0, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(-2, 0, -0.02f);
}
}
// Bucket stack right
element = stackLevel.getElementByPositionIndex(3);
if (element.getContainedElementID() != -1)
{
if (!bucketMouseWheelListener.isZoomedIn())
{
gl.glTranslatef(2f / fAspectRatio - 0.8f - 2, 2, 4.02f);
gl.glRotatef(-90, 0, 0, 1);
renderNavigationHandleBar(gl, element, 4, 0.075f, false, 1);
gl.glRotatef(90, 0, 0, 1);
gl.glTranslatef(-2f / fAspectRatio + 0.8f + 2, -2, -4.02f);
}
else
{
gl.glTranslatef(2, -4 + 4 * fZoomedInScalingFactor, 0.02f);
renderNavigationHandleBar(gl, element, 4 * fZoomedInScalingFactor, 0.075f,
false, 1 / fZoomedInScalingFactor);
gl.glTranslatef(-2, +4 - 4 * fZoomedInScalingFactor, -0.02f);
}
}
// Bucket center
element = focusLevel.getElementByPositionIndex(0);
if (element.getContainedElementID() != -1)
{
float fYCorrection = 0f;
if (!bucketMouseWheelListener.isZoomedIn())
fYCorrection = 0f;
else
fYCorrection = 0.1f;
Transform transform = element.getTransform();
Vec3f translation = transform.getTranslation();
gl.glTranslatef(translation.x(), translation.y() - 2 * 0.075f + fYCorrection,
translation.z() + 0.001f);
gl.glScalef(2, 2, 2);
renderNavigationHandleBar(gl, element, 2, 0.075f, false, 2);
gl.glScalef(1 / 2f, 1 / 2f, 1 / 2f);
gl.glTranslatef(-translation.x(), -translation.y() + 2 * 0.075f - fYCorrection,
-translation.z() - 0.001f);
}
}
private void renderNavigationHandleBar(final GL gl, RemoteLevelElement element,
float fHandleWidth, float fHandleHeight, boolean bUpsideDown, float fScalingFactor)
{
// Render icons
gl.glTranslatef(0, 2 + fHandleHeight, 0);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_DRAG_ICON_SELECTION,
EIconTextures.NAVIGATION_DRAG_VIEW, fHandleHeight, fHandleHeight);
gl.glTranslatef(fHandleWidth - 2 * fHandleHeight, 0, 0);
if (bUpsideDown)
{
gl.glRotatef(180, 1, 0, 0);
gl.glTranslatef(0, fHandleHeight, 0);
}
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_LOCK_ICON_SELECTION,
EIconTextures.NAVIGATION_LOCK_VIEW, fHandleHeight, fHandleHeight);
if (bUpsideDown)
{
gl.glTranslatef(0, -fHandleHeight, 0);
gl.glRotatef(-180, 1, 0, 0);
}
gl.glTranslatef(fHandleHeight, 0, 0);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_REMOVE_ICON_SELECTION,
EIconTextures.NAVIGATION_REMOVE_VIEW, fHandleHeight, fHandleHeight);
gl.glTranslatef(-fHandleWidth + fHandleHeight, -2 - fHandleHeight, 0);
// Render background (also draggable)
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.BUCKET_DRAG_ICON_SELECTION, element.getID()));
gl.glColor3f(0.25f, 0.25f, 0.25f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(0 + fHandleHeight, 2 + fHandleHeight, 0);
gl.glVertex3f(fHandleWidth - 2 * fHandleHeight, 2 + fHandleHeight, 0);
gl.glVertex3f(fHandleWidth - 2 * fHandleHeight, 2, 0);
gl.glVertex3f(0 + fHandleHeight, 2, 0);
gl.glEnd();
gl.glPopName();
// Render view information
String sText = generalManager.getViewGLCanvasManager().getGLEventListener(
element.getContainedElementID()).getShortInfo();
int iMaxChars = 50;
if (sText.length() > iMaxChars)
sText = sText.subSequence(0, iMaxChars - 3) + "...";
float fTextScalingFactor = 0.0027f;
if (bUpsideDown)
{
gl.glRotatef(180, 1, 0, 0);
gl.glTranslatef(0, -4 - fHandleHeight, 0);
}
textRenderer.setColor(0.7f, 0.7f, 0.7f, 1);
textRenderer.begin3DRendering();
textRenderer.draw3D(sText, 2 / fScalingFactor
- (float) textRenderer.getBounds(sText).getWidth() / 2f * fTextScalingFactor,
2.02f, 0, fTextScalingFactor);
textRenderer.end3DRendering();
if (bUpsideDown)
{
gl.glTranslatef(0, 4 + fHandleHeight, 0);
gl.glRotatef(-180, 1, 0, 0);
}
}
private void renderSingleHandle(final GL gl, int iRemoteLevelElementID,
EPickingType ePickingType, EIconTextures eIconTexture, float fWidth, float fHeight)
{
gl.glPushName(pickingManager.getPickingID(iUniqueID, ePickingType,
iRemoteLevelElementID));
Texture tempTexture = iconTextureManager.getIconTexture(gl, eIconTexture);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(0, -fHeight, 0f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(0, 0, 0f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fWidth, 0, 0f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fWidth, -fHeight, 0f);
gl.glEnd();
tempTexture.disable();
gl.glPopName();
}
private void renderNavigationOverlay(final GL gl, final int iRemoteLevelElementID)
{
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.enableRendering(false);
RemoteLevelElement remoteLevelElement = RemoteElementManager.get().getItem(
iRemoteLevelElementID);
EPickingType leftWallPickingType = null;
EPickingType rightWallPickingType = null;
EPickingType topWallPickingType = null;
EPickingType bottomWallPickingType = null;
Vec4f tmpColor_out = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_in = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_left = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_right = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
Vec4f tmpColor_lock = new Vec4f(0.9f, 0.9f, 0.9f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// Assign view symbol
Texture textureViewSymbol;
AGLEventListener view = generalManager.getViewGLCanvasManager().getGLEventListener(
remoteLevelElement.getContainedElementID());
if (view instanceof GLHeatMap)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.HEAT_MAP_SYMBOL);
}
else if (view instanceof GLParallelCoordinates)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.PAR_COORDS_SYMBOL);
}
else if (view instanceof GLPathway)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.PATHWAY_SYMBOL);
}
else if (view instanceof GLGlyph)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.GLYPH_SYMBOL);
}
else if (view instanceof GLCell)
{
textureViewSymbol = iconTextureManager.getIconTexture(gl,
EIconTextures.GLYPH_SYMBOL);
}
else
{
throw new IllegalStateException("Unknown view that has no symbol assigned.");
}
Texture textureMoveLeft = null;
Texture textureMoveRight = null;
Texture textureMoveOut = null;
Texture textureMoveIn = null;
TextureCoords texCoords = textureViewSymbol.getImageTexCoords();
if (iNavigationMouseOverViewID_lock == iRemoteLevelElementID)
tmpColor_lock.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
if (layoutMode.equals(LayoutMode.JUKEBOX))
{
topWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl, EIconTextures.ARROW_LEFT);
}
else
{
if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 0) // top
{
topWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
else if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 2) // bottom
{
topWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
else if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 1) // left
{
topWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
else if (stackLevel.getPositionIndexByElementID(remoteLevelElement) == 3) // right
{
topWallPickingType = EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
bottomWallPickingType = EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
leftWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
rightWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
if (iNavigationMouseOverViewID_out == iRemoteLevelElementID)
tmpColor_right.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_in == iRemoteLevelElementID)
tmpColor_left.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_left == iRemoteLevelElementID)
tmpColor_out.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
else if (iNavigationMouseOverViewID_right == iRemoteLevelElementID)
tmpColor_in.set(1, 0.3f, 0.3f,
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
textureMoveIn = iconTextureManager
.getIconTexture(gl, EIconTextures.ARROW_LEFT);
textureMoveOut = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveLeft = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_DOWN);
textureMoveRight = iconTextureManager.getIconTexture(gl,
EIconTextures.ARROW_LEFT);
}
// else if
// (underInteractionLayer.getPositionIndexByElementID(iViewID) == 0)
// // center
// {
// topWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
// bottomWallPickingType =
// EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
// leftWallPickingType =
// EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION;
// rightWallPickingType =
// EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
//
// if (iNavigationMouseOverViewID_out == iViewID)
// tmpColor_out.set(1, 0.3f, 0.3f, 0.9f);
// else if (iNavigationMouseOverViewID_in == iViewID)
// tmpColor_in.set(1, 0.3f, 0.3f, 0.9f);
// else if (iNavigationMouseOverViewID_left == iViewID)
// tmpColor_left.set(1, 0.3f, 0.3f, 0.9f);
// else if (iNavigationMouseOverViewID_right == iViewID)
// tmpColor_right.set(1, 0.3f, 0.3f, 0.9f);
//
// textureMoveIn =
// iconTextureManager.getIconTexture(EIconTextures.ARROW_LEFT);
// textureMoveOut =
// iconTextureManager.getIconTexture(EIconTextures.ARROW_DOWN);
// textureMoveLeft = iconTextureManager
// .getIconTexture(EIconTextures.ARROW_DOWN);
// textureMoveRight = iconTextureManager
// .getIconTexture(EIconTextures.ARROW_LEFT);
// }
}
// else if (underInteractionLayer.containsElement(iViewID))
// {
// topWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
// bottomWallPickingType =
// EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION;
// leftWallPickingType = EPickingType.BUCKET_MOVE_IN_ICON_SELECTION;
// rightWallPickingType = EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION;
// }
gl.glLineWidth(1);
float fNavigationZValue = 0f;
// CENTER - NAVIGATION: VIEW IDENTIFICATION ICON
// gl.glPushName(pickingManager.getPickingID(iUniqueID,
// EPickingType.BUCKET_LOCK_ICON_SELECTION, iViewID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_lock.x(), tmpColor_lock.y(), tmpColor_lock.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(2.66f, 2.66f, 0.02f);
// gl.glVertex3f(2.66f, 5.33f, 0.02f);
// gl.glVertex3f(5.33f, 5.33f, 0.02f);
// gl.glVertex3f(5.33f, 2.66f, 0.02f);
// gl.glEnd();
textureViewSymbol.enable();
textureViewSymbol.bind();
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glEnd();
textureViewSymbol.disable();
// gl.glPopName();
// BOTTOM - NAVIGATION: MOVE IN
gl.glPushName(pickingManager.getPickingID(iUniqueID, bottomWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 0, fNavigationZValue);
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glVertex3f(8, 0, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_in.x(), tmpColor_in.y(), tmpColor_in.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(0.05f, 0.05f, 0.02f);
// gl.glVertex3f(2.66f, 2.66f, 0.02f);
// gl.glVertex3f(5.33f, 2.66f, 0.02f);
// gl.glVertex3f(7.95f, 0.02f, 0.02f);
// gl.glEnd();
textureMoveIn.enable();
textureMoveIn.bind();
// texCoords = textureMoveIn.getImageTexCoords();
// gl.glColor4f(1,0.3f,0.3f,0.9f);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(2.66f, 0.05f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(5.33f, 0.05f, fNavigationZValue);
gl.glEnd();
textureMoveIn.disable();
gl.glPopName();
// RIGHT - NAVIGATION: MOVE RIGHT
gl.glPushName(pickingManager.getPickingID(iUniqueID, rightWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(8, 0, fNavigationZValue);
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glVertex3f(8, 8, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_right.x(), tmpColor_right.y(), tmpColor_right.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(7.95f, 0.05f, 0.02f);
// gl.glVertex3f(5.33f, 2.66f, 0.02f);
// gl.glVertex3f(5.33f, 5.33f, 0.02f);
// gl.glVertex3f(7.95f, 7.95f, 0.02f);
// gl.glEnd();
textureMoveRight.enable();
textureMoveRight.bind();
// gl.glColor4f(0,1,0,1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(7.95f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(5.33f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(7.95f, 5.33f, fNavigationZValue);
gl.glEnd();
textureMoveRight.disable();
gl.glPopName();
// LEFT - NAVIGATION: MOVE LEFT
gl.glPushName(pickingManager.getPickingID(iUniqueID, leftWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 0, fNavigationZValue);
gl.glVertex3f(0, 8, fNavigationZValue);
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_left.x(), tmpColor_left.y(), tmpColor_left.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(0.05f, 0.05f, fNavigationZValue);
// gl.glVertex3f(0.05f, 7.95f, fNavigationZValue);
// gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
// gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
// gl.glEnd();
textureMoveLeft.enable();
textureMoveLeft.bind();
// gl.glColor4f(0,1,0,1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(0.05f, 2.66f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(0.05f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(2.66f, 2.66f, fNavigationZValue);
gl.glEnd();
textureMoveLeft.disable();
gl.glPopName();
// TOP - NAVIGATION: MOVE OUT
gl.glPushName(pickingManager.getPickingID(iUniqueID, topWallPickingType,
iRemoteLevelElementID));
gl.glColor4f(0.5f, 0.5f, 0.5f, 1);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f(0, 8, fNavigationZValue);
gl.glVertex3f(8, 8, fNavigationZValue);
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glEnd();
gl.glColor4f(tmpColor_out.x(), tmpColor_out.y(), tmpColor_out.z(),
ARemoteViewLayoutRenderStyle.NAVIGATION_OVERLAY_TRANSPARENCY);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(0.05f, 7.95f, 0.02f);
// gl.glVertex3f(7.95f, 7.95f, 0.02f);
// gl.glVertex3f(5.33f, 5.33f, 0.02f);
// gl.glVertex3f(2.66f, 5.33f, 0.02f);
// gl.glEnd();
textureMoveOut.enable();
textureMoveOut.bind();
// gl.glColor4f(0,1,0,1);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(2.66f, 7.95f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(5.33f, 7.95f, fNavigationZValue);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(5.33f, 5.33f, fNavigationZValue);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(2.66f, 5.33f, fNavigationZValue);
gl.glEnd();
textureMoveOut.disable();
gl.glPopName();
}
private void renderPoolSelection(final GL gl, float fXOrigin, float fYOrigin,
float fWidth, float fHeight, RemoteLevelElement element)
{
float fPanelSideWidth = 11f;
gl.glColor3f(0.25f, 0.25f, 0.25f);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth, fYOrigin - fHeight
/ 2f + fHeight, 0f);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth + fWidth, fYOrigin
- fHeight / 2f + fHeight, 0f);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth + fWidth, fYOrigin
- fHeight / 2f, 0f);
gl.glVertex3f(fXOrigin + 1.65f / fAspectRatio + fPanelSideWidth, fYOrigin - fHeight
/ 2f, 0f);
gl.glEnd();
Texture tempTexture = iconTextureManager.getIconTexture(gl,
EIconTextures.POOL_VIEW_BACKGROUND_SELECTION);
tempTexture.enable();
tempTexture.bind();
TextureCoords texCoords = tempTexture.getImageTexCoords();
gl.glColor4f(1, 1, 1, 0.75f);
gl.glBegin(GL.GL_POLYGON);
gl.glTexCoord2f(texCoords.left(), texCoords.bottom());
gl.glVertex3f(fXOrigin + (2) / fAspectRatio + fPanelSideWidth, fYOrigin - fHeight,
-0.01f);
gl.glTexCoord2f(texCoords.left(), texCoords.top());
gl.glVertex3f(fXOrigin + (2) / fAspectRatio + fPanelSideWidth, fYOrigin + fHeight,
-0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.top());
gl.glVertex3f(fXOrigin + 2f / fAspectRatio, fYOrigin + fHeight, -0.01f);
gl.glTexCoord2f(texCoords.right(), texCoords.bottom());
gl.glVertex3f(fXOrigin + 2f / fAspectRatio, fYOrigin - fHeight, -0.01f);
gl.glEnd();
tempTexture.disable();
gl.glPopName();
gl.glPopName();
int fHandleScaleFactor = 18;
gl.glTranslatef(fXOrigin + 2.5f / fAspectRatio,
fYOrigin - fHeight / 2f + fHeight - 1f, 1.8f);
gl.glScalef(fHandleScaleFactor, fHandleScaleFactor, fHandleScaleFactor);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_DRAG_ICON_SELECTION,
EIconTextures.POOL_DRAG_VIEW, 0.1f, 0.1f);
gl.glTranslatef(0, -0.2f, 0);
renderSingleHandle(gl, element.getID(), EPickingType.BUCKET_REMOVE_ICON_SELECTION,
EIconTextures.POOL_REMOVE_VIEW, 0.1f, 0.1f);
gl.glTranslatef(0, 0.2f, 0);
gl.glScalef(1f / fHandleScaleFactor, 1f / fHandleScaleFactor, 1f / fHandleScaleFactor);
gl.glTranslatef(-fXOrigin - 2.5f / fAspectRatio, -fYOrigin + fHeight / 2f - fHeight
+ 1f, -1.8f);
// gl.glColor3f(0.25f, 0.25f, 0.25f);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(fXOrigin + 3f, fYOrigin - fHeight / 2f + fHeight -
// 2.5f, 0f);
// gl.glVertex3f(fXOrigin + 5.1f, fYOrigin - fHeight / 2f + fHeight -
// 2.5f, 0f);
// gl.glVertex3f(fXOrigin + 5.1f, fYOrigin- fHeight / 2f + 1.5f, 0f);
// gl.glVertex3f(fXOrigin + 3f, fYOrigin- fHeight / 2f + 1.5f , 0f);
// gl.glEnd();
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, element.getID()));
gl.glPushName(pickingManager.getPickingID(iUniqueID, EPickingType.VIEW_SELECTION,
element.getID()));
}
private void doSlerpActions(final GL gl)
{
if (arSlerpActions.isEmpty())
return;
SlerpAction tmpSlerpAction = arSlerpActions.get(0);
if (iSlerpFactor == 0)
{
tmpSlerpAction.start();
// System.out.println("Start slerp action " +tmpSlerpAction);
}
if (iSlerpFactor < SLERP_RANGE)
{
// Makes animation rendering speed independent
iSlerpFactor += SLERP_SPEED * time.deltaT();
if (iSlerpFactor > SLERP_RANGE)
iSlerpFactor = SLERP_RANGE;
}
slerpView(gl, tmpSlerpAction);
}
private void slerpView(final GL gl, SlerpAction slerpAction)
{
int iViewID = slerpAction.getElementId();
SlerpMod slerpMod = new SlerpMod();
if ((iSlerpFactor == 0))
{
slerpMod.playSlerpSound();
}
Transform transform = slerpMod.interpolate(slerpAction.getOriginRemoteLevelElement()
.getTransform(),
slerpAction.getDestinationRemoteLevelElement().getTransform(),
(float) iSlerpFactor / SLERP_RANGE);
gl.glPushMatrix();
slerpMod.applySlerp(gl, transform);
(generalManager.getViewGLCanvasManager().getGLEventListener(iViewID))
.displayRemote(gl);
gl.glPopMatrix();
// Check if slerp action is finished
if (iSlerpFactor >= SLERP_RANGE)
{
arSlerpActions.remove(slerpAction);
iSlerpFactor = 0;
slerpAction.finished();
RemoteLevelElement destinationElement = slerpAction
.getDestinationRemoteLevelElement();
updateViewDetailLevels(destinationElement);
}
// After last slerp action is done the line connections are turned on
// again
if (arSlerpActions.isEmpty())
{
if (glConnectionLineRenderer != null)
glConnectionLineRenderer.enableRendering(true);
generalManager.getViewGLCanvasManager().getInfoAreaManager().enable(
!bEnableNavigationOverlay);
}
}
private void updateViewDetailLevels(RemoteLevelElement element)
{
RemoteLevel destinationLevel = element.getRemoteLevel();
if (element.getContainedElementID() == -1)
return;
AGLEventListener glActiveSubView = GeneralManager.get().getViewGLCanvasManager()
.getGLEventListener(element.getContainedElementID());
glActiveSubView.setRemoteLevelElement(element);
// Update detail level of moved view when slerp action is finished;
if (destinationLevel == focusLevel)
{
if (bucketMouseWheelListener.isZoomedIn()
|| layoutRenderStyle instanceof ListLayoutRenderStyle)
glActiveSubView.setDetailLevel(EDetailLevel.HIGH);
else
glActiveSubView.setDetailLevel(EDetailLevel.MEDIUM);
// if (glActiveSubView instanceof GLPathway)
// {
// ((GLPathway) glActiveSubView).enableTitleRendering(true);
// ((GLPathway) glActiveSubView).setAlignment(SWT.CENTER,
// SWT.BOTTOM);
// }
// generalManager.getGUIBridge().setActiveGLSubView(this,
// glActiveSubView);
}
else if (destinationLevel == stackLevel)
{
glActiveSubView.setDetailLevel(EDetailLevel.LOW);
// if (glActiveSubView instanceof GLPathway)
// {
// ((GLPathway) glActiveSubView).enableTitleRendering(true);
//
// int iStackPos = stackLevel.getPositionIndexByElementID(element);
// switch (iStackPos)
// {
// case 0:
// ((GLPathway) glActiveSubView).setAlignment(SWT.CENTER, SWT.TOP);
// break;
// case 1:
// ((GLPathway) glActiveSubView).setAlignment(SWT.LEFT, SWT.BOTTOM);
// break;
// case 2:
// ((GLPathway) glActiveSubView).setAlignment(SWT.CENTER,
// SWT.BOTTOM);
// break;
// case 3:
// ((GLPathway) glActiveSubView).setAlignment(SWT.RIGHT,
// SWT.BOTTOM);
// break;
// default:
// break;
// }
// }
}
else if (destinationLevel == poolLevel || destinationLevel == selectionLevel)
{
glActiveSubView.setDetailLevel(EDetailLevel.VERY_LOW);
// if (glActiveSubView instanceof GLPathway)
// {
// ((GLPathway) glActiveSubView).enableTitleRendering(false);
// }
}
compactPoolLevel();
}
private void loadViewToFocusLevel(final int iRemoteLevelElementID)
{
RemoteLevelElement element = RemoteElementManager.get().getItem(iRemoteLevelElementID);
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
return;
arSlerpActions.clear();
int iViewID = element.getContainedElementID();
if (iViewID == -1)
return;
// Only broadcast elements if view is moved from pool to bucket
if (poolLevel.containsElement(element))
{
generalManager.getViewGLCanvasManager().getGLEventListener(iViewID)
.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
// if (layoutRenderStyle instanceof ListLayoutRenderStyle)
// {
// // Slerp selected view to under interaction transition position
// SlerpAction slerpActionTransition = new
// SlerpAction(iRemoteLevelElementID, poolLevel,
// transitionLevel);
// arSlerpActions.add(slerpActionTransition);
//
// // Check if focus has a free spot
// if (focusLevel.getElementByPositionIndex(0).getContainedElementID()
// != -1)
// {
// // Slerp under interaction view to free spot in pool
// SlerpAction reverseSlerpAction = new SlerpAction(focusLevel
// .getElementIDByPositionIndex(0), focusLevel, poolLevel);
// arSlerpActions.add(reverseSlerpAction);
// }
//
// // Slerp selected view from transition position to under interaction
// // position
// SlerpAction slerpAction = new SlerpAction(iViewID, transitionLevel,
// focusLevel);
// arSlerpActions.add(slerpAction);
// }
// else
{
// Check if view is already loaded in the stack layer
if (stackLevel.containsElement(element))
{
// Slerp selected view to transition position
SlerpAction slerpActionTransition = new SlerpAction(element, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
// Check if focus level is free
if (!focusLevel.hasFreePosition())
{
// Slerp focus view to free spot in stack
SlerpAction reverseSlerpAction = new SlerpAction(focusLevel
.getElementByPositionIndex(0).getContainedElementID(), focusLevel
.getElementByPositionIndex(0), element);
arSlerpActions.add(reverseSlerpAction);
}
// Slerp selected view from transition position to focus
// position
SlerpAction slerpAction = new SlerpAction(element.getContainedElementID(),
transitionLevel.getElementByPositionIndex(0), focusLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpAction);
}
else
{
// Slerp selected view to transition position
SlerpAction slerpActionTransition = new SlerpAction(element, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
RemoteLevelElement freeStackElement = null;
if (!stackLevel.hasFreePosition())
{
int iReplacePosition = 1;
// // Determine non locked stack position for view movement
// to pool
// for (int iTmpReplacePosition = 0; iTmpReplacePosition <
// stackLevel.getCapacity(); iTmpReplacePosition++)
// {
// if
// (stackLevel.getElementByPositionIndex(iTmpReplacePosition).isLocked())
// continue;
//
// iReplacePosition = iTmpReplacePosition + 1; // +1 to
// start with left view for outsourcing
//
// if (iReplacePosition == 4)
// iReplacePosition = 0;
//
// break;
// }
//
// if (iReplacePosition == -1)
// throw new
// IllegalStateException("All views in stack are locked!");
freeStackElement = stackLevel.getElementByPositionIndex(iReplacePosition);
// Slerp view from stack to pool
SlerpAction reverseSlerpAction = new SlerpAction(freeStackElement,
poolLevel.getNextFree());
arSlerpActions.add(reverseSlerpAction);
// Unregister all elements of the view that is moved out
generalManager.getViewGLCanvasManager().getGLEventListener(
freeStackElement.getContainedElementID()).broadcastElements(
EVAOperation.REMOVE_ELEMENT);
}
else
{
freeStackElement = stackLevel.getNextFree();
}
if (!focusLevel.hasFreePosition())
{
// Slerp focus view to free spot in stack
SlerpAction reverseSlerpAction2 = new SlerpAction(focusLevel
.getElementByPositionIndex(0), freeStackElement);
arSlerpActions.add(reverseSlerpAction2);
}
// Slerp selected view from transition position to focus
// position
SlerpAction slerpAction = new SlerpAction(iViewID, transitionLevel
.getElementByPositionIndex(0), focusLevel.getElementByPositionIndex(0));
arSlerpActions.add(slerpAction);
}
}
iSlerpFactor = 0;
}
@SuppressWarnings("unchecked")
@Override
public void handleExternalEvent(IUniqueObject eventTrigger, IEventContainer eventContainer)
{
switch (eventContainer.getEventType())
{
// pathway loading based on gene id
case LOAD_PATHWAY_BY_GENE:
// take care here, if we ever use non integer ids this has to be
// cast to raw type first to determine the actual id data types
IDListEventContainer<Integer> idContainer = (IDListEventContainer<Integer>) eventContainer;
if (idContainer.getIDType() == EIDType.DAVID)
{
int iGraphItemID = 0;
ArrayList<ICaleydoGraphItem> alPathwayVertexGraphItem = new ArrayList<ICaleydoGraphItem>();
for (Integer iDavidID : idContainer.getIDs())
{
iGraphItemID = generalManager.getPathwayItemManager()
.getPathwayVertexGraphItemIdByDavidId(iDavidID);
if (iGraphItemID == -1)
continue;
PathwayVertexGraphItem tmpPathwayVertexGraphItem = ((PathwayVertexGraphItem) generalManager
.getPathwayItemManager().getItem(iGraphItemID));
if (tmpPathwayVertexGraphItem == null)
continue;
alPathwayVertexGraphItem.add(tmpPathwayVertexGraphItem);
}
if (!alPathwayVertexGraphItem.isEmpty())
{
loadDependentPathways(alPathwayVertexGraphItem);
}
}
else
{
throw new IllegalStateException("Not Implemented");
}
break;
// Handle incoming pathways
case LOAD_PATHWAY_BY_PATHWAY_ID:
IDListEventContainer<Integer> pathwayIDContainer = (IDListEventContainer<Integer>) eventContainer;
for (Integer iPathwayID : pathwayIDContainer.getIDs())
{
addPathwayView(iPathwayID);
}
break;
case SELECTION_UPDATE:
lastSelectionDelta = ((DeltaEventContainer<ISelectionDelta>) eventContainer)
.getSelectionDelta();
}
bUpdateOffScreenTextures = true;
}
/**
* Add pathway view. Also used when serialized pathways are loaded.
*
* @param iPathwayIDToLoad
*/
public synchronized void addPathwayView(final int iPathwayIDToLoad)
{
iAlUninitializedPathwayIDs.add(iPathwayIDToLoad);
}
public synchronized void loadDependentPathways(final List<ICaleydoGraphItem> alVertex)
{
// Remove pathways from stacked layer view
// poolLayer.removeAllElements();
Iterator<ICaleydoGraphItem> iterPathwayGraphItem = alVertex.iterator();
Iterator<IGraphItem> iterIdenticalPathwayGraphItemRep = null;
IGraphItem pathwayGraphItem;
int iPathwayID = 0;
while (iterPathwayGraphItem.hasNext())
{
pathwayGraphItem = iterPathwayGraphItem.next();
if (pathwayGraphItem == null)
{
// generalManager.logMsg(
// this.getClass().getSimpleName() + " (" + iUniqueID
// + "): pathway graph item is null. ",
// LoggerType.VERBOSE);
continue;
}
iterIdenticalPathwayGraphItemRep = pathwayGraphItem.getAllItemsByProp(
EGraphItemProperty.ALIAS_CHILD).iterator();
while (iterIdenticalPathwayGraphItemRep.hasNext())
{
iPathwayID = ((PathwayGraph) iterIdenticalPathwayGraphItemRep.next()
.getAllGraphByType(EGraphItemHierarchy.GRAPH_PARENT).toArray()[0])
.getId();
// Only add pathway if it is not loaded yet
if (!generalManager.getPathwayManager().isPathwayVisible(iPathwayID))
iAlUninitializedPathwayIDs.add(iPathwayID);
}
}
if (iAlUninitializedPathwayIDs.isEmpty())
return;
// Disable picking until pathways are loaded
pickingManager.enablePicking(false);
// Zoom out of the bucket when loading pathways
if (bucketMouseWheelListener.isZoomedIn())
bucketMouseWheelListener.triggerZoom(false);
// Turn on busy mode
for (AGLEventListener tmpGLEventListener : GeneralManager.get()
.getViewGLCanvasManager().getAllGLEventListeners())
{
if (!tmpGLEventListener.isRenderedRemote())
tmpGLEventListener.enableBusyMode(true);
}
// iSlerpFactor = 0;
}
@Override
protected void handleEvents(EPickingType pickingType, EPickingMode pickingMode,
int iExternalID, Pick pick)
{
switch (pickingType)
{
case BUCKET_DRAG_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
if (!dragAndDrop.isDragActionRunning())
{
// System.out.println("Start drag!");
dragAndDrop.startDragAction(iExternalID);
}
iMouseOverObjectID = iExternalID;
compactPoolLevel();
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.BUCKET_DRAG_ICON_SELECTION);
pickingManager.flushHits(iUniqueID, EPickingType.REMOTE_LEVEL_ELEMENT);
break;
case BUCKET_REMOVE_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
RemoteLevelElement element = RemoteElementManager.get().getItem(
iExternalID);
AGLEventListener glEventListener = ((AGLEventListener) generalManager
.getViewGLCanvasManager().getGLEventListener(
element.getContainedElementID()));
// Unregister all elements of the view that is removed
glEventListener.broadcastElements(EVAOperation.REMOVE_ELEMENT);
removeView(glEventListener);
element.setContainedElementID(-1);
if (element.getRemoteLevel() == poolLevel)
compactPoolLevel();
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.BUCKET_REMOVE_ICON_SELECTION);
break;
case BUCKET_LOCK_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
RemoteLevelElement element = RemoteElementManager.get().getItem(
iExternalID);
// Toggle lock flag
element.lock(!element.isLocked());
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.BUCKET_LOCK_ICON_SELECTION);
break;
case REMOTE_LEVEL_ELEMENT:
switch (pickingMode)
{
case MOUSE_OVER:
case DRAGGED:
iMouseOverObjectID = iExternalID;
break;
case CLICKED:
// Do not handle click if element is dragged
if (dragAndDrop.isDragActionRunning())
break;
// Check if view is contained in pool level
for (RemoteLevelElement element : poolLevel.getAllElements())
{
if (element.getID() == iExternalID)
{
loadViewToFocusLevel(iExternalID);
break;
}
}
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.REMOTE_LEVEL_ELEMENT);
break;
case VIEW_SELECTION:
switch (pickingMode)
{
case MOUSE_OVER:
// generalManager.getViewGLCanvasManager().getInfoAreaManager()
// .setDataAboutView(iExternalID);
// Prevent update flood when moving mouse over view
if (iActiveViewID == iExternalID)
break;
iActiveViewID = iExternalID;
setDisplayListDirty();
// TODO
// generalManager.getEventPublisher().triggerEvent(
// EMediatorType.VIEW_SELECTION,
// generalManager.getViewGLCanvasManager().getGLEventListener(
// iExternalID), );
break;
case CLICKED:
// generalManager.getViewGLCanvasManager().getInfoAreaManager()
// .setDataAboutView(iExternalID);
break;
}
pickingManager.flushHits(iUniqueID, EPickingType.VIEW_SELECTION);
break;
// case BUCKET_LOCK_ICON_SELECTION:
// switch (pickingMode)
// {
// case CLICKED:
//
// break;
//
// case MOUSE_OVER:
//
// iNavigationMouseOverViewID_lock = iExternalID;
// iNavigationMouseOverViewID_left = -1;
// iNavigationMouseOverViewID_right = -1;
// iNavigationMouseOverViewID_out = -1;
// iNavigationMouseOverViewID_in = -1;
//
// break;
// }
//
// pickingManager.flushHits(iUniqueID,
// EPickingType.BUCKET_LOCK_ICON_SELECTION);
//
// break;
case BUCKET_MOVE_IN_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
loadViewToFocusLevel(iExternalID);
bEnableNavigationOverlay = false;
// glConnectionLineRenderer.enableRendering(true);
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = -1;
iNavigationMouseOverViewID_right = -1;
iNavigationMouseOverViewID_out = -1;
iNavigationMouseOverViewID_in = iExternalID;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager
.flushHits(iUniqueID, EPickingType.BUCKET_MOVE_IN_ICON_SELECTION);
break;
case BUCKET_MOVE_OUT_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
break;
// glConnectionLineRenderer.enableRendering(true);
arSlerpActions.clear();
RemoteLevelElement element = RemoteElementManager.get().getItem(
iExternalID);
SlerpAction slerpActionTransition = new SlerpAction(element, poolLevel
.getNextFree());
arSlerpActions.add(slerpActionTransition);
bEnableNavigationOverlay = false;
// Unregister all elements of the view that is moved out
generalManager.getViewGLCanvasManager().getGLEventListener(
element.getContainedElementID()).broadcastElements(
EVAOperation.REMOVE_ELEMENT);
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = -1;
iNavigationMouseOverViewID_right = -1;
iNavigationMouseOverViewID_out = iExternalID;
iNavigationMouseOverViewID_in = -1;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager.flushHits(iUniqueID,
EPickingType.BUCKET_MOVE_OUT_ICON_SELECTION);
break;
case BUCKET_MOVE_LEFT_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
break;
// glConnectionLineRenderer.enableRendering(true);
arSlerpActions.clear();
RemoteLevelElement selectedElement = RemoteElementManager.get()
.getItem(iExternalID);
int iDestinationPosIndex = stackLevel
.getPositionIndexByElementID(selectedElement);
if (iDestinationPosIndex == 3)
iDestinationPosIndex = 0;
else
iDestinationPosIndex++;
// Check if destination position in stack is free
if (stackLevel.getElementByPositionIndex(iDestinationPosIndex)
.getContainedElementID() == -1)
{
SlerpAction slerpAction = new SlerpAction(selectedElement,
stackLevel.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpAction);
}
else
{
SlerpAction slerpActionTransition = new SlerpAction(
selectedElement, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
SlerpAction slerpAction = new SlerpAction(stackLevel
.getElementByPositionIndex(iDestinationPosIndex),
selectedElement);
arSlerpActions.add(slerpAction);
SlerpAction slerpActionTransitionReverse = new SlerpAction(
selectedElement.getContainedElementID(), transitionLevel
.getElementByPositionIndex(0), stackLevel
.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpActionTransitionReverse);
}
bEnableNavigationOverlay = false;
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = iExternalID;
iNavigationMouseOverViewID_right = -1;
iNavigationMouseOverViewID_out = -1;
iNavigationMouseOverViewID_in = -1;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager.flushHits(iUniqueID,
EPickingType.BUCKET_MOVE_LEFT_ICON_SELECTION);
break;
case BUCKET_MOVE_RIGHT_ICON_SELECTION:
switch (pickingMode)
{
case CLICKED:
// Check if other slerp action is currently running
if (iSlerpFactor > 0 && iSlerpFactor < SLERP_RANGE)
break;
// glConnectionLineRenderer.enableRendering(true);
arSlerpActions.clear();
RemoteLevelElement selectedElement = RemoteElementManager.get()
.getItem(iExternalID);
int iDestinationPosIndex = stackLevel
.getPositionIndexByElementID(selectedElement);
if (iDestinationPosIndex == 0)
iDestinationPosIndex = 3;
else
iDestinationPosIndex--;
// Check if destination position in stack is free
if (stackLevel.getElementByPositionIndex(iDestinationPosIndex)
.getContainedElementID() == -1)
{
SlerpAction slerpAction = new SlerpAction(selectedElement,
stackLevel.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpAction);
}
else
{
SlerpAction slerpActionTransition = new SlerpAction(
selectedElement, transitionLevel
.getElementByPositionIndex(0));
arSlerpActions.add(slerpActionTransition);
SlerpAction slerpAction = new SlerpAction(stackLevel
.getElementByPositionIndex(iDestinationPosIndex),
selectedElement);
arSlerpActions.add(slerpAction);
SlerpAction slerpActionTransitionReverse = new SlerpAction(
selectedElement.getContainedElementID(), transitionLevel
.getElementByPositionIndex(0), stackLevel
.getElementByPositionIndex(iDestinationPosIndex));
arSlerpActions.add(slerpActionTransitionReverse);
}
bEnableNavigationOverlay = false;
break;
case MOUSE_OVER:
iNavigationMouseOverViewID_left = -1;
iNavigationMouseOverViewID_right = iExternalID;
iNavigationMouseOverViewID_out = -1;
iNavigationMouseOverViewID_in = -1;
iNavigationMouseOverViewID_lock = -1;
break;
}
pickingManager.flushHits(iUniqueID,
EPickingType.BUCKET_MOVE_RIGHT_ICON_SELECTION);
break;
// case MEMO_PAD_SELECTION:
// switch (pickingMode)
// {
// case CLICKED:
//
// break;
//
// case DRAGGED:
//
// int iDraggedObjectId = dragAndDrop.getDraggedObjectedId();
//
// if (iExternalID == TRASH_CAN_PICKING_ID)
// {
// if (iDraggedObjectId != -1)
// {
// // if
// // (memoLayer.containsElement(iDraggedObjectId))
// // {
// memoLayer.removeElement(iDraggedObjectId);
// // dragAndDrop.stopDragAction();
// // break;
// // }
//
// underInteractionLayer.removeElement(iDraggedObjectId);
// stackLayer.removeElement(iDraggedObjectId);
// poolLayer.removeElement(iDraggedObjectId);
// }
// }
// else if (iExternalID == MEMO_PAD_PICKING_ID)
// {
// if (iDraggedObjectId != -1)
// {
// if (!memoLayer.containsElement(iDraggedObjectId))
// {
// memoLayer.addElement(iDraggedObjectId);
// memoLayer.setElementVisibilityById(true, iDraggedObjectId);
// }
// }
// }
//
// dragAndDrop.stopDragAction();
//
// break;
// }
//
// pickingManager.flushHits(iUniqueID,
// EPickingType.MEMO_PAD_SELECTION);
// break;
}
}
@Override
public String getShortInfo()
{
return "Bucket / Jukebox";
}
@Override
public String getDetailedInfo()
{
StringBuffer sInfoText = new StringBuffer();
sInfoText.append("Bucket / Jukebox");
return sInfoText.toString();
}
private void createEventMediator()
{
generalManager.getEventPublisher().addSender(EMediatorType.SELECTION_MEDIATOR,
(IMediatorSender) this);
generalManager.getEventPublisher().addReceiver(EMediatorType.SELECTION_MEDIATOR,
(IMediatorReceiver) this);
}
public synchronized void toggleLayoutMode()
{
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
layoutMode = ARemoteViewLayoutRenderStyle.LayoutMode.LIST;
// layoutMode = ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX;
else
layoutMode = ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET;
if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.BUCKET))
{
layoutRenderStyle = new BucketLayoutRenderStyle(viewFrustum, layoutRenderStyle);
bucketMouseWheelListener = new BucketMouseWheelListener(this,
(BucketLayoutRenderStyle) layoutRenderStyle);
// Unregister standard mouse wheel listener
parentGLCanvas.removeMouseWheelListener(pickingTriggerMouseAdapter);
// Register specialized bucket mouse wheel listener
parentGLCanvas.addMouseWheelListener(bucketMouseWheelListener);
glConnectionLineRenderer = new GLConnectionLineRendererBucket(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.JUKEBOX))
{
layoutRenderStyle = new JukeboxLayoutRenderStyle(viewFrustum, layoutRenderStyle);
// Unregister bucket wheel listener
parentGLCanvas.removeMouseWheelListener(bucketMouseWheelListener);
// Register standard mouse wheel listener
parentGLCanvas.addMouseWheelListener(pickingTriggerMouseAdapter);
glConnectionLineRenderer = new GLConnectionLineRendererJukebox(focusLevel,
stackLevel, poolLevel);
}
else if (layoutMode.equals(ARemoteViewLayoutRenderStyle.LayoutMode.LIST))
{
layoutRenderStyle = new ListLayoutRenderStyle(viewFrustum, layoutRenderStyle);
glConnectionLineRenderer = null;
// // Copy views from stack to pool
// for (Integer iElementID : stackLevel.getElementList())
// {
// if (iElementID == -1)
// continue;
//
// poolLevel.addElement(iElementID);
// // poolLevel.setElementVisibilityById(true, iElementID);
// }
// stackLevel.clear();
}
focusLevel = layoutRenderStyle.initFocusLevel();
stackLevel = layoutRenderStyle.initStackLevel(bucketMouseWheelListener.isZoomedIn());
poolLevel = layoutRenderStyle.initPoolLevel(bucketMouseWheelListener.isZoomedIn(), -1);
selectionLevel = layoutRenderStyle.initMemoLevel();
transitionLevel = layoutRenderStyle.initTransitionLevel();
spawnLevel = layoutRenderStyle.initSpawnLevel();
viewFrustum.setProjectionMode(layoutRenderStyle.getProjectionMode());
// Trigger reshape to apply new projection mode
// Is there a better way to achieve this? :)
parentGLCanvas.setSize(parentGLCanvas.getWidth(), parentGLCanvas.getHeight());
}
public synchronized void toggleConnectionLines()
{
bEnableConnectinLines = !bEnableConnectinLines;
}
/**
* Unregister view from event system. Remove view from GL render loop.
*/
public void removeView(AGLEventListener glEventListener)
{
glEventListener.destroy();
}
public synchronized void clearAll()
{
enableBusyMode(false);
pickingManager.enablePicking(true);
iAlUninitializedPathwayIDs.clear();
arSlerpActions.clear();
generalManager.getPathwayManager().resetPathwayVisiblityState();
clearRemoteLevel(focusLevel);
clearRemoteLevel(stackLevel);
clearRemoteLevel(poolLevel);
generalManager.getViewGLCanvasManager().getConnectedElementRepresentationManager().clearAll();
}
private void clearRemoteLevel(RemoteLevel remoteLevel)
{
int iViewID;
IViewManager viewManager = generalManager.getViewGLCanvasManager();
AGLEventListener glEventListener = null;
for (RemoteLevelElement element : remoteLevel.getAllElements())
{
iViewID = element.getContainedElementID();
if (iViewID == -1)
continue;
glEventListener = viewManager.getGLEventListener(iViewID);
if (glEventListener instanceof GLHeatMap
|| glEventListener instanceof GLParallelCoordinates)
{
// Remove all elements from heatmap and parallel coordinates
((AStorageBasedView) glEventListener).resetView();
if (!glEventListener.isRenderedRemote())
glEventListener.enableBusyMode(false);
}
else
{
removeView(glEventListener);
element.setContainedElementID(-1);
}
}
}
// @Override
// public synchronized RemoteLevel getHierarchyLayerByGLEventListenerId(
// final int iGLEventListenerId)
// {
// if (focusLevel.containsElement(iGLEventListenerId))
// return focusLevel;
// else if (stackLevel.containsElement(iGLEventListenerId))
// return stackLevel;
// else if (poolLevel.containsElement(iGLEventListenerId))
// return poolLevel;
// else if (transitionLevel.containsElement(iGLEventListenerId))
// return transitionLevel;
// else if (spawnLevel.containsElement(iGLEventListenerId))
// return spawnLevel;
// else if (selectionLevel.containsElement(iGLEventListenerId))
// return selectionLevel;
//
// generalManager.getLogger().log(Level.WARNING,
// "GL Event Listener " + iGLEventListenerId +
// " is not contained in any layer!");
//
// return null;
// }
@Override
public RemoteLevel getFocusLevel()
{
return focusLevel;
}
@Override
public BucketMouseWheelListener getBucketMouseWheelListener()
{
return bucketMouseWheelListener;
}
@Override
public synchronized void reshape(GLAutoDrawable drawable, int x, int y, int width,
int height)
{
super.reshape(drawable, x, y, width, height);
// Update aspect ratio and reinitialize stack and focus layer
layoutRenderStyle.setAspectRatio(fAspectRatio);
layoutRenderStyle.initFocusLevel();
layoutRenderStyle.initStackLevel(bucketMouseWheelListener.isZoomedIn());
layoutRenderStyle.initPoolLevel(bucketMouseWheelListener.isZoomedIn(),
iMouseOverObjectID);
layoutRenderStyle.initMemoLevel();
}
protected void renderPoolAndMemoLayerBackground(final GL gl)
{
// Pool layer background
float fWidth = 0.8f;
float fXCorrection = 0.07f; // Detach pool level from stack
if (layoutMode.equals(LayoutMode.BUCKET))
{
gl.glPushName(pickingManager.getPickingID(iUniqueID,
EPickingType.REMOTE_LEVEL_ELEMENT, iPoolLevelCommonID));
gl.glColor4f(0.85f, 0.85f, 0.85f, 1f);
gl.glLineWidth(1);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, -2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, -2, 4);
gl.glEnd();
if (dragAndDrop.isDragActionRunning() && iMouseOverObjectID == iPoolLevelCommonID)
{
gl.glLineWidth(5);
gl.glColor4f(0.2f, 0.2f, 0.2f, 1);
}
else
{
gl.glLineWidth(1);
gl.glColor4f(0.4f, 0.4f, 0.4f, 1);
}
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, -2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, 2, 4);
gl.glVertex3f((-2 - fXCorrection) / fAspectRatio + fWidth, -2, 4);
gl.glEnd();
gl.glPopName();
// // Render memo pad background
// gl.glColor4f(0.85f, 0.85f, 0.85f, 1f);
// gl.glLineWidth(1);
// gl.glBegin(GL.GL_POLYGON);
// gl.glVertex3f(2 / fAspectRatio, -2, 4);
// gl.glVertex3f(2 / fAspectRatio, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, -2, 4);
// gl.glEnd();
//
// gl.glColor4f(0.4f, 0.4f, 0.4f, 1);
// gl.glLineWidth(1);
// gl.glBegin(GL.GL_LINE_LOOP);
// gl.glVertex3f(2 / fAspectRatio, -2, 4);
// gl.glVertex3f(2 / fAspectRatio, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, 2, 4);
// gl.glVertex3f(2 / fAspectRatio - fWidth, -2, 4);
// gl.glEnd();
}
// Render caption
if (textRenderer == null)
return;
String sTmp = "POOL AREA";
textRenderer.begin3DRendering();
textRenderer.setColor(0.6f, 0.6f, 0.6f, 1.0f);
textRenderer.draw3D(sTmp, (-1.9f - fXCorrection) / fAspectRatio, -1.97f, 4.001f,
0.003f);
textRenderer.end3DRendering();
}
public synchronized void enableGeneMapping(final boolean bEnableMapping)
{
for (GLEventListener tmpGLEventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (tmpGLEventListener instanceof GLPathway)
{
((GLPathway) tmpGLEventListener).enableGeneMapping(bEnableMapping);
}
}
}
public synchronized void enablePathwayTextures(final boolean bEnablePathwayTexture)
{
for (GLEventListener tmpGLEventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (tmpGLEventListener instanceof GLPathway)
{
((GLPathway) tmpGLEventListener).enablePathwayTextures(bEnablePathwayTexture);
}
}
}
public synchronized void enableNeighborhood(final boolean bEnableNeighborhood)
{
for (GLEventListener tmpGLEventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (tmpGLEventListener instanceof GLPathway)
{
((GLPathway) tmpGLEventListener).enableNeighborhood(bEnableNeighborhood);
}
}
}
@Override
public void triggerEvent(EMediatorType eMediatorType, IEventContainer eventContainer)
{
generalManager.getEventPublisher().triggerEvent(eMediatorType, this, eventContainer);
}
@Override
public synchronized void broadcastElements(EVAOperation type)
{
throw new IllegalStateException("Not Implemented");
}
private synchronized void initializeNewPathways(final GL gl)
{
// Init newly created pathways
// FIXME: this specialization to pathways in the bucket is not good!
if (!iAlUninitializedPathwayIDs.isEmpty() && arSlerpActions.isEmpty())
{
int iTmpPathwayID = iAlUninitializedPathwayIDs.get(0);
// Check if pathway is already loaded in bucket
if (!generalManager.getPathwayManager().isPathwayVisible(iTmpPathwayID))
{
ArrayList<Integer> iAlSetIDs = new ArrayList<Integer>();
for (ISet tmpSet : alSets)
{
if (tmpSet.getSetType() != ESetType.GENE_EXPRESSION_DATA)
continue;
iAlSetIDs.add(tmpSet.getID());
}
// Create Pathway3D view
CmdCreateGLPathway cmdPathway = (CmdCreateGLPathway) generalManager
.getCommandManager().createCommandByType(
ECommandType.CREATE_GL_PATHWAY_3D);
cmdPathway.setAttributes(iTmpPathwayID, iAlSetIDs,
EProjectionMode.ORTHOGRAPHIC, -4, 4, 4, -4, -20, 20);
cmdPathway.doCommand();
GLPathway glPathway = (GLPathway) cmdPathway.getCreatedObject();
int iGeneratedViewID = glPathway.getID();
GeneralManager.get().getEventPublisher().addSender(
EMediatorType.SELECTION_MEDIATOR, (IMediatorSender) glPathway);
GeneralManager.get().getEventPublisher().addReceiver(
EMediatorType.SELECTION_MEDIATOR, (IMediatorReceiver) glPathway);
iAlContainedViewIDs.add(iGeneratedViewID);
// Trigger last delta to new pathways
if (lastSelectionDelta != null)
triggerEvent(EMediatorType.SELECTION_MEDIATOR,
new DeltaEventContainer<ISelectionDelta>(lastSelectionDelta));
if (focusLevel.hasFreePosition())
{
spawnLevel.getElementByPositionIndex(0).setContainedElementID(
iGeneratedViewID);
SlerpAction slerpActionTransition = new SlerpAction(spawnLevel
.getElementByPositionIndex(0), focusLevel.getNextFree());
arSlerpActions.add(slerpActionTransition);
glPathway.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
glPathway.setDetailLevel(EDetailLevel.MEDIUM);
// Trigger initial gene propagation
glPathway.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
else if (stackLevel.hasFreePosition()
&& !(layoutRenderStyle instanceof ListLayoutRenderStyle))
{
spawnLevel.getElementByPositionIndex(0).setContainedElementID(
iGeneratedViewID);
SlerpAction slerpActionTransition = new SlerpAction(spawnLevel
.getElementByPositionIndex(0), stackLevel.getNextFree());
arSlerpActions.add(slerpActionTransition);
glPathway.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
glPathway.setDetailLevel(EDetailLevel.LOW);
// Trigger initial gene propagation
glPathway.broadcastElements(EVAOperation.APPEND_UNIQUE);
}
else if (poolLevel.hasFreePosition())
{
spawnLevel.getElementByPositionIndex(0).setContainedElementID(
iGeneratedViewID);
SlerpAction slerpActionTransition = new SlerpAction(spawnLevel
.getElementByPositionIndex(0), poolLevel.getNextFree());
arSlerpActions.add(slerpActionTransition);
glPathway.initRemote(gl, iUniqueID, pickingTriggerMouseAdapter, this);
glPathway.setDetailLevel(EDetailLevel.VERY_LOW);
}
else
{
generalManager.getLogger().log(Level.SEVERE,
"No empty space left to add new pathway!");
iAlUninitializedPathwayIDs.clear();
for (AGLEventListener eventListener : generalManager
.getViewGLCanvasManager().getAllGLEventListeners())
{
if (!eventListener.isRenderedRemote())
eventListener.enableBusyMode(false);
}
// Enable picking after all pathways are loaded
generalManager.getViewGLCanvasManager().getPickingManager().enablePicking(
true);
return;
}
}
else
{
generalManager.getLogger().log(Level.WARNING,
"Pathway with ID: " + iTmpPathwayID + " is already loaded in Bucket.");
}
iAlUninitializedPathwayIDs.remove(0);
if (iAlUninitializedPathwayIDs.isEmpty())
{
// Enable picking after all pathways are loaded
generalManager.getViewGLCanvasManager().getPickingManager()
.enablePicking(true);
for (AGLEventListener eventListener : generalManager.getViewGLCanvasManager()
.getAllGLEventListeners())
{
if (!eventListener.isRenderedRemote())
eventListener.enableBusyMode(false);
}
}
}
}
@Override
public void enableBusyMode(boolean busyMode)
{
super.enableBusyMode(busyMode);
if (eBusyModeState == EBusyModeState.ON)
{
// parentGLCanvas.removeMouseListener(pickingTriggerMouseAdapter);
parentGLCanvas.removeMouseWheelListener(bucketMouseWheelListener);
}
else
{
// parentGLCanvas.addMouseListener(pickingTriggerMouseAdapter);
parentGLCanvas.addMouseWheelListener(bucketMouseWheelListener);
}
}
@Override
public int getNumberOfSelections(ESelectionType eSelectionType)
{
return 0;
}
private void compactPoolLevel()
{
RemoteLevelElement element;
RemoteLevelElement elementInner;
for (int iIndex = 0; iIndex < poolLevel.getCapacity(); iIndex++)
{
element = poolLevel.getElementByPositionIndex(iIndex);
if (element.isFree())
{
// Search for next element to put it in the free position
for (int iInnerIndex = iIndex + 1; iInnerIndex < poolLevel.getCapacity(); iInnerIndex++)
{
elementInner = poolLevel.getElementByPositionIndex(iInnerIndex);
if (elementInner.isFree())
continue;
element.setContainedElementID(elementInner.getContainedElementID());
elementInner.setContainedElementID(-1);
break;
}
}
}
}
public ArrayList<Integer> getRemoteRenderedViews()
{
return iAlContainedViewIDs;
}
private void updateOffScreenTextures(final GL gl)
{
bUpdateOffScreenTextures = false;
gl.glPushMatrix();
int iViewWidth = parentGLCanvas.getWidth();
int iViewHeight = parentGLCanvas.getHeight();
if (stackLevel.getElementByPositionIndex(0).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(0)
.getContainedElementID(), 0, iViewWidth, iViewHeight);
}
if (stackLevel.getElementByPositionIndex(1).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(1)
.getContainedElementID(), 1, iViewWidth, iViewHeight);
}
if (stackLevel.getElementByPositionIndex(2).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(2)
.getContainedElementID(), 2, iViewWidth, iViewHeight);
}
if (stackLevel.getElementByPositionIndex(3).getContainedElementID() != -1)
{
glOffScreenRenderer.renderToTexture(gl, stackLevel.getElementByPositionIndex(3)
.getContainedElementID(), 3, iViewWidth, iViewHeight);
}
gl.glPopMatrix();
}
}
| Fixed pathway loading bug. Implementation used old DAVID updates.
git-svn-id: 149221363d454b9399d51e0b24a857a738336ca8@1739 1f7349ae-fd9f-0d40-aeb8-9798e6c0fce3
| org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/remote/GLRemoteRendering.java | Fixed pathway loading bug. Implementation used old DAVID updates. | <ide><path>rg.caleydo.core/src/org/caleydo/core/view/opengl/canvas/remote/GLRemoteRendering.java
<ide> import org.caleydo.core.data.graph.pathway.core.PathwayGraph;
<ide> import org.caleydo.core.data.graph.pathway.item.vertex.PathwayVertexGraphItem;
<ide> import org.caleydo.core.data.mapping.EIDType;
<add>import org.caleydo.core.data.mapping.EMappingType;
<ide> import org.caleydo.core.data.selection.DeltaEventContainer;
<ide> import org.caleydo.core.data.selection.ESelectionType;
<ide> import org.caleydo.core.data.selection.EVAOperation;
<ide> // take care here, if we ever use non integer ids this has to be
<ide> // cast to raw type first to determine the actual id data types
<ide> IDListEventContainer<Integer> idContainer = (IDListEventContainer<Integer>) eventContainer;
<del> if (idContainer.getIDType() == EIDType.DAVID)
<add> if (idContainer.getIDType() == EIDType.REFSEQ_MRNA_INT)
<ide> {
<del>
<ide> int iGraphItemID = 0;
<add> Integer iDavidID = -1;
<ide> ArrayList<ICaleydoGraphItem> alPathwayVertexGraphItem = new ArrayList<ICaleydoGraphItem>();
<ide>
<del> for (Integer iDavidID : idContainer.getIDs())
<add> for (Integer iRefSeqID : idContainer.getIDs())
<ide> {
<del>
<add> iDavidID = idMappingManager.getID(EMappingType.REFSEQ_MRNA_INT_2_DAVID, iRefSeqID);
<add>
<add> if (iDavidID == null || iDavidID == -1)
<add> throw new IllegalStateException("Cannot resolve RefSeq ID to David ID.");
<add>
<ide> iGraphItemID = generalManager.getPathwayItemManager()
<ide> .getPathwayVertexGraphItemIdByDavidId(iDavidID);
<ide> |
|
Java | apache-2.0 | f933d63e175a6c7a31273a2906333dd3e2d1092c | 0 | bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.core;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.lang.reflect.*;
/*
Copyright 2013-2017 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.
*/
/**
* A JSON parser.
* Not much to say. It can take a valid json string and generate a standing
* object that represents the document string, and also generate a string
* from such an object.
* @author Bo Zimmerman
*
*/
public class MiniJSON
{
private enum ObjectParseState
{
INITIAL, NEEDKEY, GOTKEY, NEEDOBJECT, GOTOBJECT
}
private enum NumberParseState
{
INITIAL, NEEDN0DIGIT, HAVEDIGIT, NEEDDOT, NEEDDOTDIGIT, HAVEDOTDIGIT, HAVEE, HAVEEDIGIT
}
private enum ArrayParseState
{
INITIAL, EXPECTOBJECT, NEEDOBJECT, GOTOBJECT
}
/**
* The official definition of "null" for a JSON object
*/
public static final Object NULL = new Object();
/**
* An official MiniJSON parsing exception. It means the document being parsed was malformed in some way.
* @author Bo Zimmerman
*/
public static class MJSONException extends Exception
{
private static final long serialVersionUID = -2651922052891126260L;
/**
* Constructs a new exception with the given parse error
* @param string the parse error
*/
public MJSONException(String string)
{
super(string);
}
/**
* Constructs a new exception with the given parse error, and underlying cause
* @param string the parse error
* @param e an underlying cause of the parse error
*/
public MJSONException(String string, Exception e)
{
super(string, e);
}
}
/**
* Given a normal string, this method will return a JSON-Safe
* string, which means escaped crlf, escaped tabs and backslashes, etc.
* @param value the unsafe string
* @return the JSON safe string
*/
public static String toJSONString(final String value)
{
final StringBuilder strBldr=new StringBuilder("");
for(final char c : value.toCharArray())
{
switch(c)
{
case '\"':
case '\\':
strBldr.append('\\').append(c);
break;
case '\b':
strBldr.append('\\').append('b');
break;
case '\f':
strBldr.append('\\').append('f');
break;
case '\n':
strBldr.append('\\').append('n');
break;
case '\r':
strBldr.append('\\').append('r');
break;
case '\t':
strBldr.append('\\').append('t');
break;
default:
strBldr.append(c);
break;
}
}
return strBldr.toString();
}
/**
* An official JSON object. Implemented as a Map, this class
* has numerous methods for accessing the internal keys and
* their mapped values in different ways, both raw, and checked.
* @author Bo Zimmerman
*/
public static class JSONObject extends TreeMap<String,Object>
{
private static final long serialVersionUID = 8390676973120915175L;
/**
* Internal method that returns a raw value object, or throws
* an exception if the key is not found
* @param key the key to look for
* @return the raw Object the key is mapped to
* @throws MJSONException the key was not found
*/
private Object getCheckedObject(String key) throws MJSONException
{
if(!containsKey(key))
throw new MJSONException("Key '"+key+"' not found");
return get(key);
}
/**
* Returns a JSONObject mapped in THIS object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the object
* @return the JSON Object mapped to by that key
* @throws MJSONException a missing key, or not a JSON Object
*/
public JSONObject getCheckedJSONObject(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof JSONObject))
throw new MJSONException("Key '"+key+"' is not a JSON object");
return (JSONObject)o;
}
/**
* Returns a JSON Array mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Array
* @return the JSON Array mapped to by that key
* @throws MJSONException a missing key, or not a JSON Array
*/
public Object[] getCheckedArray(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Object[]))
throw new MJSONException("Key '"+key+"' is not an array");
return (Object[])o;
}
/**
* Returns a String mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the String
* @return the String mapped to by that key
* @throws MJSONException a missing key, or not a String
*/
public String getCheckedString(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof String))
throw new MJSONException("Key '"+key+"' is not a String");
return (String)o;
}
/**
* Returns a Long mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the Long mapped to by that key
* @throws MJSONException a missing key, or not a Long
*/
public Long getCheckedLong(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Long))
throw new MJSONException("Key '"+key+"' is not a long");
return (Long)o;
}
/**
* Returns a Double mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the Double mapped to by that key
* @throws MJSONException a missing key, or not a Double
*/
public Double getCheckedDouble(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Double))
throw new MJSONException("Key '"+key+"' is not a double");
return (Double)o;
}
/**
* Returns a Boolean mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the Boolean mapped to by that key
* @throws MJSONException a missing key, or not a Boolean
*/
public Boolean getCheckedBoolean(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Boolean))
throw new MJSONException("Key '"+key+"' is not a boolean");
return (Boolean)o;
}
/**
* Returns a numeric value mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the double value of the number mapped to by that key
* @throws MJSONException a missing key, or not a numeric value
*/
public double getCheckedNumber(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(o instanceof Double)
return ((Double)o).doubleValue();
if(o instanceof Long)
return ((Long)o).doubleValue();
throw new MJSONException("Key '"+key+"' is not a number");
}
/**
* Checks this object for the given key, and checks if it
* is an official NULL or not.
* Throws an exception if the key is missing.
* @param key the key of the possible null
* @return true if the key maps to NULL or false otherwise
* @throws MJSONException the key was missing
*/
public boolean isCheckedNULL(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
return o == NULL;
}
/**
* Correctly appends the given thing to the given stringbuffer which
* is assumed to be in the middle of a JSON obect definition, right
* after the key and the colon:
* @param value the StringBuffer to append a value to
* @param obj the value to append -- a string, null, array, or number
*/
public static void appendJSONValue(final StringBuilder value, Object obj)
{
if(obj instanceof String)
{
value.append("\"").append(toJSONString((String)obj)).append("\"");
}
else
if(obj == NULL)
{
value.append("null");
}
else
if(obj instanceof Object[])
{
value.append("[");
final Object[] array=(Object[])obj;
for(int i=0; i<array.length; i++)
{
if(i>0)
value.append(",");
appendJSONValue(value, array[i]);
}
value.append("]");
}
else
if(obj != null)
{
value.append(obj.toString());
}
}
/**
* Returns a full JSON document representation of this JSON object
*/
@Override
public String toString()
{
final StringBuilder value = new StringBuilder("");
value.append("{");
for(final Iterator<String> k = keySet().iterator(); k.hasNext();)
{
final String keyVar = k.next();
value.append("\"").append(toJSONString(keyVar)).append("\":");
final Object obj = get(keyVar);
appendJSONValue(value, obj);
if(k.hasNext())
{
value.append(",");
}
}
value.append("}");
return value.toString();
}
public Object jsonDeepCopy(Object obj)
{
if(obj instanceof JSONObject)
return ((JSONObject)obj).copyOf();
else
if(obj.getClass().isArray())
{
final Object[] newArray = Arrays.copyOf((Object[])obj, ((Object[])obj).length);
for(int i=0;i<newArray.length;i++)
newArray[i] = jsonDeepCopy(newArray[i]);
return newArray;
}
else
return obj;
}
public JSONObject copyOf()
{
final JSONObject newObj = new JSONObject();
for(String key : this.keySet())
newObj.put(key, jsonDeepCopy(this.get(key)));
return newObj;
}
}
/**
* Parse either an Long, or Double object from the doc buffer
* @param doc the full JSON document
* @param index one dimensional array containing current index into the doc
* @return either an Long or a Double
* @throws MJSONException any parsing errors
*/
private Object parseNumber(char[] doc, int[] index) throws MJSONException
{
final int numStart = index[0];
NumberParseState state = NumberParseState.INITIAL;
while(index[0] < doc.length)
{
final char c=doc[index[0]];
switch(state)
{
case INITIAL:
if(c=='0')
state=NumberParseState.NEEDDOT;
else
if(c=='-')
state=NumberParseState.NEEDN0DIGIT;
else
if(Character.isDigit(c))
state=NumberParseState.HAVEDIGIT;
else
throw new MJSONException("Expected digit at "+index[0]);
break;
case NEEDN0DIGIT:
if(c=='0')
throw new MJSONException("Expected digit at "+index[0]);
else
if(Character.isDigit(c))
state=NumberParseState.HAVEDIGIT;
else
throw new MJSONException("Expected digit at "+index[0]);
break;
case HAVEDIGIT:
if(c=='.')
state=NumberParseState.NEEDDOTDIGIT;
else
if((c=='E')||(c=='e'))
state=NumberParseState.HAVEE;
else
if(Character.isDigit(c))
state=NumberParseState.HAVEDIGIT;
else
{
index[0]--;
return Long.valueOf(new String(doc,numStart,index[0]-numStart+1));
}
break;
case NEEDDOT:
if(c=='.')
state=NumberParseState.NEEDDOTDIGIT;
else
{
index[0]--;
return Long.valueOf(new String(doc,numStart,index[0]-numStart+1));
}
break;
case NEEDDOTDIGIT:
if(Character.isDigit(c))
state=NumberParseState.HAVEDOTDIGIT;
else
throw new MJSONException("Expected digit at "+index[0]);
break;
case HAVEDOTDIGIT:
if(Character.isDigit(c))
state=NumberParseState.HAVEDOTDIGIT;
else
if((c=='e')||(c=='E'))
state=NumberParseState.HAVEE;
else
{
index[0]--;
return Double.valueOf(new String(doc,numStart,index[0]-numStart+1));
}
break;
case HAVEE:
if(c=='0')
throw new MJSONException("Expected non-zero digit at "+index[0]);
else
if(Character.isDigit(c)||(c=='+')||(c=='-'))
state=NumberParseState.HAVEEDIGIT;
else
throw new MJSONException("Expected +- or non-zero digit at "+index[0]);
break;
case HAVEEDIGIT:
if(!Character.isDigit(c))
{
index[0]--;
return Double.valueOf(new BigDecimal(new String(doc,numStart,index[0]-numStart+1)).doubleValue());
}
break;
}
index[0]++;
}
throw new MJSONException("Unexpected end of number at"+index[0]);
}
/**
* Given a char array, and index into it, returns the byte value of the 1 hex
* digits at the indexed point of the char array.
* @param doc the json doc containing a hex number
* @param index the index into that json doc where the hex number begins
* @return the byte value of the 1 digit hex number
* @throws MJSONException a parse error meaning it wasn't a hex number at all
*/
private byte getByteFromHex(char[] doc, int index) throws MJSONException
{
final char c = doc[index];
if((c >= '0') && (c <= '9'))
return (byte)(c-'0');
if((c >= 'a') && (c <= 'f'))
return (byte)(10 + (c-'a'));
if((c >= 'A') && (c <= 'F'))
return (byte)(10 + (c-'A'));
throw new MJSONException("Illegal hex digit at "+index);
}
/**
* Given a json document char array, and an index into it, parses a string at
* the indexed point of the char array and returns its value.
* @param doc the json doc containing the string
* @param index the index into that json doc where the string begins
* @return the value of the found string
* @throws MJSONException a parse exception, meaning no string was there
*/
private String parseString(char[] doc, int[] index) throws MJSONException
{
final StringBuilder value=new StringBuilder("");
if(doc[index[0]]!='\"')
{
throw new MJSONException("Expectged quote at: "+doc[index[0]]);
}
index[0]++;
while(index[0] < doc.length)
{
final char c=doc[index[0]];
if(c=='\"')
return value.toString();
else
if(c=='\\')
{
if(index[0] == doc.length-1)
throw new MJSONException("Unfinished escape");
index[0]++;
switch(doc[index[0]])
{
case '\"':
case '\\':
case '/':
value.append(doc[index[0]]);
break;
case 'b':
value.append('\b');
break;
case 'f':
value.append('\f');
break;
case 'n':
value.append('\n');
break;
case 'r':
value.append('\r');
break;
case 't':
value.append('\t');
break;
case 'u':
{
if(index[0] >= doc.length-5)
throw new MJSONException("Unfinished unicode escape at "+index[0]);
final byte[] hexBuf=new byte[4];
hexBuf[0] = getByteFromHex(doc,++index[0]);
hexBuf[1] = getByteFromHex(doc,++index[0]);
hexBuf[2] = getByteFromHex(doc,++index[0]);
hexBuf[3] = getByteFromHex(doc,++index[0]);
try
{
value.append(new String(hexBuf, "Cp1251"));
}
catch (final UnsupportedEncodingException e)
{
throw new MJSONException("Illegal character at"+index[0],e);
}
break;
}
default:
throw new MJSONException("Illegal escape character: "+doc[index[0]]);
}
}
else
value.append(c);
index[0]++;
}
throw new MJSONException("Unfinished string at "+index[0]);
}
/**
* Given a json document char array, and an index into it, parses an array at
* the indexed point of the char array and returns its value object.
* @param doc the json doc containing the array
* @param index the index into that json doc where the array begins
* @return the value object of the found array
* @throws MJSONException a parse exception, meaning no array was there
*/
private Object[] parseArray(char[] doc, int[] index) throws MJSONException
{
ArrayParseState state=ArrayParseState.INITIAL;
final List<Object> finalSet=new ArrayList<Object>();
while(index[0] < doc.length)
{
final char c=doc[index[0]];
if(!Character.isWhitespace(c))
{
switch(state)
{
case INITIAL:
if(c=='[')
state = ArrayParseState.NEEDOBJECT;
else
throw new MJSONException("Expected String at "+index[0]);
break;
case EXPECTOBJECT:
finalSet.add(parseElement(doc,index));
state = ArrayParseState.GOTOBJECT;
break;
case NEEDOBJECT:
if(c==']')
return finalSet.toArray(new Object[0]);
else
{
finalSet.add(parseElement(doc,index));
state = ArrayParseState.GOTOBJECT;
}
break;
case GOTOBJECT:
if(c==']')
return finalSet.toArray(new Object[0]);
else
if(c==',')
state = ArrayParseState.EXPECTOBJECT;
else
throw new MJSONException("Expected ] or , at "+index[0]);
break;
}
}
index[0]++;
}
throw new MJSONException("Expected ] at "+index[0]);
}
/**
* Given a json document char array, and an index into it, parses a value object at
* the indexed point of the char array and returns its value object. A value object
* may be anything from a string, array, a JSON object, boolean, null, or a number.
* @param doc the json doc containing the value
* @param index the index into that json doc where the value begins
* @return the value object of the found value
* @throws MJSONException a parse exception, meaning no recognized value was there
*/
private Object parseElement(char[] doc, int[] index) throws MJSONException
{
switch(doc[index[0]])
{
case '\"':
return parseString(doc,index);
case '[':
return parseArray(doc,index);
case '{':
return parseObject(doc,index);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return parseNumber(doc,index);
case 't':
if((index[0] < doc.length-5) && (new String(doc,index[0],4).equals("true")))
{
index[0]+=3;
return Boolean.TRUE;
}
throw new MJSONException("Invalid true at "+index[0]);
case 'f':
if((index[0] < doc.length-6) && (new String(doc,index[0],5).equals("false")))
{
index[0]+=4;
return Boolean.FALSE;
}
throw new MJSONException("Invalid false at "+index[0]);
case 'n':
if((index[0] < doc.length-5) && (new String(doc,index[0],4).equals("null")))
{
index[0]+=3;
return NULL;
}
throw new MJSONException("Invalid null at "+index[0]);
default:
throw new MJSONException("Unknown character at "+index[0]);
}
}
/**
* Given a json document char array, and an index into it, parses a JSON object at
* the indexed point of the char array and returns it as a mapped JSON object.
* @param doc the json doc containing the JSON object
* @param index the index into that json doc where the JSON object begins
* @return the value object of the found JSON object
* @throws MJSONException a parse exception, meaning no JSON object was there
*/
private JSONObject parseObject(char[] doc, int[] index) throws MJSONException
{
final JSONObject map = new JSONObject();
String key = null;
ObjectParseState state = ObjectParseState.INITIAL;
while(index[0] < doc.length)
{
final char c=doc[index[0]];
if(!Character.isWhitespace(c))
{
switch(state)
{
case INITIAL:
if(c=='{')
state = ObjectParseState.NEEDKEY;
else
throw new MJSONException("Expected Key/String at "+index[0]);
break;
case NEEDKEY:
if(c=='\"')
{
key = parseString(doc,index);
state = ObjectParseState.GOTKEY;
}
else
if(c=='}')
return map;
else
throw new MJSONException("Expected Key/String at "+index[0]);
break;
case GOTKEY:
if(c==':')
state = ObjectParseState.NEEDOBJECT;
else
throw new MJSONException("Expected Colon at "+index[0]);
break;
case NEEDOBJECT:
map.put(key, parseElement(doc,index));
state = ObjectParseState.GOTOBJECT;
break;
case GOTOBJECT:
if(c==',')
state = ObjectParseState.NEEDKEY;
else
if(c=='}')
return map;
else
throw new MJSONException("Expected } or , at "+index[0]);
break;
}
}
index[0]++;
}
throw new MJSONException("Expected } at "+index[0]);
}
/**
* Given a string containing a JSON object, this method will parse it
* into a mapped JSONObject object recursively.
* @param doc the JSON document that contains a top-level JSON object
* @return the JSON object at the top level
* @throws MJSONException the parse error
*/
public JSONObject parseObject(String doc) throws MJSONException
{
try
{
return parseObject(doc.toCharArray(), new int[]{0});
}
catch (final MJSONException e)
{
throw e;
}
catch (final Exception e)
{
throw new MJSONException("Internal error",e);
}
}
/**
* Converts a pojo field to a JSON value.
* @param type the class type
* @param val the value
* @return the json value
*/
public String fromPOJOFieldtoJSON(Class<?> type, Object val)
{
final StringBuilder str=new StringBuilder("");
if(val==null)
str.append("null");
else
if(type.isArray())
{
str.append("[");
final int length = Array.getLength(val);
for (int i=0; i<length; i++)
{
Object e = Array.get(val, i);
if(i>0)
str.append(",");
str.append(fromPOJOFieldtoJSON(type.getComponentType(),e));
}
str.append("]");
}
else
if(type == String.class)
str.append("\"").append(toJSONString(val.toString())).append("\"");
else
if(type.isPrimitive())
str.append(val.toString());
else
if((type == Float.class)||(type==Integer.class)||(type==Double.class)||(type==Boolean.class)||(type==Long.class))
str.append(val.toString());
else
str.append(fromPOJOtoJSON(val));
return str.toString();
}
/**
* Converts a pojo object to a JSON document.
* @param o the object to convert
* @return the json document
*/
public String fromPOJOtoJSON(Object o)
{
StringBuilder str=new StringBuilder("");
str.append("{");
final Field[] fields = o.getClass().getDeclaredFields();
boolean firstField=true;
for(final Field field : fields)
{
try
{
field.setAccessible(true);
if(field.isAccessible())
{
if(!firstField)
str.append(",");
else
firstField=false;
str.append("\"").append(field.getName()).append("\":");
str.append(fromPOJOFieldtoJSON(field.getType(),field.get(o)));
}
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
}
str.append("}");
return str.toString();
}
/**
* Converts a JSON document to a pojo object.
* @param json the json document
* @param o the object to convert
*/
public void fromJSONtoPOJO(String json, Object o) throws MJSONException
{
fromJSONtoPOJO(parseObject(json),o);
}
/**
* Converts a json object to a pojo object.
* @param jsonObj the json object
* @param o the object to convert
*/
public void fromJSONtoPOJO(MiniJSON.JSONObject jsonObj, Object o) throws MJSONException
{
final Field[] fields = o.getClass().getDeclaredFields();
for(final Field field : fields)
{
try
{
field.setAccessible(true);
if(field.isAccessible() && jsonObj.containsKey(field.getName()))
{
Object jo = jsonObj.get(field.getName());
if((jo == null) || (jo == MiniJSON.NULL))
field.set(o, null);
else
if(field.getType().isArray() && (jo instanceof Object[]))
{
final Object[] objs = (Object[])jo;
final Object tgt;
final Class<?> cType = field.getType().getComponentType();
tgt = Array.newInstance(cType, objs.length);
for(int i=0;i<objs.length;i++)
{
if(objs[i].getClass() == cType)
Array.set(tgt, i, objs[i]);
else
if((cType == Float.class)&&(objs[i] instanceof Double))
Array.set(tgt, i, Float.valueOf(((Double)objs[i]).floatValue()));
else
if((cType == Integer.class)&&(objs[i] instanceof Long))
Array.set(tgt, i, Integer.valueOf(((Long)objs[i]).intValue()));
else
if(cType.isPrimitive())
{
if(cType == boolean.class)
Array.setBoolean(tgt, i, Boolean.valueOf(objs[i].toString()).booleanValue());
else
if(cType == int.class)
Array.setInt(tgt, i, Long.valueOf(objs[i].toString()).intValue());
else
if(cType == short.class)
Array.setShort(tgt, i, Long.valueOf(objs[i].toString()).shortValue());
else
if(cType == byte.class)
Array.setByte(tgt, i, Long.valueOf(objs[i].toString()).byteValue());
else
if(cType == long.class)
Array.setLong(tgt, i, Long.valueOf(objs[i].toString()).longValue());
else
if(cType == float.class)
Array.setFloat(tgt, i, Double.valueOf(objs[i].toString()).floatValue());
else
if(cType == double.class)
Array.setDouble(tgt, i, Double.valueOf(objs[i].toString()).doubleValue());
}
else
if(objs[i] instanceof JSONObject)
{
Object newObj = cType.newInstance();
fromJSONtoPOJO((JSONObject)objs[i], newObj);
Array.set(tgt, i, newObj);
}
}
field.set(o, tgt);
}
else
if((field.getType() == String.class)&&(jo instanceof String))
field.set(o, jo);
else
if(field.getType().isPrimitive())
{
final Class<?> cType=field.getType();
if(cType == boolean.class)
field.setBoolean(o, Boolean.valueOf(jo.toString()).booleanValue());
else
if(cType == int.class)
field.setInt(o, Long.valueOf(jo.toString()).intValue());
else
if(cType == short.class)
field.setShort(o, Long.valueOf(jo.toString()).shortValue());
else
if(cType == byte.class)
field.setByte(o, Long.valueOf(jo.toString()).byteValue());
else
if(cType == long.class)
field.setLong(o, Long.valueOf(jo.toString()).longValue());
else
if(cType == float.class)
field.setFloat(o, Double.valueOf(jo.toString()).floatValue());
else
if(cType == double.class)
field.setDouble(o, Double.valueOf(jo.toString()).doubleValue());
else
field.set(o, jo);
}
else
if(jo instanceof JSONObject)
{
Object newObj = field.getType().newInstance();
fromJSONtoPOJO((JSONObject)jo, newObj);
field.set(o, newObj);
}
else
if((field.getType() == Integer.class)&&(jo instanceof Long))
field.set(o, Integer.valueOf(((Long)jo).intValue()));
else
if((field.getType() == Short.class)&&(jo instanceof Long))
field.set(o, Short.valueOf(((Long)jo).shortValue()));
else
if((field.getType() == Byte.class)&&(jo instanceof Long))
field.set(o, Byte.valueOf(((Long)jo).byteValue()));
else
if((field.getType() == Long.class)&&(jo instanceof Long))
field.set(o, Long.valueOf(((Long)jo).longValue()));
else
if((field.getType() == Double.class)&&(jo instanceof Double))
field.set(o, Double.valueOf(((Double)jo).doubleValue()));
else
if((field.getType() == Float.class)&&(jo instanceof Double))
field.set(o, Float.valueOf(((Double)jo).floatValue()));
else
if((field.getType() == Boolean.class)&&(jo instanceof Boolean))
field.set(o, Boolean.valueOf(((Boolean)jo).booleanValue()));
else
field.set(o, jo);
}
}
catch (IllegalArgumentException e)
{
throw new MJSONException(e.getMessage(),e);
}
catch (IllegalAccessException e)
{
throw new MJSONException(e.getMessage(),e);
}
catch (InstantiationException e)
{
throw new MJSONException(e.getMessage(),e);
}
}
}
}
| com/planet_ink/coffee_mud/core/MiniJSON.java | package com.planet_ink.coffee_mud.core;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.lang.reflect.*;
/*
Copyright 2013-2017 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.
*/
/**
* A JSON parser.
* Not much to say. It can take a valid json string and generate a standing
* object that represents the document string, and also generate a string
* from such an object.
* @author Bo Zimmerman
*
*/
public class MiniJSON
{
private enum ObjectParseState
{
INITIAL, NEEDKEY, GOTKEY, NEEDOBJECT, GOTOBJECT
}
private enum NumberParseState
{
INITIAL, NEEDN0DIGIT, HAVEDIGIT, NEEDDOT, NEEDDOTDIGIT, HAVEDOTDIGIT, HAVEE, HAVEEDIGIT
}
private enum ArrayParseState
{
INITIAL, EXPECTOBJECT, NEEDOBJECT, GOTOBJECT
}
/**
* The official definition of "null" for a JSON object
*/
public static final Object NULL = new Object();
/**
* An official MiniJSON parsing exception. It means the document being parsed was malformed in some way.
* @author Bo Zimmerman
*/
public static class MJSONException extends Exception
{
private static final long serialVersionUID = -2651922052891126260L;
/**
* Constructs a new exception with the given parse error
* @param string the parse error
*/
public MJSONException(String string)
{
super(string);
}
/**
* Constructs a new exception with the given parse error, and underlying cause
* @param string the parse error
* @param e an underlying cause of the parse error
*/
public MJSONException(String string, Exception e)
{
super(string, e);
}
}
/**
* Given a normal string, this method will return a JSON-Safe
* string, which means escaped crlf, escaped tabs and backslashes, etc.
* @param value the unsafe string
* @return the JSON safe string
*/
public static String toJSONString(final String value)
{
final StringBuilder strBldr=new StringBuilder("");
for(final char c : value.toCharArray())
{
switch(c)
{
case '\"':
case '\\':
strBldr.append('\\').append(c);
break;
case '\b':
strBldr.append('\\').append('b');
break;
case '\f':
strBldr.append('\\').append('f');
break;
case '\n':
strBldr.append('\\').append('n');
break;
case '\r':
strBldr.append('\\').append('r');
break;
case '\t':
strBldr.append('\\').append('t');
break;
default:
strBldr.append(c);
break;
}
}
return strBldr.toString();
}
/**
* An official JSON object. Implemented as a Map, this class
* has numerous methods for accessing the internal keys and
* their mapped values in different ways, both raw, and checked.
* @author Bo Zimmerman
*/
public static class JSONObject extends TreeMap<String,Object>
{
private static final long serialVersionUID = 8390676973120915175L;
/**
* Internal method that returns a raw value object, or throws
* an exception if the key is not found
* @param key the key to look for
* @return the raw Object the key is mapped to
* @throws MJSONException the key was not found
*/
private Object getCheckedObject(String key) throws MJSONException
{
if(!containsKey(key))
throw new MJSONException("Key '"+key+"' not found");
return get(key);
}
/**
* Returns a JSONObject mapped in THIS object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the object
* @return the JSON Object mapped to by that key
* @throws MJSONException a missing key, or not a JSON Object
*/
public JSONObject getCheckedJSONObject(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof JSONObject))
throw new MJSONException("Key '"+key+"' is not a JSON object");
return (JSONObject)o;
}
/**
* Returns a JSON Array mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Array
* @return the JSON Array mapped to by that key
* @throws MJSONException a missing key, or not a JSON Array
*/
public Object[] getCheckedArray(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Object[]))
throw new MJSONException("Key '"+key+"' is not an array");
return (Object[])o;
}
/**
* Returns a String mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the String
* @return the String mapped to by that key
* @throws MJSONException a missing key, or not a String
*/
public String getCheckedString(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof String))
throw new MJSONException("Key '"+key+"' is not a String");
return (String)o;
}
/**
* Returns a Long mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the Long mapped to by that key
* @throws MJSONException a missing key, or not a Long
*/
public Long getCheckedLong(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Long))
throw new MJSONException("Key '"+key+"' is not a long");
return (Long)o;
}
/**
* Returns a Double mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the Double mapped to by that key
* @throws MJSONException a missing key, or not a Double
*/
public Double getCheckedDouble(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Double))
throw new MJSONException("Key '"+key+"' is not a double");
return (Double)o;
}
/**
* Returns a Boolean mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the Boolean mapped to by that key
* @throws MJSONException a missing key, or not a Boolean
*/
public Boolean getCheckedBoolean(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(!(o instanceof Boolean))
throw new MJSONException("Key '"+key+"' is not a boolean");
return (Boolean)o;
}
/**
* Returns a numeric value mapped in this object by the given key.
* Throws an exception if anything goes wrong.
* @param key the key of the Long
* @return the double value of the number mapped to by that key
* @throws MJSONException a missing key, or not a numeric value
*/
public double getCheckedNumber(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
if(o instanceof Double)
return ((Double)o).doubleValue();
if(o instanceof Long)
return ((Long)o).doubleValue();
throw new MJSONException("Key '"+key+"' is not a number");
}
/**
* Checks this object for the given key, and checks if it
* is an official NULL or not.
* Throws an exception if the key is missing.
* @param key the key of the possible null
* @return true if the key maps to NULL or false otherwise
* @throws MJSONException the key was missing
*/
public boolean isCheckedNULL(String key) throws MJSONException
{
final Object o = getCheckedObject(key);
return o == NULL;
}
/**
* Correctly appends the given thing to the given stringbuffer which
* is assumed to be in the middle of a JSON obect definition, right
* after the key and the colon:
* @param value the StringBuffer to append a value to
* @param obj the value to append -- a string, null, array, or number
*/
public static void appendJSONValue(final StringBuilder value, Object obj)
{
if(obj instanceof String)
{
value.append("\"").append(toJSONString((String)obj)).append("\"");
}
else
if(obj == NULL)
{
value.append("null");
}
else
if(obj instanceof Object[])
{
value.append("[");
final Object[] array=(Object[])obj;
for(int i=0; i<array.length; i++)
{
if(i>0)
value.append(",");
appendJSONValue(value, array[i]);
}
value.append("]");
}
else
if(obj != null)
{
value.append(obj.toString());
}
}
/**
* Returns a full JSON document representation of this JSON object
*/
@Override
public String toString()
{
final StringBuilder value = new StringBuilder("");
value.append("{");
for(final Iterator<String> k = keySet().iterator(); k.hasNext();)
{
final String keyVar = k.next();
value.append("\"").append(toJSONString(keyVar)).append("\":");
final Object obj = get(keyVar);
appendJSONValue(value, obj);
if(k.hasNext())
{
value.append(",");
}
}
value.append("}");
return value.toString();
}
public Object jsonDeepCopy(Object obj)
{
if(obj instanceof JSONObject)
return ((JSONObject)obj).copyOf();
else
if(obj.getClass().isArray())
{
final Object[] newArray = Arrays.copyOf((Object[])obj, ((Object[])obj).length);
for(int i=0;i<newArray.length;i++)
newArray[i] = jsonDeepCopy(newArray[i]);
return newArray;
}
else
return obj;
}
public JSONObject copyOf()
{
final JSONObject newObj = new JSONObject();
for(String key : this.keySet())
newObj.put(key, jsonDeepCopy(this.get(key)));
return newObj;
}
}
/**
* Parse either an Long, or Double object from the doc buffer
* @param doc the full JSON document
* @param index one dimensional array containing current index into the doc
* @return either an Long or a Double
* @throws MJSONException any parsing errors
*/
private Object parseNumber(char[] doc, int[] index) throws MJSONException
{
final int numStart = index[0];
NumberParseState state = NumberParseState.INITIAL;
while(index[0] < doc.length)
{
final char c=doc[index[0]];
switch(state)
{
case INITIAL:
if(c=='0')
state=NumberParseState.NEEDDOT;
else
if(c=='-')
state=NumberParseState.NEEDN0DIGIT;
else
if(Character.isDigit(c))
state=NumberParseState.HAVEDIGIT;
else
throw new MJSONException("Expected digit at "+index[0]);
break;
case NEEDN0DIGIT:
if(c=='0')
throw new MJSONException("Expected digit at "+index[0]);
else
if(Character.isDigit(c))
state=NumberParseState.HAVEDIGIT;
else
throw new MJSONException("Expected digit at "+index[0]);
break;
case HAVEDIGIT:
if(c=='.')
state=NumberParseState.NEEDDOTDIGIT;
else
if((c=='E')||(c=='e'))
state=NumberParseState.HAVEE;
else
if(Character.isDigit(c))
state=NumberParseState.HAVEDIGIT;
else
{
index[0]--;
return Long.valueOf(new String(doc,numStart,index[0]-numStart+1));
}
break;
case NEEDDOT:
if(c=='.')
state=NumberParseState.NEEDDOTDIGIT;
else
{
index[0]--;
return Long.valueOf(new String(doc,numStart,index[0]-numStart+1));
}
break;
case NEEDDOTDIGIT:
if(Character.isDigit(c))
state=NumberParseState.HAVEDOTDIGIT;
else
throw new MJSONException("Expected digit at "+index[0]);
break;
case HAVEDOTDIGIT:
if(Character.isDigit(c))
state=NumberParseState.HAVEDOTDIGIT;
else
if((c=='e')||(c=='E'))
state=NumberParseState.HAVEE;
else
{
index[0]--;
return Double.valueOf(new String(doc,numStart,index[0]-numStart+1));
}
break;
case HAVEE:
if(c=='0')
throw new MJSONException("Expected non-zero digit at "+index[0]);
else
if(Character.isDigit(c)||(c=='+')||(c=='-'))
state=NumberParseState.HAVEEDIGIT;
else
throw new MJSONException("Expected +- or non-zero digit at "+index[0]);
break;
case HAVEEDIGIT:
if(!Character.isDigit(c))
{
index[0]--;
return Double.valueOf(new BigDecimal(new String(doc,numStart,index[0]-numStart+1)).doubleValue());
}
break;
}
index[0]++;
}
throw new MJSONException("Unexpected end of number at"+index[0]);
}
/**
* Given a char array, and index into it, returns the byte value of the 1 hex
* digits at the indexed point of the char array.
* @param doc the json doc containing a hex number
* @param index the index into that json doc where the hex number begins
* @return the byte value of the 1 digit hex number
* @throws MJSONException a parse error meaning it wasn't a hex number at all
*/
private byte getByteFromHex(char[] doc, int index) throws MJSONException
{
final char c = doc[index];
if((c >= '0') && (c <= '9'))
return (byte)(c-'0');
if((c >= 'a') && (c <= 'f'))
return (byte)(10 + (c-'a'));
if((c >= 'A') && (c <= 'F'))
return (byte)(10 + (c-'A'));
throw new MJSONException("Illegal hex digit at "+index);
}
/**
* Given a json document char array, and an index into it, parses a string at
* the indexed point of the char array and returns its value.
* @param doc the json doc containing the string
* @param index the index into that json doc where the string begins
* @return the value of the found string
* @throws MJSONException a parse exception, meaning no string was there
*/
private String parseString(char[] doc, int[] index) throws MJSONException
{
final StringBuilder value=new StringBuilder("");
if(doc[index[0]]!='\"')
{
throw new MJSONException("Expectged quote at: "+doc[index[0]]);
}
index[0]++;
while(index[0] < doc.length)
{
final char c=doc[index[0]];
if(c=='\"')
return value.toString();
else
if(c=='\\')
{
if(index[0] == doc.length-1)
throw new MJSONException("Unfinished escape");
index[0]++;
switch(doc[index[0]])
{
case '\"':
case '\\':
case '/':
value.append(doc[index[0]]);
break;
case 'b':
value.append('\b');
break;
case 'f':
value.append('\f');
break;
case 'n':
value.append('\n');
break;
case 'r':
value.append('\r');
break;
case 't':
value.append('\t');
break;
case 'u':
{
if(index[0] >= doc.length-5)
throw new MJSONException("Unfinished unicode escape at "+index[0]);
final byte[] hexBuf=new byte[4];
hexBuf[0] = getByteFromHex(doc,++index[0]);
hexBuf[1] = getByteFromHex(doc,++index[0]);
hexBuf[2] = getByteFromHex(doc,++index[0]);
hexBuf[3] = getByteFromHex(doc,++index[0]);
try
{
value.append(new String(hexBuf, "Cp1251"));
}
catch (final UnsupportedEncodingException e)
{
throw new MJSONException("Illegal character at"+index[0],e);
}
break;
}
default:
throw new MJSONException("Illegal escape character: "+doc[index[0]]);
}
}
else
value.append(c);
index[0]++;
}
throw new MJSONException("Unfinished string at "+index[0]);
}
/**
* Given a json document char array, and an index into it, parses an array at
* the indexed point of the char array and returns its value object.
* @param doc the json doc containing the array
* @param index the index into that json doc where the array begins
* @return the value object of the found array
* @throws MJSONException a parse exception, meaning no array was there
*/
private Object[] parseArray(char[] doc, int[] index) throws MJSONException
{
ArrayParseState state=ArrayParseState.INITIAL;
final List<Object> finalSet=new ArrayList<Object>();
while(index[0] < doc.length)
{
final char c=doc[index[0]];
if(!Character.isWhitespace(c))
{
switch(state)
{
case INITIAL:
if(c=='[')
state = ArrayParseState.NEEDOBJECT;
else
throw new MJSONException("Expected String at "+index[0]);
break;
case EXPECTOBJECT:
finalSet.add(parseElement(doc,index));
state = ArrayParseState.GOTOBJECT;
break;
case NEEDOBJECT:
if(c==']')
return finalSet.toArray(new Object[0]);
else
{
finalSet.add(parseElement(doc,index));
state = ArrayParseState.GOTOBJECT;
}
break;
case GOTOBJECT:
if(c==']')
return finalSet.toArray(new Object[0]);
else
if(c==',')
state = ArrayParseState.EXPECTOBJECT;
else
throw new MJSONException("Expected ] or , at "+index[0]);
break;
}
}
index[0]++;
}
throw new MJSONException("Expected ] at "+index[0]);
}
/**
* Given a json document char array, and an index into it, parses a value object at
* the indexed point of the char array and returns its value object. A value object
* may be anything from a string, array, a JSON object, boolean, null, or a number.
* @param doc the json doc containing the value
* @param index the index into that json doc where the value begins
* @return the value object of the found value
* @throws MJSONException a parse exception, meaning no recognized value was there
*/
private Object parseElement(char[] doc, int[] index) throws MJSONException
{
switch(doc[index[0]])
{
case '\"':
return parseString(doc,index);
case '[':
return parseArray(doc,index);
case '{':
return parseObject(doc,index);
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return parseNumber(doc,index);
case 't':
if((index[0] < doc.length-5) && (new String(doc,index[0],4).equals("true")))
{
index[0]+=3;
return Boolean.TRUE;
}
throw new MJSONException("Invalid true at "+index[0]);
case 'f':
if((index[0] < doc.length-6) && (new String(doc,index[0],5).equals("false")))
{
index[0]+=4;
return Boolean.FALSE;
}
throw new MJSONException("Invalid false at "+index[0]);
case 'n':
if((index[0] < doc.length-5) && (new String(doc,index[0],4).equals("null")))
{
index[0]+=3;
return NULL;
}
throw new MJSONException("Invalid null at "+index[0]);
default:
throw new MJSONException("Unknown character at "+index[0]);
}
}
/**
* Given a json document char array, and an index into it, parses a JSON object at
* the indexed point of the char array and returns it as a mapped JSON object.
* @param doc the json doc containing the JSON object
* @param index the index into that json doc where the JSON object begins
* @return the value object of the found JSON object
* @throws MJSONException a parse exception, meaning no JSON object was there
*/
private JSONObject parseObject(char[] doc, int[] index) throws MJSONException
{
final JSONObject map = new JSONObject();
String key = null;
ObjectParseState state = ObjectParseState.INITIAL;
while(index[0] < doc.length)
{
final char c=doc[index[0]];
if(!Character.isWhitespace(c))
{
switch(state)
{
case INITIAL:
if(c=='{')
state = ObjectParseState.NEEDKEY;
else
throw new MJSONException("Expected Key/String at "+index[0]);
break;
case NEEDKEY:
if(c=='\"')
{
key = parseString(doc,index);
state = ObjectParseState.GOTKEY;
}
else
if(c=='}')
return map;
else
throw new MJSONException("Expected Key/String at "+index[0]);
break;
case GOTKEY:
if(c==':')
state = ObjectParseState.NEEDOBJECT;
else
throw new MJSONException("Expected Colon at "+index[0]);
break;
case NEEDOBJECT:
map.put(key, parseElement(doc,index));
state = ObjectParseState.GOTOBJECT;
break;
case GOTOBJECT:
if(c==',')
state = ObjectParseState.NEEDKEY;
else
if(c=='}')
return map;
else
throw new MJSONException("Expected } or , at "+index[0]);
break;
}
}
index[0]++;
}
throw new MJSONException("Expected } at "+index[0]);
}
/**
* Given a string containing a JSON object, this method will parse it
* into a mapped JSONObject object recursively.
* @param doc the JSON document that contains a top-level JSON object
* @return the JSON object at the top level
* @throws MJSONException the parse error
*/
public JSONObject parseObject(String doc) throws MJSONException
{
try
{
return parseObject(doc.toCharArray(), new int[]{0});
}
catch (final MJSONException e)
{
throw e;
}
catch (final Exception e)
{
throw new MJSONException("Internal error",e);
}
}
/**
* Converts a pojo field to a JSON value.
* @param type the class type
* @param val the value
* @return the json value
*/
public String fromPOJOFieldtoJSON(Class<?> type, Object val)
{
final StringBuilder str=new StringBuilder("");
if(val==null)
str.append("null");
else
if(type.isArray())
{
str.append("[");
final int length = Array.getLength(val);
for (int i=0; i<length; i++)
{
Object e = Array.get(val, i);
if(i>0)
str.append(",");
str.append(fromPOJOFieldtoJSON(type.getComponentType(),e));
}
str.append("]");
}
else
if(type == String.class)
str.append("\"").append(toJSONString(val.toString())).append("\"");
else
if(type.isPrimitive())
str.append(val.toString());
else
if((type == Float.class)||(type==Integer.class)||(type==Double.class)||(type==Boolean.class)||(type==Long.class))
str.append(val.toString());
else
str.append(fromPOJOtoJSON(val));
return str.toString();
}
/**
* Converts a pojo object to a JSON document.
* @param o the object to convert
* @return the json document
*/
public String fromPOJOtoJSON(Object o)
{
StringBuilder str=new StringBuilder("");
str.append("{");
final Field[] fields = o.getClass().getDeclaredFields();
boolean firstField=true;
for(final Field field : fields)
{
try
{
field.setAccessible(true);
if(field.isAccessible())
{
if(!firstField)
str.append(",");
else
firstField=false;
str.append("\"").append(field.getName()).append("\":");
str.append(fromPOJOFieldtoJSON(field.getType(),field.get(o)));
}
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
}
str.append("}");
return str.toString();
}
/**
* Converts a JSON document to a pojo object.
* @param json the json document
* @param o the object to convert
*/
public void fromJSONtoPOJO(String json, Object o) throws MJSONException
{
fromJSONtoPOJO(parseObject(json),o);
}
/**
* Converts a json object to a pojo object.
* @param jsonObj the json object
* @param o the object to convert
*/
public void fromJSONtoPOJO(MiniJSON.JSONObject jsonObj, Object o) throws MJSONException
{
final Field[] fields = o.getClass().getDeclaredFields();
for(final Field field : fields)
{
try
{
field.setAccessible(true);
if(field.isAccessible() && jsonObj.containsKey(field.getName()))
{
Object jo = jsonObj.get(field.getName());
if((jo == null) || (jo == MiniJSON.NULL))
field.set(o, null);
else
if(field.getType().isArray() && (jo instanceof Object[]))
{
final Object[] objs = (Object[])jo;
final Object tgt;
final Class<?> cType = field.getType().getComponentType();
tgt = Array.newInstance(cType, objs.length);
for(int i=0;i<objs.length;i++)
{
if(objs[i].getClass() == cType)
Array.set(tgt, i, objs[i]);
else
if((cType == Float.class)&&(objs[i] instanceof Double))
Array.set(tgt, i, Float.valueOf(((Double)objs[i]).floatValue()));
else
if((cType == Integer.class)&&(objs[i] instanceof Long))
Array.set(tgt, i, Integer.valueOf(((Long)objs[i]).intValue()));
else
if(cType.isPrimitive())
{
if(cType == boolean.class)
Array.setBoolean(tgt, i, Boolean.valueOf(objs[i].toString()).booleanValue());
else
if(cType == int.class)
Array.setInt(tgt, i, Long.valueOf(objs[i].toString()).intValue());
else
if(cType == short.class)
Array.setShort(tgt, i, Long.valueOf(objs[i].toString()).shortValue());
else
if(cType == byte.class)
Array.setByte(tgt, i, Long.valueOf(objs[i].toString()).byteValue());
else
if(cType == long.class)
Array.setLong(tgt, i, Long.valueOf(objs[i].toString()).longValue());
else
if(cType == float.class)
Array.setFloat(tgt, i, Double.valueOf(objs[i].toString()).floatValue());
else
if(cType == double.class)
Array.setDouble(tgt, i, Double.valueOf(objs[i].toString()).doubleValue());
}
else
if(objs[i] instanceof JSONObject)
{
Object newObj = cType.newInstance();
fromJSONtoPOJO((JSONObject)objs[i], newObj);
Array.set(tgt, i, newObj);
}
}
field.set(o, tgt);
}
else
if((field.getType() == String.class)&&(jo instanceof String))
field.set(o, jo);
else
if(field.getType().isPrimitive())
{
final Class<?> cType=field.getType();
if(cType == boolean.class)
field.setBoolean(o, Boolean.valueOf(jo.toString()).booleanValue());
else
if(cType == int.class)
field.setInt(o, Long.valueOf(jo.toString()).intValue());
else
if(cType == short.class)
field.setShort(o, Long.valueOf(jo.toString()).shortValue());
else
if(cType == byte.class)
field.setByte(o, Long.valueOf(jo.toString()).byteValue());
else
if(cType == long.class)
field.setLong(o, Long.valueOf(jo.toString()).longValue());
else
if(cType == float.class)
field.setFloat(o, Double.valueOf(jo.toString()).floatValue());
else
if(cType == double.class)
field.setDouble(o, Double.valueOf(jo.toString()).doubleValue());
else
field.set(o, jo);
}
else
if(jo instanceof JSONObject)
{
Object newObj = field.getType().newInstance();
fromJSONtoPOJO((JSONObject)jo, newObj);
field.set(o, newObj);
}
else
if((field.getType() == Integer.class)&&(jo instanceof Long))
field.set(o, Integer.valueOf(((Long)jo).intValue()));
else
if((field.getType() == Long.class)&&(jo instanceof Long))
field.set(o, Long.valueOf(((Long)jo).longValue()));
else
if((field.getType() == Double.class)&&(jo instanceof Double))
field.set(o, Double.valueOf(((Double)jo).doubleValue()));
else
if((field.getType() == Float.class)&&(jo instanceof Double))
field.set(o, Float.valueOf(((Double)jo).floatValue()));
else
if((field.getType() == Boolean.class)&&(jo instanceof Boolean))
field.set(o, Boolean.valueOf(((Boolean)jo).booleanValue()));
else
field.set(o, jo);
}
}
catch (IllegalArgumentException e)
{
throw new MJSONException(e.getMessage(),e);
}
catch (IllegalAccessException e)
{
throw new MJSONException(e.getMessage(),e);
}
catch (InstantiationException e)
{
throw new MJSONException(e.getMessage(),e);
}
}
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@15557 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/core/MiniJSON.java | <ide><path>om/planet_ink/coffee_mud/core/MiniJSON.java
<ide> if((field.getType() == Integer.class)&&(jo instanceof Long))
<ide> field.set(o, Integer.valueOf(((Long)jo).intValue()));
<ide> else
<add> if((field.getType() == Short.class)&&(jo instanceof Long))
<add> field.set(o, Short.valueOf(((Long)jo).shortValue()));
<add> else
<add> if((field.getType() == Byte.class)&&(jo instanceof Long))
<add> field.set(o, Byte.valueOf(((Long)jo).byteValue()));
<add> else
<ide> if((field.getType() == Long.class)&&(jo instanceof Long))
<ide> field.set(o, Long.valueOf(((Long)jo).longValue()));
<ide> else |
||
JavaScript | mit | 40bcadca5b367372703e3fea0911d4272f547df4 | 0 | flancer32/dbear | 'use strict'
/* libraries */
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should()
/* own code */
var Convertor = require('./convert.js')
var params = require('./convert/params')
describe('convert', function () {
it('should be fulfilled with skipWriteOut param', function (done) {
var convert = new Convertor()
params.demFileIn = 'sample/sample.dem.xml'
params.skipWriteOut = true
convert.run(params).should.be.fulfilled.notify(done)
})
it('should be rejected with skipWriteOut param, but w/o demFileIn', function (done) {
var convert = new Convertor()
params.demFileIn = undefined
params.skipWriteOut = true
convert.run(params).should.be.rejectedWith(console.log()).notify(done)
})
it('should be rejected with skipWriteOut param, but w/o correct path', function (done) {
var convert = new Convertor()
params.demFileIn = 'test.xm'
params.skipWriteOut = true
convert.run(params).should.be.rejectedWith(console.log()).notify(done)
})
it('should be fulfilled w/o skipWriteOut param', function (done) {
var convert = new Convertor()
params.demFileIn = 'sample/sample.dem.xml'
params.demFileOut = 'sample/sample.dem.json'
params.skipWriteOut = undefined
convert.run(params).should.be.fulfilled.notify(done)
})
it('should be rejected w/o demFileIn and demFileOut params, when skipWriteOut = false', function(done) {
var convert = new Convertor()
params.demFileIn = undefined
params.demFileOut = undefined
params.skipWriteOut = undefined
convert.run(params).should.be.rejectedWith(console.log()).notify(done)
})
it('should be rejected with incorrect name or extension of input file, when skipWriteOut = false', function(done) {
var convert = new Convertor()
params.demFileIn = 'test.xm'
params.demFileOut = 'test.json'
params.skipWriteOut = undefined
convert.run(params).should.be.rejectedWith(console.log()).notify(done)
})
it('should be rejected with incorrect name or extension of output file, when skipWriteOut = false', function(done) {
var convert = new Convertor()
params.demFileIn = 'test.xml'
params.demFileOut = 'test.jso'
params.skipWriteOut = undefined
convert.run(params).should.be.rejectedWith(console.log()).notify(done)
})
}) | src/inc/convert.spec.js | 'use strict'
/* libraries */
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var should = chai.should()
/* own code */
var Convertor = require('./convert.js')
var params = require('./convert/params')
describe('convert', function () {
it('should be fulfilled with skipWriteOut param', function (done) {
var convert = new Convertor()
params.demFileIn = 'sample/sample.dem.xml'
params.skipWriteOut = true
convert.run(params).should.be.fulfilled.notify(done)
})
it('should be fulfilled w/o skipWriteOut param', function (done) {
var convert = new Convertor()
params.demFileIn = 'sample/sample.dem.xml'
params.demFileOut = 'sample/sample.dem.json'
params.skipWriteOut = undefined
convert.run(params).should.be.fulfilled.notify(done)
})
}) | WF-72 - Spec review
| src/inc/convert.spec.js | WF-72 - Spec review | <ide><path>rc/inc/convert.spec.js
<ide> convert.run(params).should.be.fulfilled.notify(done)
<ide> })
<ide>
<add> it('should be rejected with skipWriteOut param, but w/o demFileIn', function (done) {
<add> var convert = new Convertor()
<add> params.demFileIn = undefined
<add> params.skipWriteOut = true
<add> convert.run(params).should.be.rejectedWith(console.log()).notify(done)
<add> })
<add>
<add> it('should be rejected with skipWriteOut param, but w/o correct path', function (done) {
<add> var convert = new Convertor()
<add> params.demFileIn = 'test.xm'
<add> params.skipWriteOut = true
<add> convert.run(params).should.be.rejectedWith(console.log()).notify(done)
<add> })
<add>
<ide> it('should be fulfilled w/o skipWriteOut param', function (done) {
<ide> var convert = new Convertor()
<ide> params.demFileIn = 'sample/sample.dem.xml'
<ide> params.skipWriteOut = undefined
<ide> convert.run(params).should.be.fulfilled.notify(done)
<ide> })
<add>
<add> it('should be rejected w/o demFileIn and demFileOut params, when skipWriteOut = false', function(done) {
<add> var convert = new Convertor()
<add> params.demFileIn = undefined
<add> params.demFileOut = undefined
<add> params.skipWriteOut = undefined
<add> convert.run(params).should.be.rejectedWith(console.log()).notify(done)
<add> })
<add>
<add> it('should be rejected with incorrect name or extension of input file, when skipWriteOut = false', function(done) {
<add> var convert = new Convertor()
<add> params.demFileIn = 'test.xm'
<add> params.demFileOut = 'test.json'
<add> params.skipWriteOut = undefined
<add> convert.run(params).should.be.rejectedWith(console.log()).notify(done)
<add> })
<add>
<add> it('should be rejected with incorrect name or extension of output file, when skipWriteOut = false', function(done) {
<add> var convert = new Convertor()
<add> params.demFileIn = 'test.xml'
<add> params.demFileOut = 'test.jso'
<add> params.skipWriteOut = undefined
<add> convert.run(params).should.be.rejectedWith(console.log()).notify(done)
<add> })
<ide> }) |
|
Java | apache-2.0 | 01237e9d5af3f895d57218b54f648ca26967bf99 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.search;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.VolatileNotNullLazyValue;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiModifierList;
import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchScopeUtil;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtil;
import com.intellij.reference.SoftReference;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.Reference;
import java.util.*;
/**
* To avoid expensive super type resolve, if there's only one suitable class with the required name in the project anyway
*/
public class RelaxedDirectInheritorChecker {
private final String myBaseClassName;
private final PsiClass myBaseClass;
private final VolatileNotNullLazyValue<PsiClass[]> myClasses;
private final VolatileNotNullLazyValue<Boolean> myHasGlobalAmbiguities;
private final ProjectFileIndex myFileIndex;
public RelaxedDirectInheritorChecker(@NotNull PsiClass baseClass) {
myBaseClass = baseClass;
myBaseClassName = Objects.requireNonNull(baseClass.getName());
myClasses = VolatileNotNullLazyValue.createValue(() -> getClassesByName(myBaseClass.getProject(), myBaseClassName));
myHasGlobalAmbiguities = VolatileNotNullLazyValue.createValue(() -> hasAmbiguities(JBIterable.of(myClasses.getValue())));
myFileIndex = ProjectFileIndex.getInstance(myBaseClass.getProject());
}
@NotNull
private static PsiClass[] getClassesByName(Project project, String name) {
Map<String, Reference<PsiClass[]>> cache = CachedValuesManager.getManager(project).getCachedValue(project, () -> {
Map<String, Reference<PsiClass[]>> map = ContainerUtil.newConcurrentMap();
return CachedValueProvider.Result.create(map, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
});
PsiClass[] result = SoftReference.dereference(cache.get(name));
if (result == null) {
result = PsiShortNamesCache.getInstance(project).getClassesByName(name, GlobalSearchScope.allScope(project));
cache.put(name, new SoftReference<>(result));
}
return result;
}
private static boolean hasAmbiguities(Iterable<PsiClass> classes) {
int locals = 0;
Set<String> qNames = new HashSet<>();
for (PsiClass psiClass : classes) {
String qName = psiClass.getQualifiedName();
if (qName == null) {
locals++;
if (locals > 1) break;
} else {
qNames.add(qName);
if (qNames.size() > 1) break;
}
}
return locals + qNames.size() > 1;
}
public boolean checkInheritance(@NotNull PsiClass inheritorCandidate) {
if (!inheritorCandidate.isValid() || !myBaseClass.isValid()) return false;
if (myFileIndex.isInSourceContent(inheritorCandidate.getContainingFile().getVirtualFile())) {
if (!myHasGlobalAmbiguities.getValue()) {
return true;
}
GlobalSearchScope scope = inheritorCandidate.getResolveScope();
List<PsiClass> accessible = ContainerUtil.findAll(myClasses.getValue(), base ->
PsiSearchScopeUtil.isInScope(scope, base) && isAccessibleLight(inheritorCandidate, base));
if (!hasAmbiguities(accessible)) {
return accessible.contains(myBaseClass);
}
}
return inheritorCandidate.isInheritor(myBaseClass, false);
}
private static boolean isAccessibleLight(@NotNull PsiClass inheritorCandidate, @NotNull PsiClass base) {
PsiModifierList modifierList = base.getModifierList();
if (modifierList != null && PsiUtil.getAccessLevel(modifierList) == PsiUtil.ACCESS_LEVEL_PROTECTED) {
return true; // requires hierarchy checks => resolve
}
return JavaResolveUtil.isAccessible(base, base.getContainingClass(), modifierList, inheritorCandidate, null, null);
}
}
| java/java-indexing-impl/src/com/intellij/psi/impl/search/RelaxedDirectInheritorChecker.java | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.search;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.VolatileNotNullLazyValue;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiModifierList;
import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchScopeUtil;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtil;
import com.intellij.reference.SoftReference;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
import java.lang.ref.Reference;
import java.util.*;
/**
* To avoid expensive super type resolve, if there's only one suitable class with the required name in the project anyway
*/
public class RelaxedDirectInheritorChecker {
private final String myBaseClassName;
private final PsiClass myBaseClass;
private final VolatileNotNullLazyValue<PsiClass[]> myClasses;
private final VolatileNotNullLazyValue<Boolean> myHasGlobalAmbiguities;
private final ProjectFileIndex myFileIndex;
public RelaxedDirectInheritorChecker(@NotNull PsiClass baseClass) {
myBaseClass = baseClass;
myBaseClassName = Objects.requireNonNull(baseClass.getName());
myClasses = VolatileNotNullLazyValue.createValue(() -> getClassesByName(myBaseClass.getProject(), myBaseClassName));
myHasGlobalAmbiguities = VolatileNotNullLazyValue.createValue(() -> hasAmbiguities(JBIterable.of(myClasses.getValue())));
myFileIndex = ProjectFileIndex.getInstance(myBaseClass.getProject());
}
@NotNull
private static PsiClass[] getClassesByName(Project project, String name) {
Map<String, Reference<PsiClass[]>> cache = CachedValuesManager.getManager(project).getCachedValue(project, () -> {
Map<String, Reference<PsiClass[]>> map = ContainerUtil.newConcurrentMap();
return CachedValueProvider.Result.create(map, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
});
PsiClass[] result = SoftReference.dereference(cache.get(name));
if (result == null) {
result = PsiShortNamesCache.getInstance(project).getClassesByName(name, GlobalSearchScope.allScope(project));
cache.put(name, new SoftReference<>(result));
}
return result;
}
private static boolean hasAmbiguities(Iterable<PsiClass> classes) {
int locals = 0;
Set<String> qNames = new HashSet<>();
for (PsiClass psiClass : classes) {
String qName = psiClass.getQualifiedName();
if (qName == null) {
locals++;
if (locals > 1) return true;
} else {
qNames.add(qName);
if (qNames.size() > 1) return true;
}
}
return false;
}
public boolean checkInheritance(@NotNull PsiClass inheritorCandidate) {
if (!inheritorCandidate.isValid() || !myBaseClass.isValid()) return false;
if (myFileIndex.isInSourceContent(inheritorCandidate.getContainingFile().getVirtualFile())) {
if (!myHasGlobalAmbiguities.getValue()) {
return true;
}
GlobalSearchScope scope = inheritorCandidate.getResolveScope();
List<PsiClass> accessible = ContainerUtil.findAll(myClasses.getValue(), base ->
PsiSearchScopeUtil.isInScope(scope, base) && isAccessibleLight(inheritorCandidate, base));
if (!hasAmbiguities(accessible)) {
return accessible.contains(myBaseClass);
}
}
return inheritorCandidate.isInheritor(myBaseClass, false);
}
private static boolean isAccessibleLight(@NotNull PsiClass inheritorCandidate, @NotNull PsiClass base) {
PsiModifierList modifierList = base.getModifierList();
if (modifierList != null && PsiUtil.getAccessLevel(modifierList) == PsiUtil.ACCESS_LEVEL_PROTECTED) {
return true; // requires hierarchy checks => resolve
}
return JavaResolveUtil.isAccessible(base, base.getContainingClass(), modifierList, inheritorCandidate, null, null);
}
}
| consider super type ambiguous if there's one local and one FQN class of the same name (IDEA-CR-31820)
| java/java-indexing-impl/src/com/intellij/psi/impl/search/RelaxedDirectInheritorChecker.java | consider super type ambiguous if there's one local and one FQN class of the same name (IDEA-CR-31820) | <ide><path>ava/java-indexing-impl/src/com/intellij/psi/impl/search/RelaxedDirectInheritorChecker.java
<ide> String qName = psiClass.getQualifiedName();
<ide> if (qName == null) {
<ide> locals++;
<del> if (locals > 1) return true;
<add> if (locals > 1) break;
<ide> } else {
<ide> qNames.add(qName);
<del> if (qNames.size() > 1) return true;
<add> if (qNames.size() > 1) break;
<ide> }
<ide> }
<del> return false;
<add> return locals + qNames.size() > 1;
<ide> }
<ide>
<ide> public boolean checkInheritance(@NotNull PsiClass inheritorCandidate) { |
|
JavaScript | apache-2.0 | a4351ef5584c340bb74beea7e12edc53926fc317 | 0 | crrobinson14/actionhero,gcoonrod/actionhero,witem/actionhero,gcoonrod/actionhero,crrobinson14/actionhero,chimmelb/actionhero,actionhero/actionhero,witem/actionhero,actionhero/actionhero,actionhero/actionhero,chimmelb/actionhero,gcoonrod/actionhero,witem/actionhero,witem/actionhero,actionhero/actionhero,crrobinson14/actionhero,gcoonrod/actionhero,chimmelb/actionhero | 'use strict'
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const argv = require('optimist').argv
const ActionHero = require('./../index.js')
const api = ActionHero.api
const RELOAD_DELAY = 2000
/**
* Countains ActionHero configuration.
*
* @namespace api.config
* @extends ActionHero.Initializer
*/
module.exports = class Config extends ActionHero.Initializer {
constructor () {
super()
this.name = 'config'
this.loadPriority = 1
this.startPriority = 1
this.stopPriority = 1
}
async initialize () {
if (api._startingParams && api._startingParams.api) {
api.utils.hashMerge(api, api._startingParams.api)
}
api.env = 'development'
if (argv.NODE_ENV) {
api.env = argv.NODE_ENV
} else if (process.env.NODE_ENV) {
api.env = process.env.NODE_ENV
}
// reloading in development mode
api.watchedFiles = api.watchedFiles || {}
api.watchFileAndAct = (file, handler) => {
file = path.normalize(file)
if (!fs.existsSync(file)) {
throw new Error(file + ' does not exist, and cannot be watched')
}
if (api.config.general.developmentMode === true && !api.watchedFiles[file]) {
const watcher = fs.watch(file, {persistent: false}, (eventType) => {
const stats = fs.statSync(file)
if (
api.running === true &&
api.config.general.developmentMode === true &&
eventType === 'change' &&
(stats.mtimeMs - api.watchedFiles[file].stats.mtimeMs) >= RELOAD_DELAY
) {
api.watchedFiles[file].stats = stats
let cleanPath = file
if (process.platform === 'win32') { cleanPath = file.replace(/\//g, '\\') }
delete require.cache[require.resolve(cleanPath)]
handler(file)
}
})
api.watchedFiles[file] = {watcher, stats: fs.statSync(file)}
}
}
api.unWatchAllFiles = () => {
for (let file in api.watchedFiles) {
api.watchedFiles[file].watcher.close()
delete api.watchedFiles[file]
}
}
// We support multiple configuration paths as follows:
//
// 1. Use the project 'config' folder, if it exists.
// 2. "actionhero --config=PATH1 --config=PATH2 --config=PATH3,PATH4"
// 3. "ACTIONHERO_CONFIG=PATH1,PATH2 npm start"
//
// Note that if --config or ACTIONHERO_CONFIG are used, they _overwrite_ the use of the default "config" folder. If
// you wish to use both, you need to re-specify "config", e.g. "--config=config,local-config". Also, note that
// specifying multiple --config options on the command line does exactly the same thing as using one parameter with
// comma separators, however the environment variable method only supports the comma-delimited syntax.
let configPaths = []
function addConfigPath (pathToCheck, alreadySplit) {
if (typeof pathToCheck === 'string') {
if (!alreadySplit) {
addConfigPath(pathToCheck.split(','), true)
} else {
if (pathToCheck.charAt(0) !== '/') {
pathToCheck = path.resolve(api.projectRoot, pathToCheck)
}
if (fs.existsSync(pathToCheck)) {
configPaths.push(pathToCheck)
}
}
} else if (Array.isArray(pathToCheck)) {
pathToCheck.map((entry) => { addConfigPath(entry, alreadySplit) })
}
}
[argv.config, process.env.ACTIONHERO_CONFIG].map((entry) => {
addConfigPath(entry, false)
})
if (configPaths.length < 1) {
addConfigPath('config', false)
}
if (configPaths.length < 1) {
throw new Error(configPaths + 'No config directory found in this project, specified with --config, or found in process.env.ACTIONHERO_CONFIG')
}
const rebootHandler = (file) => {
api.log(`*** rebooting due to config change (${file}) ***`, 'info')
delete require.cache[require.resolve(file)]
api.commands.restart()
}
api.loadConfigDirectory = (configPath, watch) => {
const configFiles = glob.sync(path.join(configPath, '**', '*.js'))
let loadRetries = 0
let loadErrors = {}
for (let i = 0, limit = configFiles.length; (i < limit); i++) {
const f = configFiles[i]
try {
// attempt configuration file load
let localConfig = require(f)
if (localConfig['default']) { api.config = api.utils.hashMerge(api.config, localConfig['default'], api) }
if (localConfig[api.env]) { api.config = api.utils.hashMerge(api.config, localConfig[api.env], api) }
// configuration file load success: clear retries and
// errors since progress has been made
loadRetries = 0
loadErrors = {}
} catch (error) {
// error loading configuration, abort if all remaining
// configuration files have been tried and failed
// indicating inability to progress
loadErrors[f] = {error: error, msg: error.toString()}
if (++loadRetries === limit - i) {
Object.keys(loadErrors).forEach((e) => {
console.log(loadErrors[e].error.stack)
console.log('')
delete loadErrors[e].error
})
throw new Error('Unable to load configurations, errors: ' + JSON.stringify(loadErrors))
}
// adjust configuration files list: remove and push
// failed configuration to the end of the list and
// continue with next file at same index
configFiles.push(configFiles.splice(i--, 1)[0])
continue
}
if (watch !== false) {
// configuration file loaded: set watch
api.watchFileAndAct(f, rebootHandler)
}
}
// We load the config twice. Utilize configuration files load order that succeeded on the first pass.
// This is to allow 'literal' values to be loaded whenever possible, and then for refrences to be resolved
configFiles.forEach((f) => {
const localConfig = require(f)
if (localConfig['default']) { api.config = api.utils.hashMerge(api.config, localConfig['default'], api) }
if (localConfig[api.env]) { api.config = api.utils.hashMerge(api.config, localConfig[api.env], api) }
})
}
api.config = {}
// load the default config of actionhero
api.loadConfigDirectory(path.join(__dirname, '/../config'), false)
// load the project specific config
configPaths.map(api.loadConfigDirectory)
// apply any configChanges
if (api._startingParams && api._startingParams.configChanges) {
api.config = api.utils.hashMerge(api.config, api._startingParams.configChanges)
}
}
start () {
api.log(`environment: ${api.env}`, 'notice')
}
stop () {
api.unWatchAllFiles()
}
}
| initializers/config.js | 'use strict'
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const argv = require('optimist').argv
const ActionHero = require('./../index.js')
const api = ActionHero.api
const RELOAD_DELAY = 2000
/**
* Countains ActionHero configuration.
*
* @namespace api.config
* @extends ActionHero.Initializer
*/
module.exports = class Config extends ActionHero.Initializer {
constructor () {
super()
this.name = 'config'
this.loadPriority = 1
this.startPriority = 1
this.stopPriority = 1
}
async initialize () {
if (api._startingParams && api._startingParams.api) {
api.utils.hashMerge(api, api._startingParams.api)
}
api.env = 'development'
if (argv.NODE_ENV) {
api.env = argv.NODE_ENV
} else if (process.env.NODE_ENV) {
api.env = process.env.NODE_ENV
}
// reloading in development mode
api.watchedFiles = api.watchedFiles || {}
api.watchFileAndAct = (file, handler) => {
file = path.normalize(file)
if (!fs.existsSync(file)) {
throw new Error(file + ' does not exist, and cannot be watched')
}
if (api.config.general.developmentMode === true && !api.watchedFiles[file]) {
const watcher = fs.watch(file, {persistent: false}, (eventType) => {
const stats = fs.statSync(file)
if (
api.running === true &&
api.config.general.developmentMode === true &&
eventType === 'change' &&
(stats.mtimeMs - api.watchedFiles[file].stats.mtimeMs) >= RELOAD_DELAY
) {
api.watchedFiles[file].stats = stats
let cleanPath = file
if (process.platform === 'win32') { cleanPath = file.replace(/\//g, '\\') }
delete require.cache[require.resolve(cleanPath)]
setTimeout(() => { api.watchedFiles[file].blocked = false }, 1000)
handler(file)
}
})
api.watchedFiles[file] = {watcher, stats: fs.statSync(file)}
}
}
api.unWatchAllFiles = () => {
for (let file in api.watchedFiles) {
api.watchedFiles[file].watcher.close()
delete api.watchedFiles[file]
}
}
// We support multiple configuration paths as follows:
//
// 1. Use the project 'config' folder, if it exists.
// 2. "actionhero --config=PATH1 --config=PATH2 --config=PATH3,PATH4"
// 3. "ACTIONHERO_CONFIG=PATH1,PATH2 npm start"
//
// Note that if --config or ACTIONHERO_CONFIG are used, they _overwrite_ the use of the default "config" folder. If
// you wish to use both, you need to re-specify "config", e.g. "--config=config,local-config". Also, note that
// specifying multiple --config options on the command line does exactly the same thing as using one parameter with
// comma separators, however the environment variable method only supports the comma-delimited syntax.
let configPaths = []
function addConfigPath (pathToCheck, alreadySplit) {
if (typeof pathToCheck === 'string') {
if (!alreadySplit) {
addConfigPath(pathToCheck.split(','), true)
} else {
if (pathToCheck.charAt(0) !== '/') {
pathToCheck = path.resolve(api.projectRoot, pathToCheck)
}
if (fs.existsSync(pathToCheck)) {
configPaths.push(pathToCheck)
}
}
} else if (Array.isArray(pathToCheck)) {
pathToCheck.map((entry) => { addConfigPath(entry, alreadySplit) })
}
}
[argv.config, process.env.ACTIONHERO_CONFIG].map((entry) => {
addConfigPath(entry, false)
})
if (configPaths.length < 1) {
addConfigPath('config', false)
}
if (configPaths.length < 1) {
throw new Error(configPaths + 'No config directory found in this project, specified with --config, or found in process.env.ACTIONHERO_CONFIG')
}
const rebootHandler = (file) => {
api.log(`*** rebooting due to config change (${file}) ***`, 'info')
delete require.cache[require.resolve(file)]
api.commands.restart()
}
api.loadConfigDirectory = (configPath, watch) => {
const configFiles = glob.sync(path.join(configPath, '**', '*.js'))
let loadRetries = 0
let loadErrors = {}
for (let i = 0, limit = configFiles.length; (i < limit); i++) {
const f = configFiles[i]
try {
// attempt configuration file load
let localConfig = require(f)
if (localConfig['default']) { api.config = api.utils.hashMerge(api.config, localConfig['default'], api) }
if (localConfig[api.env]) { api.config = api.utils.hashMerge(api.config, localConfig[api.env], api) }
// configuration file load success: clear retries and
// errors since progress has been made
loadRetries = 0
loadErrors = {}
} catch (error) {
// error loading configuration, abort if all remaining
// configuration files have been tried and failed
// indicating inability to progress
loadErrors[f] = {error: error, msg: error.toString()}
if (++loadRetries === limit - i) {
Object.keys(loadErrors).forEach((e) => {
console.log(loadErrors[e].error.stack)
console.log('')
delete loadErrors[e].error
})
throw new Error('Unable to load configurations, errors: ' + JSON.stringify(loadErrors))
}
// adjust configuration files list: remove and push
// failed configuration to the end of the list and
// continue with next file at same index
configFiles.push(configFiles.splice(i--, 1)[0])
continue
}
if (watch !== false) {
// configuration file loaded: set watch
api.watchFileAndAct(f, rebootHandler)
}
}
// We load the config twice. Utilize configuration files load order that succeeded on the first pass.
// This is to allow 'literal' values to be loaded whenever possible, and then for refrences to be resolved
configFiles.forEach((f) => {
const localConfig = require(f)
if (localConfig['default']) { api.config = api.utils.hashMerge(api.config, localConfig['default'], api) }
if (localConfig[api.env]) { api.config = api.utils.hashMerge(api.config, localConfig[api.env], api) }
})
}
api.config = {}
// load the default config of actionhero
api.loadConfigDirectory(path.join(__dirname, '/../config'), false)
// load the project specific config
configPaths.map(api.loadConfigDirectory)
// apply any configChanges
if (api._startingParams && api._startingParams.configChanges) {
api.config = api.utils.hashMerge(api.config, api._startingParams.configChanges)
}
}
start () {
api.log(`environment: ${api.env}`, 'notice')
}
stop () {
api.unWatchAllFiles()
}
}
| no need for a timer to check file locks in development mode
| initializers/config.js | no need for a timer to check file locks in development mode | <ide><path>nitializers/config.js
<ide> let cleanPath = file
<ide> if (process.platform === 'win32') { cleanPath = file.replace(/\//g, '\\') }
<ide> delete require.cache[require.resolve(cleanPath)]
<del> setTimeout(() => { api.watchedFiles[file].blocked = false }, 1000)
<ide> handler(file)
<ide> }
<ide> }) |
|
Java | apache-2.0 | f1998c19dad9992d22d9febd7a6969eacf433d64 | 0 | venusdrogon/feilong-spring | /*
* Copyright (C) 2008 feilong
*
* 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.feilong.spring.web.servlet.interceptor;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.feilong.core.lang.reflect.FieldUtil;
import com.feilong.core.tools.jsonlib.JsonUtil;
/**
* The Class AbstractHandlerInterceptorAdapter.
*
* @author feilong
* @version 1.4.0 2015年8月6日 下午10:59:16
* @since 1.4.0
*/
public abstract class AbstractHandlerInterceptorAdapter extends HandlerInterceptorAdapter implements Ordered{
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHandlerInterceptorAdapter.class);
/**
* Post construct.
*/
@PostConstruct
protected void postConstruct(){
if (LOGGER.isInfoEnabled()){
Map<String, Object> map = FieldUtil.getAllFieldNameAndValueMap(this);
LOGGER.info("\n[{}] fieldValueMap: \n[{}]", getClass().getCanonicalName(), JsonUtil.format(map));
}
}
/*
* (non-Javadoc)
*
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder(){
return 0;
}
} | feilong-spring-web/src/main/java/com/feilong/spring/web/servlet/interceptor/AbstractHandlerInterceptorAdapter.java | /*
* Copyright (C) 2008 feilong
*
* 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.feilong.spring.web.servlet.interceptor;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.feilong.core.lang.reflect.FieldUtil;
import com.feilong.core.tools.jsonlib.JsonUtil;
/**
* The Class AbstractHandlerInterceptorAdapter.
*
* @author feilong
* @version 1.4.0 2015年8月6日 下午10:59:16
* @since 1.4.0
*/
public abstract class AbstractHandlerInterceptorAdapter extends HandlerInterceptorAdapter implements Ordered{
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractHandlerInterceptorAdapter.class);
/**
* Post construct.
*/
@PostConstruct
protected void postConstruct(){
if (LOGGER.isInfoEnabled()){
Map<String, Object> map = FieldUtil.getFieldValueMap(this);
LOGGER.info("\n[{}] fieldValueMap: \n[{}]", getClass().getCanonicalName(), JsonUtil.format(map));
}
}
/*
* (non-Javadoc)
*
* @see org.springframework.core.Ordered#getOrder()
*/
@Override
public int getOrder(){
return 0;
}
} | call feilong-core some new method | feilong-spring-web/src/main/java/com/feilong/spring/web/servlet/interceptor/AbstractHandlerInterceptorAdapter.java | call feilong-core some new method | <ide><path>eilong-spring-web/src/main/java/com/feilong/spring/web/servlet/interceptor/AbstractHandlerInterceptorAdapter.java
<ide> @PostConstruct
<ide> protected void postConstruct(){
<ide> if (LOGGER.isInfoEnabled()){
<del> Map<String, Object> map = FieldUtil.getFieldValueMap(this);
<add> Map<String, Object> map = FieldUtil.getAllFieldNameAndValueMap(this);
<ide> LOGGER.info("\n[{}] fieldValueMap: \n[{}]", getClass().getCanonicalName(), JsonUtil.format(map));
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | 883f2e176db0fb8f297a00e2fa30f25d6f3b4dd3 | 0 | zbraniecki/l20n.js,Swaven/l20n.js,zbraniecki/fluent.js,projectfluent/fluent.js,stasm/l20n.js,mail-apps/l20n.js,projectfluent/fluent.js,Pike/l20n.js,projectfluent/fluent.js,mail-apps/l20n.js,zbraniecki/fluent.js,l20n/l20n.js,Pike/l20n.js | 'use strict';
var Context = require('./context').Context;
var isPretranslated = false;
var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
var ctx = new Context();
// Public API
navigator.mozL10n = {
translate: translateFragment,
localize: localizeElement,
get: ctx.get.bind(ctx),
ready: ctx.ready.bind(ctx),
get readyState() {
return ctx.isReady ? 'complete' : 'loading';
},
language: {
set code(lang) {
initLocale(lang, true);
},
get code() {
return ctx.supportedLocales[0];
},
get direction() {
return getDirection(ctx.supportedLocales[0]);
}
}
};
function getDirection(lang) {
return (rtlList.indexOf(lang) >= 0) ? 'rtl' : 'ltr';
}
var readyStates = {
'loading': 0,
'interactive': 1,
'complete': 2
};
function waitFor(state, callback) {
state = readyStates[state];
if (readyStates[document.readyState] >= state) {
callback();
return;
}
document.addEventListener('readystatechange', function l10n_onrsc() {
if (readyStates[document.readyState] >= state) {
document.removeEventListener('readystatechange', l10n_onrsc);
callback();
}
});
}
if (window.document) {
isPretranslated = (document.documentElement.lang === navigator.language);
if (isPretranslated) {
waitFor('complete', function() {
window.setTimeout(initDocumentLocalization.bind(null, initLocale));
});
} else {
initDocumentLocalization(initLocale);
}
}
function initDocumentLocalization(cb) {
var resLinks = document.head.querySelectorAll('link[type="application/l10n"]');
var iniLinks = [];
var link;
for (link of resLinks) {
var url = link.getAttribute('href');
var type = url.substr(url.lastIndexOf('.') + 1);
if (type === 'ini') {
iniLinks.push(url);
} else {
ctx.resLinks.push(url);
}
}
ctx.ready(fireLocalizedEvent);
var iniLoads = iniLinks.length;
if (iniLoads === 0) {
onIniLoaded();
}
function onIniLoaded() {
iniLoads--;
if (iniLoads <= 0) {
cb();
}
}
for (link of iniLinks) {
loadINI(link, onIniLoaded);
}
}
function initLocale(lang, forced) {
ctx.registerLocales('en-US');
ctx.requestLocales(navigator.language);
}
function fireLocalizedEvent() {
var event = document.createEvent('Event');
event.initEvent('localized', false, false);
event.language = ctx.supportedLocales[0];
window.dispatchEvent(event);
}
// INI loader functions
function loadINI(url, cb) {
io.load(url, function(err, source) {
if (!source) {
cb();
return;
}
var ini = parseINI(source, url);
var pos = ctx.resLinks.indexOf(url);
var patterns = ini.resources.map(function(x) {
return x.replace('en-US', '{{locale}}');
});
var args = [pos, 1].concat(patterns);
ctx.resLinks.splice.apply(ctx.resLinks, args);
cb();
});
}
function relativePath(baseUrl, url) {
if (url[0] === '/') {
return url;
}
var dirs = baseUrl.split('/')
.slice(0, -1)
.concat(url.split('/'))
.filter(function(path) {
return path !== '.';
});
return dirs.join('/');
}
var iniPatterns = {
section: /^\s*\[(.*)\]\s*$/,
import: /^\s*@import\s+url\((.*)\)\s*$/i,
entry: /[\r\n]+/
};
function parseINI(source, iniPath) {
var entries = source.split(iniPatterns.entry);
var locales = ['en-US'];
var genericSection = true;
var uris = [];
var match;
for (var line of entries) {
// we only care about en-US resources
if (genericSection && iniPatterns['import'].test(line)) {
match = iniPatterns['import'].exec(line);
var uri = relativePath(iniPath, match[1]);
uris.push(uri);
continue;
}
// but we need the list of all locales in the ini, too
if (iniPatterns.section.test(line)) {
genericSection = false;
match = iniPatterns.section.exec(line);
locales.push(match[1]);
}
}
return {
locales: locales,
resources: uris
};
}
// HTML translation functions
function translateFragment(element) {
element = element || document.documentElement;
translateElement(element);
var nodes = getTranslatableChildren(element);
for (var node of nodes) {
translateElement(node);
}
}
function getTranslatableChildren(element) {
return element ? element.querySelectorAll('*[data-l10n-id]') : [];
}
function localizeElement(element, id, args) {
if (!id) {
element.removeAttribute('data-l10n-id');
element.removeAttribute('data-l10n-args');
element.textContent = '';
} else {
element.textContent = '#'+id;
}
}
function translateElement(element, id) {
}
| bindings/l20n/runtime.js | 'use strict';
var Context = require('./context').Context;
var isPretranslated = false;
var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
var ctx = new Context();
navigator.mozL10n = {
translate: translateFragment,
localize: localizeElement,
get: ctx.get.bind(ctx),
ready: ctx.ready.bind(ctx),
get readyState() {
return ctx.isReady ? 'complete' : 'loading';
},
language: {
set code(lang) {
initLocale(lang, true);
},
get code() {
return ctx.supportedLocales[0];
},
get direction() {
return getDirection(ctx.supportedLocales[0]);
}
}
};
function getDirection(lang) {
return (rtlList.indexOf(lang) >= 0) ? 'rtl' : 'ltr';
}
var readyStates = {
'loading': 0,
'interactive': 1,
'complete': 2
};
function waitFor(state, callback) {
state = readyStates[state];
if (readyStates[document.readyState] >= state) {
callback();
return;
}
document.addEventListener('readystatechange', function l10n_onrsc() {
if (readyStates[document.readyState] >= state) {
document.removeEventListener('readystatechange', l10n_onrsc);
callback();
}
});
}
if (window.document) {
isPretranslated = (document.documentElement.lang === navigator.language);
if (isPretranslated) {
waitFor('complete', function() {
window.setTimeout(initDocumentLocalization.bind(null, initLocale));
});
} else {
initDocumentLocalization(initLocale);
}
}
function initDocumentLocalization(cb) {
var resLinks = document.head.querySelectorAll('link[type="application/l10n"]');
var iniLinks = [];
var link;
for (link of resLinks) {
var url = link.getAttribute('href');
var type = url.substr(url.lastIndexOf('.') + 1);
if (type === 'ini') {
iniLinks.push(url);
} else {
ctx.resLinks.push(url);
}
}
ctx.ready(fireLocalizedEvent);
var iniLoads = iniLinks.length;
if (iniLoads === 0) {
onIniLoaded();
}
function onIniLoaded() {
iniLoads--;
if (iniLoads <= 0) {
cb();
}
}
for (link of iniLinks) {
loadINI(link, onIniLoaded);
}
}
function loadINI(url, cb) {
io.load(url, function(err, source) {
if (!source) {
cb();
return;
}
var ini = parseINI(source, url);
var pos = ctx.resLinks.indexOf(url);
var patterns = ini.resources.map(function(x) {
return x.replace('en-US', '{{locale}}');
});
var args = [pos, 1].concat(patterns);
ctx.resLinks.splice.apply(ctx.resLinks, args);
cb();
});
}
function relativePath(baseUrl, url) {
if (url[0] === '/') {
return url;
}
var dirs = baseUrl.split('/')
.slice(0, -1)
.concat(url.split('/'))
.filter(function(path) {
return path !== '.';
});
return dirs.join('/');
}
var iniPatterns = {
section: /^\s*\[(.*)\]\s*$/,
import: /^\s*@import\s+url\((.*)\)\s*$/i,
entry: /[\r\n]+/
};
function parseINI(source, iniPath) {
var entries = source.split(iniPatterns.entry);
var locales = ['en-US'];
var genericSection = true;
var uris = [];
var match;
for (var line of entries) {
// we only care about en-US resources
if (genericSection && iniPatterns['import'].test(line)) {
match = iniPatterns['import'].exec(line);
var uri = relativePath(iniPath, match[1]);
uris.push(uri);
continue;
}
// but we need the list of all locales in the ini, too
if (iniPatterns.section.test(line)) {
genericSection = false;
match = iniPatterns.section.exec(line);
locales.push(match[1]);
}
}
return {
locales: locales,
resources: uris
};
}
function initLocale(lang, forced) {
ctx.registerLocales('en-US');
ctx.requestLocales(navigator.language);
}
function fireLocalizedEvent() {
var event = document.createEvent('Event');
event.initEvent('localized', false, false);
event.language = ctx.supportedLocales[0];
window.dispatchEvent(event);
}
function translateFragment(element) {
element = element || document.documentElement;
translateElement(element);
var nodes = getTranslatableChildren(element);
for (var node of nodes) {
translateElement(node);
}
}
function getTranslatableChildren(element) {
return element ? element.querySelectorAll('*[data-l10n-id]') : [];
}
function localizeElement(element, id, args) {
if (!id) {
element.removeAttribute('data-l10n-id');
element.removeAttribute('data-l10n-args');
element.textContent = '';
} else {
element.textContent = '#'+id;
}
}
function translateElement(element, id) {
}
| separate sections in runtime
| bindings/l20n/runtime.js | separate sections in runtime | <ide><path>indings/l20n/runtime.js
<ide> var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
<ide>
<ide> var ctx = new Context();
<add>
<add>// Public API
<ide>
<ide> navigator.mozL10n = {
<ide> translate: translateFragment,
<ide> }
<ide> }
<ide>
<add>function initLocale(lang, forced) {
<add> ctx.registerLocales('en-US');
<add> ctx.requestLocales(navigator.language);
<add>}
<add>
<add>function fireLocalizedEvent() {
<add> var event = document.createEvent('Event');
<add> event.initEvent('localized', false, false);
<add> event.language = ctx.supportedLocales[0];
<add> window.dispatchEvent(event);
<add>}
<add>
<add>// INI loader functions
<ide>
<ide> function loadINI(url, cb) {
<ide> io.load(url, function(err, source) {
<ide> };
<ide> }
<ide>
<del>function initLocale(lang, forced) {
<del> ctx.registerLocales('en-US');
<del> ctx.requestLocales(navigator.language);
<del>}
<del>
<del>function fireLocalizedEvent() {
<del> var event = document.createEvent('Event');
<del> event.initEvent('localized', false, false);
<del> event.language = ctx.supportedLocales[0];
<del> window.dispatchEvent(event);
<del>}
<add>// HTML translation functions
<ide>
<ide> function translateFragment(element) {
<ide> element = element || document.documentElement; |
|
JavaScript | apache-2.0 | 9ef1c1554359aa0c5416315f71b8b702d03e5ade | 0 | jvkops/titanium_mobile,taoger/titanium_mobile,shopmium/titanium_mobile,csg-coder/titanium_mobile,pinnamur/titanium_mobile,hieupham007/Titanium_Mobile,mvitr/titanium_mobile,collinprice/titanium_mobile,openbaoz/titanium_mobile,taoger/titanium_mobile,indera/titanium_mobile,KangaCoders/titanium_mobile,jhaynie/titanium_mobile,mvitr/titanium_mobile,FokkeZB/titanium_mobile,AngelkPetkov/titanium_mobile,linearhub/titanium_mobile,AngelkPetkov/titanium_mobile,cheekiatng/titanium_mobile,sriks/titanium_mobile,KoketsoMabuela92/titanium_mobile,KangaCoders/titanium_mobile,bright-sparks/titanium_mobile,indera/titanium_mobile,jhaynie/titanium_mobile,openbaoz/titanium_mobile,openbaoz/titanium_mobile,kopiro/titanium_mobile,rblalock/titanium_mobile,taoger/titanium_mobile,csg-coder/titanium_mobile,bright-sparks/titanium_mobile,pec1985/titanium_mobile,prop/titanium_mobile,smit1625/titanium_mobile,jvkops/titanium_mobile,collinprice/titanium_mobile,AngelkPetkov/titanium_mobile,pec1985/titanium_mobile,emilyvon/titanium_mobile,formalin14/titanium_mobile,ashcoding/titanium_mobile,perdona/titanium_mobile,hieupham007/Titanium_Mobile,prop/titanium_mobile,taoger/titanium_mobile,jvkops/titanium_mobile,sriks/titanium_mobile,bhatfield/titanium_mobile,KangaCoders/titanium_mobile,csg-coder/titanium_mobile,taoger/titanium_mobile,smit1625/titanium_mobile,ashcoding/titanium_mobile,pec1985/titanium_mobile,falkolab/titanium_mobile,formalin14/titanium_mobile,bright-sparks/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,AngelkPetkov/titanium_mobile,csg-coder/titanium_mobile,mano-mykingdom/titanium_mobile,rblalock/titanium_mobile,FokkeZB/titanium_mobile,falkolab/titanium_mobile,hieupham007/Titanium_Mobile,cheekiatng/titanium_mobile,emilyvon/titanium_mobile,emilyvon/titanium_mobile,jvkops/titanium_mobile,rblalock/titanium_mobile,mano-mykingdom/titanium_mobile,pinnamur/titanium_mobile,pec1985/titanium_mobile,perdona/titanium_mobile,cheekiatng/titanium_mobile,indera/titanium_mobile,hieupham007/Titanium_Mobile,cheekiatng/titanium_mobile,pec1985/titanium_mobile,indera/titanium_mobile,falkolab/titanium_mobile,collinprice/titanium_mobile,kopiro/titanium_mobile,openbaoz/titanium_mobile,openbaoz/titanium_mobile,benbahrenburg/titanium_mobile,prop/titanium_mobile,emilyvon/titanium_mobile,pinnamur/titanium_mobile,FokkeZB/titanium_mobile,bhatfield/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,bright-sparks/titanium_mobile,rblalock/titanium_mobile,KoketsoMabuela92/titanium_mobile,peymanmortazavi/titanium_mobile,perdona/titanium_mobile,formalin14/titanium_mobile,FokkeZB/titanium_mobile,ashcoding/titanium_mobile,indera/titanium_mobile,sriks/titanium_mobile,benbahrenburg/titanium_mobile,smit1625/titanium_mobile,formalin14/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,cheekiatng/titanium_mobile,jvkops/titanium_mobile,emilyvon/titanium_mobile,KangaCoders/titanium_mobile,AngelkPetkov/titanium_mobile,kopiro/titanium_mobile,peymanmortazavi/titanium_mobile,smit1625/titanium_mobile,bhatfield/titanium_mobile,pinnamur/titanium_mobile,ashcoding/titanium_mobile,AngelkPetkov/titanium_mobile,ashcoding/titanium_mobile,hieupham007/Titanium_Mobile,prop/titanium_mobile,mano-mykingdom/titanium_mobile,falkolab/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,shopmium/titanium_mobile,openbaoz/titanium_mobile,rblalock/titanium_mobile,pec1985/titanium_mobile,shopmium/titanium_mobile,taoger/titanium_mobile,jvkops/titanium_mobile,kopiro/titanium_mobile,collinprice/titanium_mobile,prop/titanium_mobile,KangaCoders/titanium_mobile,collinprice/titanium_mobile,pinnamur/titanium_mobile,rblalock/titanium_mobile,kopiro/titanium_mobile,KoketsoMabuela92/titanium_mobile,pec1985/titanium_mobile,sriks/titanium_mobile,mano-mykingdom/titanium_mobile,collinprice/titanium_mobile,linearhub/titanium_mobile,falkolab/titanium_mobile,bright-sparks/titanium_mobile,hieupham007/Titanium_Mobile,ashcoding/titanium_mobile,shopmium/titanium_mobile,KoketsoMabuela92/titanium_mobile,emilyvon/titanium_mobile,pinnamur/titanium_mobile,csg-coder/titanium_mobile,emilyvon/titanium_mobile,pec1985/titanium_mobile,KangaCoders/titanium_mobile,KoketsoMabuela92/titanium_mobile,benbahrenburg/titanium_mobile,csg-coder/titanium_mobile,shopmium/titanium_mobile,indera/titanium_mobile,prop/titanium_mobile,bright-sparks/titanium_mobile,formalin14/titanium_mobile,openbaoz/titanium_mobile,smit1625/titanium_mobile,falkolab/titanium_mobile,bhatfield/titanium_mobile,ashcoding/titanium_mobile,peymanmortazavi/titanium_mobile,benbahrenburg/titanium_mobile,mano-mykingdom/titanium_mobile,perdona/titanium_mobile,falkolab/titanium_mobile,benbahrenburg/titanium_mobile,jhaynie/titanium_mobile,peymanmortazavi/titanium_mobile,jhaynie/titanium_mobile,KangaCoders/titanium_mobile,formalin14/titanium_mobile,bright-sparks/titanium_mobile,mano-mykingdom/titanium_mobile,jhaynie/titanium_mobile,peymanmortazavi/titanium_mobile,bhatfield/titanium_mobile,kopiro/titanium_mobile,pinnamur/titanium_mobile,prop/titanium_mobile,bhatfield/titanium_mobile,ashcoding/titanium_mobile,linearhub/titanium_mobile,indera/titanium_mobile,smit1625/titanium_mobile,smit1625/titanium_mobile,hieupham007/Titanium_Mobile,benbahrenburg/titanium_mobile,taoger/titanium_mobile,rblalock/titanium_mobile,jvkops/titanium_mobile,mvitr/titanium_mobile,mano-mykingdom/titanium_mobile,KangaCoders/titanium_mobile,FokkeZB/titanium_mobile,jhaynie/titanium_mobile,benbahrenburg/titanium_mobile,mvitr/titanium_mobile,bhatfield/titanium_mobile,mvitr/titanium_mobile,prop/titanium_mobile,mvitr/titanium_mobile,kopiro/titanium_mobile,formalin14/titanium_mobile,linearhub/titanium_mobile,csg-coder/titanium_mobile,smit1625/titanium_mobile,shopmium/titanium_mobile,sriks/titanium_mobile,benbahrenburg/titanium_mobile,emilyvon/titanium_mobile,bhatfield/titanium_mobile,FokkeZB/titanium_mobile,jhaynie/titanium_mobile,cheekiatng/titanium_mobile,perdona/titanium_mobile,sriks/titanium_mobile,openbaoz/titanium_mobile,collinprice/titanium_mobile,KoketsoMabuela92/titanium_mobile,collinprice/titanium_mobile,falkolab/titanium_mobile,bright-sparks/titanium_mobile,perdona/titanium_mobile,shopmium/titanium_mobile,KoketsoMabuela92/titanium_mobile,linearhub/titanium_mobile,perdona/titanium_mobile,AngelkPetkov/titanium_mobile,cheekiatng/titanium_mobile,peymanmortazavi/titanium_mobile,cheekiatng/titanium_mobile,csg-coder/titanium_mobile,hieupham007/Titanium_Mobile,FokkeZB/titanium_mobile,formalin14/titanium_mobile,pec1985/titanium_mobile,kopiro/titanium_mobile,linearhub/titanium_mobile,linearhub/titanium_mobile,jhaynie/titanium_mobile,taoger/titanium_mobile,AngelkPetkov/titanium_mobile,indera/titanium_mobile,FokkeZB/titanium_mobile,sriks/titanium_mobile,pinnamur/titanium_mobile,rblalock/titanium_mobile,sriks/titanium_mobile,perdona/titanium_mobile,linearhub/titanium_mobile,jvkops/titanium_mobile | /*global describe, Ti, valueOf */
describe("Ti.Filesystem tests", {
optionalArgAPIs: function() {
// https://appcelerator.lighthouseapp.com/projects/32238/tickets/2211-android-filesystem-test-generates-runtime-error
var newDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'mydir');
newDir.createDirectory();
valueOf(newDir.exists()).shouldBeTrue();
newDir.deleteDirectory();
valueOf(newDir.exists()).shouldBeFalse();
},
readWriteText: function() {
var TEXT = "This is my text";
var FILENAME = 'test.txt';
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, FILENAME);
if (file.exists()) {
file.deleteFile();
}
//TODO: What is the writability of a file that does not exist? The spec is silent on this.
//Arguments can be made either way (True, we can write, false, no file exists)
file.write(TEXT);
valueOf(file.writable).shouldBeTrue();
// nullify and re-create to test
file = null;
file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, FILENAME);
valueOf(file.exists()).shouldBeTrue();
var blob = file.read();
valueOf(blob).shouldNotBeNull();
var readText = blob.text;
valueOf(readText).shouldNotBeNull();
valueOf(readText).shouldNotBeUndefined();
valueOf(readText).shouldBeString();
valueOf(readText.length).shouldBe(TEXT.length);
valueOf(readText).shouldBe(TEXT);
file.deleteFile();
},
blobNativeFile: function() {
var filename = 'blobtest';
var testphrase = 'Revenge of the Blob';
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
if (file.exists()) {
file.deleteFile();
}
file.write(testphrase);
var blob = file.read();
file = null;
var path = blob.nativePath;
file = Ti.Filesystem.getFile(path);
valueOf(file.exists()).shouldBeTrue();
var readphrase = file.read().text;
valueOf(readphrase).shouldBe(testphrase);
},
blobFile: function() {
var filename = 'blobtest';
var testphrase = 'Revenge of the Blob';
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
if (file.exists()) {
file.deleteFile();
}
file.write(testphrase);
var blob = file.read();
var blobFile = blob.file;
valueOf(blobFile.nativePath).shouldBe(file.nativePath);
valueOf(blobFile.exists()).shouldBeTrue();
var readphrase = blobFile.read().text;
valueOf(readphrase).shouldBe(testphrase);
file = null;
},
// https://appcelerator.lighthouseapp.com/projects/32238-titanium-mobile/tickets/2443-android-paths-beginning-with-are-not-recognised#ticket-2443-6
dotSlash: function() {
var f;
var blob;
valueOf(function(){f = Ti.Filesystem.getFile('./file.txt');}).shouldNotThrowException();
//Resource files are readonly, but only on device, not simulator. As such, we can't test
//the use case of where writable should be false.
valueOf(function(){blob = f.read();}).shouldNotThrowException();
var text;
valueOf(function(){text = blob.text;}).shouldNotThrowException();
valueOf(text.length).shouldBeGreaterThan(0);
},
appendStringTest:function() {
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'data.txt');
valueOf(f).shouldNotBeNull();
var appended_text = 'Some appended text';
var previous_text = "";
// Check if the file exists before trying to read from it!
if(f.exists()) {
var prev_blob;
valueOf(function() {
prev_blob = f.read();
previous_text = prev_blob.text;
}).shouldNotThrowException();
}
f.write(appended_text, true);
var final_blob = f.read();
valueOf(final_blob).shouldNotBeNull();
valueOf(final_blob.text).shouldBe(previous_text + appended_text);
},
appendBlobTest: function() {
var blob = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'file.txt').read();
var dest = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'append_blob.txt');
valueOf(blob).shouldNotBeNull();
valueOf(dest).shouldNotBeNull();
var previous = "";
if(dest.exists()) {
var dest_blob = dest.read();
valueOf(dest_blob).shouldNotBeNull();
previous = dest_blob.text;
}
dest.write(blob, true);
var final_blob = dest.read();
valueOf(final_blob).shouldNotBeNull();
valueOf(final_blob.text).shouldBe(previous + blob.text);
},
appendFileTest: function() {
var source = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'file.txt');
var dest = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'append_file.txt');
var previous = "";
valueOf(source).shouldNotBeNull();
valueOf(dest).shouldNotBeNull();
if(dest.exists()) {
previous = dest.read().text;
}
dest.write(source, true);
var source_blob = source.read();
valueOf(source_blob).shouldNotBeNull();
var dest_blob = dest.read();
valueOf(dest_blob).shouldNotBeNull();
valueOf(dest_blob.text).shouldBe(previous + source_blob.text);
},
// FileStream tests
fileStreamBasicTest:function() {
valueOf(Ti.createBuffer).shouldBeFunction();
valueOf(Ti.Filesystem.openStream).shouldBeFunction();
var resourceFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
valueOf(resourceFileStream).shouldBeObject();
valueOf(resourceFileStream.read).shouldBeFunction();
valueOf(resourceFileStream.write).shouldBeFunction();
var inBuffer = Ti.createBuffer();
valueOf(inBuffer).shouldBeObject();
var tempBufferLength = 50;
var tempBuffer = Ti.createBuffer({length:tempBufferLength});
valueOf(tempBuffer).shouldBeObject();
valueOf(tempBuffer.length).shouldBe(tempBufferLength);
var bytesRead = resourceFileStream.read(tempBuffer);
while(bytesRead > -1) {
Ti.API.info('bytes read ' + bytesRead);
// buffer is expanded to contain the new data and the length is updated to reflect this
var previousData = inBuffer.toString();
inBuffer.append(tempBuffer);
// assert that the append worked correctly
valueOf(previousData + tempBuffer.toString()).shouldBe(inBuffer.toString());
// clear the buffer rather than creating a new temp one
tempBuffer.clear();
bytesRead = resourceFileStream.read(tempBuffer);
}
resourceFileStream.close();
// assert that we can read/write successfully from the out file.
var appDataFileOutStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_out.txt');
appDataFileOutStream.write(inBuffer); //write inBuffer to outfile
appDataFileOutStream.close();
var outBuffer = Ti.createBuffer({length:50}); // have to set length on read buffer or no data will be read
var appDataFileInStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.applicationDataDirectory, 'stream_test_out.txt');
bytesRead = appDataFileInStream.read(outBuffer); //read 50 byes of data from outfile into outBuffer
appDataFileInStream.close();
for (var i=0; i < bytesRead; i++) {
valueOf(inBuffer[i]).shouldBeExactly(outBuffer[i]);
}
},
fileStreamWriteTest:function() {
var infile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
var instream = infile.open(Ti.Filesystem.MODE_READ);
var outfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fswritetest.jpg');
var outstream = outfile.open(Ti.Filesystem.MODE_WRITE);
var buffer = Ti.createBuffer({length: 20});
var totalWriteSize = 0;
var size = 0;
while ((size = instream.read(buffer)) > -1) {
outstream.write(buffer, 0, size);
totalWriteSize += size;
}
instream.close();
outstream.close();
infile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fswritetest.jpg');
instream = infile.open(Ti.Filesystem.MODE_READ);
var inBuffer = Ti.Stream.readAll(instream);
var totalReadSize = inBuffer.length;
valueOf(totalReadSize).shouldBeExactly(totalWriteSize);
instream.close();
},
fileStreamAppendTest:function() {
var infile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
var instream = infile.open(Ti.Filesystem.MODE_READ);
var outfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fsappendtest.jpg');
if(outfile.exists()) {
outfile.deleteFile();
}
var outstream = outfile.open(Ti.Filesystem.MODE_WRITE);
var bytesStreamed = Ti.Stream.writeStream(instream, outstream, 40);
instream.close();
outstream.close();
infile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
instream = infile.open(Ti.Filesystem.MODE_READ);
var appendfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fsappendtest.jpg');
var appendstream = appendfile.open(Ti.Filesystem.MODE_APPEND);
var buffer = Ti.createBuffer({length: 20});
var totalWriteSize = 0;
var size = 0;
while ((size = instream.read(buffer)) > -1) {
appendstream.write(buffer, 0, size);
totalWriteSize += size;
}
instream.close();
appendstream.close();
infile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fsappendtest.jpg');
instream = infile.open(Ti.Filesystem.MODE_READ);
var inBuffer = Ti.Stream.readAll(instream);
var totalReadSize = inBuffer.length;
Ti.API.info('Total read size: '+totalReadSize);
Ti.API.info('Streamed: '+bytesStreamed);
Ti.API.info('Total write size: '+totalWriteSize);
valueOf(totalReadSize).shouldBeExactly(bytesStreamed + totalWriteSize);
instream.close();
},
fileStreamPumpTest:function() {
var pumpInputFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
valueOf(pumpInputFile).shouldBeObject();
valueOf(pumpInputFile.open).shouldBeFunction();
valueOf(pumpInputFile.exists()).shouldBeTrue();
var step = 10;
var pumpTotal = 0;
var pumpCallback = function(e) {
if(e.bytesProcessed == -1) {
//EOF
Ti.API.info('Reached EOF in pumpCallback');
return;
}
Ti.API.info('Received data chunk of size <' + e.bytesProcessed + '>');
Ti.API.info('Received buffer <' + e.buffer + '>');
Ti.API.info('Total bytes received thus far <' + e.totalBytesProcessed + '>');
valueOf(e.bytesProcessed).shouldBe(step);
valueOf(e.totalBytesProcessed).shouldBe(step + pumpTotal);
pumpTotal += e.bytesProcessed;
};
var pumpStream = pumpInputFile.open(Ti.Filesystem.MODE_READ);
valueOf(pumpStream).shouldBeObject();
Ti.Stream.pump(pumpStream, pumpCallback, step);
pumpStream.close();
},
fileStreamWriteStreamTest:function() {
var inBuffer = Ti.createBuffer({value:"huray for data, lets have a party for data1 huray for data, lets have a party for data2 huray for data, lets have a party for data3"});
valueOf(inBuffer).shouldBeObject();
var inStream = Ti.Stream.createStream({source:inBuffer, mode:Ti.Stream.MODE_READ});
valueOf(inStream).shouldNotBeNull();
var outFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_out.txt');
valueOf(outFileStream).shouldBeObject();
// writes all data from inBufferStream to outFileStream in chunks of 30
var bytesWritten = Ti.Stream.writeStream(inStream, outFileStream, 30);
Ti.API.info('<' + bytesWritten + '> bytes written, closing both streams');
// assert that the length of the outBuffer is equal to the amount of bytes that were written
valueOf(bytesWritten).shouldBe(inBuffer.length);
outFileStream.close();
},
fileStreamResourceFileTest:function() {
if(Ti.Platform.osname === 'android') {
valueOf(function() {Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt')}).shouldThrowException();
valueOf(function() {Ti.Filesystem.openStream(Ti.Filesystem.MODE_APPEND, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt')}).shouldThrowException();
valueOf(function() {
var resourceFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
resourceFileStream.close()
}).shouldNotThrowException();
}
},
fileStreamTruncateTest:function() {
var inBuffer = Ti.createBuffer({value:"huray for data, lets have a party for data1 huray for data, lets have a party for data2 huray for data, lets have a party for data3"});
valueOf(inBuffer).shouldBeObject();
var inStream = Ti.Stream.createStream({source:inBuffer, mode:Ti.Stream.MODE_READ});
valueOf(inStream).shouldNotBeNull();
var outFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_truncate.txt');
valueOf(outFileStream).shouldBeObject();
// writes all data from inBufferStream to outFileStream in chunks of 30
var bytesWritten = Ti.Stream.writeStream(inStream, outFileStream, 30);
Ti.API.info('<' + bytesWritten + '> bytes written, closing both streams');
// assert that the length of the outBuffer is equal to the amount of bytes that were written
valueOf(bytesWritten).shouldBe(inBuffer.length);
outFileStream.close();
var outFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_truncate.txt');
valueOf(outFileStream).shouldBeObject();
outFileStream.close();
var inFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.applicationDataDirectory, 'stream_test_truncate.txt');
valueOf(inFileStream).shouldBeObject();
var truncateBuffer = Ti.Stream.readAll(inFileStream);
valueOf(truncateBuffer.length).shouldBeExactly(0);
inFileStream.close();
},
fileMove: function() {
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'text.txt');
var contents = f.read();
var newDir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'movedir');
if(!newDir.exists()) {
newDir.createDirectory();
}
valueOf(newDir.exists()).shouldBeTrue();
var newFile = Titanium.Filesystem.getFile(newDir.nativePath,'newfile.txt');
newFile.write(f.read());
valueOf(newFile.exists()).shouldBeTrue();
// remove destination file if it exists otherwise the test will fail on multiple runs
var destinationFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory+'/moved.txt');
if(destinationFile.exists()) {
destinationFile.deleteFile();
}
valueOf(newFile.move(Titanium.Filesystem.applicationDataDirectory+'/moved.txt')).shouldBeTrue();
},
tempDirTest:function() {
var filename = "drillbit_temp_file.txt";
valueOf(Ti.Filesystem.getTempDirectory).shouldBeFunction();
var outBuffer = Ti.createBuffer({value:"huray for data, lets have a party for data1 huray for data, lets have a party for data2 huray for data, lets have a party for data3"});
valueOf(outBuffer).shouldBeObject();
var tempFileOutStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.tempDirectory, filename);
tempFileOutStream.write(outBuffer); //write inBuffer to outfile
tempFileOutStream.close();
var inBuffer = Ti.createBuffer({length:200}); // have to set length on read buffer or no data will be read
var tempFileInStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.tempDirectory, filename);
bytesRead = tempFileInStream.read(inBuffer); //read 200 byes of data from outfile into outBuffer
tempFileInStream.close();
for (var i=0; i < bytesRead; i++) {
valueOf(inBuffer[i]).shouldBeExactly(outBuffer[i]);
}
},
emptyFile: function() {
var emptyFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "empty.txt");
valueOf(emptyFile).shouldNotBeNull();
valueOf(emptyFile.size).shouldBe(0);
var blob = emptyFile.read();
valueOf(blob.length).shouldBe(0);
valueOf(blob.text).shouldBe("");
valueOf(blob.toString()).shouldBe("");
},
fileSize:function() {
// For now, all we can do is make sure the size is not 0
// without dumping a file of an exact size
// NOTE: Android might be failing this right now; I only
// found a getSize() op in their code.
var testFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "file.txt");
valueOf(testFile).shouldNotBeNull();
valueOf(testFile.size).shouldNotBe(0);
var blob = testFile.read();
valueOf(blob.length).shouldNotBe(0);
},
mimeType:function() {
// Android currently fails this http://jira.appcelerator.org/browse/TIMOB-7394
// removing for the time being as this is not a regression against 1.8.0.1
// fallout work from the Filesystem parity effort will resolve this difference
// with udpated tests
if (Ti.Platform.osname != 'android') {
var files = ['test.css','test.xml','test.txt','test.js','test.htm','test.html','test.svg','test.svgz','test.png','test.jpg','test.jpeg','test.gif','test.wav','test.mp4','test.mov','test.mpeg','test.m4v'];
//Use common suffix when more than 1 mimeType is associated with an extension.
//Otherwise use full mimeType for comparison
var extensions = ['css','xml','text/plain','javascript','text/html','text/html','image/svg+xml','image/svg+xml','image/png','image/jpeg','image/jpeg','image/gif','wav','mp4','video/quicktime','mpeg','video/x-m4v'];
var i=0;
for (i=0;i<files.length;i++)
{
var filename = files[i];
var testExt = extensions[i];
var file1 = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,filename);
if(file1.exists() == false)
{
file1.createFile();
}
valueOf(file1).shouldNotBeNull();
var blob1 = file1.read();
valueOf(blob1).shouldNotBeNull();
var mimeType = blob1.mimeType;
var result = ( (mimeType.length >= testExt.length) && (mimeType.substr(mimeType.length - testExt.length) == testExt) );
Ti.API.info(filename+" "+mimeType+" "+testExt);
valueOf(result).shouldBeTrue();
}
}
}
});
| drillbit/tests/filesystem/filesystem.js | /*global describe, Ti, valueOf */
describe("Ti.Filesystem tests", {
optionalArgAPIs: function() {
// https://appcelerator.lighthouseapp.com/projects/32238/tickets/2211-android-filesystem-test-generates-runtime-error
var newDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'mydir');
newDir.createDirectory();
valueOf(newDir.exists()).shouldBeTrue();
newDir.deleteDirectory();
valueOf(newDir.exists()).shouldBeFalse();
},
readWriteText: function() {
var TEXT = "This is my text";
var FILENAME = 'test.txt';
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, FILENAME);
if (file.exists()) {
file.deleteFile();
}
//TODO: What is the writability of a file that does not exist? The spec is silent on this.
//Arguments can be made either way (True, we can write, false, no file exists)
file.write(TEXT);
valueOf(file.writable).shouldBeTrue();
// nullify and re-create to test
file = null;
file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, FILENAME);
valueOf(file.exists()).shouldBeTrue();
var blob = file.read();
valueOf(blob).shouldNotBeNull();
var readText = blob.text;
valueOf(readText).shouldNotBeNull();
valueOf(readText).shouldNotBeUndefined();
valueOf(readText).shouldBeString();
valueOf(readText.length).shouldBe(TEXT.length);
valueOf(readText).shouldBe(TEXT);
file.deleteFile();
},
blobNativeFile: function() {
var filename = 'blobtest';
var testphrase = 'Revenge of the Blob';
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
if (file.exists()) {
file.deleteFile();
}
file.write(testphrase);
var blob = file.read();
file = null;
var path = blob.nativePath;
file = Ti.Filesystem.getFile(path);
valueOf(file.exists()).shouldBeTrue();
var readphrase = file.read().text;
valueOf(readphrase).shouldBe(testphrase);
},
blobFile: function() {
var filename = 'blobtest';
var testphrase = 'Revenge of the Blob';
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
if (file.exists()) {
file.deleteFile();
}
file.write(testphrase);
var blob = file.read();
var blobFile = blob.file;
valueOf(blobFile.nativePath).shouldBe(file.nativePath);
valueOf(blobFile.exists()).shouldBeTrue();
var readphrase = blobFile.read().text;
valueOf(readphrase).shouldBe(testphrase);
file = null;
},
// https://appcelerator.lighthouseapp.com/projects/32238-titanium-mobile/tickets/2443-android-paths-beginning-with-are-not-recognised#ticket-2443-6
dotSlash: function() {
var f;
var blob;
valueOf(function(){f = Ti.Filesystem.getFile('./file.txt');}).shouldNotThrowException();
//Resource files are readonly, but only on device, not simulator. As such, we can't test
//the use case of where writable should be false.
valueOf(function(){blob = f.read();}).shouldNotThrowException();
var text;
valueOf(function(){text = blob.text;}).shouldNotThrowException();
valueOf(text.length).shouldBeGreaterThan(0);
},
appendStringTest:function() {
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'data.txt');
valueOf(f).shouldNotBeNull();
var appended_text = 'Some appended text';
var previous_text = "";
// Check if the file exists before trying to read from it!
if(f.exists()) {
var prev_blob;
valueOf(function() {
prev_blob = f.read();
previous_text = prev_blob.text;
}).shouldNotThrowException();
}
f.write(appended_text, true);
var final_blob = f.read();
valueOf(final_blob).shouldNotBeNull();
valueOf(final_blob.text).shouldBe(previous_text + appended_text);
},
appendBlobTest: function() {
var blob = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'file.txt').read();
var dest = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'append_blob.txt');
valueOf(blob).shouldNotBeNull();
valueOf(dest).shouldNotBeNull();
var previous = "";
if(dest.exists()) {
var dest_blob = dest.read();
valueOf(dest_blob).shouldNotBeNull();
previous = dest_blob.text;
}
dest.write(blob, true);
var final_blob = dest.read();
valueOf(final_blob).shouldNotBeNull();
valueOf(final_blob.text).shouldBe(previous + blob.text);
},
appendFileTest: function() {
var source = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'file.txt');
var dest = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'append_file.txt');
var previous = "";
valueOf(source).shouldNotBeNull();
valueOf(dest).shouldNotBeNull();
if(dest.exists()) {
previous = dest.read().text;
}
dest.write(source, true);
var source_blob = source.read();
valueOf(source_blob).shouldNotBeNull();
var dest_blob = dest.read();
valueOf(dest_blob).shouldNotBeNull();
valueOf(dest_blob.text).shouldBe(previous + source_blob.text);
},
// FileStream tests
fileStreamBasicTest:function() {
valueOf(Ti.createBuffer).shouldBeFunction();
valueOf(Ti.Filesystem.openStream).shouldBeFunction();
var resourceFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
valueOf(resourceFileStream).shouldBeObject();
valueOf(resourceFileStream.read).shouldBeFunction();
valueOf(resourceFileStream.write).shouldBeFunction();
var inBuffer = Ti.createBuffer();
valueOf(inBuffer).shouldBeObject();
var tempBufferLength = 50;
var tempBuffer = Ti.createBuffer({length:tempBufferLength});
valueOf(tempBuffer).shouldBeObject();
valueOf(tempBuffer.length).shouldBe(tempBufferLength);
var bytesRead = resourceFileStream.read(tempBuffer);
while(bytesRead > -1) {
Ti.API.info('bytes read ' + bytesRead);
// buffer is expanded to contain the new data and the length is updated to reflect this
var previousData = inBuffer.toString();
inBuffer.append(tempBuffer);
// assert that the append worked correctly
valueOf(previousData + tempBuffer.toString()).shouldBe(inBuffer.toString());
// clear the buffer rather than creating a new temp one
tempBuffer.clear();
bytesRead = resourceFileStream.read(tempBuffer);
}
resourceFileStream.close();
// assert that we can read/write successfully from the out file.
var appDataFileOutStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_out.txt');
appDataFileOutStream.write(inBuffer); //write inBuffer to outfile
appDataFileOutStream.close();
var outBuffer = Ti.createBuffer({length:50}); // have to set length on read buffer or no data will be read
var appDataFileInStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.applicationDataDirectory, 'stream_test_out.txt');
bytesRead = appDataFileInStream.read(outBuffer); //read 50 byes of data from outfile into outBuffer
appDataFileInStream.close();
for (var i=0; i < bytesRead; i++) {
valueOf(inBuffer[i]).shouldBeExactly(outBuffer[i]);
}
},
fileStreamWriteTest:function() {
var infile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
var instream = infile.open(Ti.Filesystem.MODE_READ);
var outfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fswritetest.jpg');
var outstream = outfile.open(Ti.Filesystem.MODE_WRITE);
var buffer = Ti.createBuffer({length: 20});
var totalWriteSize = 0;
var size = 0;
while ((size = instream.read(buffer)) > -1) {
outstream.write(buffer, 0, size);
totalWriteSize += size;
}
instream.close();
outstream.close();
infile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fswritetest.jpg');
instream = infile.open(Ti.Filesystem.MODE_READ);
var inBuffer = Ti.Stream.readAll(instream);
var totalReadSize = inBuffer.length;
valueOf(totalReadSize).shouldBeExactly(totalWriteSize);
instream.close();
},
fileStreamAppendTest:function() {
var infile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
var instream = infile.open(Ti.Filesystem.MODE_READ);
var outfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fsappendtest.jpg');
if(outfile.exists()) {
outfile.deleteFile();
}
var outstream = outfile.open(Ti.Filesystem.MODE_WRITE);
var bytesStreamed = Ti.Stream.writeStream(instream, outstream, 40);
instream.close();
outstream.close();
infile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
instream = infile.open(Ti.Filesystem.MODE_READ);
var appendfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fsappendtest.jpg');
var appendstream = appendfile.open(Ti.Filesystem.MODE_APPEND);
var buffer = Ti.createBuffer({length: 20});
var totalWriteSize = 0;
var size = 0;
while ((size = instream.read(buffer)) > -1) {
appendstream.write(buffer, 0, size);
totalWriteSize += size;
}
instream.close();
appendstream.close();
infile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'fsappendtest.jpg');
instream = infile.open(Ti.Filesystem.MODE_READ);
var inBuffer = Ti.Stream.readAll(instream);
var totalReadSize = inBuffer.length;
Ti.API.info('Total read size: '+totalReadSize);
Ti.API.info('Streamed: '+bytesStreamed);
Ti.API.info('Total write size: '+totalWriteSize);
valueOf(totalReadSize).shouldBeExactly(bytesStreamed + totalWriteSize);
instream.close();
},
fileStreamPumpTest:function() {
var pumpInputFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
valueOf(pumpInputFile).shouldBeObject();
valueOf(pumpInputFile.open).shouldBeFunction();
valueOf(pumpInputFile.exists()).shouldBeTrue();
var step = 10;
var pumpTotal = 0;
var pumpCallback = function(e) {
if(e.bytesProcessed == -1) {
//EOF
Ti.API.info('Reached EOF in pumpCallback');
return;
}
Ti.API.info('Received data chunk of size <' + e.bytesProcessed + '>');
Ti.API.info('Received buffer <' + e.buffer + '>');
Ti.API.info('Total bytes received thus far <' + e.totalBytesProcessed + '>');
valueOf(e.bytesProcessed).shouldBe(step);
valueOf(e.totalBytesProcessed).shouldBe(step + pumpTotal);
pumpTotal += e.bytesProcessed;
};
var pumpStream = pumpInputFile.open(Ti.Filesystem.MODE_READ);
valueOf(pumpStream).shouldBeObject();
Ti.Stream.pump(pumpStream, pumpCallback, step);
pumpStream.close();
},
fileStreamWriteStreamTest:function() {
var inBuffer = Ti.createBuffer({value:"huray for data, lets have a party for data1 huray for data, lets have a party for data2 huray for data, lets have a party for data3"});
valueOf(inBuffer).shouldBeObject();
var inStream = Ti.Stream.createStream({source:inBuffer, mode:Ti.Stream.MODE_READ});
valueOf(inStream).shouldNotBeNull();
var outFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_out.txt');
valueOf(outFileStream).shouldBeObject();
// writes all data from inBufferStream to outFileStream in chunks of 30
var bytesWritten = Ti.Stream.writeStream(inStream, outFileStream, 30);
Ti.API.info('<' + bytesWritten + '> bytes written, closing both streams');
// assert that the length of the outBuffer is equal to the amount of bytes that were written
valueOf(bytesWritten).shouldBe(inBuffer.length);
outFileStream.close();
},
fileStreamResourceFileTest:function() {
if(Ti.Platform.osname === 'android') {
valueOf(function() {Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt')}).shouldThrowException();
valueOf(function() {Ti.Filesystem.openStream(Ti.Filesystem.MODE_APPEND, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt')}).shouldThrowException();
valueOf(function() {
var resourceFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.resourcesDirectory, 'stream_test_in.txt');
resourceFileStream.close()
}).shouldNotThrowException();
}
},
fileStreamTruncateTest:function() {
var inBuffer = Ti.createBuffer({value:"huray for data, lets have a party for data1 huray for data, lets have a party for data2 huray for data, lets have a party for data3"});
valueOf(inBuffer).shouldBeObject();
var inStream = Ti.Stream.createStream({source:inBuffer, mode:Ti.Stream.MODE_READ});
valueOf(inStream).shouldNotBeNull();
var outFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_truncate.txt');
valueOf(outFileStream).shouldBeObject();
// writes all data from inBufferStream to outFileStream in chunks of 30
var bytesWritten = Ti.Stream.writeStream(inStream, outFileStream, 30);
Ti.API.info('<' + bytesWritten + '> bytes written, closing both streams');
// assert that the length of the outBuffer is equal to the amount of bytes that were written
valueOf(bytesWritten).shouldBe(inBuffer.length);
outFileStream.close();
var outFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.applicationDataDirectory, 'stream_test_truncate.txt');
valueOf(outFileStream).shouldBeObject();
outFileStream.close();
var inFileStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.applicationDataDirectory, 'stream_test_truncate.txt');
valueOf(inFileStream).shouldBeObject();
var truncateBuffer = Ti.Stream.readAll(inFileStream);
valueOf(truncateBuffer.length).shouldBeExactly(0);
inFileStream.close();
},
fileMove: function() {
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'text.txt');
var contents = f.read();
var newDir = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'movedir');
if(!newDir.exists()) {
newDir.createDirectory();
}
valueOf(newDir.exists()).shouldBeTrue();
var newFile = Titanium.Filesystem.getFile(newDir.nativePath,'newfile.txt');
newFile.write(f.read());
valueOf(newFile.exists()).shouldBeTrue();
// remove destination file if it exists otherwise the test will fail on multiple runs
var destinationFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory+'/moved.txt');
if(destinationFile.exists()) {
destinationFile.deleteFile();
}
valueOf(newFile.move(Titanium.Filesystem.applicationDataDirectory+'/moved.txt')).shouldBeTrue();
},
tempDirTest:function() {
var filename = "drillbit_temp_file.txt";
valueOf(Ti.Filesystem.getTempDirectory).shouldBeFunction();
var outBuffer = Ti.createBuffer({value:"huray for data, lets have a party for data1 huray for data, lets have a party for data2 huray for data, lets have a party for data3"});
valueOf(outBuffer).shouldBeObject();
var tempFileOutStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_WRITE, Ti.Filesystem.tempDirectory, filename);
tempFileOutStream.write(outBuffer); //write inBuffer to outfile
tempFileOutStream.close();
var inBuffer = Ti.createBuffer({length:200}); // have to set length on read buffer or no data will be read
var tempFileInStream = Ti.Filesystem.openStream(Ti.Filesystem.MODE_READ, Ti.Filesystem.tempDirectory, filename);
bytesRead = tempFileInStream.read(inBuffer); //read 200 byes of data from outfile into outBuffer
tempFileInStream.close();
for (var i=0; i < bytesRead; i++) {
valueOf(inBuffer[i]).shouldBeExactly(outBuffer[i]);
}
},
emptyFile: function() {
var emptyFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "empty.txt");
valueOf(emptyFile).shouldNotBeNull();
valueOf(emptyFile.size).shouldBe(0);
var blob = emptyFile.read();
valueOf(blob.length).shouldBe(0);
valueOf(blob.text).shouldBe("");
valueOf(blob.toString()).shouldBe("");
},
fileSize:function() {
// For now, all we can do is make sure the size is not 0
// without dumping a file of an exact size
// NOTE: Android might be failing this right now; I only
// found a getSize() op in their code.
var testFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, "file.txt");
valueOf(testFile).shouldNotBeNull();
valueOf(testFile.size).shouldNotBe(0);
var blob = testFile.read();
valueOf(blob.length).shouldNotBe(0);
},
mimeType:function() {
var files = ['test.css','test.xml','test.txt','test.js','test.htm','test.html','test.svg','test.svgz','test.png','test.jpg','test.jpeg','test.gif','test.wav','test.mp4','test.mov','test.mpeg','test.m4v'];
//Use common suffix when more than 1 mimeType is associated with an extension.
//Otherwise use full mimeType for comparison
var extensions = ['css','xml','text/plain','javascript','text/html','text/html','image/svg+xml','image/svg+xml','image/png','image/jpeg','image/jpeg','image/gif','wav','mp4','video/quicktime','mpeg','video/x-m4v'];
var i=0;
for (i=0;i<files.length;i++)
{
var filename = files[i];
var testExt = extensions[i];
var file1 = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,filename);
if(file1.exists() == false)
{
file1.createFile();
}
valueOf(file1).shouldNotBeNull();
var blob1 = file1.read();
valueOf(blob1).shouldNotBeNull();
var mimeType = blob1.mimeType;
var result = ( (mimeType.length >= testExt.length) && (mimeType.substr(mimeType.length - testExt.length) == testExt) );
Ti.API.info(filename+" "+mimeType+" "+testExt);
valueOf(result).shouldBeTrue();
}
}
});
| TIMOB-7395 update filesystem system check in drillbit for mimetype to include platform check
| drillbit/tests/filesystem/filesystem.js | TIMOB-7395 update filesystem system check in drillbit for mimetype to include platform check | <ide><path>rillbit/tests/filesystem/filesystem.js
<ide> },
<ide>
<ide> mimeType:function() {
<del>
<del> var files = ['test.css','test.xml','test.txt','test.js','test.htm','test.html','test.svg','test.svgz','test.png','test.jpg','test.jpeg','test.gif','test.wav','test.mp4','test.mov','test.mpeg','test.m4v'];
<del>
<del> //Use common suffix when more than 1 mimeType is associated with an extension.
<del> //Otherwise use full mimeType for comparison
<del> var extensions = ['css','xml','text/plain','javascript','text/html','text/html','image/svg+xml','image/svg+xml','image/png','image/jpeg','image/jpeg','image/gif','wav','mp4','video/quicktime','mpeg','video/x-m4v'];
<del>
<del> var i=0;
<del>
<del> for (i=0;i<files.length;i++)
<del> {
<del> var filename = files[i];
<del> var testExt = extensions[i];
<del> var file1 = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,filename);
<del> if(file1.exists() == false)
<add> // Android currently fails this http://jira.appcelerator.org/browse/TIMOB-7394
<add> // removing for the time being as this is not a regression against 1.8.0.1
<add> // fallout work from the Filesystem parity effort will resolve this difference
<add> // with udpated tests
<add>
<add> if (Ti.Platform.osname != 'android') {
<add> var files = ['test.css','test.xml','test.txt','test.js','test.htm','test.html','test.svg','test.svgz','test.png','test.jpg','test.jpeg','test.gif','test.wav','test.mp4','test.mov','test.mpeg','test.m4v'];
<add>
<add> //Use common suffix when more than 1 mimeType is associated with an extension.
<add> //Otherwise use full mimeType for comparison
<add> var extensions = ['css','xml','text/plain','javascript','text/html','text/html','image/svg+xml','image/svg+xml','image/png','image/jpeg','image/jpeg','image/gif','wav','mp4','video/quicktime','mpeg','video/x-m4v'];
<add>
<add> var i=0;
<add>
<add> for (i=0;i<files.length;i++)
<ide> {
<del> file1.createFile();
<add> var filename = files[i];
<add> var testExt = extensions[i];
<add> var file1 = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,filename);
<add> if(file1.exists() == false)
<add> {
<add> file1.createFile();
<add> }
<add> valueOf(file1).shouldNotBeNull();
<add>
<add> var blob1 = file1.read();
<add> valueOf(blob1).shouldNotBeNull();
<add> var mimeType = blob1.mimeType;
<add>
<add> var result = ( (mimeType.length >= testExt.length) && (mimeType.substr(mimeType.length - testExt.length) == testExt) );
<add>
<add> Ti.API.info(filename+" "+mimeType+" "+testExt);
<add> valueOf(result).shouldBeTrue();
<ide> }
<del> valueOf(file1).shouldNotBeNull();
<del>
<del> var blob1 = file1.read();
<del> valueOf(blob1).shouldNotBeNull();
<del> var mimeType = blob1.mimeType;
<del>
<del> var result = ( (mimeType.length >= testExt.length) && (mimeType.substr(mimeType.length - testExt.length) == testExt) );
<del>
<del> Ti.API.info(filename+" "+mimeType+" "+testExt);
<del> valueOf(result).shouldBeTrue();
<del>
<ide> }
<ide> }
<ide> }); |
|
Java | apache-2.0 | de05e55500de05169068982deb8075e9346c1a2a | 0 | inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service | /*
* Copyright 2012 Shared Learning Collaborative, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slc.sli.ingestion.transformation;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.slc.sli.api.constants.EntityNames;
import org.slc.sli.common.util.datetime.DateTimeUtil;
import org.slc.sli.common.util.uuid.UUIDGeneratorStrategy;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.ingestion.NeutralRecord;
import org.slc.sli.ingestion.util.spring.MessageSourceHelper;
/**
* Transforms disjoint set of attendance events into cleaner set of {school year : list of
* attendance events} mappings and stores in the appropriate student-school or student-section
* associations.
*
* @author shalka
*/
@Scope("prototype")
@Component("attendanceTransformationStrategy")
public class AttendanceTransformer extends AbstractTransformationStrategy implements MessageSourceAware{
private static final Logger LOG = LoggerFactory.getLogger(AttendanceTransformer.class);
private static final String ATTENDANCE = "attendance";
private static final String ATTENDANCE_EVENT = "attendanceEvent";
private static final String ATTENDANCE_EVENT_REASON = "attendanceEventReason";
private static final String ATTENDANCE_TRANSFORMED = ATTENDANCE + "_transformed";
private static final String STATE_ORGANIZATION_ID = "StateOrganizationId";
private static final String EDUCATIONAL_ORG_ID = "EducationalOrgIdentity";
private static final String SCHOOL = "school";
private static final String SCHOOL_ID = "schoolId";
private static final String SCHOOL_YEAR = "schoolYear";
private static final String STUDENT_ID = "studentId";
private static final String SESSION = "session";
private static final String STUDENT_SCHOOL_ASSOCIATION = "studentSchoolAssociation";
private static final String DATE = "date";
private static final String EVENT = "event";
private int numAttendancesIngested = 0;
private Map<Object, NeutralRecord> attendances;
private MessageSource messageSource;
@Autowired
private UUIDGeneratorStrategy type1UUIDGeneratorStrategy;
/**
* Default constructor.
*/
public AttendanceTransformer() {
attendances = new HashMap<Object, NeutralRecord>();
}
/**
* The chaining of transformation steps. This implementation assumes that all data will be
* processed in "one-go."
*/
@Override
public void performTransformation() {
loadData();
transform();
}
/**
* Pre-requisite interchanges for daily attendance data to be successfully transformed:
* student, education organization, education organization calendar, master schedule,
* student enrollment
*/
public void loadData() {
LOG.info("Loading data for attendance transformation.");
attendances = getCollectionFromDb(ATTENDANCE);
LOG.info("{} is loaded into local storage. Total Count = {}", ATTENDANCE, attendances.size());
}
/**
* Transforms attendance events from Ed-Fi model into SLI model.
*/
public void transform() {
LOG.info("Transforming attendance data");
Map<String, List<Map<String, Object>>> studentAttendanceEvents = new HashMap<String, List<Map<String, Object>>>();
Map<Pair<String, String>, List<Map<String, Object>>> studentSchoolAttendanceEvents = new HashMap<Pair<String, String>, List<Map<String, Object>>>();
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : attendances.entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
Map<String, Object> attributes = neutralRecord.getAttributes();
String studentId = null;
try {
studentId = (String) PropertyUtils.getNestedProperty(attributes,
"StudentReference.StudentIdentity.StudentUniqueStateId");
} catch (IllegalAccessException e) {
LOG.error("Failed to extract StudentUniqueStateId from attendance entity", e);
} catch (InvocationTargetException e) {
LOG.error("Failed to extract StudentUniqueStateId from attendance entity", e);
} catch (NoSuchMethodException e) {
LOG.error("Failed to extract StudentUniqueStateId from attendance entity", e);
}
if (attributes.containsKey(SCHOOL_ID)) {
Object stateOrganizationId = attributes.get(SCHOOL_ID);
if (stateOrganizationId instanceof String) {
String schoolId = (String) stateOrganizationId;
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
if (studentSchoolAttendanceEvents.containsKey(Pair.of(studentId, schoolId))) {
events = studentSchoolAttendanceEvents.get(Pair.of(studentId, schoolId));
}
Map<String, Object> event = new HashMap<String, Object>();
String eventDate = (String) attributes.get("eventDate");
String eventCategory = (String) attributes.get("attendanceEventCategory");
event.put(DATE, eventDate);
event.put(EVENT, eventCategory);
if (attributes.containsKey(ATTENDANCE_EVENT_REASON)) {
String eventReason = (String) attributes.get(ATTENDANCE_EVENT_REASON);
event.put("reason", eventReason);
}
events.add(event);
studentSchoolAttendanceEvents.put(Pair.of(studentId, schoolId), events);
}
} else {
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
if (studentAttendanceEvents.containsKey(studentId)) {
events = studentAttendanceEvents.get(studentId);
}
Map<String, Object> event = new HashMap<String, Object>();
String eventDate = (String) attributes.get("eventDate");
String eventCategory = (String) attributes.get("attendanceEventCategory");
event.put(DATE, eventDate);
event.put(EVENT, eventCategory);
if (attributes.containsKey(ATTENDANCE_EVENT_REASON)) {
String eventReason = (String) attributes.get(ATTENDANCE_EVENT_REASON);
event.put("reason", eventReason);
}
events.add(event);
studentAttendanceEvents.put(studentId, events);
}
}
if (studentSchoolAttendanceEvents.size() > 0) {
LOG.info("Discovered {} student-school associations from attendance events",
studentSchoolAttendanceEvents.size());
for (Map.Entry<Pair<String, String>, List<Map<String, Object>>> entry : studentSchoolAttendanceEvents
.entrySet()) {
Pair<String, String> studentSchoolPair = entry.getKey();
List<Map<String, Object>> attendance = entry.getValue();
String studentId = studentSchoolPair.getLeft();
String schoolId = studentSchoolPair.getRight();
transformAndPersistAttendanceEvents(studentId, schoolId, attendance);
}
}
if (studentAttendanceEvents.size() > 0) {
LOG.info("Discovered {} students from attendance events that need school mappings",
studentAttendanceEvents.size());
for (Map.Entry<String, List<Map<String, Object>>> entry : studentAttendanceEvents.entrySet()) {
String studentId = entry.getKey();
List<Map<String, Object>> attendance = entry.getValue();
List<NeutralRecord> schools = getSchoolsForStudent(studentId);
if (schools.size() == 0) {
LOG.error("Student with id: {} is not associated to any schools.", studentId);
} else if (schools.size() > 1) {
LOG.error("Student with id: {} is associated to more than one school.", studentId);
} else {
NeutralRecord school = schools.get(0);
String schoolId = (String) school.getAttributes().get("stateOrganizationId");
transformAndPersistAttendanceEvents(studentId, schoolId, attendance);
}
}
}
long numAttendance = attendances.size();
if (numAttendance != numAttendancesIngested) {
long remainingAttendances = numAttendance - numAttendancesIngested;
super.getErrorReport(attendances.values().iterator().next().getSourceFile())
.warning(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG1",Long.toString(remainingAttendances) ) , this);
}
LOG.info("Finished transforming attendance data");
}
/**
* Transforms attendance data for the given student-school pair and persists to staging mongo
* db.
*
* @param studentId
* Student Unique State Id.
* @param schoolId
* State Organization Id.
* @param attendance
* List of transformed attendance events.
*/
private void transformAndPersistAttendanceEvents(String studentId, String schoolId,
List<Map<String, Object>> attendance) {
Map<Object, NeutralRecord> sessions = getSessions(schoolId);
LOG.debug("For student with id: {} in school: {}", studentId, schoolId);
LOG.debug(" Found {} associated sessions.", sessions.size());
LOG.debug(" Found {} attendance events.", attendance.size());
try {
// create a placeholder for the student-school pair and write to staging mongo db
NeutralRecord placeholder = createAttendanceRecordPlaceholder(studentId, schoolId, sessions);
placeholder.setCreationTime(getWorkNote().getRangeMinimum());
insertRecord(placeholder);
} catch (DuplicateKeyException dke) {
LOG.warn(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG2"));
}
Map<String, List<Map<String, Object>>> schoolYears = mapAttendanceIntoSchoolYears(attendance, sessions, studentId, schoolId);
if (schoolYears.entrySet().size() > 0) {
for (Map.Entry<String, List<Map<String, Object>>> attendanceEntry : schoolYears.entrySet()) {
String schoolYear = attendanceEntry.getKey();
List<Map<String, Object>> events = attendanceEntry.getValue();
NeutralQuery query = new NeutralQuery(1);
query.addCriteria(new NeutralCriteria(BATCH_JOB_ID_KEY, NeutralCriteria.OPERATOR_EQUAL, getBatchJobId(), false));
query.addCriteria(new NeutralCriteria(STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, studentId));
query.addCriteria(new NeutralCriteria("schoolId." + EDUCATIONAL_ORG_ID + "." + STATE_ORGANIZATION_ID, NeutralCriteria.OPERATOR_EQUAL, schoolId));
query.addCriteria(new NeutralCriteria("schoolYearAttendance.schoolYear",
NeutralCriteria.OPERATOR_EQUAL, schoolYear));
Map<String, Object> attendanceEventsToPush = new HashMap<String, Object>();
attendanceEventsToPush.put("body.schoolYearAttendance.$.attendanceEvent", events.toArray());
Map<String, Object> update = new HashMap<String, Object>();
update.put("pushAll", attendanceEventsToPush);
getNeutralRecordMongoAccess().getRecordRepository().updateFirstForJob(query, update,
ATTENDANCE_TRANSFORMED);
LOG.debug("Added {} attendance events for school year: {}", events.size(), schoolYear);
}
} else {
LOG.warn(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG3", studentId, schoolId));
}
}
/**
* Creates a Neutral Record of type 'attendance'.
*
* @return newly created 'attendance' Neutral Record.
*/
private NeutralRecord createAttendanceRecordPlaceholder(String studentId, String schoolId,
Map<Object, NeutralRecord> sessions) {
NeutralRecord record = new NeutralRecord();
record.setRecordId(type1UUIDGeneratorStrategy.generateId().toString());
record.setRecordType(ATTENDANCE_TRANSFORMED);
record.setBatchJobId(getBatchJobId());
Map<String, List<Map<String, Object>>> placeholders = createAttendancePlaceholdersFromSessions(sessions);
List<Map<String, Object>> daily = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, List<Map<String, Object>>> year : placeholders.entrySet()) {
String schoolYear = year.getKey();
List<Map<String, Object>> events = year.getValue();
Map<String, Object> schoolYearAttendanceEvents = new HashMap<String, Object>();
schoolYearAttendanceEvents.put(SCHOOL_YEAR, schoolYear);
schoolYearAttendanceEvents.put(ATTENDANCE_EVENT, events);
daily.add(schoolYearAttendanceEvents);
}
Map<String, Object> attendanceAttributes = new HashMap<String, Object>();
// rebuild StudentReference, since that is what reference resolution will expect
Map<String, Object> studentReference = new HashMap<String, Object>();
Map<String, Object> studentIdentity = new HashMap<String, Object>();
studentIdentity.put("StudentUniqueStateId", studentId);
studentReference.put("StudentIdentity", studentIdentity);
attendanceAttributes.put("StudentReference", studentReference);
attendanceAttributes.put(STUDENT_ID, studentId);
attendanceAttributes.put(SCHOOL_ID, createEdfiSchoolReference(schoolId));
attendanceAttributes.put("schoolYearAttendance", daily);
record.setAttributes(attendanceAttributes);
record.setSourceFile(attendances.values().iterator().next().getSourceFile());
record.setLocationInSourceFile(attendances.values().iterator().next().getLocationInSourceFile());
return record;
}
/**
* Gets all schools associated with the specified student.
*
* @param studentId
* StudentUniqueStateId for student.
* @return List of Neutral Records representing schools.
*/
private List<NeutralRecord> getSchoolsForStudent(String studentId) {
List<NeutralRecord> schools = new ArrayList<NeutralRecord>();
Query query = new Query().limit(0);
query.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
query.addCriteria(Criteria.where("body.studentId").is(studentId));
Iterable<NeutralRecord> associations = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
STUDENT_SCHOOL_ASSOCIATION, query);
if (associations != null) {
List<String> schoolIds = new ArrayList<String>();
for (NeutralRecord association : associations) {
Map<String, Object> associationAttributes = association.getAttributes();
String schoolId = (String) associationAttributes.get(SCHOOL_ID);
schoolIds.add(schoolId);
}
Query schoolQuery = new Query().limit(0);
schoolQuery.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
schoolQuery.addCriteria(Criteria.where("body.stateOrganizationId").in(schoolIds));
Iterable<NeutralRecord> queriedSchools = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
SCHOOL, schoolQuery);
if (queriedSchools != null) {
Iterator<NeutralRecord> itr = queriedSchools.iterator();
NeutralRecord record = null;
while (itr.hasNext()) {
record = itr.next();
schools.add(record);
}
}
}
if (schools.size() == 0) {
schools.addAll(getSchoolsForStudentFromSLI(studentId));
}
return schools;
}
private List<NeutralRecord> getSchoolsForStudentFromSLI(String studentUniqueStateId) {
List<NeutralRecord> schools = new ArrayList<NeutralRecord>();
NeutralQuery studentQuery = new NeutralQuery(0);
studentQuery.addCriteria(new NeutralCriteria("studentUniqueStateId", NeutralCriteria.OPERATOR_EQUAL, studentUniqueStateId));
Entity studentEntity = getMongoEntityRepository().findOne(EntityNames.STUDENT, studentQuery);
String studentEntityId = "";
if (studentEntity != null) {
studentEntityId = studentEntity.getEntityId();
}
NeutralQuery query = new NeutralQuery(0);
query.addCriteria(new NeutralCriteria(STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, studentEntityId));
Iterable<Entity> associations = getMongoEntityRepository().findAll(EntityNames.STUDENT_SCHOOL_ASSOCIATION, query);
if (associations != null) {
List<String> schoolIds = new ArrayList<String>();
for (Entity association : associations) {
Map<String, Object> associationAttributes = association.getBody();
String schoolId = (String) associationAttributes.get(SCHOOL_ID);
schoolIds.add(schoolId);
}
NeutralQuery schoolQuery = new NeutralQuery(0);
schoolQuery.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, schoolIds));
Iterable<Entity> queriedSchools = getMongoEntityRepository().findAll(EntityNames.EDUCATION_ORGANIZATION, schoolQuery);
if (queriedSchools != null) {
Iterator<Entity> itr = queriedSchools.iterator();
NeutralRecord record = null;
Entity entity = null;
while (itr.hasNext()) {
entity = itr.next();
record = new NeutralRecord();
record.setAttributes(entity.getBody());
schools.add(record);
}
}
}
return schools;
}
/**
* Gets all sessions associated with the specified student-school pair.
*
* @param studentId
* StudentUniqueStateId for student.
* @param schoolId
* StateOrganizationId for school.
* @return Map of Sessions for student-school pair.
*/
private Map<Object, NeutralRecord> getSessions(String schoolId) {
Map<Object, NeutralRecord> sessions = new HashMap<Object, NeutralRecord>();
Query query = new Query().limit(0);
query.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
query.addCriteria(Criteria.where("body.schoolId").is(schoolId));
Iterable<NeutralRecord> queriedSessions = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
SESSION, query);
//get sessions of the school from SLI db
Iterable<NeutralRecord> sliSessions = getSliSessions(schoolId);
queriedSessions = concat((List<NeutralRecord>) queriedSessions, (List<NeutralRecord>) sliSessions);
if (queriedSessions != null) {
Iterator<NeutralRecord> itr = queriedSessions.iterator();
NeutralRecord record = null;
while (itr.hasNext()) {
record = itr.next();
sessions.put(record.getRecordId(), record);
}
}
String parentEducationAgency = getParentEdOrg(schoolId);
if (parentEducationAgency != null) {
sessions.putAll(getSessions(parentEducationAgency));
}
return sessions;
}
/**
* Gets the Parent Education Organization associated with a specific school
*
* @param schoolId
* The StateOrganizationid for the school
* @return The Id of the Parent Education Organization
*/
@SuppressWarnings("unchecked")
private String getParentEdOrg(String schoolId) {
Query schoolQuery = new Query().limit(1);
schoolQuery.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
schoolQuery.addCriteria(Criteria.where("body.stateOrganizationId").is(schoolId));
Iterable<NeutralRecord> queriedSchool = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
SCHOOL, schoolQuery);
String parentEducationAgency = null;
if (queriedSchool.iterator().hasNext()) {
NeutralRecord record = queriedSchool.iterator().next();
Map<String, Object> edorgReference = (Map<String, Object>) record.getAttributes().get("LocalEducationAgencyReference");
if (edorgReference != null) {
Map<String, Object> edorgIdentity = (Map<String, Object>) edorgReference.get(EDUCATIONAL_ORG_ID);
if (edorgIdentity != null) {
parentEducationAgency = (String) (edorgIdentity.get(STATE_ORGANIZATION_ID));
}
}
} else {
Entity school = getSliSchool(schoolId);
if (school != null) {
String parentEducationAgencyID = (String) school.getBody().get("parentEducationAgencyReference");
if (parentEducationAgencyID != null) {
// look up the state edorg id of parent from SLI using its _id. Since the child is in sli, the parent must be as well.
NeutralQuery parentQuery = new NeutralQuery(0);
parentQuery.addCriteria(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, parentEducationAgencyID));
Entity parent = getMongoEntityRepository().findOne(EntityNames.EDUCATION_ORGANIZATION, parentQuery);
parentEducationAgency = (String) parent.getBody().get("stateOrganizationId");
}
}
}
return parentEducationAgency;
}
/**
* Creates placeholders for attendance events based on provided sessions.
*
* @param sessions
* Sessions enumerating school years to key off of for attendance events.
* @return Map containing { schoolYear --> empty list }
*/
private Map<String, List<Map<String, Object>>> createAttendancePlaceholdersFromSessions(
Map<Object, NeutralRecord> sessions) {
Map<String, List<Map<String, Object>>> placeholders = new HashMap<String, List<Map<String, Object>>>();
for (Map.Entry<Object, NeutralRecord> session : sessions.entrySet()) {
NeutralRecord sessionRecord = session.getValue();
Map<String, Object> sessionAttributes = sessionRecord.getAttributes();
String schoolYear = (String) sessionAttributes.get(SCHOOL_YEAR);
if (schoolYear != null) {
placeholders.put(schoolYear, new ArrayList<Map<String, Object>>());
}
}
return placeholders;
}
/**
* Maps the set of student attendance events into a transformed map of form {school year : list
* of attendance events} based
* on dates published in the sessions.
*
* @param studentAttendance
* Set of student attendance events.
* @param sessions
* Set of sessions that correspond to the school the student attends.
* @param studentId
* studentUniqueStateId of the student.
* @param schoolId
* stateOrganizationId of the school the student attends.
* @return Map containing transformed attendance information.
*/
protected Map<String, List<Map<String, Object>>> mapAttendanceIntoSchoolYears(List<Map<String, Object>> attendance,
Map<Object, NeutralRecord> sessions, String studentId, String schoolId) {
// Step 1: prepare stageing SchoolYearAttendances
Set<SchoolYearAttendance> stageSchoolYearAttendances = new HashSet<SchoolYearAttendance>();
Set<Integer> processedAttendances = new HashSet<Integer>();
for (Map.Entry<Object, NeutralRecord> session : sessions.entrySet()) {
NeutralRecord sessionRecord = session.getValue();
Map<String, Object> sessionAttributes = sessionRecord.getAttributes();
String schoolYear = (String) sessionAttributes.get(SCHOOL_YEAR);
DateTime sessionBegin = DateTimeUtil.parseDateTime((String) sessionAttributes.get("beginDate"));
DateTime sessionEnd = DateTimeUtil.parseDateTime((String) sessionAttributes.get("endDate"));
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
for (int i = 0; i < attendance.size(); i++) {
Map<String, Object> event = attendance.get(i);
String eventDate = (String) event.get(DATE);
DateTime date = DateTimeUtil.parseDateTime(eventDate);
if (DateTimeUtil.isLeftDateBeforeRightDate(sessionBegin, date)
&& DateTimeUtil.isLeftDateBeforeRightDate(date, sessionEnd)) {
events.add(event);
//Only count one attendance event once.
processedAttendances.add(i);
}
}
int eventSize = events.size();
if (eventSize > 0 ) {
stageSchoolYearAttendances.add(new SchoolYearAttendance(schoolYear, events));
}
}
numAttendancesIngested += processedAttendances.size();
if (sessions.entrySet().size() == 0 && attendance.size() > 0) {
super.getErrorReport(attendances.values().iterator().next().getSourceFile())
.warning(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG4",studentId,schoolId), this);
}
// Step 2: retrieve sli SchoolYearAttendances
Set<SchoolYearAttendance> sliSchoolYearAttendances = getSliSchoolYearAttendances(studentId, schoolId);
// Step 3: merge sli and staging SchoolYearAttendances
Set<SchoolYearAttendance> mergedAttendances = mergeSchoolYearAttendance(sliSchoolYearAttendances, stageSchoolYearAttendances);
Map<String, List<Map<String, Object>>> schoolYears = new HashMap<String, List<Map<String, Object>>>();
for (SchoolYearAttendance schoolYearAttendance : mergedAttendances) {
schoolYears.put(schoolYearAttendance.getSchoolYear(), schoolYearAttendance.getAttendanceEvent());
}
return schoolYears;
}
/**
* Merge the sets of SchoolYearAttendance from SLI and stage.
*
* @param sliSchoolYearAttendances
* Set containing SchoolYearAttendance from sli.
* @param stageSchoolYearAttendances
* Set containing SchoolYearAttendance from stage.
* @return Set containing SchoolYearAttendance merged from both.
*/
private Set<SchoolYearAttendance> mergeSchoolYearAttendance(Set<SchoolYearAttendance> sliSchoolYearAttendances,
Set<SchoolYearAttendance> stageSchoolYearAttendances) {
if (sliSchoolYearAttendances.size() == 0) {
return stageSchoolYearAttendances;
}
if (stageSchoolYearAttendances.size() == 0) {
return sliSchoolYearAttendances;
}
Set<SchoolYearAttendance> newSchoolYearAttendances = new HashSet<SchoolYearAttendance>();
for (SchoolYearAttendance stageSchoolYearAttendance : stageSchoolYearAttendances) {
boolean merged = false;
for (SchoolYearAttendance sliSchoolYearAttendance : sliSchoolYearAttendances) {
//check and merge
if (sliSchoolYearAttendance.sameSchoolYear(stageSchoolYearAttendance)) {
//find same school year
//merge stageSchoolYearAttendance into sliSchoolYearAttendance
sliSchoolYearAttendance.mergeAndUpdateAttendanceEvent(stageSchoolYearAttendance);
merged = true;
break;
}
}
if (!merged) {
//Add new school year
newSchoolYearAttendances.add(stageSchoolYearAttendance);
}
}
newSchoolYearAttendances.addAll(sliSchoolYearAttendances);
return newSchoolYearAttendances;
}
/**
* Retrieve the set of student attendance events from SLI.
*
* @param studentUniqueStateId
* studentUniqueStateId of the student.
* @param stateOrganizationId
* stateOrganizationId of the school the student attends.
* @return Set containing SchoolYearAttendance retrieved from SLI.
*/
@SuppressWarnings("unchecked")
private Set<SchoolYearAttendance> getSliSchoolYearAttendances(String studentUniqueStateId, String stateOrganizationId) {
Set<SchoolYearAttendance> attendanceSet = new HashSet<SchoolYearAttendance>();
NeutralQuery studentQuery = new NeutralQuery(0);
studentQuery.addCriteria(new NeutralCriteria("studentUniqueStateId", NeutralCriteria.OPERATOR_EQUAL, studentUniqueStateId));
Entity studentEntity = getMongoEntityRepository().findOne(EntityNames.STUDENT, studentQuery);
String studentEntityId = null;
if (studentEntity != null) {
studentEntityId = studentEntity.getEntityId();
} else {
return attendanceSet;
}
NeutralQuery schoolQuery = new NeutralQuery(0);
schoolQuery.addCriteria(new NeutralCriteria("stateOrganizationId", NeutralCriteria.OPERATOR_EQUAL, stateOrganizationId));
Entity schoolEntity = getMongoEntityRepository().findOne(EntityNames.EDUCATION_ORGANIZATION, schoolQuery);
String schoolEntityId = null;
if (schoolEntity != null) {
schoolEntityId = schoolEntity.getEntityId();
} else {
return attendanceSet;
}
NeutralQuery attendanceQuery = new NeutralQuery(0);
attendanceQuery.addCriteria(new NeutralCriteria(STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, studentEntityId));
attendanceQuery.addCriteria(new NeutralCriteria(SCHOOL_ID, NeutralCriteria.OPERATOR_EQUAL, schoolEntityId));
Entity attendanceEntity = getMongoEntityRepository().findOne(EntityNames.ATTENDANCE, attendanceQuery);
if (attendanceEntity == null) {
return attendanceSet;
}
List<Map<String, Object>> schoolYearAttendance = (List<Map<String, Object>>) attendanceEntity.getBody().get("schoolYearAttendance");
if (schoolYearAttendance == null || schoolYearAttendance.size() == 0) {
return attendanceSet;
}
for (Map<String, Object> yearAttendance : schoolYearAttendance) {
String schoolYear = (String) yearAttendance.get(SCHOOL_YEAR);
List<Map<String, Object>> attendanceEvent = (List<Map<String, Object>>) yearAttendance.get(ATTENDANCE_EVENT);
if (attendanceEvent.size() > 0) {
attendanceSet.add(new SchoolYearAttendance(schoolYear, attendanceEvent));
}
}
return attendanceSet;
}
private Entity getSliSchool(String stateOrganizationId) {
NeutralQuery schoolQuery = new NeutralQuery(0);
schoolQuery.addCriteria(new NeutralCriteria("stateOrganizationId", NeutralCriteria.OPERATOR_EQUAL, stateOrganizationId));
return getMongoEntityRepository().findOne(EntityNames.EDUCATION_ORGANIZATION, schoolQuery);
}
/**
* Get the sessions from SLI db
* @param schoolName:
* @return: List of sessions of the school from SLI
*/
private Iterable<NeutralRecord> getSliSessions(String stateOrganizationId) {
//Get schoolId within SLI db
//TODO: we may not need this query when deterministic ID is implemented.
Entity school = getSliSchool(stateOrganizationId);
String sliSchoolId = "";
if (school != null) {
sliSchoolId = school.getEntityId();
} else {
return new ArrayList<NeutralRecord>();
}
NeutralQuery sessionQuery = new NeutralQuery(0);
sessionQuery.addCriteria(new NeutralCriteria(SCHOOL_ID, NeutralCriteria.OPERATOR_EQUAL, sliSchoolId));
Iterable<NeutralRecord> sliSessions = transformIntoNeutralRecord(getMongoEntityRepository().findAll(EntityNames.SESSION, sessionQuery));
return sliSessions;
}
private Iterable<NeutralRecord> transformIntoNeutralRecord(Iterable<Entity> entities) {
Iterator<Entity> entityItr = entities.iterator();
List<NeutralRecord> sessionRecords = new ArrayList<NeutralRecord>();
//Trasnforming SLI entity back to neutralRecord
Entity sliSession = null;
while (entityItr.hasNext()) {
sliSession = entityItr.next();
NeutralRecord session = new NeutralRecord();
session.setRecordId(sliSession.getEntityId());
session.setRecordType(sliSession.getType());
session.setBatchJobId(getBatchJobId());
session.setAttributes(sliSession.getBody());
sessionRecords.add(session);
}
return sessionRecords;
}
/*
* This function only concatenate 2 lists sessions of the same school. Since the keys for sessions are schoolId
* and session name, this functions only needs to distinguish sessions via sessionName.
*/
private Iterable<NeutralRecord> concat(List<NeutralRecord> first, List<NeutralRecord> second) {
List<NeutralRecord> res = new ArrayList<NeutralRecord>();
res.addAll(first);
Set<String> sessions = new HashSet<String>();
for(NeutralRecord record : first) {
sessions.add((String) record.getAttributes().get("sessionName"));
}
for(NeutralRecord record : second) {
String sKey = (String) record.getAttributes().get("sessionName");
if(!sessions.contains(sKey)) {
sessions.add(sKey);
res.add(record);
}
}
return res;
}
/**
* create a school reference that can be resolved by the deterministic ID resolver
*/
private static Map<String, Object> createEdfiSchoolReference(String schoolId) {
Map<String, Object> schoolReferenceObj = new HashMap<String, Object>();
Map<String, Object> idObj = new HashMap<String, Object>();
idObj.put(STATE_ORGANIZATION_ID, schoolId);
schoolReferenceObj.put(EDUCATIONAL_ORG_ID, idObj);
return schoolReferenceObj;
}
/**
* TODO: add javadoc
*
*/
static class SchoolYearAttendance {
private String schoolYear;
private List<Map<String, Object>> attendanceEvent;
public SchoolYearAttendance(String schoolYear, List<Map<String, Object>> attendanceEvent) {
this.schoolYear = schoolYear;
this.attendanceEvent = attendanceEvent;
}
public void mergeAndUpdateAttendanceEvent(SchoolYearAttendance obj) {
if (!sameSchoolYear(obj)) {
return;
}
for (Map<String, Object> stageAttendance : obj.attendanceEvent) {
for (Map<String, Object> sliAttendance : this.attendanceEvent) {
Object sliEvent = sliAttendance.get(EVENT);
Object stageEvent = stageAttendance.get(EVENT);
Object sliDate = sliAttendance.get(DATE);
Object stageDate = stageAttendance.get(DATE);
boolean eventMatch = sliEvent != null && stageEvent != null && sliEvent.equals(stageEvent);
boolean dateMatch = sliDate != null && stageDate != null && sliDate.equals(stageDate);
if (eventMatch && dateMatch) {
//remove matched to prevent duplicated
this.attendanceEvent.remove(sliAttendance);
break;
}
}
}
List<Map<String, Object>> mergedAttendanceEvent = new ArrayList<Map<String, Object>>();
mergedAttendanceEvent.addAll(this.attendanceEvent);
mergedAttendanceEvent.addAll(obj.attendanceEvent);
this.attendanceEvent = mergedAttendanceEvent;
}
public boolean sameSchoolYear(SchoolYearAttendance obj) {
return obj.schoolYear != null && obj.schoolYear.equals(this.schoolYear);
}
public String getSchoolYear() {
return this.schoolYear;
}
public List<Map<String, Object>> getAttendanceEvent() {
return this.attendanceEvent;
}
@Override
public String toString() {
return "schoolYear:" + schoolYear + ",attendanceEvent:" + attendanceEvent;
}
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
}
| sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AttendanceTransformer.java | /*
* Copyright 2012 Shared Learning Collaborative, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slc.sli.ingestion.transformation;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.slc.sli.api.constants.EntityNames;
import org.slc.sli.common.util.datetime.DateTimeUtil;
import org.slc.sli.common.util.uuid.UUIDGeneratorStrategy;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.ingestion.NeutralRecord;
import org.slc.sli.ingestion.util.spring.MessageSourceHelper;
/**
* Transforms disjoint set of attendance events into cleaner set of {school year : list of
* attendance events} mappings and stores in the appropriate student-school or student-section
* associations.
*
* @author shalka
*/
@Scope("prototype")
@Component("attendanceTransformationStrategy")
public class AttendanceTransformer extends AbstractTransformationStrategy implements MessageSourceAware{
private static final Logger LOG = LoggerFactory.getLogger(AttendanceTransformer.class);
private static final String ATTENDANCE = "attendance";
private static final String ATTENDANCE_EVENT = "attendanceEvent";
private static final String ATTENDANCE_EVENT_REASON = "attendanceEventReason";
private static final String ATTENDANCE_TRANSFORMED = ATTENDANCE + "_transformed";
private static final String STATE_ORGANIZATION_ID = "StateOrganizationId";
private static final String EDUCATIONAL_ORG_ID = "EducationalOrgIdentity";
private static final String SCHOOL = "school";
private static final String SCHOOL_ID = "schoolId";
private static final String SCHOOL_YEAR = "schoolYear";
private static final String STUDENT_ID = "studentId";
private static final String SESSION = "session";
private static final String STUDENT_SCHOOL_ASSOCIATION = "studentSchoolAssociation";
private static final String DATE = "date";
private static final String EVENT = "event";
private int numAttendancesIngested = 0;
private Map<Object, NeutralRecord> attendances;
private MessageSource messageSource;
@Autowired
private UUIDGeneratorStrategy type1UUIDGeneratorStrategy;
/**
* Default constructor.
*/
public AttendanceTransformer() {
attendances = new HashMap<Object, NeutralRecord>();
}
/**
* The chaining of transformation steps. This implementation assumes that all data will be
* processed in "one-go."
*/
@Override
public void performTransformation() {
loadData();
transform();
}
/**
* Pre-requisite interchanges for daily attendance data to be successfully transformed:
* student, education organization, education organization calendar, master schedule,
* student enrollment
*/
public void loadData() {
LOG.info("Loading data for attendance transformation.");
attendances = getCollectionFromDb(ATTENDANCE);
LOG.info("{} is loaded into local storage. Total Count = {}", ATTENDANCE, attendances.size());
}
/**
* Transforms attendance events from Ed-Fi model into SLI model.
*/
public void transform() {
LOG.info("Transforming attendance data");
Map<String, List<Map<String, Object>>> studentAttendanceEvents = new HashMap<String, List<Map<String, Object>>>();
Map<Pair<String, String>, List<Map<String, Object>>> studentSchoolAttendanceEvents = new HashMap<Pair<String, String>, List<Map<String, Object>>>();
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : attendances.entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
Map<String, Object> attributes = neutralRecord.getAttributes();
String studentId = null;
try {
studentId = (String) PropertyUtils.getNestedProperty(attributes,
"StudentReference.StudentIdentity.StudentUniqueStateId");
} catch (IllegalAccessException e) {
LOG.error("Failed to extract StudentUniqueStateId from attendance entity", e);
} catch (InvocationTargetException e) {
LOG.error("Failed to extract StudentUniqueStateId from attendance entity", e);
} catch (NoSuchMethodException e) {
LOG.error("Failed to extract StudentUniqueStateId from attendance entity", e);
}
if (attributes.containsKey(SCHOOL_ID)) {
Object stateOrganizationId = attributes.get(SCHOOL_ID);
if (stateOrganizationId != null && stateOrganizationId instanceof String) {
String schoolId = (String) stateOrganizationId;
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
if (studentSchoolAttendanceEvents.containsKey(Pair.of(studentId, schoolId))) {
events = studentSchoolAttendanceEvents.get(Pair.of(studentId, schoolId));
}
Map<String, Object> event = new HashMap<String, Object>();
String eventDate = (String) attributes.get("eventDate");
String eventCategory = (String) attributes.get("attendanceEventCategory");
event.put(DATE, eventDate);
event.put(EVENT, eventCategory);
if (attributes.containsKey(ATTENDANCE_EVENT_REASON)) {
String eventReason = (String) attributes.get(ATTENDANCE_EVENT_REASON);
event.put("reason", eventReason);
}
events.add(event);
studentSchoolAttendanceEvents.put(Pair.of(studentId, schoolId), events);
}
} else {
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
if (studentAttendanceEvents.containsKey(studentId)) {
events = studentAttendanceEvents.get(studentId);
}
Map<String, Object> event = new HashMap<String, Object>();
String eventDate = (String) attributes.get("eventDate");
String eventCategory = (String) attributes.get("attendanceEventCategory");
event.put(DATE, eventDate);
event.put(EVENT, eventCategory);
if (attributes.containsKey(ATTENDANCE_EVENT_REASON)) {
String eventReason = (String) attributes.get(ATTENDANCE_EVENT_REASON);
event.put("reason", eventReason);
}
events.add(event);
studentAttendanceEvents.put(studentId, events);
}
}
if (studentSchoolAttendanceEvents.size() > 0) {
LOG.info("Discovered {} student-school associations from attendance events",
studentSchoolAttendanceEvents.size());
for (Map.Entry<Pair<String, String>, List<Map<String, Object>>> entry : studentSchoolAttendanceEvents
.entrySet()) {
Pair<String, String> studentSchoolPair = entry.getKey();
List<Map<String, Object>> attendance = entry.getValue();
String studentId = studentSchoolPair.getLeft();
String schoolId = studentSchoolPair.getRight();
transformAndPersistAttendanceEvents(studentId, schoolId, attendance);
}
}
if (studentAttendanceEvents.size() > 0) {
LOG.info("Discovered {} students from attendance events that need school mappings",
studentAttendanceEvents.size());
for (Map.Entry<String, List<Map<String, Object>>> entry : studentAttendanceEvents.entrySet()) {
String studentId = entry.getKey();
List<Map<String, Object>> attendance = entry.getValue();
List<NeutralRecord> schools = getSchoolsForStudent(studentId);
if (schools.size() == 0) {
LOG.error("Student with id: {} is not associated to any schools.", studentId);
} else if (schools.size() > 1) {
LOG.error("Student with id: {} is associated to more than one school.", studentId);
} else {
NeutralRecord school = schools.get(0);
String schoolId = (String) school.getAttributes().get("stateOrganizationId");
transformAndPersistAttendanceEvents(studentId, schoolId, attendance);
}
}
}
long numAttendance = attendances.size();
if (numAttendance != numAttendancesIngested) {
long remainingAttendances = numAttendance - numAttendancesIngested;
super.getErrorReport(attendances.values().iterator().next().getSourceFile())
.warning(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG1",Long.toString(remainingAttendances) ) , this);
}
LOG.info("Finished transforming attendance data");
}
/**
* Transforms attendance data for the given student-school pair and persists to staging mongo
* db.
*
* @param studentId
* Student Unique State Id.
* @param schoolId
* State Organization Id.
* @param attendance
* List of transformed attendance events.
*/
private void transformAndPersistAttendanceEvents(String studentId, String schoolId,
List<Map<String, Object>> attendance) {
Map<Object, NeutralRecord> sessions = getSessions(schoolId);
LOG.debug("For student with id: {} in school: {}", studentId, schoolId);
LOG.debug(" Found {} associated sessions.", sessions.size());
LOG.debug(" Found {} attendance events.", attendance.size());
try {
// create a placeholder for the student-school pair and write to staging mongo db
NeutralRecord placeholder = createAttendanceRecordPlaceholder(studentId, schoolId, sessions);
placeholder.setCreationTime(getWorkNote().getRangeMinimum());
insertRecord(placeholder);
} catch (DuplicateKeyException dke) {
LOG.warn(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG2"));
}
Map<String, List<Map<String, Object>>> schoolYears = mapAttendanceIntoSchoolYears(attendance, sessions, studentId, schoolId);
if (schoolYears.entrySet().size() > 0) {
for (Map.Entry<String, List<Map<String, Object>>> attendanceEntry : schoolYears.entrySet()) {
String schoolYear = attendanceEntry.getKey();
List<Map<String, Object>> events = attendanceEntry.getValue();
NeutralQuery query = new NeutralQuery(1);
query.addCriteria(new NeutralCriteria(BATCH_JOB_ID_KEY, NeutralCriteria.OPERATOR_EQUAL, getBatchJobId(), false));
query.addCriteria(new NeutralCriteria(STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, studentId));
query.addCriteria(new NeutralCriteria("schoolId." + EDUCATIONAL_ORG_ID + "." + STATE_ORGANIZATION_ID, NeutralCriteria.OPERATOR_EQUAL, schoolId));
query.addCriteria(new NeutralCriteria("schoolYearAttendance.schoolYear",
NeutralCriteria.OPERATOR_EQUAL, schoolYear));
Map<String, Object> attendanceEventsToPush = new HashMap<String, Object>();
attendanceEventsToPush.put("body.schoolYearAttendance.$.attendanceEvent", events.toArray());
Map<String, Object> update = new HashMap<String, Object>();
update.put("pushAll", attendanceEventsToPush);
getNeutralRecordMongoAccess().getRecordRepository().updateFirstForJob(query, update,
ATTENDANCE_TRANSFORMED);
LOG.debug("Added {} attendance events for school year: {}", events.size(), schoolYear);
}
} else {
LOG.warn(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG3", studentId, schoolId));
}
}
/**
* Creates a Neutral Record of type 'attendance'.
*
* @return newly created 'attendance' Neutral Record.
*/
private NeutralRecord createAttendanceRecordPlaceholder(String studentId, String schoolId,
Map<Object, NeutralRecord> sessions) {
NeutralRecord record = new NeutralRecord();
record.setRecordId(type1UUIDGeneratorStrategy.generateId().toString());
record.setRecordType(ATTENDANCE_TRANSFORMED);
record.setBatchJobId(getBatchJobId());
Map<String, List<Map<String, Object>>> placeholders = createAttendancePlaceholdersFromSessions(sessions);
List<Map<String, Object>> daily = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, List<Map<String, Object>>> year : placeholders.entrySet()) {
String schoolYear = year.getKey();
List<Map<String, Object>> events = year.getValue();
Map<String, Object> schoolYearAttendanceEvents = new HashMap<String, Object>();
schoolYearAttendanceEvents.put(SCHOOL_YEAR, schoolYear);
schoolYearAttendanceEvents.put(ATTENDANCE_EVENT, events);
daily.add(schoolYearAttendanceEvents);
}
Map<String, Object> attendanceAttributes = new HashMap<String, Object>();
// rebuild StudentReference, since that is what reference resolution will expect
Map<String, Object> studentReference = new HashMap<String, Object>();
Map<String, Object> studentIdentity = new HashMap<String, Object>();
studentIdentity.put("StudentUniqueStateId", studentId);
studentReference.put("StudentIdentity", studentIdentity);
attendanceAttributes.put("StudentReference", studentReference);
attendanceAttributes.put(STUDENT_ID, studentId);
attendanceAttributes.put(SCHOOL_ID, createEdfiSchoolReference(schoolId));
attendanceAttributes.put("schoolYearAttendance", daily);
record.setAttributes(attendanceAttributes);
record.setSourceFile(attendances.values().iterator().next().getSourceFile());
record.setLocationInSourceFile(attendances.values().iterator().next().getLocationInSourceFile());
return record;
}
/**
* Gets all schools associated with the specified student.
*
* @param studentId
* StudentUniqueStateId for student.
* @return List of Neutral Records representing schools.
*/
private List<NeutralRecord> getSchoolsForStudent(String studentId) {
List<NeutralRecord> schools = new ArrayList<NeutralRecord>();
Query query = new Query().limit(0);
query.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
query.addCriteria(Criteria.where("body.studentId").is(studentId));
Iterable<NeutralRecord> associations = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
STUDENT_SCHOOL_ASSOCIATION, query);
if (associations != null) {
List<String> schoolIds = new ArrayList<String>();
for (NeutralRecord association : associations) {
Map<String, Object> associationAttributes = association.getAttributes();
String schoolId = (String) associationAttributes.get(SCHOOL_ID);
schoolIds.add(schoolId);
}
Query schoolQuery = new Query().limit(0);
schoolQuery.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
schoolQuery.addCriteria(Criteria.where("body.stateOrganizationId").in(schoolIds));
Iterable<NeutralRecord> queriedSchools = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
SCHOOL, schoolQuery);
if (queriedSchools != null) {
Iterator<NeutralRecord> itr = queriedSchools.iterator();
NeutralRecord record = null;
while (itr.hasNext()) {
record = itr.next();
schools.add(record);
}
}
}
if (schools.size() == 0) {
schools.addAll(getSchoolsForStudentFromSLI(studentId));
}
return schools;
}
private List<NeutralRecord> getSchoolsForStudentFromSLI(String studentUniqueStateId) {
List<NeutralRecord> schools = new ArrayList<NeutralRecord>();
NeutralQuery studentQuery = new NeutralQuery(0);
studentQuery.addCriteria(new NeutralCriteria("studentUniqueStateId", NeutralCriteria.OPERATOR_EQUAL, studentUniqueStateId));
Entity studentEntity = getMongoEntityRepository().findOne(EntityNames.STUDENT, studentQuery);
String studentEntityId = "";
if (studentEntity != null) {
studentEntityId = studentEntity.getEntityId();
}
NeutralQuery query = new NeutralQuery(0);
query.addCriteria(new NeutralCriteria(STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, studentEntityId));
Iterable<Entity> associations = getMongoEntityRepository().findAll(EntityNames.STUDENT_SCHOOL_ASSOCIATION, query);
if (associations != null) {
List<String> schoolIds = new ArrayList<String>();
for (Entity association : associations) {
Map<String, Object> associationAttributes = association.getBody();
String schoolId = (String) associationAttributes.get(SCHOOL_ID);
schoolIds.add(schoolId);
}
NeutralQuery schoolQuery = new NeutralQuery(0);
schoolQuery.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, schoolIds));
Iterable<Entity> queriedSchools = getMongoEntityRepository().findAll(EntityNames.EDUCATION_ORGANIZATION, schoolQuery);
if (queriedSchools != null) {
Iterator<Entity> itr = queriedSchools.iterator();
NeutralRecord record = null;
Entity entity = null;
while (itr.hasNext()) {
entity = itr.next();
record = new NeutralRecord();
record.setAttributes(entity.getBody());
schools.add(record);
}
}
}
return schools;
}
/**
* Gets all sessions associated with the specified student-school pair.
*
* @param studentId
* StudentUniqueStateId for student.
* @param schoolId
* StateOrganizationId for school.
* @return Map of Sessions for student-school pair.
*/
private Map<Object, NeutralRecord> getSessions(String schoolId) {
Map<Object, NeutralRecord> sessions = new HashMap<Object, NeutralRecord>();
Query query = new Query().limit(0);
query.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
query.addCriteria(Criteria.where("body.schoolId").is(schoolId));
Iterable<NeutralRecord> queriedSessions = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
SESSION, query);
//get sessions of the school from SLI db
Iterable<NeutralRecord> sliSessions = getSliSessions(schoolId);
queriedSessions = concat((List<NeutralRecord>) queriedSessions, (List<NeutralRecord>) sliSessions);
if (queriedSessions != null) {
Iterator<NeutralRecord> itr = queriedSessions.iterator();
NeutralRecord record = null;
while (itr.hasNext()) {
record = itr.next();
sessions.put(record.getRecordId(), record);
}
}
String parentEducationAgency = getParentEdOrg(schoolId);
if (parentEducationAgency != null) {
sessions.putAll(getSessions(parentEducationAgency));
}
return sessions;
}
/**
* Gets the Parent Education Organization associated with a specific school
*
* @param schoolId
* The StateOrganizationid for the school
* @return The Id of the Parent Education Organization
*/
@SuppressWarnings("unchecked")
private String getParentEdOrg(String schoolId) {
Query schoolQuery = new Query().limit(1);
schoolQuery.addCriteria(Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId()));
schoolQuery.addCriteria(Criteria.where("body.stateOrganizationId").is(schoolId));
Iterable<NeutralRecord> queriedSchool = getNeutralRecordMongoAccess().getRecordRepository().findAllByQuery(
SCHOOL, schoolQuery);
String parentEducationAgency = null;
if (queriedSchool.iterator().hasNext()) {
NeutralRecord record = queriedSchool.iterator().next();
Map<String, Object> edorgReference = (Map<String, Object>) record.getAttributes().get("LocalEducationAgencyReference");
if (edorgReference != null) {
Map<String, Object> edorgIdentity = (Map<String, Object>) edorgReference.get(EDUCATIONAL_ORG_ID);
if (edorgIdentity != null) {
parentEducationAgency = (String) (edorgIdentity.get(STATE_ORGANIZATION_ID));
}
}
} else {
Entity school = getSliSchool(schoolId);
if (school != null) {
String parentEducationAgencyID = (String) school.getBody().get("parentEducationAgencyReference");
if (parentEducationAgencyID != null) {
// look up the state edorg id of parent from SLI using its _id. Since the child is in sli, the parent must be as well.
NeutralQuery parentQuery = new NeutralQuery(0);
parentQuery.addCriteria(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, parentEducationAgencyID));
Entity parent = getMongoEntityRepository().findOne(EntityNames.EDUCATION_ORGANIZATION, parentQuery);
parentEducationAgency = (String) parent.getBody().get("stateOrganizationId");
}
}
}
return parentEducationAgency;
}
/**
* Creates placeholders for attendance events based on provided sessions.
*
* @param sessions
* Sessions enumerating school years to key off of for attendance events.
* @return Map containing { schoolYear --> empty list }
*/
private Map<String, List<Map<String, Object>>> createAttendancePlaceholdersFromSessions(
Map<Object, NeutralRecord> sessions) {
Map<String, List<Map<String, Object>>> placeholders = new HashMap<String, List<Map<String, Object>>>();
for (Map.Entry<Object, NeutralRecord> session : sessions.entrySet()) {
NeutralRecord sessionRecord = session.getValue();
Map<String, Object> sessionAttributes = sessionRecord.getAttributes();
String schoolYear = (String) sessionAttributes.get(SCHOOL_YEAR);
if (schoolYear != null) {
placeholders.put(schoolYear, new ArrayList<Map<String, Object>>());
}
}
return placeholders;
}
/**
* Maps the set of student attendance events into a transformed map of form {school year : list
* of attendance events} based
* on dates published in the sessions.
*
* @param studentAttendance
* Set of student attendance events.
* @param sessions
* Set of sessions that correspond to the school the student attends.
* @param studentId
* studentUniqueStateId of the student.
* @param schoolId
* stateOrganizationId of the school the student attends.
* @return Map containing transformed attendance information.
*/
protected Map<String, List<Map<String, Object>>> mapAttendanceIntoSchoolYears(List<Map<String, Object>> attendance,
Map<Object, NeutralRecord> sessions, String studentId, String schoolId) {
// Step 1: prepare stageing SchoolYearAttendances
Set<SchoolYearAttendance> stageSchoolYearAttendances = new HashSet<SchoolYearAttendance>();
Set<Integer> processedAttendances = new HashSet<Integer>();
for (Map.Entry<Object, NeutralRecord> session : sessions.entrySet()) {
NeutralRecord sessionRecord = session.getValue();
Map<String, Object> sessionAttributes = sessionRecord.getAttributes();
String schoolYear = (String) sessionAttributes.get(SCHOOL_YEAR);
DateTime sessionBegin = DateTimeUtil.parseDateTime((String) sessionAttributes.get("beginDate"));
DateTime sessionEnd = DateTimeUtil.parseDateTime((String) sessionAttributes.get("endDate"));
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
for (int i = 0; i < attendance.size(); i++) {
Map<String, Object> event = attendance.get(i);
String eventDate = (String) event.get(DATE);
DateTime date = DateTimeUtil.parseDateTime(eventDate);
if (DateTimeUtil.isLeftDateBeforeRightDate(sessionBegin, date)
&& DateTimeUtil.isLeftDateBeforeRightDate(date, sessionEnd)) {
events.add(event);
//Only count one attendance event once.
processedAttendances.add(i);
}
}
int eventSize = events.size();
if (eventSize > 0 ) {
stageSchoolYearAttendances.add(new SchoolYearAttendance(schoolYear, events));
}
}
numAttendancesIngested += processedAttendances.size();
if (sessions.entrySet().size() == 0 && attendance.size() > 0) {
super.getErrorReport(attendances.values().iterator().next().getSourceFile())
.warning(MessageSourceHelper.getMessage(messageSource, "ATTENDANCE_TRANSFORMER_WRNG_MSG4",studentId,schoolId), this);
}
// Step 2: retrieve sli SchoolYearAttendances
Set<SchoolYearAttendance> sliSchoolYearAttendances = getSliSchoolYearAttendances(studentId, schoolId);
// Step 3: merge sli and staging SchoolYearAttendances
Set<SchoolYearAttendance> mergedAttendances = mergeSchoolYearAttendance(sliSchoolYearAttendances, stageSchoolYearAttendances);
Map<String, List<Map<String, Object>>> schoolYears = new HashMap<String, List<Map<String, Object>>>();
for (SchoolYearAttendance schoolYearAttendance : mergedAttendances) {
schoolYears.put(schoolYearAttendance.getSchoolYear(), schoolYearAttendance.getAttendanceEvent());
}
return schoolYears;
}
/**
* Merge the sets of SchoolYearAttendance from SLI and stage.
*
* @param sliSchoolYearAttendances
* Set containing SchoolYearAttendance from sli.
* @param stageSchoolYearAttendances
* Set containing SchoolYearAttendance from stage.
* @return Set containing SchoolYearAttendance merged from both.
*/
private Set<SchoolYearAttendance> mergeSchoolYearAttendance(Set<SchoolYearAttendance> sliSchoolYearAttendances,
Set<SchoolYearAttendance> stageSchoolYearAttendances) {
if (sliSchoolYearAttendances.size() == 0) {
return stageSchoolYearAttendances;
}
if (stageSchoolYearAttendances.size() == 0) {
return sliSchoolYearAttendances;
}
Set<SchoolYearAttendance> newSchoolYearAttendances = new HashSet<SchoolYearAttendance>();
for (SchoolYearAttendance stageSchoolYearAttendance : stageSchoolYearAttendances) {
boolean merged = false;
for (SchoolYearAttendance sliSchoolYearAttendance : sliSchoolYearAttendances) {
//check and merge
if (sliSchoolYearAttendance.sameSchoolYear(stageSchoolYearAttendance)) {
//find same school year
//merge stageSchoolYearAttendance into sliSchoolYearAttendance
sliSchoolYearAttendance.mergeAndUpdateAttendanceEvent(stageSchoolYearAttendance);
merged = true;
break;
}
}
if (!merged) {
//Add new school year
newSchoolYearAttendances.add(stageSchoolYearAttendance);
}
}
newSchoolYearAttendances.addAll(sliSchoolYearAttendances);
return newSchoolYearAttendances;
}
/**
* Retrieve the set of student attendance events from SLI.
*
* @param studentUniqueStateId
* studentUniqueStateId of the student.
* @param stateOrganizationId
* stateOrganizationId of the school the student attends.
* @return Set containing SchoolYearAttendance retrieved from SLI.
*/
@SuppressWarnings("unchecked")
private Set<SchoolYearAttendance> getSliSchoolYearAttendances(String studentUniqueStateId, String stateOrganizationId) {
Set<SchoolYearAttendance> attendanceSet = new HashSet<SchoolYearAttendance>();
NeutralQuery studentQuery = new NeutralQuery(0);
studentQuery.addCriteria(new NeutralCriteria("studentUniqueStateId", NeutralCriteria.OPERATOR_EQUAL, studentUniqueStateId));
Entity studentEntity = getMongoEntityRepository().findOne(EntityNames.STUDENT, studentQuery);
String studentEntityId = null;
if (studentEntity != null) {
studentEntityId = studentEntity.getEntityId();
} else {
return attendanceSet;
}
NeutralQuery schoolQuery = new NeutralQuery(0);
schoolQuery.addCriteria(new NeutralCriteria("stateOrganizationId", NeutralCriteria.OPERATOR_EQUAL, stateOrganizationId));
Entity schoolEntity = getMongoEntityRepository().findOne(EntityNames.EDUCATION_ORGANIZATION, schoolQuery);
String schoolEntityId = null;
if (schoolEntity != null) {
schoolEntityId = schoolEntity.getEntityId();
} else {
return attendanceSet;
}
NeutralQuery attendanceQuery = new NeutralQuery(0);
attendanceQuery.addCriteria(new NeutralCriteria(STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, studentEntityId));
attendanceQuery.addCriteria(new NeutralCriteria(SCHOOL_ID, NeutralCriteria.OPERATOR_EQUAL, schoolEntityId));
Entity attendanceEntity = getMongoEntityRepository().findOne(EntityNames.ATTENDANCE, attendanceQuery);
if (attendanceEntity == null) {
return attendanceSet;
}
List<Map<String, Object>> schoolYearAttendance = (List<Map<String, Object>>) attendanceEntity.getBody().get("schoolYearAttendance");
if (schoolYearAttendance == null || schoolYearAttendance.size() == 0) {
return attendanceSet;
}
for (Map<String, Object> yearAttendance : schoolYearAttendance) {
String schoolYear = (String) yearAttendance.get(SCHOOL_YEAR);
List<Map<String, Object>> attendanceEvent = (List<Map<String, Object>>) yearAttendance.get(ATTENDANCE_EVENT);
if (attendanceEvent.size() > 0) {
attendanceSet.add(new SchoolYearAttendance(schoolYear, attendanceEvent));
}
}
return attendanceSet;
}
private Entity getSliSchool(String stateOrganizationId) {
NeutralQuery schoolQuery = new NeutralQuery(0);
schoolQuery.addCriteria(new NeutralCriteria("stateOrganizationId", NeutralCriteria.OPERATOR_EQUAL, stateOrganizationId));
return getMongoEntityRepository().findOne(EntityNames.EDUCATION_ORGANIZATION, schoolQuery);
}
/**
* Get the sessions from SLI db
* @param schoolName:
* @return: List of sessions of the school from SLI
*/
private Iterable<NeutralRecord> getSliSessions(String stateOrganizationId) {
//Get schoolId within SLI db
//TODO: we may not need this query when deterministic ID is implemented.
Entity school = getSliSchool(stateOrganizationId);
String sliSchoolId = "";
if (school != null) {
sliSchoolId = school.getEntityId();
} else {
return new ArrayList<NeutralRecord>();
}
NeutralQuery sessionQuery = new NeutralQuery(0);
sessionQuery.addCriteria(new NeutralCriteria(SCHOOL_ID, NeutralCriteria.OPERATOR_EQUAL, sliSchoolId));
Iterable<NeutralRecord> sliSessions = transformIntoNeutralRecord(getMongoEntityRepository().findAll(EntityNames.SESSION, sessionQuery));
return sliSessions;
}
private Iterable<NeutralRecord> transformIntoNeutralRecord(Iterable<Entity> entities) {
Iterator<Entity> entityItr = entities.iterator();
List<NeutralRecord> sessionRecords = new ArrayList<NeutralRecord>();
//Trasnforming SLI entity back to neutralRecord
Entity sliSession = null;
while (entityItr.hasNext()) {
sliSession = entityItr.next();
NeutralRecord session = new NeutralRecord();
session.setRecordId(sliSession.getEntityId());
session.setRecordType(sliSession.getType());
session.setBatchJobId(getBatchJobId());
session.setAttributes(sliSession.getBody());
sessionRecords.add(session);
}
return sessionRecords;
}
/*
* This function only concatenate 2 lists sessions of the same school. Since the keys for sessions are schoolId
* and session name, this functions only needs to distinguish sessions via sessionName.
*/
private Iterable<NeutralRecord> concat(List<NeutralRecord> first, List<NeutralRecord> second) {
List<NeutralRecord> res = new ArrayList<NeutralRecord>();
res.addAll(first);
Set<String> sessions = new HashSet<String>();
for(NeutralRecord record : first) {
sessions.add((String) record.getAttributes().get("sessionName"));
}
for(NeutralRecord record : second) {
String sKey = (String) record.getAttributes().get("sessionName");
if(!sessions.contains(sKey)) {
sessions.add(sKey);
res.add(record);
}
}
return res;
}
/**
* create a school reference that can be resolved by the deterministic ID resolver
*/
private static Map<String, Object> createEdfiSchoolReference(String schoolId) {
Map<String, Object> schoolReferenceObj = new HashMap<String, Object>();
Map<String, Object> idObj = new HashMap<String, Object>();
idObj.put(STATE_ORGANIZATION_ID, schoolId);
schoolReferenceObj.put(EDUCATIONAL_ORG_ID, idObj);
return schoolReferenceObj;
}
/**
* TODO: add javadoc
*
*/
class SchoolYearAttendance {
private String schoolYear;
private List<Map<String, Object>> attendanceEvent;
public SchoolYearAttendance(String schoolYear, List<Map<String, Object>> attendanceEvent) {
this.schoolYear = schoolYear;
this.attendanceEvent = attendanceEvent;
}
public void mergeAndUpdateAttendanceEvent(SchoolYearAttendance obj) {
if (!sameSchoolYear(obj)) {
return;
}
for (Map<String, Object> stageAttendance : obj.attendanceEvent) {
for (Map<String, Object> sliAttendance : this.attendanceEvent) {
Object sliEvent = sliAttendance.get(EVENT);
Object stageEvent = stageAttendance.get(EVENT);
Object sliDate = sliAttendance.get(DATE);
Object stageDate = stageAttendance.get(DATE);
boolean eventMatch = sliEvent != null && stageEvent != null && sliEvent.equals(stageEvent);
boolean dateMatch = sliDate != null && stageDate != null && sliDate.equals(stageDate);
if (eventMatch && dateMatch) {
//remove matched to prevent duplicated
this.attendanceEvent.remove(sliAttendance);
break;
}
}
}
List<Map<String, Object>> mergedAttendanceEvent = new ArrayList<Map<String, Object>>();
mergedAttendanceEvent.addAll(this.attendanceEvent);
mergedAttendanceEvent.addAll(obj.attendanceEvent);
this.attendanceEvent = mergedAttendanceEvent;
}
public boolean sameSchoolYear(SchoolYearAttendance obj) {
return obj.schoolYear != null && obj.schoolYear.equals(this.schoolYear);
}
public String getSchoolYear() {
return this.schoolYear;
}
public List<Map<String, Object>> getAttendanceEvent() {
return this.attendanceEvent;
}
@Override
public String toString() {
return "schoolYear:" + schoolYear + ",attendanceEvent:" + attendanceEvent;
}
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
}
| [DE2221] Change inner class to static and Simplify a Conditional statement
| sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AttendanceTransformer.java | [DE2221] Change inner class to static and Simplify a Conditional statement | <ide><path>li/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AttendanceTransformer.java
<ide>
<ide> if (attributes.containsKey(SCHOOL_ID)) {
<ide> Object stateOrganizationId = attributes.get(SCHOOL_ID);
<del> if (stateOrganizationId != null && stateOrganizationId instanceof String) {
<add> if (stateOrganizationId instanceof String) {
<ide> String schoolId = (String) stateOrganizationId;
<ide> List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
<ide>
<ide> * TODO: add javadoc
<ide> *
<ide> */
<del> class SchoolYearAttendance {
<add> static class SchoolYearAttendance {
<ide> private String schoolYear;
<ide> private List<Map<String, Object>> attendanceEvent;
<ide> |
|
Java | apache-2.0 | f5e3580f8d6cefb9ac47349c12768c0fbcddf12c | 0 | jmiserez/onos,planoAccess/clonedONOS,sonu283304/onos,gkatsikas/onos,gkatsikas/onos,osinstom/onos,osinstom/onos,oplinkoms/onos,rvhub/onos,SmartInfrastructures/dreamer,CNlukai/onos-gerrit-test,planoAccess/clonedONOS,osinstom/onos,mengmoya/onos,oplinkoms/onos,donNewtonAlpha/onos,y-higuchi/onos,CNlukai/onos-gerrit-test,kuangrewawa/onos,opennetworkinglab/onos,CNlukai/onos-gerrit-test,chenxiuyang/onos,packet-tracker/onos,castroflavio/onos,LorenzReinhart/ONOSnew,maheshraju-Huawei/actn,sdnwiselab/onos,sdnwiselab/onos,Shashikanth-Huawei/bmp,SmartInfrastructures/dreamer,ravikumaran2015/ravikumaran201504,maheshraju-Huawei/actn,castroflavio/onos,y-higuchi/onos,zsh2938/onos,kuangrewawa/onos,lsinfo3/onos,oplinkoms/onos,oeeagle/onos,y-higuchi/onos,jmiserez/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,LorenzReinhart/ONOSnew,chenxiuyang/onos,kuujo/onos,packet-tracker/onos,oplinkoms/onos,jmiserez/onos,SmartInfrastructures/dreamer,VinodKumarS-Huawei/ietf96yang,oeeagle/onos,VinodKumarS-Huawei/ietf96yang,oplinkoms/onos,mengmoya/onos,rvhub/onos,planoAccess/clonedONOS,Shashikanth-Huawei/bmp,kuujo/onos,LorenzReinhart/ONOSnew,mengmoya/onos,ravikumaran2015/ravikumaran201504,maheshraju-Huawei/actn,opennetworkinglab/onos,sonu283304/onos,Shashikanth-Huawei/bmp,sdnwiselab/onos,sdnwiselab/onos,planoAccess/clonedONOS,jinlongliu/onos,jmiserez/onos,packet-tracker/onos,gkatsikas/onos,sdnwiselab/onos,mengmoya/onos,kkkane/ONOS,donNewtonAlpha/onos,sdnwiselab/onos,oeeagle/onos,donNewtonAlpha/onos,LorenzReinhart/ONOSnew,kkkane/ONOS,chinghanyu/onos,kuujo/onos,jinlongliu/onos,castroflavio/onos,oplinkoms/onos,ravikumaran2015/ravikumaran201504,packet-tracker/onos,kuujo/onos,maheshraju-Huawei/actn,y-higuchi/onos,chenxiuyang/onos,mengmoya/onos,zsh2938/onos,gkatsikas/onos,rvhub/onos,gkatsikas/onos,chenxiuyang/onos,jinlongliu/onos,chinghanyu/onos,Shashikanth-Huawei/bmp,VinodKumarS-Huawei/ietf96yang,lsinfo3/onos,zsh2938/onos,chinghanyu/onos,kkkane/ONOS,VinodKumarS-Huawei/ietf96yang,chinghanyu/onos,opennetworkinglab/onos,oplinkoms/onos,opennetworkinglab/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,opennetworkinglab/onos,osinstom/onos,gkatsikas/onos,donNewtonAlpha/onos,oeeagle/onos,kuujo/onos,kkkane/ONOS,rvhub/onos,jinlongliu/onos,y-higuchi/onos,maheshraju-Huawei/actn,CNlukai/onos-gerrit-test,kuangrewawa/onos,sonu283304/onos,castroflavio/onos,sonu283304/onos,lsinfo3/onos,zsh2938/onos,lsinfo3/onos,kuujo/onos,LorenzReinhart/ONOSnew,kuujo/onos,donNewtonAlpha/onos | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.onos.net.intent.impl;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.onos.net.ConnectPoint;
import org.onlab.onos.net.DeviceId;
import org.onlab.onos.net.Link;
import org.onlab.onos.net.Path;
import org.onlab.onos.net.intent.Intent;
import org.onlab.onos.net.intent.IntentCompiler;
import org.onlab.onos.net.intent.IntentExtensionService;
import org.onlab.onos.net.intent.LinkCollectionIntent;
import org.onlab.onos.net.intent.MultiPointToSinglePointIntent;
import org.onlab.onos.net.intent.PointToPointIntent;
import org.onlab.onos.net.resource.LinkResourceAllocations;
import org.onlab.onos.net.topology.PathService;
import com.google.common.collect.Sets;
/**
* An intent compiler for
* {@link org.onlab.onos.net.intent.MultiPointToSinglePointIntent}.
*/
@Component(immediate = true)
public class MultiPointToSinglePointIntentCompiler
implements IntentCompiler<MultiPointToSinglePointIntent> {
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected IntentExtensionService intentManager;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected PathService pathService;
@Activate
public void activate() {
intentManager.registerCompiler(MultiPointToSinglePointIntent.class, this);
}
@Deactivate
public void deactivate() {
intentManager.unregisterCompiler(PointToPointIntent.class);
}
@Override
public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable,
Set<LinkResourceAllocations> resources) {
Map<DeviceId, Link> links = new HashMap<>();
for (ConnectPoint ingressPoint : intent.ingressPoints()) {
Path path = getPath(ingressPoint, intent.egressPoint());
for (Link link : path.links()) {
if (links.containsKey(link.src().deviceId())) {
// We've already reached the existing tree with the first
// part of this path. Don't add the remainder of the path
// in case it differs from the path we already have.
break;
}
links.put(link.src().deviceId(), link);
}
}
Intent result = new LinkCollectionIntent(intent.appId(),
intent.selector(), intent.treatment(),
Sets.newHashSet(links.values()), intent.egressPoint());
return Arrays.asList(result);
}
/**
* Computes a path between two ConnectPoints.
*
* @param one start of the path
* @param two end of the path
* @return Path between the two
* @throws org.onlab.onos.net.intent.impl.PathNotFoundException if a path cannot be found
*/
private Path getPath(ConnectPoint one, ConnectPoint two) {
Set<Path> paths = pathService.getPaths(one.deviceId(), two.deviceId());
if (paths.isEmpty()) {
throw new PathNotFoundException("No path from " + one + " to " + two);
}
// TODO: let's be more intelligent about this eventually
return paths.iterator().next();
}
}
| core/net/src/main/java/org/onlab/onos/net/intent/impl/MultiPointToSinglePointIntentCompiler.java | /*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.onos.net.intent.impl;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onlab.onos.net.ConnectPoint;
import org.onlab.onos.net.Link;
import org.onlab.onos.net.Path;
import org.onlab.onos.net.intent.Intent;
import org.onlab.onos.net.intent.IntentCompiler;
import org.onlab.onos.net.intent.IntentExtensionService;
import org.onlab.onos.net.intent.LinkCollectionIntent;
import org.onlab.onos.net.intent.MultiPointToSinglePointIntent;
import org.onlab.onos.net.intent.PointToPointIntent;
import org.onlab.onos.net.resource.LinkResourceAllocations;
import org.onlab.onos.net.topology.PathService;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* An intent compiler for
* {@link org.onlab.onos.net.intent.MultiPointToSinglePointIntent}.
*/
@Component(immediate = true)
public class MultiPointToSinglePointIntentCompiler
implements IntentCompiler<MultiPointToSinglePointIntent> {
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected IntentExtensionService intentManager;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected PathService pathService;
@Activate
public void activate() {
intentManager.registerCompiler(MultiPointToSinglePointIntent.class, this);
}
@Deactivate
public void deactivate() {
intentManager.unregisterCompiler(PointToPointIntent.class);
}
@Override
public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable,
Set<LinkResourceAllocations> resources) {
Set<Link> links = new HashSet<>();
for (ConnectPoint ingressPoint : intent.ingressPoints()) {
Path path = getPath(ingressPoint, intent.egressPoint());
links.addAll(path.links());
}
Intent result = new LinkCollectionIntent(intent.appId(),
intent.selector(), intent.treatment(),
links, intent.egressPoint());
return Arrays.asList(result);
}
/**
* Computes a path between two ConnectPoints.
*
* @param one start of the path
* @param two end of the path
* @return Path between the two
* @throws org.onlab.onos.net.intent.impl.PathNotFoundException if a path cannot be found
*/
private Path getPath(ConnectPoint one, ConnectPoint two) {
Set<Path> paths = pathService.getPaths(one.deviceId(), two.deviceId());
if (paths.isEmpty()) {
throw new PathNotFoundException("No path from " + one + " to " + two);
}
// TODO: let's be more intelligent about this eventually
return paths.iterator().next();
}
}
| Modified the MultiPointToSinglePointIntentCompiler to prevent duplicate packets
Change-Id: Ifb7609be04ed8a0330b7a0b47420ca33af0656c6
| core/net/src/main/java/org/onlab/onos/net/intent/impl/MultiPointToSinglePointIntentCompiler.java | Modified the MultiPointToSinglePointIntentCompiler to prevent duplicate packets | <ide><path>ore/net/src/main/java/org/onlab/onos/net/intent/impl/MultiPointToSinglePointIntentCompiler.java
<ide> */
<ide> package org.onlab.onos.net.intent.impl;
<ide>
<add>import java.util.Arrays;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.Set;
<add>
<ide> import org.apache.felix.scr.annotations.Activate;
<ide> import org.apache.felix.scr.annotations.Component;
<ide> import org.apache.felix.scr.annotations.Deactivate;
<ide> import org.apache.felix.scr.annotations.Reference;
<ide> import org.apache.felix.scr.annotations.ReferenceCardinality;
<ide> import org.onlab.onos.net.ConnectPoint;
<add>import org.onlab.onos.net.DeviceId;
<ide> import org.onlab.onos.net.Link;
<ide> import org.onlab.onos.net.Path;
<ide> import org.onlab.onos.net.intent.Intent;
<ide> import org.onlab.onos.net.resource.LinkResourceAllocations;
<ide> import org.onlab.onos.net.topology.PathService;
<ide>
<del>import java.util.Arrays;
<del>import java.util.HashSet;
<del>import java.util.List;
<del>import java.util.Set;
<add>import com.google.common.collect.Sets;
<ide>
<ide> /**
<ide> * An intent compiler for
<ide> @Override
<ide> public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable,
<ide> Set<LinkResourceAllocations> resources) {
<del> Set<Link> links = new HashSet<>();
<add> Map<DeviceId, Link> links = new HashMap<>();
<ide>
<ide> for (ConnectPoint ingressPoint : intent.ingressPoints()) {
<ide> Path path = getPath(ingressPoint, intent.egressPoint());
<del> links.addAll(path.links());
<add> for (Link link : path.links()) {
<add> if (links.containsKey(link.src().deviceId())) {
<add> // We've already reached the existing tree with the first
<add> // part of this path. Don't add the remainder of the path
<add> // in case it differs from the path we already have.
<add> break;
<add> }
<add>
<add> links.put(link.src().deviceId(), link);
<add> }
<ide> }
<ide>
<ide> Intent result = new LinkCollectionIntent(intent.appId(),
<ide> intent.selector(), intent.treatment(),
<del> links, intent.egressPoint());
<add> Sets.newHashSet(links.values()), intent.egressPoint());
<ide> return Arrays.asList(result);
<ide> }
<ide> |
|
Java | apache-2.0 | 4b794eb648e5046414e6f2f510df1c904d5afae0 | 0 | OpenSextant/Xponents,voyagersearch/Xponents,voyagersearch/Xponents,voyagersearch/Xponents,OpenSextant/Xponents,OpenSextant/Xponents,voyagersearch/Xponents,voyagersearch/Xponents | /**
Copyright 2009-2013 The MITRE Corporation.
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.
* **************************************************************************
* NOTICE
* This software was produced for the U. S. Government under Contract No.
* W15P7T-12-C-F600, and is subject to the Rights in Noncommercial Computer
* Software and Noncommercial Computer Software Documentation Clause
* 252.227-7014 (JUN 1995)
*
* (c) 2012 The MITRE Corporation. All Rights Reserved.
* **************************************************************************
**/
package org.opensextant.output;
import java.util.HashMap;
import java.util.Map;
import org.opensextant.ConfigException;
import org.opensextant.giscore.events.SimpleField;
/**
* GISCore-based output schema.
*
* @author Marc C. Ubaldino, MITRE, ubaldino at mitre dot org
*/
public final class OpenSextantSchema {
public static final SimpleField SCHEMA_OID = new SimpleField("id", SimpleField.Type.OID);
/** Match Text captures the raw text matched by the tagger. */
public static final SimpleField MATCH_TEXT = new SimpleField("matchtext", SimpleField.Type.STRING);
/** ISO Country code */
public static final SimpleField ISO_COUNTRY = new SimpleField("iso_cc", SimpleField.Type.STRING);
/** Geonames Feature class */
public static final SimpleField FEATURE_CLASS = new SimpleField("feat_class", SimpleField.Type.STRING);
/** Geonames style feature coding */
public static final SimpleField FEATURE_CODE = new SimpleField("feat_code", SimpleField.Type.STRING);
/** confidence 0.000 to 1.000 suggests our confidence that we code the MATCH TEXT to the right LAT/LON
* this is a string for now to keep the actual sig-figs accurate.
*/
public static final SimpleField CONFIDENCE = new SimpleField("confidence", SimpleField.Type.STRING);
/** Number of meters of error in coordinate of location. Example, a city location match is likely to be 1-2 KM of error
* depending on which gazetteer is referenced. A coordinate's precision is implied by number of decimal places, etc.
*/
public static final SimpleField PRECISION = new SimpleField("precision", SimpleField.Type.INT);
/** the name in the Gazetteer entry; which aligns with the MATCH TEXT
*/
public static final SimpleField PLACE_NAME = new SimpleField("placename", SimpleField.Type.STRING);
/** Field names: filepath */
public static final String FILEPATH_FLD = "filepath";
/** Optionally the File path for the text */
public static final SimpleField FILEPATH = new SimpleField(FILEPATH_FLD, SimpleField.Type.STRING);
public static final SimpleField FILENAME = new SimpleField("filename", SimpleField.Type.STRING);
public static final SimpleField TEXTPATH = new SimpleField("textpath", SimpleField.Type.STRING);
//private static SimpleField prematchField = new SimpleField("prematch", SimpleField.Type.STRING);
//private static SimpleField postmatchField = new SimpleField("postmatch", SimpleField.Type.STRING);
/** A text window around the MATCH TEXT delineated by START/END offsets. Default window size is +/- 150 characters
*/
public static final SimpleField CONTEXT = new SimpleField("context", SimpleField.Type.STRING);
public static final SimpleField START_OFFSET = new SimpleField("start", SimpleField.Type.INT);
public static final SimpleField END_OFFSET = new SimpleField("end", SimpleField.Type.INT);
/** The method used to match the data in MATCH TEXT */
public static final SimpleField MATCH_METHOD = new SimpleField("method", SimpleField.Type.STRING);
public static final SimpleField PROVINCE = new SimpleField("province", SimpleField.Type.STRING);
public static final SimpleField LAT = new SimpleField("lat", SimpleField.Type.FLOAT);
public static final SimpleField LON = new SimpleField("lon", SimpleField.Type.FLOAT);
private static final Map<String, SimpleField> fields = new HashMap<String, SimpleField>();
static {
fields.put("id", SCHEMA_OID);
fields.put("matchtext", MATCH_TEXT);
fields.put("iso_cc", ISO_COUNTRY);
fields.put("feat_class", FEATURE_CLASS);
fields.put("feat_code", FEATURE_CODE);
fields.put("confidence", CONFIDENCE);
fields.put("precision", PRECISION);
fields.put("placename", PLACE_NAME);
fields.put(FILEPATH_FLD, FILEPATH);
fields.put("filename", FILENAME);
fields.put("textpath", TEXTPATH);
fields.put("context", CONTEXT);
fields.put("start", START_OFFSET);
fields.put("end", END_OFFSET);
fields.put("lat", LAT);
fields.put("lon", LON);
fields.put("province", PROVINCE);
fields.put("method", MATCH_METHOD);
}
public static SimpleField getField(String f) throws ConfigException {
SimpleField F = fields.get(f);
if (F == null) {
throw new ConfigException("Field " + f + "not found");
}
return F;
}
/** Cache an arbitrary date field in schema
*/
public static void addDateField(String f) {
fields.put(f, new SimpleField(f, SimpleField.Type.DATE));
}
/** Cache an arbitrary text field in schema
*/
public static void addTextField(String f) {
fields.put(f, new SimpleField(f, SimpleField.Type.STRING));
}
}
| Extraction/src/main/java/org/opensextant/output/OpenSextantSchema.java | /**
Copyright 2009-2013 The MITRE Corporation.
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.
* **************************************************************************
* NOTICE
* This software was produced for the U. S. Government under Contract No.
* W15P7T-12-C-F600, and is subject to the Rights in Noncommercial Computer
* Software and Noncommercial Computer Software Documentation Clause
* 252.227-7014 (JUN 1995)
*
* (c) 2012 The MITRE Corporation. All Rights Reserved.
* **************************************************************************
**/
package org.opensextant.output;
import java.util.HashMap;
import java.util.Map;
import org.opensextant.ConfigException;
import org.opensextant.giscore.events.SimpleField;
/**
*
* @author Marc C. Ubaldino, MITRE, ubaldino at mitre dot org
*/
public final class OpenSextantSchema {
public static final SimpleField SCHEMA_OID = new SimpleField("id", SimpleField.Type.OID);
/** Match Text captures the raw text matched by the tagger. */
public static final SimpleField MATCH_TEXT = new SimpleField("matchtext", SimpleField.Type.STRING);
/** ISO Country code */
public static final SimpleField ISO_COUNTRY = new SimpleField("iso_cc", SimpleField.Type.STRING);
/** Geonames Feature class */
public static final SimpleField FEATURE_CLASS = new SimpleField("feat_class", SimpleField.Type.STRING);
/** Geonames style feature coding */
public static final SimpleField FEATURE_CODE = new SimpleField("feat_code", SimpleField.Type.STRING);
/** confidence 0.000 to 1.000 suggests our confidence that we code the MATCH TEXT to the right LAT/LON
* this is a string for now to keep the actual sig-figs accurate.
*/
public static final SimpleField CONFIDENCE = new SimpleField("confidence", SimpleField.Type.STRING);
/** Number of meters of error in coordinate of location. Example, a city location match is likely to be 1-2 KM of error
* depending on which gazetteer is referenced. A coordinate's precision is implied by number of decimal places, etc.
*/
public static final SimpleField PRECISION = new SimpleField("precision", SimpleField.Type.INT);
/** the name in the Gazetteer entry; which aligns with the MATCH TEXT
*/
public static final SimpleField PLACE_NAME = new SimpleField("placename", SimpleField.Type.STRING);
/** Field names: filepath */
public static final String FILEPATH_FLD = "filepath";
/** Optionally the File path for the text */
public static final SimpleField FILEPATH = new SimpleField(FILEPATH_FLD, SimpleField.Type.STRING);
public static final SimpleField FILENAME = new SimpleField("filename", SimpleField.Type.STRING);
public static final SimpleField TEXTPATH = new SimpleField("textpath", SimpleField.Type.STRING);
//private static SimpleField prematchField = new SimpleField("prematch", SimpleField.Type.STRING);
//private static SimpleField postmatchField = new SimpleField("postmatch", SimpleField.Type.STRING);
/** A text window around the MATCH TEXT delineated by START/END offsets. Default window size is +/- 150 characters
*/
public static final SimpleField CONTEXT = new SimpleField("context", SimpleField.Type.STRING);
public static final SimpleField START_OFFSET = new SimpleField("start", SimpleField.Type.INT);
public static final SimpleField END_OFFSET = new SimpleField("end", SimpleField.Type.INT);
/** The method used to match the data in MATCH TEXT */
public static final SimpleField MATCH_METHOD = new SimpleField("method", SimpleField.Type.STRING);
public static final SimpleField PROVINCE = new SimpleField("province", SimpleField.Type.STRING);
public static final SimpleField LAT = new SimpleField("lat", SimpleField.Type.FLOAT);
public static final SimpleField LON = new SimpleField("lon", SimpleField.Type.FLOAT);
private static final Map<String, SimpleField> fields = new HashMap<String, SimpleField>();
static {
fields.put("id", SCHEMA_OID);
fields.put("matchtext", MATCH_TEXT);
fields.put("iso_cc", ISO_COUNTRY);
fields.put("feat_class", FEATURE_CLASS);
fields.put("feat_code", FEATURE_CODE);
fields.put("confidence", CONFIDENCE);
fields.put("precision", PRECISION);
fields.put("placename", PLACE_NAME);
fields.put(FILEPATH_FLD, FILEPATH);
fields.put("filename", FILENAME);
fields.put("textpath", TEXTPATH);
fields.put("context", CONTEXT);
fields.put("start", START_OFFSET);
fields.put("end", END_OFFSET);
fields.put("lat", LAT);
fields.put("lon", LON);
fields.put("province", PROVINCE);
fields.put("method", MATCH_METHOD);
}
public static SimpleField getField(String f) throws ConfigException {
SimpleField F = fields.get(f);
if (F == null) {
throw new ConfigException("Field " + f + "not found");
}
return F;
}
/** Cache an arbitrary date field in schema
*/
public static void addDateField(String f) {
fields.put(f, new SimpleField(f, SimpleField.Type.DATE));
}
/** Cache an arbitrary text field in schema
*/
public static void addTextField(String f) {
fields.put(f, new SimpleField(f, SimpleField.Type.STRING));
}
}
| Comment that this schema is GISCore specific
| Extraction/src/main/java/org/opensextant/output/OpenSextantSchema.java | Comment that this schema is GISCore specific | <ide><path>xtraction/src/main/java/org/opensextant/output/OpenSextantSchema.java
<ide> import org.opensextant.ConfigException;
<ide> import org.opensextant.giscore.events.SimpleField;
<ide> /**
<del> *
<add> * GISCore-based output schema.
<add> *
<ide> * @author Marc C. Ubaldino, MITRE, ubaldino at mitre dot org
<ide> */
<ide> public final class OpenSextantSchema { |
|
Java | apache-2.0 | 9a4f8abff7e01a0cc34c564ebf9fbfd6d318a5ab | 0 | OSEHRA/ISAAC,OSEHRA/ISAAC,OSEHRA/ISAAC | /*
* 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.
*
* Contributions from 2013-2017 where performed either by US government
* employees, or under US Veterans Health Administration contracts.
*
* US Veterans Health Administration contributions by government employees
* are work of the U.S. Government and are not subject to copyright
* protection in the United States. Portions contributed by government
* employees are USGovWork (17USC §105). Not subject to copyright.
*
* Contribution by contractors to the US Veterans Health Administration
* during this period are contractually contributed under the
* Apache License, Version 2.0.
*
* See: https://www.usa.gov/government-works
*
* Contributions prior to 2013:
*
* Copyright (C) International Health Terminology Standards Development Organisation.
* Licensed under the Apache License, Version 2.0.
*
*/
package sh.isaac.convert.directUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.ContextEnabled;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import sh.isaac.MetaData;
import sh.isaac.api.ConceptProxy;
import sh.isaac.api.ConfigurationService.BuildMode;
import sh.isaac.api.Get;
import sh.isaac.api.LookupService;
import sh.isaac.api.Status;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.constants.DatabaseInitialization;
import sh.isaac.api.coordinate.StampCoordinate;
import sh.isaac.api.datastore.DataStore;
import sh.isaac.api.index.IndexBuilderService;
import sh.isaac.api.util.UuidT5Generator;
import sh.isaac.converters.sharedUtils.stats.ConverterUUID;
import sh.isaac.model.configuration.StampCoordinates;
import sh.isaac.mojo.LoadTermstore;
/**
*
* {@link DirectConverterBaseMojo}
*
* Base mojo class with shared parameters for reuse by terminology specific converters.
*
* This base mojo is intended for converters that have been rewritten as "direct" importers, and also serves for
* mojo support.
*
* Note, due to class path issues with the convoluted project structure, this entire maven module will not contain
* any @Mojo annotations. All @Mojo annotations for classes that extend this should reside in the importers-mojos module.
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
public abstract class DirectConverterBaseMojo extends AbstractMojo implements Mojo, ContextEnabled
{
protected Logger log = LogManager.getLogger();
protected ConverterUUID converterUUID;
protected DirectWriteHelper dwh;
//Variables for the progress printer
protected boolean runningInMaven = false;
private boolean disableFancyConsoleProgress = (System.console() == null);
private int printsSinceReturn = 0;
private int lastStatus;
protected StampCoordinate readbackCoordinate;
/**
* A optional function that can be specified by a concrete subclass, which when called, will provide a set of nids that will be passed
* into {@link DataWriteListenerImpl#DataWriteListenerImpl(Path, java.util.Set)} as the assemblage types to ignore.
* This function will be executed AFTER isaac is started.
*/
protected Supplier<HashSet<Integer>> toIgnore = null;
/**
* Location to write the output file.
*/
@Parameter(required = true, defaultValue = "${project.build.directory}")
protected File outputDirectory;
/**
* Location of the input source file(s). May be a file or a directory, depending on the specific loader. Usually a
* directory.
*/
@Parameter(required = true)
private File inputFileLocation;
//The file version, above, gets populated by maven, but we need to work with the Path version, to make things happy with both
//maven and the GUI impl
protected Path inputFileLocationPath;
/**
* Output artifactId.
*/
@Parameter(required = true, defaultValue = "${project.artifactId}")
protected String converterOutputArtifactId;
/**
* Loader version number.
*/
@Parameter(required = true, defaultValue = "${loader.version}")
protected String converterVersion;
/**
* Converter result version number.
*/
@Parameter(required = true, defaultValue = "${project.version}")
protected String converterOutputArtifactVersion;
/**
* Converter result classifier.
*/
@Parameter(required = false, defaultValue = "${resultArtifactClassifier}")
protected String converterOutputArtifactClassifier;
/**
* Converter source artifact version.
*/
@Parameter(required = true, defaultValue = "${sourceData.version}")
protected String converterSourceArtifactVersion;
/**
* Set '-Dsdp' (skipUUIDDebugPublish) on the command line, to prevent the publishing of the debug UUID map (it will
* still be created, and written to a file) At the moment, this param is never used in code - it is just used as a
* pom trigger (but documented here).
*/
@Parameter(required = false, defaultValue = "${sdp}")
private String createDebugUUIDMapSkipPublish;
/**
* Set '-DskipUUIDDebug' on the command line, to disable the in memory UUID Debug map entirely (this disables UUID
* duplicate detection, but significantly cuts the required RAM overhead to run a loader).
*/
@Parameter(required = false, defaultValue = "${skipUUIDDebug}")
private String skipUUIDDebugMap;
/**
* Execute.
*
* @throws MojoExecutionException the mojo execution exception
*/
@Override
public void execute() throws MojoExecutionException
{
runningInMaven = true;
if (inputFileLocation != null)
{
inputFileLocationPath = inputFileLocation.toPath();
}
try
{
// Set up the output
if (!this.outputDirectory.exists())
{
this.outputDirectory.mkdirs();
}
LoggingConfig.configureLogging(outputDirectory, converterOutputArtifactClassifier);
log.info(this.getClass().getName() + " converter begins in maven mode");
converterUUID = Get.service(ConverterUUID.class);
converterUUID.clearCache();
converterUUID.configureNamespace(UuidT5Generator.PATH_ID_FROM_FS_DESC);
converterUUID.setUUIDMapState(
((this.skipUUIDDebugMap == null) || (this.skipUUIDDebugMap.length() == 0)) ? true : !Boolean.parseBoolean(this.skipUUIDDebugMap));
if (!converterUUID.isUUIDMapEnabled())
{
log.info("The UUID Debug map is disabled - this also prevents duplicate ID detection");
}
String outputName = converterOutputArtifactId
+ (StringUtils.isBlank(converterOutputArtifactClassifier) ? "" : "-" + converterOutputArtifactClassifier) + "-"
+ converterOutputArtifactVersion;
Path ibdfFileToWrite = new File(outputDirectory, outputName + ".ibdf").toPath();
ibdfFileToWrite.toFile().delete();
log.info("Writing IBDF to " + ibdfFileToWrite.toFile().getCanonicalPath());
File file = new File(outputDirectory, "isaac-db");
// make sure this is empty
FileUtils.deleteDirectory(file);
Get.configurationService().setDataStoreFolderPath(file.toPath());
LookupService.startupPreferenceProvider();
Get.configurationService().setDBBuildMode(BuildMode.IBDF); //enabled the nid to uuid cache
Get.configurationService().setDatabaseInitializationMode(DatabaseInitialization.LOAD_METADATA);
LookupService.startupIsaac();
readbackCoordinate = StampCoordinates.getDevelopmentLatest();
Path[] filesToPreload = getIBDFFilesToPreload();
if (filesToPreload != null && filesToPreload.length > 0)
{
log.info("Preloading IBDF files");
LoadTermstore lt = new LoadTermstore();
lt.dontSetDBMode();
lt.setLog(new SystemStreamLog());
lt.setibdfFiles(filesToPreload);
lt.setActiveOnly(IBDFPreloadActiveOnly());
lt.skipVersionTypes(getIBDFSkipTypes());
lt.execute();
}
// Don't need to build indexes - but don't disable till after the pre-loads, as we might need indexes on those.
for (IndexBuilderService ibs : LookupService.getServices(IndexBuilderService.class))
{
ibs.refreshQueryEngine(); //refresh, so that the data loaded above is available
ibs.setEnabled(false);
}
DataWriteListenerImpl listener = new DataWriteListenerImpl(ibdfFileToWrite, toIgnore == null ? null : toIgnore.get());
// we register this after the metadata has already been written.
LookupService.get().getService(DataStore.class).registerDataWriteListener(listener);
convertContent(statusUpdate -> {}, (workDone, workTotal) -> {});
LookupService.shutdownSystem();
listener.close();
log.info("Conversion complete");
}
catch (Exception ex)
{
throw new MojoExecutionException(ex.getLocalizedMessage(), ex);
}
}
/**
* Where the logic should be implemented to actually do the conversion
* @param statusUpdates - the converter should post status updates here.
* @param progresUpdates - optional - if provided, the converter should post progress on workDone here, the first argument
* is work done, the second argument is work total.
* @throws IOException
*/
protected abstract void convertContent(Consumer<String> statusUpdates, BiConsumer<Double, Double> progresUpdates) throws IOException;
/**
* Implementors should override this method, if they have IBDF files that should be pre-loaded, prior to the callback to
* {@link #convertContent(Consumer)}, and prior to the injection of the IBDF change set listener.
*
* This is only used by loaders that cannot execute without having another terminology preloaded - such as snomed extensions
* that need to do snomed lookups, or loinc tech preview, which requires snomed, and loinc, for example.
* @return
* @throws IOException
*/
protected Path[] getIBDFFilesToPreload() throws IOException
{
return new Path[0];
}
/**
* Subclasses may override this, if they want to change the behavior. The default behavior is to preload only active concepts
* and semantics
* @return
*/
protected boolean IBDFPreloadActiveOnly()
{
return true;
}
/**
* Subclasses may override this, if they want to change the behavior. If a subclass provides a return that includes
* {@link VersionType#COMPONENT_NID}, for example, then that type will be skipped when encountered during IBDF preload
* @return
*/
protected Collection<VersionType> getIBDFSkipTypes()
{
return new HashSet<>(0);
}
/**
* Create the version specific module concept, and add the loader metadata to it.
* @param name
* @param parentModule
* @param releaseTime
* @return
*/
protected UUID setupModule(String name, UUID parentModule, Optional<String> fhirURI, long releaseTime)
{
//Create a module for this version.
String fullName = name + " " + converterSourceArtifactVersion + " module";
UUID versionModule = converterUUID.createNamespaceUUIDFromString(fullName);
int moduleNid = Get.identifierService().assignNid(versionModule);
dwh.changeModule(moduleNid); //change to the version specific module for all future work.
//Actually create the module concept
dwh.makeConcept(versionModule, Status.ACTIVE, releaseTime);
dwh.makeDescriptionEnNoDialect(versionModule, fullName + " (" + ConceptProxy.METADATA_SEMANTIC_TAG + ")",
MetaData.FULLY_QUALIFIED_NAME_DESCRIPTION_TYPE____SOLOR.getPrimordialUuid(),
Status.ACTIVE, releaseTime);
dwh.makeDescriptionEnNoDialect(versionModule, fullName,
MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getPrimordialUuid(),
Status.ACTIVE, releaseTime);
dwh.makeParentGraph(versionModule, Arrays.asList(new UUID[] {parentModule}), Status.ACTIVE, releaseTime);
dwh.makeTerminologyMetadataAnnotations(versionModule, converterSourceArtifactVersion, Optional.of(new Date(releaseTime).toString()),
Optional.ofNullable(converterOutputArtifactVersion), Optional.ofNullable(converterOutputArtifactClassifier), fhirURI, releaseTime);
return versionModule;
}
/**
* Should be called after calling showProgress(), but prior to logging anything else, to advance the console prior to the log output.
* Does nothing if not running on a console in maven mode
*/
protected void advanceProgressLine()
{
if (runningInMaven && printsSinceReturn > 0)
{
System.out.println();
printsSinceReturn = 0;
}
}
/**
* Can be called by converters to show progress on a console in maven mode
* Does nothing if not running on a console in maven mode
*/
protected void showProgress()
{
if (runningInMaven)
{
lastStatus++;
if (lastStatus > 3)
{
lastStatus = 0;
}
if (disableFancyConsoleProgress)
{
System.out.print(".");
printsSinceReturn++;
if (printsSinceReturn >= 75)
{
advanceProgressLine();
}
}
else
{
char c;
switch (lastStatus)
{
case 0:
c = '/';
break;
case 1:
c = '-';
break;
case 2:
c = '\\';
break;
case 3:
c = '|';
break;
default : // shouldn't be used
c = '-';
break;
}
if (printsSinceReturn == 0)
{
System.out.print(c);
}
else
{
System.out.print("\r" + c);
}
printsSinceReturn++;
}
}
else
{
//TODO maybe provide a progress bar?
}
}
}
| misc/importers/src/main/java/sh/isaac/convert/directUtils/DirectConverterBaseMojo.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.
*
* Contributions from 2013-2017 where performed either by US government
* employees, or under US Veterans Health Administration contracts.
*
* US Veterans Health Administration contributions by government employees
* are work of the U.S. Government and are not subject to copyright
* protection in the United States. Portions contributed by government
* employees are USGovWork (17USC §105). Not subject to copyright.
*
* Contribution by contractors to the US Veterans Health Administration
* during this period are contractually contributed under the
* Apache License, Version 2.0.
*
* See: https://www.usa.gov/government-works
*
* Contributions prior to 2013:
*
* Copyright (C) International Health Terminology Standards Development Organisation.
* Licensed under the Apache License, Version 2.0.
*
*/
package sh.isaac.convert.directUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.ContextEnabled;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.util.FileUtils;
import sh.isaac.MetaData;
import sh.isaac.api.ConceptProxy;
import sh.isaac.api.ConfigurationService.BuildMode;
import sh.isaac.api.Get;
import sh.isaac.api.LookupService;
import sh.isaac.api.Status;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.constants.DatabaseInitialization;
import sh.isaac.api.coordinate.StampCoordinate;
import sh.isaac.api.datastore.DataStore;
import sh.isaac.api.util.UuidT5Generator;
import sh.isaac.converters.sharedUtils.stats.ConverterUUID;
import sh.isaac.model.configuration.StampCoordinates;
import sh.isaac.mojo.LoadTermstore;
/**
*
* {@link DirectConverterBaseMojo}
*
* Base mojo class with shared parameters for reuse by terminology specific converters.
*
* This base mojo is intended for converters that have been rewritten as "direct" importers, and also serves for
* mojo support.
*
* Note, due to class path issues with the convoluted project structure, this entire maven module will not contain
* any @Mojo annotations. All @Mojo annotations for classes that extend this should reside in the importers-mojos module.
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
public abstract class DirectConverterBaseMojo extends AbstractMojo implements Mojo, ContextEnabled
{
protected Logger log = LogManager.getLogger();
protected ConverterUUID converterUUID;
protected DirectWriteHelper dwh;
//Variables for the progress printer
protected boolean runningInMaven = false;
private boolean disableFancyConsoleProgress = (System.console() == null);
private int printsSinceReturn = 0;
private int lastStatus;
protected StampCoordinate readbackCoordinate;
/**
* A optional function that can be specified by a concrete subclass, which when called, will provide a set of nids that will be passed
* into {@link DataWriteListenerImpl#DataWriteListenerImpl(Path, java.util.Set)} as the assemblage types to ignore.
* This function will be executed AFTER isaac is started.
*/
protected Supplier<HashSet<Integer>> toIgnore = null;
/**
* Location to write the output file.
*/
@Parameter(required = true, defaultValue = "${project.build.directory}")
protected File outputDirectory;
/**
* Location of the input source file(s). May be a file or a directory, depending on the specific loader. Usually a
* directory.
*/
@Parameter(required = true)
private File inputFileLocation;
//The file version, above, gets populated by maven, but we need to work with the Path version, to make things happy with both
//maven and the GUI impl
protected Path inputFileLocationPath;
/**
* Output artifactId.
*/
@Parameter(required = true, defaultValue = "${project.artifactId}")
protected String converterOutputArtifactId;
/**
* Loader version number.
*/
@Parameter(required = true, defaultValue = "${loader.version}")
protected String converterVersion;
/**
* Converter result version number.
*/
@Parameter(required = true, defaultValue = "${project.version}")
protected String converterOutputArtifactVersion;
/**
* Converter result classifier.
*/
@Parameter(required = false, defaultValue = "${resultArtifactClassifier}")
protected String converterOutputArtifactClassifier;
/**
* Converter source artifact version.
*/
@Parameter(required = true, defaultValue = "${sourceData.version}")
protected String converterSourceArtifactVersion;
/**
* Set '-Dsdp' (skipUUIDDebugPublish) on the command line, to prevent the publishing of the debug UUID map (it will
* still be created, and written to a file) At the moment, this param is never used in code - it is just used as a
* pom trigger (but documented here).
*/
@Parameter(required = false, defaultValue = "${sdp}")
private String createDebugUUIDMapSkipPublish;
/**
* Set '-DskipUUIDDebug' on the command line, to disable the in memory UUID Debug map entirely (this disables UUID
* duplicate detection, but significantly cuts the required RAM overhead to run a loader).
*/
@Parameter(required = false, defaultValue = "${skipUUIDDebug}")
private String skipUUIDDebugMap;
/**
* Execute.
*
* @throws MojoExecutionException the mojo execution exception
*/
@Override
public void execute() throws MojoExecutionException
{
runningInMaven = true;
if (inputFileLocation != null)
{
inputFileLocationPath = inputFileLocation.toPath();
}
try
{
// Set up the output
if (!this.outputDirectory.exists())
{
this.outputDirectory.mkdirs();
}
LoggingConfig.configureLogging(outputDirectory, converterOutputArtifactClassifier);
log.info(this.getClass().getName() + " converter begins in maven mode");
converterUUID = Get.service(ConverterUUID.class);
converterUUID.clearCache();
converterUUID.configureNamespace(UuidT5Generator.PATH_ID_FROM_FS_DESC);
converterUUID.setUUIDMapState(
((this.skipUUIDDebugMap == null) || (this.skipUUIDDebugMap.length() == 0)) ? true : !Boolean.parseBoolean(this.skipUUIDDebugMap));
if (!converterUUID.isUUIDMapEnabled())
{
log.info("The UUID Debug map is disabled - this also prevents duplicate ID detection");
}
String outputName = converterOutputArtifactId
+ (StringUtils.isBlank(converterOutputArtifactClassifier) ? "" : "-" + converterOutputArtifactClassifier) + "-"
+ converterOutputArtifactVersion;
Path ibdfFileToWrite = new File(outputDirectory, outputName + ".ibdf").toPath();
ibdfFileToWrite.toFile().delete();
log.info("Writing IBDF to " + ibdfFileToWrite.toFile().getCanonicalPath());
File file = new File(outputDirectory, "isaac-db");
// make sure this is empty
FileUtils.deleteDirectory(file);
Get.configurationService().setDataStoreFolderPath(file.toPath());
LookupService.startupPreferenceProvider();
Get.configurationService().setDBBuildMode(BuildMode.IBDF); //enabled the nid to uuid cache
Get.configurationService().setDatabaseInitializationMode(DatabaseInitialization.LOAD_METADATA);
LookupService.startupIsaac();
readbackCoordinate = StampCoordinates.getDevelopmentLatest();
Path[] filesToPreload = getIBDFFilesToPreload();
if (filesToPreload != null && filesToPreload.length > 0)
{
log.info("Preloading IBDF files");
LoadTermstore lt = new LoadTermstore();
lt.dontSetDBMode();
lt.setLog(new SystemStreamLog());
lt.setibdfFiles(filesToPreload);
lt.setActiveOnly(IBDFPreloadActiveOnly());
lt.skipVersionTypes(getIBDFSkipTypes());
lt.execute();
}
DataWriteListenerImpl listener = new DataWriteListenerImpl(ibdfFileToWrite, toIgnore == null ? null : toIgnore.get());
// we register this after the metadata has already been written.
LookupService.get().getService(DataStore.class).registerDataWriteListener(listener);
convertContent(statusUpdate -> {}, (workDone, workTotal) -> {});
LookupService.shutdownSystem();
listener.close();
log.info("Conversion complete");
}
catch (Exception ex)
{
throw new MojoExecutionException(ex.getLocalizedMessage(), ex);
}
}
/**
* Where the logic should be implemented to actually do the conversion
* @param statusUpdates - the converter should post status updates here.
* @param progresUpdates - optional - if provided, the converter should post progress on workDone here, the first argument
* is work done, the second argument is work total.
* @throws IOException
*/
protected abstract void convertContent(Consumer<String> statusUpdates, BiConsumer<Double, Double> progresUpdates) throws IOException;
/**
* Implementors should override this method, if they have IBDF files that should be pre-loaded, prior to the callback to
* {@link #convertContent(Consumer)}, and prior to the injection of the IBDF change set listener.
*
* This is only used by loaders that cannot execute without having another terminology preloaded - such as snomed extensions
* that need to do snomed lookups, or loinc tech preview, which requires snomed, and loinc, for example.
* @return
* @throws IOException
*/
protected Path[] getIBDFFilesToPreload() throws IOException
{
return new Path[0];
}
/**
* Subclasses may override this, if they want to change the behavior. The default behavior is to preload only active concepts
* and semantics
* @return
*/
protected boolean IBDFPreloadActiveOnly()
{
return true;
}
/**
* Subclasses may override this, if they want to change the behavior. If a subclass provides a return that includes
* {@link VersionType#COMPONENT_NID}, for example, then that type will be skipped when encountered during IBDF preload
* @return
*/
protected Collection<VersionType> getIBDFSkipTypes()
{
return new HashSet<>(0);
}
/**
* Create the version specific module concept, and add the loader metadata to it.
* @param name
* @param parentModule
* @param releaseTime
* @return
*/
protected UUID setupModule(String name, UUID parentModule, Optional<String> fhirURI, long releaseTime)
{
//Create a module for this version.
String fullName = name + " " + converterSourceArtifactVersion + " module";
UUID versionModule = converterUUID.createNamespaceUUIDFromString(fullName);
int moduleNid = Get.identifierService().assignNid(versionModule);
dwh.changeModule(moduleNid); //change to the version specific module for all future work.
//Actually create the module concept
dwh.makeConcept(versionModule, Status.ACTIVE, releaseTime);
dwh.makeDescriptionEnNoDialect(versionModule, fullName + " (" + ConceptProxy.METADATA_SEMANTIC_TAG + ")",
MetaData.FULLY_QUALIFIED_NAME_DESCRIPTION_TYPE____SOLOR.getPrimordialUuid(),
Status.ACTIVE, releaseTime);
dwh.makeDescriptionEnNoDialect(versionModule, fullName,
MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getPrimordialUuid(),
Status.ACTIVE, releaseTime);
dwh.makeParentGraph(versionModule, Arrays.asList(new UUID[] {parentModule}), Status.ACTIVE, releaseTime);
dwh.makeTerminologyMetadataAnnotations(versionModule, converterSourceArtifactVersion, Optional.of(new Date(releaseTime).toString()),
Optional.ofNullable(converterOutputArtifactVersion), Optional.ofNullable(converterOutputArtifactClassifier), fhirURI, releaseTime);
return versionModule;
}
/**
* Should be called after calling showProgress(), but prior to logging anything else, to advance the console prior to the log output.
* Does nothing if not running on a console in maven mode
*/
protected void advanceProgressLine()
{
if (runningInMaven && printsSinceReturn > 0)
{
System.out.println();
printsSinceReturn = 0;
}
}
/**
* Can be called by converters to show progress on a console in maven mode
* Does nothing if not running on a console in maven mode
*/
protected void showProgress()
{
if (runningInMaven)
{
lastStatus++;
if (lastStatus > 3)
{
lastStatus = 0;
}
if (disableFancyConsoleProgress)
{
System.out.print(".");
printsSinceReturn++;
if (printsSinceReturn >= 75)
{
advanceProgressLine();
}
}
else
{
char c;
switch (lastStatus)
{
case 0:
c = '/';
break;
case 1:
c = '-';
break;
case 2:
c = '\\';
break;
case 3:
c = '|';
break;
default : // shouldn't be used
c = '-';
break;
}
if (printsSinceReturn == 0)
{
System.out.print(c);
}
else
{
System.out.print("\r" + c);
}
printsSinceReturn++;
}
}
else
{
//TODO maybe provide a progress bar?
}
}
}
| pull this lost merge over so that metadata gets indexed during ibdf
conversion | misc/importers/src/main/java/sh/isaac/convert/directUtils/DirectConverterBaseMojo.java | pull this lost merge over so that metadata gets indexed during ibdf conversion | <ide><path>isc/importers/src/main/java/sh/isaac/convert/directUtils/DirectConverterBaseMojo.java
<ide> import sh.isaac.api.constants.DatabaseInitialization;
<ide> import sh.isaac.api.coordinate.StampCoordinate;
<ide> import sh.isaac.api.datastore.DataStore;
<add>import sh.isaac.api.index.IndexBuilderService;
<ide> import sh.isaac.api.util.UuidT5Generator;
<ide> import sh.isaac.converters.sharedUtils.stats.ConverterUUID;
<ide> import sh.isaac.model.configuration.StampCoordinates;
<ide> lt.setActiveOnly(IBDFPreloadActiveOnly());
<ide> lt.skipVersionTypes(getIBDFSkipTypes());
<ide> lt.execute();
<add> }
<add>
<add> // Don't need to build indexes - but don't disable till after the pre-loads, as we might need indexes on those.
<add> for (IndexBuilderService ibs : LookupService.getServices(IndexBuilderService.class))
<add> {
<add> ibs.refreshQueryEngine(); //refresh, so that the data loaded above is available
<add> ibs.setEnabled(false);
<ide> }
<ide>
<ide> DataWriteListenerImpl listener = new DataWriteListenerImpl(ibdfFileToWrite, toIgnore == null ? null : toIgnore.get()); |
|
Java | mit | 18ba9929f98a64b5c2c2f9c836cb713bd7c96054 | 0 | iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable | package org.broadinstitute.sting.oneoffprojects.walkers.varianteval2;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.contexts.variantcontext.MutableVariantContext;
import org.broadinstitute.sting.gatk.contexts.variantcontext.VariantContext;
import org.broadinstitute.sting.gatk.contexts.variantcontext.VariantContextUtils;
import org.broadinstitute.sting.gatk.contexts.variantcontext.Genotype;
import org.broadinstitute.sting.gatk.datasources.simpleDataSources.ReferenceOrderedDataSource;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.VariantContextAdaptors;
import org.broadinstitute.sting.gatk.walkers.RodWalker;
import org.broadinstitute.sting.utils.PackageUtils;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.cmdLine.Argument;
import org.broadinstitute.sting.utils.genotype.vcf.VCFWriter;
import org.broadinstitute.sting.utils.xReadLines;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
// todo -- evalations should support comment lines
// todo -- add Mendelian variable explanations (nDeNovo and nMissingTransmissions)
// todo -- write a simple column table system and have the evaluators return this instead of the list<list<string>> objects
// todo -- site frequency spectrum eval (freq. of variants in eval as a function of their AC and AN numbers)
// todo -- multiple sample concordance tool (genotypes in eval vs. genotypes in truth)
// todo -- allele freqeuncy discovery tool (FREQ in true vs. discovery counts in eval). Needs to process subset of samples in true (pools)
// todo -- clustered SNP counter
// todo -- HWEs
// todo -- indel metrics [count of sizes in/del should be in CountVariants]
// todo -- synonymous / non-synonmous ratio, or really just comparison of observed vs. expected biological annotation values
// todo -- Performance:
// todo -- create JEXL context implementing object that simply looks up values for JEXL evaluations. Throws error for unknown fields
// todo -- deal with performance issues with variant contexts
// todo -- port over SNP density walker:
// todo -- see walker for WG calc but will need to make it work with intervals correctly
// todo -- counts of snps per target [target name, gene, etc]
// todo -- add subgroup of known variants as to those at hapmap sites [it's in the dbSNP record]
// Todo -- should really include argument parsing @annotations from subclass in this walker. Very
// todo -- useful general capability. Right now you need to add arguments to VariantEval2 to handle new
// todo -- evaluation arguments (which is better than passing a string!)
// todo -- write or find a simple way to organize the table like output of variant eval 2. A generic table of strings?
// todo -- these really should be implemented as default select expression
// todo Extend VariantEval, our general-purpose tool for SNP evaluation, to differentiate Ti/Tv at CpG islands and also
// todo classify (and count) variants into coding, non-coding, synonomous/non-symonomous, 2/4 fold degenerate sites, etc.
// todo Assume that the incoming VCF has the annotations (you don't need to do this) but VE2 should split up results by
// todo these catogies automatically (using the default selects)
// todo -- this is really more a documentation issue. Really would be nice to have a pre-defined argument packet that
// todo -- can be provided to the system
// todo -- We agreed to report two standard values for variant evaluation from here out. One, we will continue to report
// todo -- the dbSNP 129 rate. Additionally, we will start to report the % of variants found that have already been seen in
// todo -- 1000 Genomes. This should be implemented as another standard comp_1kg binding, pointing to only variants
// todo -- discovered and released by 1KG. Might need to make this data set ourselves and keep it in GATK/data like
// todo -- dbsnp rod
//
// todo -- aux. plotting routines for VE2
//
// todo -- implement as select statment, but it's hard for multi-sample calls.
// todo -- Provide separate dbsnp rates for het only calls and any call where there is at least one hom-var genotype,
// todo -- since hets are much more likely to be errors
//
// todo -- Add Heng's hom run metrics -- single sample haplotype block lengths
/**
* Test routine for new VariantContext object
*/
public class VariantEval2Walker extends RodWalker<Integer, Integer> {
// --------------------------------------------------------------------------------------------------------------
//
// walker arguments
//
// --------------------------------------------------------------------------------------------------------------
// todo -- add doc string
@Argument(shortName="select", doc="", required=false)
protected String[] SELECT_EXPS = {"QUAL > 500.0", "HARD_TO_VALIDATE==1", "GATK_STANDARD==1"};
// todo -- add doc string
@Argument(shortName="selectName", doc="", required=false)
protected String[] SELECT_NAMES = {"q500plus", "low_mapq", "gatk_std_filters"};
@Argument(shortName="known", doc="Name of ROD bindings containing variant sites that should be treated as known when splitting eval rods into known and novel subsets", required=false)
protected String[] KNOWN_NAMES = {"dbsnp"};
@Argument(shortName="sample", doc="Derive eval and comp contexts using only these sample genotypes, when genotypes are available in the original context", required=false)
protected String[] SAMPLES = {};
private List<String> SAMPLES_LIST = null;
//
// Arguments for Mendelian Violation calculations
//
@Argument(shortName="family", doc="If provided, genotypes in will be examined for mendelian violations: this argument is a string formatted as dad+mom=child where these parameters determine which sample names are examined", required=false)
protected String FAMILY_STRUCTURE;
@Argument(shortName="MVQ", fullName="MendelianViolationQualThreshold", doc="Minimum genotype QUAL score for each trio member required to accept a site as a violation", required=false)
protected double MENDELIAN_VIOLATION_QUAL_THRESHOLD = 50;
@Argument(shortName="outputVCF", fullName="InterestingSitesVCF", doc="If provided, interesting sites emitted to this vcf and the INFO field annotated as to why they are interesting", required=false)
protected String outputVCF = null;
/** Right now we will only be looking at SNPS */
EnumSet<VariantContext.Type> ALLOW_VARIANT_CONTEXT_TYPES = EnumSet.of(VariantContext.Type.SNP, VariantContext.Type.NO_VARIATION);
@Argument(shortName="rsID", fullName="rsID", doc="If provided, list of rsID and build number for capping known snps by their build date", required=false)
protected String rsIDFile = null;
@Argument(shortName="maxRsIDBuild", fullName="maxRsIDBuild", doc="If provided, only variants with rsIDs <= maxRsIDBuild will be included in the set of knwon snps", required=false)
protected int maxRsIDBuild = Integer.MAX_VALUE;
Set<String> rsIDsToExclude = null;
// --------------------------------------------------------------------------------------------------------------
//
// private walker data
//
// --------------------------------------------------------------------------------------------------------------
/** private class holding all of the information about a single evaluation group (e.g., for eval ROD) */
private class EvaluationContext implements Comparable<EvaluationContext> {
// useful for typing
public String evalTrackName, compTrackName, novelty, filtered;
public boolean enableInterestingSiteCaptures = false;
VariantContextUtils.JexlVCMatchExp selectExp;
Set<VariantEvaluator> evaluations;
public boolean isIgnoringFilters() { return filtered.equals(RAW_SET_NAME); }
public boolean requiresFiltered() { return filtered.equals(FILTERED_SET_NAME); }
public boolean requiresNotFiltered() { return filtered.equals(RETAINED_SET_NAME); }
public boolean isIgnoringNovelty() { return novelty.equals(ALL_SET_NAME); }
public boolean requiresNovel() { return novelty.equals(NOVEL_SET_NAME); }
public boolean requiresKnown() { return novelty.equals(KNOWN_SET_NAME); }
public boolean isSelected() { return selectExp == null; }
public String getDisplayName() {
return Utils.join(".", Arrays.asList(evalTrackName, compTrackName, selectExp == null ? "all" : selectExp.name, filtered, novelty));
}
public int compareTo(EvaluationContext other) {
return this.getDisplayName().compareTo(other.getDisplayName());
}
public EvaluationContext( String evalName, String compName, String novelty, String filtered, VariantContextUtils.JexlVCMatchExp selectExp ) {
this.evalTrackName = evalName;
this.compTrackName = compName;
this.novelty = novelty;
this.filtered = filtered;
this.selectExp = selectExp;
this.enableInterestingSiteCaptures = selectExp == null;
this.evaluations = instantiateEvalationsSet();
}
}
private List<EvaluationContext> contexts = null;
// lists of all comp and eval ROD track names
private Set<String> compNames = new HashSet<String>();
private Set<String> evalNames = new HashSet<String>();
private List<String> variantEvaluationNames = new ArrayList<String>();
private static String RAW_SET_NAME = "raw";
private static String RETAINED_SET_NAME = "called";
private static String FILTERED_SET_NAME = "filtered";
private static String ALL_SET_NAME = "all";
private static String KNOWN_SET_NAME = "known";
private static String NOVEL_SET_NAME = "novel";
private final static String CONTEXT_HEADER = "eval.comp.select.filter.novelty";
private final static int N_CONTEXT_NAME_PARTS = CONTEXT_HEADER.split("\\.").length;
private static int[] nameSizes = new int[N_CONTEXT_NAME_PARTS];
static {
int i = 0;
for ( String elt : CONTEXT_HEADER.split("\\.") )
nameSizes[i++] = elt.length();
}
// Dynamically determined variantEvaluation classes
private List<Class<? extends VariantEvaluator>> evaluationClasses = null;
/** output writer for interesting sites */
private VCFWriter writer = null;
private boolean wroteHeader = false;
// --------------------------------------------------------------------------------------------------------------
//
// initialize
//
// --------------------------------------------------------------------------------------------------------------
public void initialize() {
SAMPLES_LIST = Arrays.asList(SAMPLES);
determineAllEvalations();
List<VariantContextUtils.JexlVCMatchExp> selectExps = VariantContextUtils.initializeMatchExps(SELECT_NAMES, SELECT_EXPS);
for ( ReferenceOrderedDataSource d : this.getToolkit().getRodDataSources() ) {
if ( d.getName().startsWith("eval") ) {
evalNames.add(d.getName());
} else if ( d.getName().startsWith("dbsnp") || d.getName().startsWith("hapmap") || d.getName().startsWith("comp") ) {
compNames.add(d.getName());
} else {
logger.info("Not evaluating ROD binding " + d.getName());
}
}
contexts = initializeEvaluationContexts(evalNames, compNames, selectExps);
determineContextNamePartSizes();
if ( outputVCF != null )
writer = new VCFWriter(new File(outputVCF));
if ( rsIDFile != null ) {
if ( maxRsIDBuild == Integer.MAX_VALUE )
throw new IllegalArgumentException("rsIDFile " + rsIDFile + " was given but associated max RSID build parameter wasn't available");
rsIDsToExclude = getrsIDsToExclude(new File(rsIDFile), maxRsIDBuild);
}
}
private static Set<String> getrsIDsToExclude(File rsIDFile, int maxRsIDBuild) {
List<String> toExclude = new LinkedList<String>();
int n = 1;
try {
for ( String line : new xReadLines(rsIDFile) ) {
String parts[] = line.split(" ");
if ( parts.length != 2 )
throw new StingException("Invalid rsID / build pair at " + n + " line = " + line );
//System.out.printf("line %s %s %s%n", line, parts[0], parts[1]);
if ( Integer.valueOf(parts[1]) > maxRsIDBuild ) {
//System.out.printf("Excluding %s%n", line);
toExclude.add("rs"+parts[0]);
}
n++;
if ( n % 1000000 == 0 )
logger.info(String.format("Read %d rsIDs from rsID -> build file", n));
}
} catch (FileNotFoundException e) {
throw new StingException(e.getMessage());
}
logger.info(String.format("Excluding %d of %d (%.2f%%) rsIDs found from builds > %d",
toExclude.size(), n, ((100.0 * toExclude.size())/n), maxRsIDBuild));
return new HashSet<String>(toExclude);
}
private final static String ID = "ID";
private boolean excludeComp(VariantContext vc) {
String id = vc != null && vc.hasAttribute(ID) ? vc.getAttributeAsString(ID) : null;
boolean ex = rsIDsToExclude != null && id != null && rsIDsToExclude.contains(id);
//System.out.printf("Testing id %s ex=%b against %s%n", id, ex, vc);
return ex;
}
private void determineAllEvalations() {
evaluationClasses = PackageUtils.getClassesImplementingInterface(VariantEvaluator.class);
for ( VariantEvaluator e : instantiateEvalationsSet() ) {
// for collecting purposes
variantEvaluationNames.add(e.getName());
logger.debug("Including VariantEvaluator " + e.getName() + " of class " + e.getClass());
}
Collections.sort(variantEvaluationNames);
}
private <T> List<T> append(List<T> selectExps, T elt) {
List<T> l = new ArrayList<T>(selectExps);
l.add(elt);
return l;
}
private List<EvaluationContext> initializeEvaluationContexts(Set<String> evalNames, Set<String> compNames, List<VariantContextUtils.JexlVCMatchExp> selectExps) {
List<EvaluationContext> contexts = new ArrayList<EvaluationContext>();
selectExps = append(selectExps, null);
for ( String evalName : evalNames ) {
for ( String compName : compNames ) {
for ( VariantContextUtils.JexlVCMatchExp e : selectExps ) {
for ( String filteredName : Arrays.asList(RAW_SET_NAME, RETAINED_SET_NAME, FILTERED_SET_NAME) ) {
for ( String novelty : Arrays.asList(ALL_SET_NAME, KNOWN_SET_NAME, NOVEL_SET_NAME) ) {
EvaluationContext context = new EvaluationContext(evalName, compName, novelty, filteredName, e);
contexts.add(context);
}
}
}
}
}
Collections.sort(contexts);
return contexts;
}
private Set<VariantEvaluator> instantiateEvalationsSet() {
Set<VariantEvaluator> evals = new HashSet<VariantEvaluator>();
Object[] args = new Object[]{this};
Class[] argTypes = new Class[]{this.getClass()};
for ( Class c : evaluationClasses ) {
try {
Constructor constructor = c.getConstructor(argTypes);
VariantEvaluator eval = (VariantEvaluator)constructor.newInstance(args);
evals.add(eval);
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate class '%s': must be concrete class", c.getSimpleName()));
} catch (NoSuchMethodException e) {
throw new StingException(String.format("Cannot find expected constructor for class '%s': must have constructor accepting a single VariantEval2Walker object", c.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate class '%s':", c.getSimpleName()));
} catch (InvocationTargetException e) {
throw new StingException(String.format("Cannot instantiate class '%s':", c.getSimpleName()));
}
}
return evals;
}
private boolean captureInterestingSitesOfEvalSet(EvaluationContext group) {
//System.out.printf("checking %s%n", name);
return group.requiresNotFiltered() && group.isIgnoringNovelty();
}
// --------------------------------------------------------------------------------------------------------------
//
// map
//
// --------------------------------------------------------------------------------------------------------------
// todo -- call a single function to build a map from track name -> variant context / null for all
// -- eval + comp names. Use this data structure to get data throughout rest of the loops here
public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
//System.out.printf("map at %s with %d skipped%n", context.getLocation(), context.getSkippedBases());
if ( ref == null )
return 0;
Map<String, VariantContext> vcs = getVariantContexts(tracker, context);
//Collection<VariantContext> comps = getCompVariantContexts(tracker, context);
// to enable walking over pairs where eval or comps have no elements
for ( EvaluationContext group : contexts ) {
VariantContext vc = vcs.get(group.evalTrackName);
//logger.debug(String.format("Updating %s with variant", vc));
Set<VariantEvaluator> evaluations = group.evaluations;
boolean evalWantsVC = applyVCtoEvaluation(vc, vcs, group);
List<String> interestingReasons = new ArrayList<String>();
for ( VariantEvaluator evaluation : evaluations ) {
if ( evaluation.enabled() ) {
// we always call update0 in case the evaluation tracks things like number of bases covered
evaluation.update0(tracker, ref, context);
// now call the single or paired update function
switch ( evaluation.getComparisonOrder() ) {
case 1:
if ( evalWantsVC && vc != null ) {
String interesting = evaluation.update1(vc, tracker, ref, context);
if ( interesting != null ) interestingReasons.add(interesting);
}
break;
case 2:
VariantContext comp = vcs.get(group.compTrackName);
String interesting = evaluation.update2( evalWantsVC ? vc : null, comp, tracker, ref, context );
if ( interesting != null ) interestingReasons.add(interesting);
break;
default:
throw new StingException("BUG: Unexpected evaluation order " + evaluation);
}
}
}
if ( group.enableInterestingSiteCaptures && captureInterestingSitesOfEvalSet(group) )
writeInterestingSite(interestingReasons, vc, ref.getBase());
}
return 0;
}
private void writeInterestingSite(List<String> interestingReasons, VariantContext vc, char ref) {
if ( writer != null && interestingReasons.size() > 0 ) {
MutableVariantContext mvc = new MutableVariantContext(vc);
for ( String why : interestingReasons ) {
String key, value;
String[] parts = why.split("=");
switch ( parts.length ) {
case 1:
key = parts[0];
value = "1";
break;
case 2:
key = parts[0];
value = parts[1];
break;
default:
throw new IllegalStateException("BUG: saw a interesting site reason sting with multiple = signs " + why);
}
mvc.putAttribute(key, value);
}
if ( ! wroteHeader ) {
writer.writeHeader(VariantContextAdaptors.createVCFHeader(null, vc));
wroteHeader = true;
}
writer.addRecord(VariantContextAdaptors.toVCF(mvc, ref));
//interestingReasons.clear();
}
}
private boolean applyVCtoEvaluation(VariantContext vc, Map<String, VariantContext> vcs, EvaluationContext group) {
if ( vc == null )
return true;
if ( group.requiresFiltered() && vc.isNotFiltered() )
return false;
if ( group.requiresNotFiltered() && vc.isFiltered() )
return false;
boolean vcKnown = vcIsKnown(vc, vcs, KNOWN_NAMES);
if ( group.requiresKnown() && ! vcKnown )
return false;
else if ( group.requiresNovel() && vcKnown )
return false;
if ( group.selectExp != null && ! VariantContextUtils.match(vc, group.selectExp) )
return false;
// nothing invalidated our membership in this set
return true;
}
private boolean vcIsKnown(VariantContext vc, Map<String, VariantContext> vcs, String[] knownNames ) {
for ( String knownName : knownNames ) {
VariantContext known = vcs.get(knownName);
if ( known != null && known.isNotFiltered() && known.getType() == vc.getType() ) {
return true;
}
}
return false;
}
// can't handle this situation
// todo -- warning, this leads to some missing SNPs at complex loci, such as:
// todo -- 591 1 841619 841620 rs4970464 0 - A A -/C/T genomic mixed unknown 0 0 near-gene-3 exact 1
// todo -- 591 1 841619 841620 rs62677860 0 + A A C/T genomic single unknown 0 0 near-gene-3 exact 1
//
//logger.info(String.format("Ignore second+ events at locus %s in rod %s => rec is %s", context.getLocation(), rodList.getName(), rec));
private Map<String, VariantContext> getVariantContexts(RefMetaDataTracker tracker, AlignmentContext context) {
// todo -- we need to deal with dbSNP where there can be multiple records at the same start site. A potential solution is to
// todo -- allow the variant evaluation to specify the type of variants it wants to see and only take the first such record at a site
Map<String, VariantContext> bindings = new HashMap<String, VariantContext>();
bindVariantContexts(bindings, evalNames, tracker, context, false);
bindVariantContexts(bindings, compNames, tracker, context, true);
return bindings;
}
private void bindVariantContexts(Map<String, VariantContext> map, Collection<String> names,
RefMetaDataTracker tracker, AlignmentContext context, boolean allowExcludes ) {
for ( String name : names ) {
Collection<VariantContext> contexts = tracker.getVariantContexts(name, ALLOW_VARIANT_CONTEXT_TYPES, context.getLocation(), true, true);
if ( context.size() > 1 )
throw new StingException("Found multiple variant contexts at " + context.getLocation());
VariantContext vc = contexts.size() == 1 ? contexts.iterator().next() : null;
if ( vc != null && vc.hasGenotypes(SAMPLES_LIST) ) {
//if ( ! name.equals("eval") ) logger.info(String.format("subsetting VC %s", vc));
vc = vc.subContextFromGenotypes(vc.getGenotypes(SAMPLES_LIST).values());
//if ( ! name.equals("eval") ) logger.info(String.format(" => VC %s", vc));
}
map.put(name, allowExcludes && excludeComp(vc) ? null : vc);
}
}
// --------------------------------------------------------------------------------------------------------------
//
// reduce
//
// --------------------------------------------------------------------------------------------------------------
public Integer reduceInit() {
return 0;
}
public Integer reduce(Integer point, Integer sum) {
return point + sum;
}
public VariantEvaluator getEvalByName(String name, Set<VariantEvaluator> s) {
for ( VariantEvaluator e : s )
if ( e.getName().equals(name) )
return e;
return null;
}
private void determineContextNamePartSizes() {
for ( EvaluationContext group : contexts ) {
String[] parts = group.getDisplayName().split("\\.");
if ( parts.length != N_CONTEXT_NAME_PARTS ) {
throw new StingException("Unexpected number of eval name parts " + group.getDisplayName() + " length = " + parts.length + ", expected " + N_CONTEXT_NAME_PARTS);
} else {
for ( int i = 0; i < parts.length; i++ )
nameSizes[i] = Math.max(nameSizes[i], parts[i].length());
}
}
}
private String formatKeyword(String keyWord) {
//System.out.printf("keyword %s%n", keyWord);
StringBuilder s = new StringBuilder();
int i = 0;
for ( String part : keyWord.split("\\.") ) {
//System.out.printf("part %s %d%n", part, nameSizes[i]);
s.append(String.format("%" + nameSizes[i] + "s ", part));
i++;
}
return s.toString();
}
public void onTraversalDone(Integer result) {
// todo -- this really needs to be pretty printed; use some kind of table organization
// todo -- so that we can load up all of the data in one place, analyze the widths of the columns
// todo -- and pretty print it
for ( String evalName : variantEvaluationNames ) {
boolean first = true;
out.printf("%n%n");
// todo -- show that comp is dbsnp, etc. is columns
String lastEvalTrack = null;
for ( EvaluationContext group : contexts ) {
if ( lastEvalTrack == null || ! lastEvalTrack.equals(group.evalTrackName) ) {
out.printf("%s%n", Utils.dupString('-', 80));
lastEvalTrack = group.evalTrackName;
}
VariantEvaluator eval = getEvalByName(evalName, group.evaluations);
String keyWord = group.getDisplayName();
if ( eval.enabled() ) {
if ( first ) {
out.printf("%20s %s %s%n", evalName, formatKeyword(CONTEXT_HEADER), Utils.join("\t", eval.getTableHeader()));
first = false;
}
for ( List<String> row : eval.getTableRows() )
out.printf("%20s %s %s%n", evalName, formatKeyword(keyWord), Utils.join("\t", row));
}
}
}
}
protected Logger getLogger() { return logger; }
}
| java/src/org/broadinstitute/sting/oneoffprojects/walkers/varianteval2/VariantEval2Walker.java | package org.broadinstitute.sting.oneoffprojects.walkers.varianteval2;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.contexts.variantcontext.MutableVariantContext;
import org.broadinstitute.sting.gatk.contexts.variantcontext.VariantContext;
import org.broadinstitute.sting.gatk.contexts.variantcontext.VariantContextUtils;
import org.broadinstitute.sting.gatk.contexts.variantcontext.Genotype;
import org.broadinstitute.sting.gatk.datasources.simpleDataSources.ReferenceOrderedDataSource;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.VariantContextAdaptors;
import org.broadinstitute.sting.gatk.walkers.RodWalker;
import org.broadinstitute.sting.utils.PackageUtils;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.cmdLine.Argument;
import org.broadinstitute.sting.utils.genotype.vcf.VCFWriter;
import org.broadinstitute.sting.utils.xReadLines;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
// todo -- evalations should support comment lines
// todo -- add Mendelian variable explanations (nDeNovo and nMissingTransmissions)
//
// todo -- write a simple column table system and have the evaluators return this instead of the list<list<string>> objects
//
// todo -- site frequency spectrum eval (freq. of variants in eval as a function of their AC and AN numbers)
// todo -- multiple sample concordance tool (genotypes in eval vs. genotypes in truth)
// todo -- allele freqeuncy discovery tool (FREQ in true vs. discovery counts in eval). Needs to process subset of samples in true (pools)
// todo -- clustered SNP counter
// todo -- HWEs
// todo -- Validation data analysis from VE1? What is it and should we transition it over?
// todo -- indel metrics [count of sizes in/del should be in CountVariants]
//
// todo -- Performance
// todo -- create JEXL context implementing object that simply looks up values for JEXL evaluations. Throws error for unknown fields
//
//
// todo -- port over SNP density evaluator.
// todo -- make it work with intervals correctly
//
// todo -- counts of snps per target [target name, gene, etc]
// todo -- add subgroup of known variants as to those at hapmap sites [it's in the dbSNP record]
// todo -- deal with performance issues with variant contexts
//
// Todo -- should really include argument parsing @annotations from subclass in this walker. Very
// todo -- useful general capability. Right now you need to add arguments to VariantEval2 to handle new
// todo -- evaluation arguments (which is better than passing a string!)
//
//
// todo -- the whole organization only supports a single eval x comp evaluation. We need to instantiate
// todo -- new contexts for each comparison object too! The output table should be clear as to what the "comp"
// todo -- variable is in the analysis
//
//
// todo -- write or find a simple way to organize the table like output of variant eval 2. A generic table of strings?
//
// todo Extend VariantEval, our general-purpose tool for SNP evaluation, to differentiate Ti/Tv at CpG islands and also
// todo classify (and count) variants into coding, non-coding, synonomous/non-symonomous, 2/4 fold degenerate sites, etc.
// todo Assume that the incoming VCF has the annotations (you don't need to do this) but VE2 should split up results by
// todo these catogies automatically (using the default selects)
//
// todo -- We agreed to report two standard values for variant evaluation from here out. One, we will continue to report
// todo -- the dbSNP 129 rate. Additionally, we will start to report the % of variants found that have already been seen in
// todo -- 1000 Genomes. This should be implemented as another standard comp_1kg binding, pointing to only variants
// todo -- discovered and released by 1KG. Might need to make this data set ourselves and keep it in GATK/data like
// todo -- dbsnp rod
//
// todo -- aux. plotting routines for VE2
//
// todo -- Provide separate dbsnp rates for het only calls and any call where there is at least one hom-var genotype,
// todo -- since hets are much more likely to be errors
// todo -- Add Heng's hom run metrics
/**
* Test routine for new VariantContext object
*/
public class VariantEval2Walker extends RodWalker<Integer, Integer> {
// --------------------------------------------------------------------------------------------------------------
//
// walker arguments
//
// --------------------------------------------------------------------------------------------------------------
// todo -- add doc string
@Argument(shortName="select", doc="", required=false)
protected String[] SELECT_EXPS = {"QUAL > 500.0", "HARD_TO_VALIDATE==1", "GATK_STANDARD==1"};
// todo -- add doc string
@Argument(shortName="selectName", doc="", required=false)
protected String[] SELECT_NAMES = {"q500plus", "low_mapq", "gatk_std_filters"};
@Argument(shortName="known", doc="Name of ROD bindings containing variant sites that should be treated as known when splitting eval rods into known and novel subsets", required=false)
protected String[] KNOWN_NAMES = {"dbsnp"};
@Argument(shortName="sample", doc="Derive eval and comp contexts using only these sample genotypes, when genotypes are available in the original context", required=false)
protected String[] SAMPLES = {};
private List<String> SAMPLES_LIST = null;
//
// Arguments for Mendelian Violation calculations
//
@Argument(shortName="family", doc="If provided, genotypes in will be examined for mendelian violations: this argument is a string formatted as dad+mom=child where these parameters determine which sample names are examined", required=false)
protected String FAMILY_STRUCTURE;
@Argument(shortName="MVQ", fullName="MendelianViolationQualThreshold", doc="Minimum genotype QUAL score for each trio member required to accept a site as a violation", required=false)
protected double MENDELIAN_VIOLATION_QUAL_THRESHOLD = 50;
@Argument(shortName="outputVCF", fullName="InterestingSitesVCF", doc="If provided, interesting sites emitted to this vcf and the INFO field annotated as to why they are interesting", required=false)
protected String outputVCF = null;
/** Right now we will only be looking at SNPS */
EnumSet<VariantContext.Type> ALLOW_VARIANT_CONTEXT_TYPES = EnumSet.of(VariantContext.Type.SNP, VariantContext.Type.NO_VARIATION);
@Argument(shortName="rsID", fullName="rsID", doc="If provided, list of rsID and build number for capping known snps by their build date", required=false)
protected String rsIDFile = null;
@Argument(shortName="maxRsIDBuild", fullName="maxRsIDBuild", doc="If provided, only variants with rsIDs <= maxRsIDBuild will be included in the set of knwon snps", required=false)
protected int maxRsIDBuild = Integer.MAX_VALUE;
Set<String> rsIDsToExclude = null;
// --------------------------------------------------------------------------------------------------------------
//
// private walker data
//
// --------------------------------------------------------------------------------------------------------------
/** private class holding all of the information about a single evaluation group (e.g., for eval ROD) */
private class EvaluationContext implements Comparable<EvaluationContext> {
// useful for typing
public String evalTrackName, compTrackName, novelty, filtered;
public boolean enableInterestingSiteCaptures = false;
VariantContextUtils.JexlVCMatchExp selectExp;
Set<VariantEvaluator> evaluations;
public boolean isIgnoringFilters() { return filtered.equals(RAW_SET_NAME); }
public boolean requiresFiltered() { return filtered.equals(FILTERED_SET_NAME); }
public boolean requiresNotFiltered() { return filtered.equals(RETAINED_SET_NAME); }
public boolean isIgnoringNovelty() { return novelty.equals(ALL_SET_NAME); }
public boolean requiresNovel() { return novelty.equals(NOVEL_SET_NAME); }
public boolean requiresKnown() { return novelty.equals(KNOWN_SET_NAME); }
public boolean isSelected() { return selectExp == null; }
public String getDisplayName() {
return Utils.join(".", Arrays.asList(evalTrackName, compTrackName, selectExp == null ? "all" : selectExp.name, filtered, novelty));
}
public int compareTo(EvaluationContext other) {
return this.getDisplayName().compareTo(other.getDisplayName());
}
public EvaluationContext( String evalName, String compName, String novelty, String filtered, VariantContextUtils.JexlVCMatchExp selectExp ) {
this.evalTrackName = evalName;
this.compTrackName = compName;
this.novelty = novelty;
this.filtered = filtered;
this.selectExp = selectExp;
this.enableInterestingSiteCaptures = selectExp == null;
this.evaluations = instantiateEvalationsSet();
}
}
private List<EvaluationContext> contexts = null;
// lists of all comp and eval ROD track names
private Set<String> compNames = new HashSet<String>();
private Set<String> evalNames = new HashSet<String>();
private List<String> variantEvaluationNames = new ArrayList<String>();
private static String RAW_SET_NAME = "raw";
private static String RETAINED_SET_NAME = "called";
private static String FILTERED_SET_NAME = "filtered";
private static String ALL_SET_NAME = "all";
private static String KNOWN_SET_NAME = "known";
private static String NOVEL_SET_NAME = "novel";
private final static String CONTEXT_HEADER = "eval.comp.select.filter.novelty";
private final static int N_CONTEXT_NAME_PARTS = CONTEXT_HEADER.split("\\.").length;
private static int[] nameSizes = new int[N_CONTEXT_NAME_PARTS];
static {
int i = 0;
for ( String elt : CONTEXT_HEADER.split("\\.") )
nameSizes[i++] = elt.length();
}
// Dynamically determined variantEvaluation classes
private List<Class<? extends VariantEvaluator>> evaluationClasses = null;
/** output writer for interesting sites */
private VCFWriter writer = null;
private boolean wroteHeader = false;
// --------------------------------------------------------------------------------------------------------------
//
// initialize
//
// --------------------------------------------------------------------------------------------------------------
public void initialize() {
SAMPLES_LIST = Arrays.asList(SAMPLES);
determineAllEvalations();
List<VariantContextUtils.JexlVCMatchExp> selectExps = VariantContextUtils.initializeMatchExps(SELECT_NAMES, SELECT_EXPS);
for ( ReferenceOrderedDataSource d : this.getToolkit().getRodDataSources() ) {
if ( d.getName().startsWith("eval") ) {
evalNames.add(d.getName());
} else if ( d.getName().startsWith("dbsnp") || d.getName().startsWith("hapmap") || d.getName().startsWith("comp") ) {
compNames.add(d.getName());
} else {
logger.info("Not evaluating ROD binding " + d.getName());
}
}
contexts = initializeEvaluationContexts(evalNames, compNames, selectExps);
determineContextNamePartSizes();
if ( outputVCF != null )
writer = new VCFWriter(new File(outputVCF));
if ( rsIDFile != null ) {
if ( maxRsIDBuild == Integer.MAX_VALUE )
throw new IllegalArgumentException("rsIDFile " + rsIDFile + " was given but associated max RSID build parameter wasn't available");
rsIDsToExclude = getrsIDsToExclude(new File(rsIDFile), maxRsIDBuild);
}
}
private static Set<String> getrsIDsToExclude(File rsIDFile, int maxRsIDBuild) {
List<String> toExclude = new LinkedList<String>();
int n = 1;
try {
for ( String line : new xReadLines(rsIDFile) ) {
String parts[] = line.split(" ");
if ( parts.length != 2 )
throw new StingException("Invalid rsID / build pair at " + n + " line = " + line );
//System.out.printf("line %s %s %s%n", line, parts[0], parts[1]);
if ( Integer.valueOf(parts[1]) > maxRsIDBuild ) {
//System.out.printf("Excluding %s%n", line);
toExclude.add("rs"+parts[0]);
}
n++;
if ( n % 1000000 == 0 )
logger.info(String.format("Read %d rsIDs from rsID -> build file", n));
}
} catch (FileNotFoundException e) {
throw new StingException(e.getMessage());
}
logger.info(String.format("Excluding %d of %d (%.2f%%) rsIDs found from builds > %d",
toExclude.size(), n, ((100.0 * toExclude.size())/n), maxRsIDBuild));
return new HashSet<String>(toExclude);
}
private final static String ID = "ID";
private boolean excludeComp(VariantContext vc) {
String id = vc != null && vc.hasAttribute(ID) ? vc.getAttributeAsString(ID) : null;
boolean ex = rsIDsToExclude != null && id != null && rsIDsToExclude.contains(id);
//System.out.printf("Testing id %s ex=%b against %s%n", id, ex, vc);
return ex;
}
private void determineAllEvalations() {
evaluationClasses = PackageUtils.getClassesImplementingInterface(VariantEvaluator.class);
for ( VariantEvaluator e : instantiateEvalationsSet() ) {
// for collecting purposes
variantEvaluationNames.add(e.getName());
logger.debug("Including VariantEvaluator " + e.getName() + " of class " + e.getClass());
}
Collections.sort(variantEvaluationNames);
}
private <T> List<T> append(List<T> selectExps, T elt) {
List<T> l = new ArrayList<T>(selectExps);
l.add(elt);
return l;
}
private List<EvaluationContext> initializeEvaluationContexts(Set<String> evalNames, Set<String> compNames, List<VariantContextUtils.JexlVCMatchExp> selectExps) {
List<EvaluationContext> contexts = new ArrayList<EvaluationContext>();
selectExps = append(selectExps, null);
for ( String evalName : evalNames ) {
for ( String compName : compNames ) {
for ( VariantContextUtils.JexlVCMatchExp e : selectExps ) {
for ( String filteredName : Arrays.asList(RAW_SET_NAME, RETAINED_SET_NAME, FILTERED_SET_NAME) ) {
for ( String novelty : Arrays.asList(ALL_SET_NAME, KNOWN_SET_NAME, NOVEL_SET_NAME) ) {
EvaluationContext context = new EvaluationContext(evalName, compName, novelty, filteredName, e);
contexts.add(context);
}
}
}
}
}
Collections.sort(contexts);
return contexts;
}
private Set<VariantEvaluator> instantiateEvalationsSet() {
Set<VariantEvaluator> evals = new HashSet<VariantEvaluator>();
Object[] args = new Object[]{this};
Class[] argTypes = new Class[]{this.getClass()};
for ( Class c : evaluationClasses ) {
try {
Constructor constructor = c.getConstructor(argTypes);
VariantEvaluator eval = (VariantEvaluator)constructor.newInstance(args);
evals.add(eval);
} catch (InstantiationException e) {
throw new StingException(String.format("Cannot instantiate class '%s': must be concrete class", c.getSimpleName()));
} catch (NoSuchMethodException e) {
throw new StingException(String.format("Cannot find expected constructor for class '%s': must have constructor accepting a single VariantEval2Walker object", c.getSimpleName()));
} catch (IllegalAccessException e) {
throw new StingException(String.format("Cannot instantiate class '%s':", c.getSimpleName()));
} catch (InvocationTargetException e) {
throw new StingException(String.format("Cannot instantiate class '%s':", c.getSimpleName()));
}
}
return evals;
}
private boolean captureInterestingSitesOfEvalSet(EvaluationContext group) {
//System.out.printf("checking %s%n", name);
return group.requiresNotFiltered() && group.isIgnoringNovelty();
}
// --------------------------------------------------------------------------------------------------------------
//
// map
//
// --------------------------------------------------------------------------------------------------------------
// todo -- call a single function to build a map from track name -> variant context / null for all
// -- eval + comp names. Use this data structure to get data throughout rest of the loops here
public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
//System.out.printf("map at %s with %d skipped%n", context.getLocation(), context.getSkippedBases());
if ( ref == null )
return 0;
Map<String, VariantContext> vcs = getVariantContexts(tracker, context);
//Collection<VariantContext> comps = getCompVariantContexts(tracker, context);
// to enable walking over pairs where eval or comps have no elements
for ( EvaluationContext group : contexts ) {
VariantContext vc = vcs.get(group.evalTrackName);
//logger.debug(String.format("Updating %s with variant", vc));
Set<VariantEvaluator> evaluations = group.evaluations;
boolean evalWantsVC = applyVCtoEvaluation(vc, vcs, group);
List<String> interestingReasons = new ArrayList<String>();
for ( VariantEvaluator evaluation : evaluations ) {
if ( evaluation.enabled() ) {
// we always call update0 in case the evaluation tracks things like number of bases covered
evaluation.update0(tracker, ref, context);
// now call the single or paired update function
switch ( evaluation.getComparisonOrder() ) {
case 1:
if ( evalWantsVC && vc != null ) {
String interesting = evaluation.update1(vc, tracker, ref, context);
if ( interesting != null ) interestingReasons.add(interesting);
}
break;
case 2:
VariantContext comp = vcs.get(group.compTrackName);
String interesting = evaluation.update2( evalWantsVC ? vc : null, comp, tracker, ref, context );
if ( interesting != null ) interestingReasons.add(interesting);
break;
default:
throw new StingException("BUG: Unexpected evaluation order " + evaluation);
}
}
}
if ( group.enableInterestingSiteCaptures && captureInterestingSitesOfEvalSet(group) )
writeInterestingSite(interestingReasons, vc, ref.getBase());
}
return 0;
}
private void writeInterestingSite(List<String> interestingReasons, VariantContext vc, char ref) {
if ( writer != null && interestingReasons.size() > 0 ) {
MutableVariantContext mvc = new MutableVariantContext(vc);
for ( String why : interestingReasons ) {
String key, value;
String[] parts = why.split("=");
switch ( parts.length ) {
case 1:
key = parts[0];
value = "1";
break;
case 2:
key = parts[0];
value = parts[1];
break;
default:
throw new IllegalStateException("BUG: saw a interesting site reason sting with multiple = signs " + why);
}
mvc.putAttribute(key, value);
}
if ( ! wroteHeader ) {
writer.writeHeader(VariantContextAdaptors.createVCFHeader(null, vc));
wroteHeader = true;
}
writer.addRecord(VariantContextAdaptors.toVCF(mvc, ref));
//interestingReasons.clear();
}
}
private boolean applyVCtoEvaluation(VariantContext vc, Map<String, VariantContext> vcs, EvaluationContext group) {
if ( vc == null )
return true;
if ( group.requiresFiltered() && vc.isNotFiltered() )
return false;
if ( group.requiresNotFiltered() && vc.isFiltered() )
return false;
boolean vcKnown = vcIsKnown(vc, vcs, KNOWN_NAMES);
if ( group.requiresKnown() && ! vcKnown )
return false;
else if ( group.requiresNovel() && vcKnown )
return false;
if ( group.selectExp != null && ! VariantContextUtils.match(vc, group.selectExp) )
return false;
// nothing invalidated our membership in this set
return true;
}
private boolean vcIsKnown(VariantContext vc, Map<String, VariantContext> vcs, String[] knownNames ) {
for ( String knownName : knownNames ) {
VariantContext known = vcs.get(knownName);
if ( known != null && known.isNotFiltered() && known.getType() == vc.getType() ) {
return true;
}
}
return false;
}
// can't handle this situation
// todo -- warning, this leads to some missing SNPs at complex loci, such as:
// todo -- 591 1 841619 841620 rs4970464 0 - A A -/C/T genomic mixed unknown 0 0 near-gene-3 exact 1
// todo -- 591 1 841619 841620 rs62677860 0 + A A C/T genomic single unknown 0 0 near-gene-3 exact 1
//
//logger.info(String.format("Ignore second+ events at locus %s in rod %s => rec is %s", context.getLocation(), rodList.getName(), rec));
private Map<String, VariantContext> getVariantContexts(RefMetaDataTracker tracker, AlignmentContext context) {
// todo -- we need to deal with dbSNP where there can be multiple records at the same start site. A potential solution is to
// todo -- allow the variant evaluation to specify the type of variants it wants to see and only take the first such record at a site
Map<String, VariantContext> bindings = new HashMap<String, VariantContext>();
bindVariantContexts(bindings, evalNames, tracker, context, false);
bindVariantContexts(bindings, compNames, tracker, context, true);
return bindings;
}
private void bindVariantContexts(Map<String, VariantContext> map, Collection<String> names,
RefMetaDataTracker tracker, AlignmentContext context, boolean allowExcludes ) {
for ( String name : names ) {
Collection<VariantContext> contexts = tracker.getVariantContexts(name, ALLOW_VARIANT_CONTEXT_TYPES, context.getLocation(), true, true);
if ( context.size() > 1 )
throw new StingException("Found multiple variant contexts at " + context.getLocation());
VariantContext vc = contexts.size() == 1 ? contexts.iterator().next() : null;
if ( vc != null && vc.hasGenotypes(SAMPLES_LIST) ) {
//if ( ! name.equals("eval") ) logger.info(String.format("subsetting VC %s", vc));
vc = vc.subContextFromGenotypes(vc.getGenotypes(SAMPLES_LIST).values());
//if ( ! name.equals("eval") ) logger.info(String.format(" => VC %s", vc));
}
map.put(name, allowExcludes && excludeComp(vc) ? null : vc);
}
}
// --------------------------------------------------------------------------------------------------------------
//
// reduce
//
// --------------------------------------------------------------------------------------------------------------
public Integer reduceInit() {
return 0;
}
public Integer reduce(Integer point, Integer sum) {
return point + sum;
}
public VariantEvaluator getEvalByName(String name, Set<VariantEvaluator> s) {
for ( VariantEvaluator e : s )
if ( e.getName().equals(name) )
return e;
return null;
}
private void determineContextNamePartSizes() {
for ( EvaluationContext group : contexts ) {
String[] parts = group.getDisplayName().split("\\.");
if ( parts.length != N_CONTEXT_NAME_PARTS ) {
throw new StingException("Unexpected number of eval name parts " + group.getDisplayName() + " length = " + parts.length + ", expected " + N_CONTEXT_NAME_PARTS);
} else {
for ( int i = 0; i < parts.length; i++ )
nameSizes[i] = Math.max(nameSizes[i], parts[i].length());
}
}
}
private String formatKeyword(String keyWord) {
//System.out.printf("keyword %s%n", keyWord);
StringBuilder s = new StringBuilder();
int i = 0;
for ( String part : keyWord.split("\\.") ) {
//System.out.printf("part %s %d%n", part, nameSizes[i]);
s.append(String.format("%" + nameSizes[i] + "s ", part));
i++;
}
return s.toString();
}
public void onTraversalDone(Integer result) {
// todo -- this really needs to be pretty printed; use some kind of table organization
// todo -- so that we can load up all of the data in one place, analyze the widths of the columns
// todo -- and pretty print it
for ( String evalName : variantEvaluationNames ) {
boolean first = true;
out.printf("%n%n");
// todo -- show that comp is dbsnp, etc. is columns
String lastEvalTrack = null;
for ( EvaluationContext group : contexts ) {
if ( lastEvalTrack == null || ! lastEvalTrack.equals(group.evalTrackName) ) {
out.printf("%s%n", Utils.dupString('-', 80));
lastEvalTrack = group.evalTrackName;
}
VariantEvaluator eval = getEvalByName(evalName, group.evaluations);
String keyWord = group.getDisplayName();
if ( eval.enabled() ) {
if ( first ) {
out.printf("%20s %s %s%n", evalName, formatKeyword(CONTEXT_HEADER), Utils.join("\t", eval.getTableHeader()));
first = false;
}
for ( List<String> row : eval.getTableRows() )
out.printf("%20s %s %s%n", evalName, formatKeyword(keyWord), Utils.join("\t", row));
}
}
}
}
protected Logger getLogger() { return logger; }
}
| notes for eric
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2983 348d0f76-0448-11de-a6fe-93d51630548a
| java/src/org/broadinstitute/sting/oneoffprojects/walkers/varianteval2/VariantEval2Walker.java | notes for eric | <ide><path>ava/src/org/broadinstitute/sting/oneoffprojects/walkers/varianteval2/VariantEval2Walker.java
<ide> // todo -- evalations should support comment lines
<ide> // todo -- add Mendelian variable explanations (nDeNovo and nMissingTransmissions)
<ide>
<del>//
<ide> // todo -- write a simple column table system and have the evaluators return this instead of the list<list<string>> objects
<del>//
<ide>
<ide> // todo -- site frequency spectrum eval (freq. of variants in eval as a function of their AC and AN numbers)
<ide> // todo -- multiple sample concordance tool (genotypes in eval vs. genotypes in truth)
<ide> // todo -- allele freqeuncy discovery tool (FREQ in true vs. discovery counts in eval). Needs to process subset of samples in true (pools)
<ide> // todo -- clustered SNP counter
<ide> // todo -- HWEs
<del>// todo -- Validation data analysis from VE1? What is it and should we transition it over?
<ide> // todo -- indel metrics [count of sizes in/del should be in CountVariants]
<del>
<del>//
<del>// todo -- Performance
<add>// todo -- synonymous / non-synonmous ratio, or really just comparison of observed vs. expected biological annotation values
<add>
<add>// todo -- Performance:
<ide> // todo -- create JEXL context implementing object that simply looks up values for JEXL evaluations. Throws error for unknown fields
<del>//
<del>
<del>//
<del>// todo -- port over SNP density evaluator.
<del>// todo -- make it work with intervals correctly
<del>//
<add>// todo -- deal with performance issues with variant contexts
<add>
<add>// todo -- port over SNP density walker:
<add>// todo -- see walker for WG calc but will need to make it work with intervals correctly
<ide>
<ide> // todo -- counts of snps per target [target name, gene, etc]
<ide>
<ide> // todo -- add subgroup of known variants as to those at hapmap sites [it's in the dbSNP record]
<ide>
<del>// todo -- deal with performance issues with variant contexts
<del>
<del>//
<ide> // Todo -- should really include argument parsing @annotations from subclass in this walker. Very
<ide> // todo -- useful general capability. Right now you need to add arguments to VariantEval2 to handle new
<ide> // todo -- evaluation arguments (which is better than passing a string!)
<del>//
<del>
<del>//
<del>// todo -- the whole organization only supports a single eval x comp evaluation. We need to instantiate
<del>// todo -- new contexts for each comparison object too! The output table should be clear as to what the "comp"
<del>// todo -- variable is in the analysis
<del>//
<del>
<del>//
<add>
<add>
<ide> // todo -- write or find a simple way to organize the table like output of variant eval 2. A generic table of strings?
<del>//
<del>
<add>
<add>// todo -- these really should be implemented as default select expression
<ide> // todo Extend VariantEval, our general-purpose tool for SNP evaluation, to differentiate Ti/Tv at CpG islands and also
<ide> // todo classify (and count) variants into coding, non-coding, synonomous/non-symonomous, 2/4 fold degenerate sites, etc.
<ide> // todo Assume that the incoming VCF has the annotations (you don't need to do this) but VE2 should split up results by
<ide> // todo these catogies automatically (using the default selects)
<del>//
<add>
<add>// todo -- this is really more a documentation issue. Really would be nice to have a pre-defined argument packet that
<add>// todo -- can be provided to the system
<ide> // todo -- We agreed to report two standard values for variant evaluation from here out. One, we will continue to report
<ide> // todo -- the dbSNP 129 rate. Additionally, we will start to report the % of variants found that have already been seen in
<ide> // todo -- 1000 Genomes. This should be implemented as another standard comp_1kg binding, pointing to only variants
<ide> //
<ide> // todo -- aux. plotting routines for VE2
<ide> //
<add>// todo -- implement as select statment, but it's hard for multi-sample calls.
<ide> // todo -- Provide separate dbsnp rates for het only calls and any call where there is at least one hom-var genotype,
<ide> // todo -- since hets are much more likely to be errors
<del>
<del>// todo -- Add Heng's hom run metrics
<add>//
<add>// todo -- Add Heng's hom run metrics -- single sample haplotype block lengths
<ide>
<ide>
<ide> /** |
|
JavaScript | mit | 2c447bbfe69d7e3330c4a8474d5bdc54156472fb | 0 | martijnboland/moped,martijnboland/moped,martijnboland/moped | angular.module('moped.lastfm', [])
.factory('lastfmservice', function() {
var API_KEY= '077c9fa281240d1c38b24d48bc234940';
var API_SECRET = '';
var fmcache = new LastFMCache();
var lastfm = new LastFM({
apiKey : API_KEY,
apiSecret : API_SECRET,
cache : fmcache
});
return {
getTrackImage: function(track, size, callback) {
var artistName = track.artists[0].name;
var albumName = track.album !== null ? track.album.name : '';
lastfm.album.getInfo({artist: artistName, album: albumName}, {
success: function(data){
var img = _.find(data.album.image, { size: size });
if (img !== undefined) {
callback(null, img['#text']);
}
}, error: function(code, message){
console.log('Error #'+code+': '+message);
callback({ code: code, message: message}, null);
}
});
},
getAlbumImage: function(album, size, callback) {
if (album.artists && album.artists.length > 0) {
lastfm.album.getInfo({artist: album.artists[0].name, album: album.name}, {
success: function(data){
var img = _.find(data.album.image, { size: size });
if (img !== undefined) {
callback(null, img['#text']);
}
}, error: function(code, message){
console.log('Error #'+code+': '+message);
callback({ code: code, message: message}, null);
}
});
}
},
getArtistInfo: function(artistName, callback) {
lastfm.artist.getInfo({artist: artistName}, {
success: function(data){
callback(null, data);
}, error: function(code, message){
console.log('Error #'+code+': '+message);
callback({ code: code, message: message}, null);
}
});
}
};
}); | src/app/services/lastfmservice.js | angular.module('moped.lastfm', [])
.factory('lastfmservice', function() {
var API_KEY= '077c9fa281240d1c38b24d48bc234940';
var API_SECRET = '';
var fmcache = new LastFMCache();
var lastfm = new LastFM({
apiKey : API_KEY,
apiSecret : API_SECRET,
cache : fmcache
});
return {
getTrackImage: function(track, size, callback) {
var artistName = track.artists[0].name;
var albumName = track.album !== null ? track.album.name : '';
lastfm.album.getInfo({artist: artistName, album: albumName}, {
success: function(data){
var img = _.find(data.album.image, { size: size });
if (img !== undefined) {
callback(null, img['#text']);
}
}, error: function(code, message){
console.log('Error #'+code+': '+message);
callback({ code: code, message: message}, null);
}
});
},
getAlbumImage: function(album, size, callback) {
lastfm.album.getInfo({artist: album.artists[0].name, album: album.name}, {
success: function(data){
var img = _.find(data.album.image, { size: size });
if (img !== undefined) {
callback(null, img['#text']);
}
}, error: function(code, message){
console.log('Error #'+code+': '+message);
callback({ code: code, message: message}, null);
}
});
},
getArtistInfo: function(artistName, callback) {
lastfm.artist.getInfo({artist: artistName}, {
success: function(data){
callback(null, data);
}, error: function(code, message){
console.log('Error #'+code+': '+message);
callback({ code: code, message: message}, null);
}
});
}
};
}); | Fixed error for missing artists in album search result. Unable to show album image in search results however because the artist name isn't returned.
| src/app/services/lastfmservice.js | Fixed error for missing artists in album search result. Unable to show album image in search results however because the artist name isn't returned. | <ide><path>rc/app/services/lastfmservice.js
<ide> });
<ide> },
<ide> getAlbumImage: function(album, size, callback) {
<del> lastfm.album.getInfo({artist: album.artists[0].name, album: album.name}, {
<del> success: function(data){
<del> var img = _.find(data.album.image, { size: size });
<del> if (img !== undefined) {
<del> callback(null, img['#text']);
<add> if (album.artists && album.artists.length > 0) {
<add> lastfm.album.getInfo({artist: album.artists[0].name, album: album.name}, {
<add> success: function(data){
<add> var img = _.find(data.album.image, { size: size });
<add> if (img !== undefined) {
<add> callback(null, img['#text']);
<add> }
<add> }, error: function(code, message){
<add> console.log('Error #'+code+': '+message);
<add> callback({ code: code, message: message}, null);
<ide> }
<del> }, error: function(code, message){
<del> console.log('Error #'+code+': '+message);
<del> callback({ code: code, message: message}, null);
<del> }
<del> });
<add> });
<add> }
<ide> },
<ide> getArtistInfo: function(artistName, callback) {
<ide> lastfm.artist.getInfo({artist: artistName}, { |
|
Java | mit | 98e39164c88aa8f11c485af7387035c25e121752 | 0 | DemigodsRPG/Demigods3 | package com.legit2.Demigods.Listeners;
import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import com.legit2.Demigods.DSouls;
import com.legit2.Demigods.DUtil;
import com.legit2.Demigods.Demigods;
public class DEntityListener implements Listener
{
static Demigods plugin;
public DEntityListener(Demigods instance)
{
plugin = instance;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public static void damageEvent(EntityDamageEvent event)
{
// Define variables
LivingEntity attackedEntity;
if(event.getEntityType().equals(EntityType.PLAYER)) // IF IT'S A PLAYER
{
// Cancel soul drop if player kills themselves
if(((LivingEntity) event.getEntity()).getKiller() == null) return;
// Define entity as player and other variables
attackedEntity = (LivingEntity) event.getEntity();
Player attackedPlayer = (Player) attackedEntity;
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) attackedEntity.getLastDamageCause();
Entity attacker = damageEvent.getDamager();
if(attacker instanceof Player)
{
if(!DUtil.canTarget(attackedPlayer, attackedPlayer.getLocation()))
{
event.setCancelled(true);
return;
}
if(damageEvent.getDamage() > attackedPlayer.getHealth())
{
// For player deaths, we first check their opponent for # of souls and determine soul drops from there...
if(DUtil.getNumberOfSouls((attackedPlayer)) == 0) // If they have no souls then we know to drop a new soul on death
{
attackedEntity.getLocation().getWorld().dropItemNaturally(attackedEntity.getLocation(), DSouls.getSoulFromEntity(attackedEntity));
}
else // Else we cancel their death and subtract a soul
{
if(DUtil.getNumberOfSouls(attackedPlayer) > 0)
{
ItemStack usedSoul = DUtil.useSoul(attackedPlayer);
DUtil.serverMsg("TEMP: " + attackedPlayer.getName() + " just lost 1 " + usedSoul.getType().name().toLowerCase() + "!");
DUtil.serverMsg("TEMP: Attempting to cancel death...");
event.setCancelled(true);
}
}
}
}
}
else if(event.getEntityType().equals(EntityType.VILLAGER)) // IF IT'S A VILLAGER
{
// Define villager
LivingEntity villager = (LivingEntity) event.getEntity();
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) villager.getLastDamageCause();
// Define attacker and name
Player attacker = null;
if(damageEvent.getDamager() != null) attacker = (Player) damageEvent.getDamager();
if(damageEvent.getDamager() instanceof Player && damageEvent.getDamage() > villager.getHealth())
{
villager.getLocation().getWorld().dropItemNaturally(villager.getLocation(), DSouls.getSoulFromEntity(villager));
if(attacker != null) attacker.sendMessage(ChatColor.GRAY + "One weaker than you has been slain by your hand.");
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void entityDeath(EntityDeathEvent event)
{
// TODO
}
}
| src/com/legit2/Demigods/Listeners/DEntityListener.java | package com.legit2.Demigods.Listeners;
import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;
import com.legit2.Demigods.DSouls;
import com.legit2.Demigods.DUtil;
import com.legit2.Demigods.Demigods;
public class DEntityListener implements Listener
{
static Demigods plugin;
public DEntityListener(Demigods instance)
{
plugin = instance;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
public static void damageEvent(EntityDamageEvent event)
{
// Define variables
LivingEntity attackedEntity;
if(event.getEntityType().equals(EntityType.PLAYER)) // IF IT'S A PLAYER
{
// Cancel soul drop if player kills themselves
if(((LivingEntity) event.getEntity()).getKiller() == null) return;
// Define entity as player and other variables
attackedEntity = (LivingEntity) event.getEntity();
Player attackedPlayer = (Player) attackedEntity;
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) attackedEntity.getLastDamageCause();
Entity attacker = damageEvent.getDamager();
if(attacker instanceof Player)
{
if(!DUtil.canLocationPVP(attackedPlayer.getLocation()) && !DUtil.canTarget(attackedPlayer, attackedPlayer.getLocation()))
{
event.setCancelled(true);
damageEvent.setCancelled(true);
return;
}
if(damageEvent.getDamage() > attackedPlayer.getHealth())
{
// For player deaths, we first check their opponent for # of souls and determine soul drops from there...
if(DUtil.getNumberOfSouls((attackedPlayer)) == 0) // If they have no souls then we know to drop a new soul on death
{
attackedEntity.getLocation().getWorld().dropItemNaturally(attackedEntity.getLocation(), DSouls.getSoulFromEntity(attackedEntity));
}
else // Else we cancel their death and subtract a soul
{
if(DUtil.getNumberOfSouls(attackedPlayer) > 0)
{
ItemStack usedSoul = DUtil.useSoul(attackedPlayer);
DUtil.serverMsg("TEMP: " + attackedPlayer.getName() + " just lost 1 " + usedSoul.getType().name().toLowerCase() + "!");
DUtil.serverMsg("TEMP: Attempting to cancel death...");
event.setCancelled(true);
}
}
}
}
}
else if(event.getEntityType().equals(EntityType.VILLAGER)) // IF IT'S A VILLAGER
{
// Define villager
LivingEntity villager = (LivingEntity) event.getEntity();
EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) villager.getLastDamageCause();
// Define attacker and name
Player attacker = null;
if(damageEvent.getDamager() != null) attacker = (Player) damageEvent.getDamager();
if(damageEvent.getDamager() instanceof Player && damageEvent.getDamage() > villager.getHealth())
{
villager.getLocation().getWorld().dropItemNaturally(villager.getLocation(), DSouls.getSoulFromEntity(villager));
if(attacker != null) attacker.sendMessage(ChatColor.GRAY + "One weaker than you has been slain by your hand.");
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public static void entityDeath(EntityDeathEvent event)
{
// TODO
}
}
| This should work says the JavaDocs. | src/com/legit2/Demigods/Listeners/DEntityListener.java | This should work says the JavaDocs. | <ide><path>rc/com/legit2/Demigods/Listeners/DEntityListener.java
<ide>
<ide> if(attacker instanceof Player)
<ide> {
<del> if(!DUtil.canLocationPVP(attackedPlayer.getLocation()) && !DUtil.canTarget(attackedPlayer, attackedPlayer.getLocation()))
<add> if(!DUtil.canTarget(attackedPlayer, attackedPlayer.getLocation()))
<ide> {
<ide> event.setCancelled(true);
<del> damageEvent.setCancelled(true);
<ide> return;
<ide> }
<ide> |
|
Java | epl-1.0 | a4a07bdab8457139d902444ca7cdb6a13dce3203 | 0 | subclipse/subclipse,subclipse/subclipse,subclipse/subclipse | /*******************************************************************************
* Copyright (c) 2004, 2006 Subclipse project and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.operations;
import java.util.HashSet;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceRuleFactory;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.MultiRule;
import org.eclipse.team.core.TeamException;
import org.eclipse.ui.IWorkbenchPart;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.BranchTagCommand;
import org.tigris.subversion.subclipse.core.commands.GetRemoteResourceCommand;
import org.tigris.subversion.subclipse.core.commands.SwitchToUrlCommand;
import org.tigris.subversion.subclipse.core.history.Alias;
import org.tigris.subversion.subclipse.core.history.AliasManager;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
public class BranchTagOperation extends RepositoryProviderOperation {
private SVNUrl[] sourceUrls;
private SVNUrl destinationUrl;
private SVNRevision revision;
private boolean createOnServer;
private boolean makeParents;
private String message;
private Alias newAlias;
private boolean switchAfterTagBranch;
private boolean branchCreated = false;
public BranchTagOperation(IWorkbenchPart part, IResource[] resources, SVNUrl[] sourceUrls, SVNUrl destinationUrl, boolean createOnServer, SVNRevision revision, String message) {
super(part, resources);
this.sourceUrls = sourceUrls;
this.destinationUrl = destinationUrl;
this.createOnServer = createOnServer;
this.revision = revision;
this.message = message;
}
protected String getTaskName() {
return Policy.bind("BranchTagOperation.taskName"); //$NON-NLS-1$;
}
protected String getTaskName(SVNTeamProvider provider) {
return Policy.bind("BranchTagOperation.0", provider.getProject().getName()); //$NON-NLS-1$
}
protected void execute(SVNTeamProvider provider, IResource[] resources, IProgressMonitor monitor) throws SVNException, InterruptedException {
if (branchCreated) return;
branchCreated = true;
monitor.beginTask(null, 100);
try {
BranchTagCommand command = new BranchTagCommand(provider.getSVNWorkspaceRoot(),getResources(), sourceUrls, destinationUrl, message, createOnServer, revision);
command.setMakeParents(makeParents);
command.run(Policy.subMonitorFor(monitor,1000));
if (newAlias != null) updateBranchTagProperty(resources[0]);
if(switchAfterTagBranch) {
for (int i = 0; i < sourceUrls.length; i++) {
String lastPathSegment = sourceUrls[i].getLastPathSegment();
SVNUrl switchDestinationUrl = destinationUrl.appendPath(lastPathSegment);
// the copy command's destination URL can either be a path to an existing directory
// or a path to a new directory. In the former case the last path segment of the
// source path is automatically created at the destination
GetRemoteResourceCommand getRemoteResourceCommand = new GetRemoteResourceCommand(provider.getSVNWorkspaceRoot().getRepository(), switchDestinationUrl, SVNRevision.HEAD);
try {
getRemoteResourceCommand.run(null);
} catch(SVNException e) {
if(e.getStatus().getCode() == TeamException.UNABLE) {
switchDestinationUrl = destinationUrl;
} else {
throw e;
}
}
resources = getResources();
SwitchToUrlCommand switchToUrlCommand = new SwitchToUrlCommand(provider.getSVNWorkspaceRoot(), resources[i], switchDestinationUrl, SVNRevision.HEAD);
switchToUrlCommand.run(Policy.subMonitorFor(monitor,100));
}
}
} catch (SVNException e) {
collectStatus(e.getStatus());
} finally {
monitor.done();
}
}
protected ISchedulingRule getSchedulingRule(SVNTeamProvider provider) {
IResource[] resources = getResources();
if (resources == null) return super.getSchedulingRule(provider);
IResourceRuleFactory ruleFactory = provider.getRuleFactory();
HashSet rules = new HashSet();
for (int i = 0; i < resources.length; i++) {
rules.add(ruleFactory.modifyRule(resources[i].getProject()));
}
return MultiRule.combine((ISchedulingRule[]) rules.toArray(new ISchedulingRule[rules.size()]));
}
private void updateBranchTagProperty(IResource resource) {
AliasManager aliasManager = new AliasManager(resource, false);
Alias[] branchAliases = aliasManager.getBranches();
Alias[] tagAliases = aliasManager.getTags();
StringBuffer propertyValue = new StringBuffer();
for (int i = 0; i < branchAliases.length; i++) {
if (branchAliases[i].getRevision() > 0) {
if (propertyValue.length() > 0) propertyValue.append("\n"); //$NON-NLS-1$
Alias branch = branchAliases[i];
propertyValue.append(branch.getRevision() + "," + branch.getName()); //$NON-NLS-1$
if (branch.getRelativePath() != null) propertyValue.append("," + branch.getRelativePath()); //$NON-NLS-1$
if (branch.isBranch()) propertyValue.append(",branch"); //$NON-NLS-1$
else propertyValue.append(",tag"); //$NON-NLS-1$
}
}
for (int i = 0; i < tagAliases.length; i++) {
if (tagAliases[i].getRevision() > 0) {
if (propertyValue.length() > 0) propertyValue.append("\n"); //$NON-NLS-1$
Alias tag = tagAliases[i];
propertyValue.append(tag.getRevision() + "," + tag.getName()); //$NON-NLS-1$
if (tag.getRelativePath() != null) propertyValue.append("," + tag.getRelativePath()); //$NON-NLS-1$
if (tag.isBranch()) propertyValue.append(",branch"); //$NON-NLS-1$
else propertyValue.append(",tag"); //$NON-NLS-1$
}
}
if (propertyValue.length() > 0) propertyValue.append("\n"); //$NON-NLS-1$
propertyValue.append(newAlias.getRevision() + "," + newAlias.getName() + "," + newAlias.getRelativePath());
if (newAlias.isBranch()) propertyValue.append(",branch"); //$NON-NLS-1$
else propertyValue.append(",tag"); //$NON-NLS-1$
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
svnResource.setSvnProperty("subclipse:tags", propertyValue.toString(), false); //$NON-NLS-1$
} catch (SVNException e) {}
}
public void setNewAlias(Alias newAlias) {
this.newAlias = newAlias;
}
public void switchAfterTagBranchOperation(boolean switchAfterTagBranchOperation) {
this.switchAfterTagBranch = switchAfterTagBranchOperation;
}
public void setMakeParents(boolean makeParents) {
this.makeParents = makeParents;
}
}
| org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/operations/BranchTagOperation.java | /*******************************************************************************
* Copyright (c) 2004, 2006 Subclipse project and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.operations;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.TeamException;
import org.eclipse.ui.IWorkbenchPart;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.BranchTagCommand;
import org.tigris.subversion.subclipse.core.commands.GetRemoteResourceCommand;
import org.tigris.subversion.subclipse.core.commands.SwitchToUrlCommand;
import org.tigris.subversion.subclipse.core.history.Alias;
import org.tigris.subversion.subclipse.core.history.AliasManager;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
public class BranchTagOperation extends RepositoryProviderOperation {
private SVNUrl[] sourceUrls;
private SVNUrl destinationUrl;
private SVNRevision revision;
private boolean createOnServer;
private boolean makeParents;
private String message;
private Alias newAlias;
private boolean switchAfterTagBranch;
private boolean branchCreated = false;
public BranchTagOperation(IWorkbenchPart part, IResource[] resources, SVNUrl[] sourceUrls, SVNUrl destinationUrl, boolean createOnServer, SVNRevision revision, String message) {
super(part, resources);
this.sourceUrls = sourceUrls;
this.destinationUrl = destinationUrl;
this.createOnServer = createOnServer;
this.revision = revision;
this.message = message;
}
protected String getTaskName() {
return Policy.bind("BranchTagOperation.taskName"); //$NON-NLS-1$;
}
protected String getTaskName(SVNTeamProvider provider) {
return Policy.bind("BranchTagOperation.0", provider.getProject().getName()); //$NON-NLS-1$
}
protected void execute(SVNTeamProvider provider, IResource[] resources, IProgressMonitor monitor) throws SVNException, InterruptedException {
if (branchCreated) return;
branchCreated = true;
monitor.beginTask(null, 100);
try {
BranchTagCommand command = new BranchTagCommand(provider.getSVNWorkspaceRoot(),getResources(), sourceUrls, destinationUrl, message, createOnServer, revision);
command.setMakeParents(makeParents);
command.run(Policy.subMonitorFor(monitor,1000));
if (newAlias != null) updateBranchTagProperty(resources[0]);
if(switchAfterTagBranch) {
for (int i = 0; i < sourceUrls.length; i++) {
String lastPathSegment = sourceUrls[i].getLastPathSegment();
SVNUrl switchDestinationUrl = destinationUrl.appendPath(lastPathSegment);
// the copy command's destination URL can either be a path to an existing directory
// or a path to a new directory. In the former case the last path segment of the
// source path is automatically created at the destination
GetRemoteResourceCommand getRemoteResourceCommand = new GetRemoteResourceCommand(provider.getSVNWorkspaceRoot().getRepository(), switchDestinationUrl, SVNRevision.HEAD);
try {
getRemoteResourceCommand.run(null);
} catch(SVNException e) {
if(e.getStatus().getCode() == TeamException.UNABLE) {
switchDestinationUrl = destinationUrl;
} else {
throw e;
}
}
resources = getResources();
SwitchToUrlCommand switchToUrlCommand = new SwitchToUrlCommand(provider.getSVNWorkspaceRoot(), resources[i], switchDestinationUrl, SVNRevision.HEAD);
switchToUrlCommand.run(Policy.subMonitorFor(monitor,100));
}
}
} catch (SVNException e) {
collectStatus(e.getStatus());
} finally {
monitor.done();
}
}
private void updateBranchTagProperty(IResource resource) {
AliasManager aliasManager = new AliasManager(resource, false);
Alias[] branchAliases = aliasManager.getBranches();
Alias[] tagAliases = aliasManager.getTags();
StringBuffer propertyValue = new StringBuffer();
for (int i = 0; i < branchAliases.length; i++) {
if (branchAliases[i].getRevision() > 0) {
if (propertyValue.length() > 0) propertyValue.append("\n"); //$NON-NLS-1$
Alias branch = branchAliases[i];
propertyValue.append(branch.getRevision() + "," + branch.getName()); //$NON-NLS-1$
if (branch.getRelativePath() != null) propertyValue.append("," + branch.getRelativePath()); //$NON-NLS-1$
if (branch.isBranch()) propertyValue.append(",branch"); //$NON-NLS-1$
else propertyValue.append(",tag"); //$NON-NLS-1$
}
}
for (int i = 0; i < tagAliases.length; i++) {
if (tagAliases[i].getRevision() > 0) {
if (propertyValue.length() > 0) propertyValue.append("\n"); //$NON-NLS-1$
Alias tag = tagAliases[i];
propertyValue.append(tag.getRevision() + "," + tag.getName()); //$NON-NLS-1$
if (tag.getRelativePath() != null) propertyValue.append("," + tag.getRelativePath()); //$NON-NLS-1$
if (tag.isBranch()) propertyValue.append(",branch"); //$NON-NLS-1$
else propertyValue.append(",tag"); //$NON-NLS-1$
}
}
if (propertyValue.length() > 0) propertyValue.append("\n"); //$NON-NLS-1$
propertyValue.append(newAlias.getRevision() + "," + newAlias.getName() + "," + newAlias.getRelativePath());
if (newAlias.isBranch()) propertyValue.append(",branch"); //$NON-NLS-1$
else propertyValue.append(",tag"); //$NON-NLS-1$
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
svnResource.setSvnProperty("subclipse:tags", propertyValue.toString(), false); //$NON-NLS-1$
} catch (SVNException e) {}
}
public void setNewAlias(Alias newAlias) {
this.newAlias = newAlias;
}
public void switchAfterTagBranchOperation(boolean switchAfterTagBranchOperation) {
this.switchAfterTagBranch = switchAfterTagBranchOperation;
}
public void setMakeParents(boolean makeParents) {
this.makeParents = makeParents;
}
}
| Fix scheduling rule exception when switching multiple projects to newly created
branch.
Issue #: 818
| org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/operations/BranchTagOperation.java | Fix scheduling rule exception when switching multiple projects to newly created branch. Issue #: 818 | <ide><path>rg.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/operations/BranchTagOperation.java
<ide> ******************************************************************************/
<ide> package org.tigris.subversion.subclipse.ui.operations;
<ide>
<add>import java.util.HashSet;
<add>
<ide> import org.eclipse.core.resources.IResource;
<add>import org.eclipse.core.resources.IResourceRuleFactory;
<ide> import org.eclipse.core.runtime.IProgressMonitor;
<add>import org.eclipse.core.runtime.jobs.ISchedulingRule;
<add>import org.eclipse.core.runtime.jobs.MultiRule;
<ide> import org.eclipse.team.core.TeamException;
<ide> import org.eclipse.ui.IWorkbenchPart;
<ide> import org.tigris.subversion.subclipse.core.ISVNLocalResource;
<ide> }
<ide>
<ide> protected void execute(SVNTeamProvider provider, IResource[] resources, IProgressMonitor monitor) throws SVNException, InterruptedException {
<del> if (branchCreated) return;
<add> if (branchCreated) return;
<ide> branchCreated = true;
<ide> monitor.beginTask(null, 100);
<ide> try {
<ide> monitor.done();
<ide> }
<ide> }
<add>
<add> protected ISchedulingRule getSchedulingRule(SVNTeamProvider provider) {
<add> IResource[] resources = getResources();
<add> if (resources == null) return super.getSchedulingRule(provider);
<add> IResourceRuleFactory ruleFactory = provider.getRuleFactory();
<add> HashSet rules = new HashSet();
<add> for (int i = 0; i < resources.length; i++) {
<add> rules.add(ruleFactory.modifyRule(resources[i].getProject()));
<add> }
<add> return MultiRule.combine((ISchedulingRule[]) rules.toArray(new ISchedulingRule[rules.size()]));
<add> }
<ide>
<ide> private void updateBranchTagProperty(IResource resource) {
<ide> AliasManager aliasManager = new AliasManager(resource, false); |
|
JavaScript | mit | 22473309b51a31cb979889a63dd4d70f9d8f164a | 0 | davidmcclelland/notifications-of-avabur | // ==UserScript==
// @name Notifications of Avabur
// @namespace https://github.com/davidmcclelland/
// @author Dave McClelland <[email protected]>
// @homepage https://github.com/davidmcclelland/notifications-of-avabur
// @supportURL https://github.com/davidmcclelland/notifications-of-avabur/issues
// @downloadURL https://github.com/davidmcclelland/notifications-of-avabur/raw/master/notifications-of-avabur.user.js
// @description Never miss another gauntlet again!
// @match https://*.avabur.com/game*
// @version 1.12.0-beta2
// @icon https://rawgit.com/davidmcclelland/notifications-of-avabur/master/res/img/logo-32.png
// @run-at document-end
// @connect githubusercontent.com
// @connect github.com
// @connect self
// @grant GM_addStyle
// @require https://rawgit.com/davidmcclelland/notifications-of-avabur/master/lib/toastmessage/javascript/jquery.toastmessage.js
// @require https://cdnjs.cloudflare.com/ajax/libs/buzz/1.2.0/buzz.min.js
// @require https://raw.githubusercontent.com/lodash/lodash/4.17.4/dist/lodash.min.js
// @require https://cdn.jsdelivr.net/npm/vue
// @license LGPL-2.1
// @noframes
// ==/UserScript==
//Check if the user can even support the bot
if (typeof (MutationObserver) === "undefined") {
console.log("Cannot support mutation observer!");
} else {
(function ($, MutationObserver, buzz) {
'use strict';
/**
* Creates a GitHub CDN URL
* @param {String} path Path to the file without leading slashes
* @param {String} [author] The author. Defaults to davidmcclelland
* @param {String} [repo] The repository. Defaults to notifications-of-avabur
* @returns {String} The URL
*/
const gh_url = function (path, author, repo) {
author = author || "davidmcclelland";
repo = repo || "notifications-of-avabur";
// return "https://cdn.rawgit.com/" + author + "/" + repo + "/" +
// GM_info.script.version + "/" + path;
return "https://rawgit.com/" + author + "/" + repo + "/" +
'master' + "/" + path;
};
const URLS = {
sfx: {
message_ding: gh_url('res/sfx/message_ding.wav')
},
img: {
icon: gh_url('res/img/logo-32.png'),
chatSearch: gh_url('res/img/noa-chat.png'),
construction: gh_url('res/img/noa-construction.png'),
craftingSearch: gh_url('res/img/noa-crafting.png'),
lootSearch: gh_url('res/img/noa-drop.png'),
event: gh_url('res/img/noa-event.png'),
fatigued: gh_url('res/img/noa-fatigued.png'),
harvestron: gh_url('res/img/noa-harvestron.png'),
quest: gh_url('res/img/noa-quest.png'),
weakened: gh_url('res/img/noa-weakened.png'),
whisper: gh_url('res/img/noa-whisper.png')
}
};
const clickToAChannelTab = function (node) {
if (typeof node.getToAChannelInfo === 'function') {
let { channelID } = node.getToAChannelInfo();
if (false !== channelID) {
$(`#channelTab${channelID}`).click();
}
}
};
/////////////////////////////////////////////////////
// This is the script code. Don't change it unless //
// you know what you're doing ;) //
/////////////////////////////////////////////////////
const DEFAULT_USER_SETTINGS = {
recurToDiscord: false,
muteWhileAfk: true,
recurringNotificationsTimeout: 20,
soundVolume: 80,
lowStaminaThreshold: 5,
popupDurationSec: 5,
fatigue: { popup: true, sound: true, log: false, clanDiscord: false, personalDiscord: false, recur: true },
eventFiveMinuteCountdown: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventTimeRemaining: [{popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, timeMinutes: 7.5}],
harvestron: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
construction: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
whisper: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
questComplete: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
chatSearch: [],
craftingSearch: [],
lootSearch: [],
clanDiscord: { webhook: '', target: '' },
personalDiscord: { webhook: '', target: '' }
};
const SETTINGS_KEY = 'NoASettings';
const NOA_STYLES = `
.row.text-center > div {
display: inline-block;
float: none;
}
#NoASettings input {
margin-right: 10px;
}
#NoASettings textarea {
width: 50%;
height: 80px;
}
#NoASettings hr {
margin-top: 10px;
margin-bottom: 10px;
}
#notificationLogItems {
margin-top: 10px;
}
`;
const SETTINGS_DIALOG_HTML = `
<div id="NoASettings" style="display: none; margin: 10px;">
<div id="NoASettingsButtonWrapper" class="center">
<a id="NoANotificationSettingsButton">
<button class="btn btn-primary">Notifications</button>
</a>
<a id="NoAAdvancedSettingsButton">
<button class="btn btn-primary">Advanced</button>
</a>
<a id="NoALogButton">
<button class="btn btn-primary">Log</button>
</a>
</div>
<div id="NoASettingsContentWrapper">
<div id="NoANotificationSettingsWrapper">
<div>
<h4 class="nobg">General</h4>
<div class="row">
<div class="col-xs-3">
<label>
<input id="recurToDiscordEditor" type="checkbox" v-model="userSettings.recurToDiscord"> Recur to Discord
</label>
</div>
<div class="col-xs-3">
<label>Recurrence Time (sec)</label>
<input id="recurringNotificationsTimeoutEditor" type="number" min="1" max="100" v-model="userSettings.recurringNotificationsTimeout">
</div>
<div class="col-xs-3">
<label>Sound Volume</label>
<input id="soundVolumeEditor" type="number" min="1" max="100" v-model="userSettings.soundVolume">
</div>
<div class="col-xs-3">
<label>Low Stamina Threshold</label>
<input id="lowStaminaThresholdEditor" type="number" min="0" max="9999" v-model="userSettings.lowStaminaThreshold">
</div>
<div class="col-xs-3">
<label>
<input id="muteWhileAfkEditor" type="checkbox" v-model="userSettings.muteWhileAfk">Mute While AFK</label>
</div>
<div class="col-xs-3">
<label>Popup Duration (sec)
<input id="popupDurationEditor" type="number" min="1" max="60" v-model="userSettings.popupDurationSec">
</div>
</div>
</div>
<hr>
<div>
<h4 class="nobg">Clan Discord</h4>
<div class="row">
<label class="col-xs-3">
<a href="https://discordapp.com/developers/docs/resources/webhook#execute-webhook" target="_blank">Webhook</a>
</label>
<div class="col-xs-9">
<input id="clanDiscordWebhookEditor" type="text" style="width: 80%;" v-model="userSettings.clanDiscord.webhook">
</div>
</div>
<div class="row">
<label class="col-xs-3">User/Group</label>
<div class="col-xs-9">
<input id="clanDiscordTargetEditor" type="text" style="width: 80%;" v-model="userSettings.clanDiscord.target">
</div>
</div>
</div>
<hr>
<div>
<h4 class="nobg">Personal Discord</h4>
<div class="row">
<label class="col-xs-3">
<a href="https://discordapp.com/developers/docs/resources/webhook#execute-webhook" target="_blank">Webhook</a>
</label>
<div class="col-xs-9">
<input id="personalDiscordWebhookEditor" type="text" style="width: 80%;" v-model="userSettings.personalDiscord.webhook">
</div>
</div>
<div class="row">
<label class="col-xs-3">User/Group</label>
<div class="col-xs-9">
<input id="personalDiscordTargetEditor" type="text" style="width: 80%;" v-model="userSettings.personalDiscord.target">
</div>
</div>
</div>
<hr>
<table id="NoASettingsTable" class="table table-condensed">
<thead>
<tr>
<td></td>
<th scope="col">Popup</th>
<th scope="col">Sound</th>
<th scope="col">Log</th>
<th scope="col">Clan</th>
<th scope="col">Personal</th>
<th scope="col">Recur</th>
<th scope="col">Sound File URL</th>
<th scope="col">Test Notifications</th>
</tr>
</thead>
<tbody>
<tr is="settings-entry" name="Fatigue" :setting="userSettings.fatigue"></tr>
<tr is="settings-entry" name="Harvestron" :setting="userSettings.harvestron"></tr>
<tr is="settings-entry" name="Construction" :setting="userSettings.construction"></tr>
<tr is="settings-entry" name="Quest Complete" :setting="userSettings.questComplete"></tr>
<tr is="settings-entry" name="Whisper" :setting="userSettings.whisper"></tr>
<tr is="settings-entry" name="Event 5 Minute Countdown" :setting="userSettings.eventFiveMinuteCountdown"></tr>
</tbody>
</table>
</div>
<div id="NoAAdvancedSettingsWrapper">
<table class="table table-condensed">
<thead>
<tr>
<td></td>
<th scope="col">Popup</th>
<th scope="col">Sound</th>
<th scope="col">Log</th>
<th scope="col">Clan</th>
<th scope="col">Personal</th>
<th scope="col">Recur</th>
<th scope="col">Sound File URL</th>
<th scope="col">Test Notifications</th>
<th scope="col">Remove</th>
</tr>
</thead>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Chat Search (<a href="https://github.com/davidmcclelland/notifications-of-avabur/wiki/Chat-search" target="_blank">Help</a>)</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addChatSearch()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(chatSearch, index) in userSettings.chatSearch" is="settings-entry" :setting="chatSearch" type="regex" :collection="userSettings.chatSearch" :index="index"></tr>
</tbody>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Crafting Search (<a href="https://github.com/davidmcclelland/notifications-of-avabur/wiki/Loot-search" target="_blank">Help</a>)</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addCraftingSearch()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(craftingSearch, index) in userSettings.craftingSearch" is="settings-entry" :setting="craftingSearch" type="regex" :collection="userSettings.craftingSearch" :index="index"></tr>
</tbody>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Loot Search (<a href="https://github.com/davidmcclelland/notifications-of-avabur/wiki/Crafting-search" target="_blank">Help</a>)</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addLootSearch()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(lootSearch, index) in userSettings.lootSearch" is="settings-entry" :setting="lootSearch" type="regex" :collection="userSettings.lootSearch" :index="index"></tr>
</tbody>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Event Time Remaining</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addEventTime()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(eventTime, index) in userSettings.eventTimeRemaining" is="settings-entry" :setting="eventTime" type="eventTime" :collection="userSettings.eventTimeRemaining" :index="index"></tr>
</tbody>
</table>
</div>
<div id="NoANotificationLog">
<button class="btn btn-primary" id="notificationLogRefresh">Refresh</button>
<ul id="notificationLogItems"></ul>
</div>
</div>
<div class="row" style="display: none;" id="NoaSettingsSavedLabel">
<strong class="col-xs-12">
Settings have been saved
</strong>
</div>
</div>
`;
const INTERNAL_UPDATE_URL = "https://api.github.com/repos/davidmcclelland/notifications-of-avabur/contents/notifications-of-avabur.user.js";
var userSettings = null;
var isEventCountdownActive = false;
var counters = {
lastConstructionNotification: 0,
lastFatigueNotification: 0,
lastHarvestronNotification: 0,
lastQuestNotification: 0,
};
var notificationLogEntries = [];
var checkForUpdateTimer = 0;
// Obviously no sound is playing, but we need to block audio until the dom is loaded
var isSoundPlaying = true;
// I suspect that this may help fix some issues with Chrome's new auto-playing audio changes
window.addEventListener('load', function () {
isSoundPlaying = false;
});
if (!String.format) {
String.format = function (format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
}
/** Misc function container */
const fn = {
versionCompare: function (v1, v2) {
var regex = new RegExp("(\.0+)+");
v1 = v1.replace(regex, "").split(".");
v2 = v2.replace(regex, "").split(".");
var min = Math.min(v1.length, v2.length);
var diff = 0;
for (var i = 0; i < min; i++) {
diff = parseInt(v1[i], 10) - parseInt(v2[i], 10);
if (diff !== 0) {
return diff;
}
}
return v1.length - v2.length;
},
checkForUpdate: function () {
var version = "";
$.get(INTERNAL_UPDATE_URL).done(function (res) {
var match = atob(res.content).match(/\/\/\s+@version\s+([^\n]+)/);
version = match[1];
if (fn.versionCompare(GM_info.script.version, version) < 0) {
var message = "<li class=\"chat_notification\">Notifications Of Avabur has been updated to version " + version + "! <a href=\"https://github.com/davidmcclelland/notifications-of-avabur/raw/master/notifications-of-avabur.user.js\" target=\"_blank\">Update</a> | <a href=\"https://github.com/davidmcclelland/notifications-of-avabur/commits/master\" target=\"_blank\">Changelog</a></li>";
// TODO: Handle chat direction like ToA does
$("#chatMessageList").prepend(message);
} else {
checkForUpdateTimer = setTimeout(fn.checkForUpdate, 24 * 60 * 60 * 1000);
}
});
},
sendDiscordMessage: function (webhook, target, text) {
if (webhook && target && text) {
let messageContent = text;
if (target && target.length) {
messageContent = target + ' ' + text;
}
if (webhook.includes("discordapp")) {
$.post(webhook, { content: messageContent });
} else {
$.ajax({
data: 'payload=' + JSON.stringify({
"text": messageContent
}),
dataType: 'json',
processData: false,
type: 'POST',
url: webhook
});
}
}
},
/**
* Creates a floaty notification and plays a sound, based on preferences
* @param {String} text Text to display
* @param {String} iconUrl Icon to display in the popup
* @param {object} settings Settings for this type of notification
* @param {number} recurrenceCounter The number of seconds this event has recurred for. Optional, defaults to zero
* @param {Function} [onPopupClick] An optional function to be called back when/if a popup is clicked
*/
notification: function (text, iconUrl, settings, recurrenceCounter, onPopupClick, onPopupClickArgs = []) {
recurrenceCounter = _.defaultTo(recurrenceCounter, 0);
const isFirstRecurrence = (recurrenceCounter === 0);
const recurrenceEnabled = _.defaultTo(settings.recur, false);
const discordRecurrenceEnabled = _.defaultTo(userSettings.recurToDiscord, false);
// It's a good recurrence if it is the first one, or if recurring notifications are on
// and it's been long enough since the previous
const isGoodRecurrence = isFirstRecurrence ||
(recurrenceEnabled && (recurrenceCounter % userSettings.recurringNotificationsTimeout === 0));
// While muted, only log. No sounds, popups, or discord
const isMuted = fn.checkIsMuted();
// Only ever send to discord and log the first instance of a recurrence,j
// even if it's a good recurrence
// Only ever log on the first recurrence.
const doLog = settings.log && isFirstRecurrence;
// Only send to discord if discord is enabled and (it's the first recurrence or (it's a good recurrence and recur to discord is enabled))
const doClanDiscord = !isMuted && settings.clanDiscord && (isFirstRecurrence || (isGoodRecurrence && discordRecurrenceEnabled));
const doPersonalDiscord = !isMuted && settings.personalDiscord && (isFirstRecurrence || (isGoodRecurrence && discordRecurrenceEnabled));
// Recur popup and sound notifications
const doPopup = !isMuted && settings.popup && isGoodRecurrence;
const doSound = !isMuted && settings.sound && isGoodRecurrence;
if (doLog) {
notificationLogEntries.push({
timestamp: new Date(),
text: text
});
}
if (notificationLogEntries.length > 100) {
notificationLogEntries.shift();
}
if (doPopup) {
Notification.requestPermission().then(function () {
var n = new Notification(GM_info.script.name, {
icon: iconUrl,
body: text
});
const popupDurationSec = _.defaultTo(userSettings.popupDurationSec, 5);
setTimeout(n.close.bind(n), popupDurationSec * 1000);
n.addEventListener('click', function (e) {
window.focus();
e.target.close();
if (typeof onPopupClick === 'function') {
if (!Array.isArray(onPopupClickArgs)) {
onPopupClickArgs = [onPopupClickArgs];
}
onPopupClick.apply(null, onPopupClickArgs);
}
}, false);
});
}
if (doSound) {
var soundFileUrl = settings.soundFile;
if (!soundFileUrl || !soundFileUrl.length) {
soundFileUrl = URLS.sfx.message_ding;
}
if (!isSoundPlaying) {
const buzzFile = new buzz.sound(soundFileUrl, { volume: userSettings.soundVolume });
buzzFile.bind('ended', function () {
isSoundPlaying = false;
});
buzzFile.bind('error', function () {
console.log('[NoA] Error playing audio file: ', this.getErrorMessage());
isSoundPlaying = false;
});
buzzFile.play();
isSoundPlaying = true;
}
}
if (doClanDiscord) {
fn.sendDiscordMessage(userSettings.clanDiscord.webhook, userSettings.clanDiscord.target, text);
}
if (doPersonalDiscord) {
fn.sendDiscordMessage(userSettings.personalDiscord.webhook, userSettings.personalDiscord.target, text);
}
},
displaySettingsSavedLabel: function () {
const label = document.getElementById('NoaSettingsSavedLabel');
if (label && label.style) {
label.style.display = 'block';
}
},
debouncedHideSettingsSavedLabel: _.debounce(function () {
const label = document.getElementById('NoaSettingsSavedLabel');
if (label && label.style) {
label.style.display = 'none';
}
}, 3000),
getUpgradedRegexSetting: function (oldSetting) {
const retVal = [];
_.forEach(oldSetting.searchText.split(/\r?\n/), function (singleSearch) {
const newSetting = _.clone(oldSetting);
newSetting.searchText = singleSearch;
retVal.push(newSetting);
});
return retVal;
},
loadUserSettings: function () {
var loadedSettings = JSON.parse(localStorage.getItem(SETTINGS_KEY));
userSettings = _.defaultsDeep(loadedSettings, DEFAULT_USER_SETTINGS);
// Previously, regex searches were stored as a string and then split at text-search time.
if (!_.isArray(userSettings.chatSearch)) {
userSettings.chatSearch = fn.getUpgradedRegexSetting(userSettings.chatSearch);
}
if (!_.isArray(userSettings.craftingSearch)) {
userSettings.craftingSearch = fn.getUpgradedRegexSetting(userSettings.craftingSearch);
}
if (!_.isArray(userSettings.lootSearch)) {
userSettings.lootSearch = fn.getUpgradedRegexSetting(userSettings.lootSearch);
}
// Save settings to store any defaulted settings
fn.storeUserSettings();
},
storeUserSettings: function () {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(userSettings));
fn.displaySettingsSavedLabel();
fn.debouncedHideSettingsSavedLabel();
},
checkIsAfk: function () {
const element = document.getElementById('iAmAFK');
return element && (element.style.display !== 'none');
},
checkIsMuted: function () {
return userSettings.muteWhileAfk && fn.checkIsAfk();
},
checkConstructionVisible: function () {
var div = document.getElementById('constructionNotifier');
if (div && (div.style.display !== 'none')) {
const constructionCallback = function () {
$('#constructionNotifier').click();
};
fn.notification('Construction available!', URLS.img.construction, userSettings.construction, counters.lastConstructionNotification, constructionCallback);
counters.lastConstructionNotification++;
} else {
counters.lastConstructionNotification = 0;
}
},
checkFatigue: function () {
const searchSpan = document.getElementById('autosRemaining');
const staminaRemainingText = searchSpan.innerText || searchSpan.textContent;
const staminaRemainingNumber = parseInt(staminaRemainingText, 10);
if (staminaRemainingNumber <= 0) {
fn.notification('You are fatigued!', URLS.img.fatigued, userSettings.fatigue, counters.lastFatigueNotification);
counters.lastFatigueNotification++;
} else {
counters.lastFatigueNotification = 0;
}
},
checkHarvestronVisible: function () {
var div = document.getElementById('harvestronNotifier');
if (div && (div.style.display !== 'none')) {
const harvestronCallback = function () {
$('#harvestronNotifier').click();
};
fn.notification('Harvestron available!', URLS.img.harvestron, userSettings.harvestron, counters.lastHarvestronNotification, harvestronCallback);
counters.lastHarvestronNotification++;
} else {
counters.lastHarvestronNotification = 0;
}
},
checkQuestComplete: function () {
var visibleQuestDivId;
const possibleQuestDivIds = ['bq_info', 'tq_info', 'pq_info'];
for (var i = 0; i < possibleQuestDivIds.length; i++) {
var questDiv = document.getElementById(possibleQuestDivIds[i]);
if (questDiv) {
var parentDiv = questDiv.parentElement;
if (parentDiv && (parentDiv.style.display !== 'none')) {
visibleQuestDivId = possibleQuestDivIds[i];
break;
}
}
}
if (!visibleQuestDivId) {
return;
}
const visibleQuestDiv = $('#' + visibleQuestDivId);
if (visibleQuestDivId && (visibleQuestDiv.text().startsWith('You have completed your quest!'))) {
const questCallback = function () {
// Find the first <a> sibling of the vibile questDiv and click it
visibleQuestDiv.siblings('a').first().click();
};
const notificationText = visibleQuestDiv.siblings('a').first().text().trim() + ' complete!';
fn.notification(notificationText, URLS.img.quest, userSettings.questComplete, counters.lastQuestNotification, questCallback);
counters.lastQuestNotification++;
} else {
counters.lastQuestNotification = 0;
}
},
checkRecordsVisible: function (records) {
for (var i = 0; i < records.length; i++) {
const target = $(records[i].target);
var style = window.getComputedStyle(target[0]);
if (style.display !== 'none') {
return true;
}
}
return false;
},
findSearchValues: function (text, searchValues) {
// Look for any values in the array
for (var k = 0; k < searchValues.length; k++) {
if (searchValues[k].searchText.length && text.match(new RegExp(searchValues[k].searchText, 'i'))) {
return searchValues[k];
}
}
},
isToAProcessed: function (node) {
return $(node).hasClass('processed');
},
findSearchValuesInRecords: function (records, searchValues) {
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
const text = $(addedNodes[j]).text();
const foundSearchValue = fn.findSearchValues(text, searchValues);
if (!fn.isToAProcessed(addedNodes[j]) && foundSearchValue) {
return {
node: addedNodes[j],
searchValue: foundSearchValue,
}
}
}
}
}
return null;
},
checkEventParticipation: function () {
return document.querySelector('#bossWrapper').style.display !== 'none';
},
setupEventNotifications: function (countdownBadgeText) {
if (!isEventCountdownActive) {
if (countdownBadgeText === '!' || countdownBadgeText.startsWith('*')) {
return;
}
isEventCountdownActive = true;
// First thing's first, figure out how long until the event (in seconds)
/* We handle this a bit odd - if the countdown string doesn't list 'm', then it is displaying
only seconds. This could be slightly more elegantly solved with indexof, but I already wrote it this way and it works. */
var minutesString = '0';
var secondsString = '0';
if (countdownBadgeText.includes('m')) {
minutesString = countdownBadgeText.slice(0, 2);
secondsString = countdownBadgeText.slice(3, 5);
} else {
secondsString = countdownBadgeText.slice(0, 2);
}
var secondsUntilEventStart = (parseInt(minutesString, 10) * 60) + parseInt(secondsString, 10);
var secondsUntilEventEnd = secondsUntilEventStart + (60*15);
// This callback is only passed in for the five minute countdown. It would get really annoying otherwise.
const eventCallback = function () {
$('#event_start').click();
};
fn.notification('An event is starting in five minutes!', URLS.img.event, userSettings.eventFiveMinuteCountdown, null, eventCallback);
userSettings.eventTimeRemaining.forEach(function(timeSetting) {
var notificationSeconds = timeSetting.timeMinutes * 60; // This is seconds from the end of the event
setTimeout(function() {
fn.notification(timeSetting.timeMinutes + ' minute(s) left in the event!', URLS.img.event, timeSetting);
}, (secondsUntilEventEnd - notificationSeconds) * 1000);
});
}
},
};
/** Collection of mutation observers the script uses */
const OBSERVERS = {
chat_search: new MutationObserver(
/** @param {MutationRecord[]} records */
function (records) {
var searchResults = fn.findSearchValuesInRecords(records, userSettings.chatSearch);
if (searchResults && searchResults.node) {
fn.notification(searchResults.node.textContent, URLS.img.chatSearch, searchResults.searchValue, null, clickToAChannelTab, searchResults.node);
return;
}
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
const text = $(addedNodes[j]).text();
if (!fn.isToAProcessed(addedNodes[j]) && text.match(/^\[[0-9]+:[0-9]+:[0-9]+]\s*Whisper from/)) {
fn.notification(text, URLS.img.whisper, userSettings.whisper, null, clickToAChannelTab, addedNodes[j]);
return;
}
}
}
}
}
),
loot_search: new MutationObserver(
/** @param {MutationRecord[]} records */
function (records) {
var searchResults = fn.findSearchValuesInRecords(records, userSettings.lootSearch);
if (searchResults && searchResults.node) {
fn.notification(searchResults.node.textContent, URLS.img.lootSearch, searchResults.searchValue);
return;
}
}
),
crafting_search: new MutationObserver(
/** @param {MutationRecord[]} records */
function (records) {
var searchResults = fn.findSearchValuesInRecords(records, userSettings.craftingSearch);
// Weird special case, because the crafting progress bar is full of different divs, but it's very useful to search
if (!searchResults) {
const craftingXpCountText = $('#craftingXPCount').text();
searchResults = fn.findSearchValues(craftingXpCountText, userSettings.craftingSearch);
}
if (searchResults) {
fn.notification(searchResults.node.textContent, URLS.img.craftingSearch, searchResults.searchValue);
}
}
),
lowStamina: new MutationObserver(
function (records) {
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
const text = $(addedNodes[j]).text();
if (text === userSettings.lowStaminaThreshold.toString()) {
fn.notification('Your stamina is low!', URLS.img.fatigued, userSettings.fatigue);
}
}
}
}
}
),
event: new MutationObserver(
function (records) {
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
if (!isEventCountdownActive) {
const text = $(addedNodes[j]).text();
fn.setupEventNotifications(text);
}
}
}
}
}
),
bossFailure: new MutationObserver(
function (records) {
if (fn.checkRecordsVisible(records)) {
fn.notification('You are fighting while weakened!', URLS.img.weakened, userSettings.eventElimination);
}
}
),
};
(function () {
const ON_LOAD = {
"Initializing settings": function () {
GM_addStyle(NOA_STYLES);
fn.loadUserSettings();
},
"Starting script update monitor": function () {
checkForUpdateTimer = setTimeout(fn.checkForUpdate, 10000);
},
"Starting chat monitor": function () {
OBSERVERS.chat_search.observe(document.querySelector("#chatMessageList"), {
childList: true
});
},
"Starting loot monitor": function() {
OBSERVERS.loot_search.observe(document.querySelector("#latestLoot"), {
childList: true
});
},
"Starting crafting monitor": function() {
OBSERVERS.crafting_search.observe(document.querySelector('#craftingGainWrapper'), {
childList: true,
subtree: true
});
},
"Starting fatigue monitor": function () {
setInterval(fn.checkFatigue, 1000);
OBSERVERS.lowStamina.observe(document.querySelector('#autosRemaining'), {
childList: true
});
},
"Starting harvestron monitor": function () {
setInterval(fn.checkHarvestronVisible, 1000);
},
"Starting construction monitor": function () {
setInterval(fn.checkConstructionVisible, 1000);
},
"Starting quest monitor": function () {
setInterval(fn.checkQuestComplete, 1000);
},
"Starting event monitor": function () {
OBSERVERS.event.observe(document.querySelector("#eventCountdown"), { childList: true });
},
"Starting boss failure monitor": function () {
const bossFailureNotifications = document.getElementsByClassName('gauntletWeakened');
// There should be only one of these
if (bossFailureNotifications && bossFailureNotifications.length) {
OBSERVERS.bossFailure.observe(bossFailureNotifications[0], { attributes: true });
} else {
console.log('No boss failure notification divs found!');
}
},
"Adding HTML elements": function () {
const accountSettingsWrapper = $('#accountSettingsWrapper');
var settingsLinksWrapper = $('#settingsLinksWrapper');
var noaSettingsButton = $('<a id="noaPreferences"><button class="btn btn-primary">NoA</button></a>');
var noaSettingsPage = $(SETTINGS_DIALOG_HTML);
accountSettingsWrapper.append(noaSettingsPage);
Object.defineProperty(Vue.prototype, '$lodash', { value: _ });
Vue.component('settings-entry', {
props: {
setting: Object,
name: String,
type: {
type: String,
default: 'normal',
validator: function(value) {
return ['normal', 'regex', 'eventTime'].indexOf(value) !== -1;
},
},
collection: Array,
index: Number,
},
methods: {
notificationTest: function () {
const description = this.name || this.setting.searchText || 'Setting';
fn.notification('Testing ' + description + ' notifications', URLS.img.icon, this.setting);
},
remove: function() {
this.$delete(this.collection, this.index);
}
},
template: `
<tr>
<th scope="row" v-if="type === 'normal'">{{name}}</th>
<td v-if="type === 'regex'"><input type="text" v-model="setting.searchText"></td>
<td v-if="type === 'eventTime'"><input type="number" v-model="setting.timeMinutes" step="0.5"></td>
<td><input type="checkbox" v-model="setting.popup"></td>
<td><input type="checkbox" v-model="setting.sound"></td>
<td><input type="checkbox" v-model="setting.log"></td>
<td><input type="checkbox" v-model="setting.clanDiscord"></td>
<td><input type="checkbox" v-model="setting.personalDiscord"></td>
<td><input type="checkbox" v-model="setting.recur" v-if="!$lodash.isNil(setting.recur)"></td>
<td><input type="text" v-model="setting.soundFile"></td>
<td><button class="btn btn-primary btn-xs" style="margin-top: 0px;" v-on:click="notificationTest()">Test</button></td>
<td><button class="btn btn-primary btn-xs" style="margin-top: 0px;" v-if="collection" v-on:click="remove()">Remove</button></td>
</tr>
`
});
const settingsApp = new Vue({
el: '#NoASettingsContentWrapper',
data:
{
userSettings: userSettings,
},
methods:
{
addChatSearch: function () {
userSettings.chatSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
},
addCraftingSearch: function () {
userSettings.craftingSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
},
addLootSearch: function () {
userSettings.lootSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
},
addEventTime: function() {
userSettings.eventTimeRemaining.push({popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, timeMinutes: 1, });
}
},
watch: {
userSettings: {
handler: fn.storeUserSettings,
deep: true,
}
}
});
$('#NoANotificationSettingsButton').click(function () {
$('#NoANotificationSettingsButton').addClass('active').siblings().removeClass('active');
$('#NoANotificationSettingsWrapper').css('display', 'block').siblings().css('display', 'none');
});
$('#NoAAdvancedSettingsButton').click(function () {
$('#NoAAdvancedSettingsButton').addClass('active').siblings().removeClass('active');
$('#NoAAdvancedSettingsWrapper').css('display', 'block').siblings().css('display', 'none');
});
$('#NoALogButton').click(function () {
$('#NoALogButton').addClass('active').siblings().removeClass('active');
$('#NoANotificationLog').css('display', 'block').siblings().css('display', 'none');
populateNotificationLog();
});
$('#NoANotificationSettingsButton').click();
noaSettingsButton.click(function () {
// Remove the active class from all of the buttons in the settings link wrapper, then set the settings button active
noaSettingsButton.addClass('active').siblings().removeClass('active');
// Hide all the children of the settings wrapper, then display only the settings link wrapper and the NoA settings page
accountSettingsWrapper.children().css('display', 'none');
settingsLinksWrapper.css('display', 'block');
$('#NoASettings').css('display', 'block');
});
settingsLinksWrapper.append(noaSettingsButton);
function hideNoaSettings() {
$('#NoASettings').css('display', 'none');
$('#notificationLogItems').empty();
}
noaSettingsButton.siblings().each(function () {
$(this).click(hideNoaSettings);
});
const notificationLogRefreshButton = $('#notificationLogRefresh');
const notificationLogItems = $('#notificationLogItems');
notificationLogRefreshButton.click(populateNotificationLog);
function populateNotificationLog() {
notificationLogItems.empty();
// iterate backwards - display newest first
for (var notificationCounter = notificationLogEntries.length - 1; notificationCounter >= 0; notificationCounter--) {
notificationLogItems.append('<li>' + formatLogEntry(notificationLogEntries[notificationCounter]) + '</li>');
}
}
function formatLogEntry(entry) {
if (!!/^\[\d\d:\d\d:\d\d\]/.exec(entry.text)) {
return entry.text;
} else {
return '[' +
new Date(entry.timestamp).toLocaleTimeString(undefined, { timeZone: 'America/New_York', hour12: false }) +
'] ' +
entry.text;
}
}
},
};
const keys = Object.keys(ON_LOAD);
for (var i = 0; i < keys.length; i++) {
console.log('[' + GM_info.script.name + ' (' + GM_info.script.version + ')] ' + keys[i]);
ON_LOAD[keys[i]]();
}
})();
})(jQuery, MutationObserver, buzz);
}
| notifications-of-avabur.user.js | // ==UserScript==
// @name Notifications of Avabur
// @namespace https://github.com/davidmcclelland/
// @author Dave McClelland <[email protected]>
// @homepage https://github.com/davidmcclelland/notifications-of-avabur
// @supportURL https://github.com/davidmcclelland/notifications-of-avabur/issues
// @downloadURL https://github.com/davidmcclelland/notifications-of-avabur/raw/master/notifications-of-avabur.user.js
// @description Never miss another gauntlet again!
// @match https://*.avabur.com/game*
// @version 1.12.0-beta1
// @icon https://rawgit.com/davidmcclelland/notifications-of-avabur/master/res/img/logo-32.png
// @run-at document-end
// @connect githubusercontent.com
// @connect github.com
// @connect self
// @grant GM_addStyle
// @require https://rawgit.com/davidmcclelland/notifications-of-avabur/master/lib/toastmessage/javascript/jquery.toastmessage.js
// @require https://cdnjs.cloudflare.com/ajax/libs/buzz/1.2.0/buzz.min.js
// @require https://raw.githubusercontent.com/lodash/lodash/4.17.4/dist/lodash.min.js
// @require https://cdn.jsdelivr.net/npm/vue
// @license LGPL-2.1
// @noframes
// ==/UserScript==
//Check if the user can even support the bot
if (typeof (MutationObserver) === "undefined") {
console.log("Cannot support mutation observer!");
} else {
(function ($, MutationObserver, buzz) {
'use strict';
/**
* Creates a GitHub CDN URL
* @param {String} path Path to the file without leading slashes
* @param {String} [author] The author. Defaults to davidmcclelland
* @param {String} [repo] The repository. Defaults to notifications-of-avabur
* @returns {String} The URL
*/
const gh_url = function (path, author, repo) {
author = author || "davidmcclelland";
repo = repo || "notifications-of-avabur";
// return "https://cdn.rawgit.com/" + author + "/" + repo + "/" +
// GM_info.script.version + "/" + path;
return "https://rawgit.com/" + author + "/" + repo + "/" +
'master' + "/" + path;
};
const URLS = {
sfx: {
message_ding: gh_url('res/sfx/message_ding.wav')
},
img: {
icon: gh_url('res/img/logo-32.png'),
chatSearch: gh_url('res/img/noa-chat.png'),
construction: gh_url('res/img/noa-construction.png'),
craftingSearch: gh_url('res/img/noa-crafting.png'),
lootSearch: gh_url('res/img/noa-drop.png'),
event: gh_url('res/img/noa-event.png'),
fatigued: gh_url('res/img/noa-fatigued.png'),
harvestron: gh_url('res/img/noa-harvestron.png'),
quest: gh_url('res/img/noa-quest.png'),
weakened: gh_url('res/img/noa-weakened.png'),
whisper: gh_url('res/img/noa-whisper.png')
}
};
const clickToAChannelTab = function (node) {
if (typeof node.getToAChannelInfo === 'function') {
let { channelID } = node.getToAChannelInfo();
if (false !== channelID) {
$(`#channelTab${channelID}`).click();
}
}
};
/////////////////////////////////////////////////////
// This is the script code. Don't change it unless //
// you know what you're doing ;) //
/////////////////////////////////////////////////////
const DEFAULT_USER_SETTINGS = {
recurToDiscord: false,
muteWhileAfk: true,
recurringNotificationsTimeout: 20,
soundVolume: 80,
lowStaminaThreshold: 5,
popupDurationSec: 5,
fatigue: { popup: true, sound: true, log: false, clanDiscord: false, personalDiscord: false, recur: true },
eventFiveMinuteCountdown: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventThirtySecondCountdown: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventStarting: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventTenMinutesRemaining: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventFiveMinutesRemaining: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventEnd: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
eventElimination: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
harvestron: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
construction: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
whisper: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
questComplete: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
chatSearch: [],
craftingSearch: [],
lootSearch: [],
clanDiscord: { webhook: '', target: '' },
personalDiscord: { webhook: '', target: '' }
};
const SETTINGS_KEY = 'NoASettings';
const NOA_STYLES = `
.row.text-center > div {
display: inline-block;
float: none;
}
#NoASettings input {
margin-right: 10px;
}
#NoASettings textarea {
width: 50%;
height: 80px;
}
#NoASettings hr {
margin-top: 10px;
margin-bottom: 10px;
}
#notificationLogItems {
margin-top: 10px;
}
`;
const SETTINGS_DIALOG_HTML = `
<div id="NoASettings" style="display: none; margin: 10px;">
<div id="NoASettingsButtonWrapper" class="center">
<a id="NoANotificationSettingsButton">
<button class="btn btn-primary">Notifications</button>
</a>
<a id="NoAAdvancedSettingsButton">
<button class="btn btn-primary">Advanced</button>
</a>
<a id="NoALogButton">
<button class="btn btn-primary">Log</button>
</a>
</div>
<div id="NoASettingsContentWrapper">
<div id="NoANotificationSettingsWrapper">
<div>
<h4 class="nobg">General</h4>
<div class="row">
<div class="col-xs-3">
<label>
<input id="recurToDiscordEditor" type="checkbox" v-model="userSettings.recurToDiscord"> Recur to Discord
</label>
</div>
<div class="col-xs-3">
<label>Recurrence Time (sec)</label>
<input id="recurringNotificationsTimeoutEditor" type="number" min="1" max="100" v-model="userSettings.recurringNotificationsTimeout">
</div>
<div class="col-xs-3">
<label>Sound Volume</label>
<input id="soundVolumeEditor" type="number" min="1" max="100" v-model="userSettings.soundVolume">
</div>
<div class="col-xs-3">
<label>Low Stamina Threshold</label>
<input id="lowStaminaThresholdEditor" type="number" min="0" max="9999" v-model="userSettings.lowStaminaThreshold">
</div>
<div class="col-xs-3">
<label>
<input id="muteWhileAfkEditor" type="checkbox" v-model="userSettings.muteWhileAfk">Mute While AFK</label>
</div>
<div class="col-xs-3">
<label>Popup Duration (sec)
<input id="popupDurationEditor" type="number" min="1" max="60" v-model="userSettings.popupDurationSec">
</div>
</div>
</div>
<hr>
<div>
<h4 class="nobg">Clan Discord</h4>
<div class="row">
<label class="col-xs-3">
<a href="https://discordapp.com/developers/docs/resources/webhook#execute-webhook" target="_blank">Webhook</a>
</label>
<div class="col-xs-9">
<input id="clanDiscordWebhookEditor" type="text" style="width: 80%;" v-model="userSettings.clanDiscord.webhook">
</div>
</div>
<div class="row">
<label class="col-xs-3">User/Group</label>
<div class="col-xs-9">
<input id="clanDiscordTargetEditor" type="text" style="width: 80%;" v-model="userSettings.clanDiscord.target">
</div>
</div>
</div>
<hr>
<div>
<h4 class="nobg">Personal Discord</h4>
<div class="row">
<label class="col-xs-3">
<a href="https://discordapp.com/developers/docs/resources/webhook#execute-webhook" target="_blank">Webhook</a>
</label>
<div class="col-xs-9">
<input id="personalDiscordWebhookEditor" type="text" style="width: 80%;" v-model="userSettings.personalDiscord.webhook">
</div>
</div>
<div class="row">
<label class="col-xs-3">User/Group</label>
<div class="col-xs-9">
<input id="personalDiscordTargetEditor" type="text" style="width: 80%;" v-model="userSettings.personalDiscord.target">
</div>
</div>
</div>
<hr>
<table id="NoASettingsTable" class="table">
<thead>
<tr>
<td></td>
<th scope="col">Popup</th>
<th scope="col">Sound</th>
<th scope="col">Log</th>
<th scope="col">Clan</th>
<th scope="col">Personal</th>
<th scope="col">Recur</th>
<th scope="col">Sound File URL</th>
<th scope="col">Test Notifications</th>
</tr>
</thead>
<tbody>
<tr is="settings-entry" name="Fatigue" :setting="userSettings.fatigue"></tr>
<tr is="settings-entry" name="Harvestron" :setting="userSettings.harvestron"></tr>
<tr is="settings-entry" name="Construction" :setting="userSettings.construction"></tr>
<tr is="settings-entry" name="Quest Complete" :setting="userSettings.questComplete"></tr>
<tr is="settings-entry" name="Whisper" :setting="userSettings.whisper"></tr>
<tr is="settings-entry" name="Event 5 Minute Countdown" :setting="userSettings.eventFiveMinuteCountdown"></tr>
<tr is="settings-entry" name="Event 30 Second Countdown" :setting="userSettings.eventThirtySecondCountdown"></tr>
<tr is="settings-entry" name="Event Starting" :setting="userSettings.eventStarting"></tr>
<tr is="settings-entry" name="Event 10 Minutes Remaining" :setting="userSettings.eventTenMinutesRemaining"></tr>
<tr is="settings-entry" name="Event 5 Minutes Remaining" :setting="userSettings.eventFiveMinutesRemaining"></tr>
<tr is="settings-entry" name="Event End" :setting="userSettings.eventEnd"></tr>
<tr is="settings-entry" name="Event Weakened" :setting="userSettings.eventElimination"></tr>
</tbody>
</table>
</div>
<div id="NoAAdvancedSettingsWrapper">
<table class="table">
<thead>
<tr>
<td></td>
<th scope="col">Popup</th>
<th scope="col">Sound</th>
<th scope="col">Log</th>
<th scope="col">Clan</th>
<th scope="col">Personal</th>
<th scope="col">Recur</th>
<th scope="col">Sound File URL</th>
<th scope="col">Test Notifications</th>
<th scope="col">Remove</th>
</tr>
</thead>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Chat Search (<a href="https://github.com/davidmcclelland/notifications-of-avabur/wiki/Chat-search" target="_blank">Help</a>)</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addChatSearch()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(chatSearch, index) in userSettings.chatSearch" is="settings-entry" :setting="chatSearch" :collection="userSettings.chatSearch" :index="index"></tr>
</tbody>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Crafting Search (<a href="https://github.com/davidmcclelland/notifications-of-avabur/wiki/Loot-search" target="_blank">Help</a>)</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addCraftingSearch()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(craftingSearch, index) in userSettings.craftingSearch" is="settings-entry" :setting="craftingSearch" :collection="userSettings.craftingSearch" :index="index"></tr>
</tbody>
<tbody>
<tr class="header">
<th colspan="3" scope="col">
<h3 class="nobg">
<span>Loot Search (<a href="https://github.com/davidmcclelland/notifications-of-avabur/wiki/Crafting-search" target="_blank">Help</a>)</span>
<button type="button" class="btn btn-primary btn-sm" v-on:click="addLootSearch()" style="margin-top: 0;">Add</button>
</h3>
</th>
</tr>
<tr v-for="(lootSearch, index) in userSettings.lootSearch" is="settings-entry" :setting="lootSearch" :collection="userSettings.lootSearch" :index="index"></tr>
</tbody>
</table>
</div>
<div id="NoANotificationLog">
<button class="btn btn-primary" id="notificationLogRefresh">Refresh</button>
<ul id="notificationLogItems"></ul>
</div>
</div>
<div class="row" style="display: none;" id="NoaSettingsSavedLabel">
<strong class="col-xs-12">
Settings have been saved
</strong>
</div>
</div>
`;
const INTERNAL_UPDATE_URL = "https://api.github.com/repos/davidmcclelland/notifications-of-avabur/contents/notifications-of-avabur.user.js";
var userSettings = null;
var isEventCountdownActive = false;
var counters = {
lastConstructionNotification: 0,
lastFatigueNotification: 0,
lastHarvestronNotification: 0,
lastQuestNotification: 0,
};
var notificationLogEntries = [];
var checkForUpdateTimer = 0;
// Obviously no sound is playing, but we need to block audio until the dom is loaded
var isSoundPlaying = true;
// I suspect that this may help fix some issues with Chrome's new auto-playing audio changes
window.addEventListener('load', function () {
isSoundPlaying = false;
});
if (!String.format) {
String.format = function (format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
}
/** Misc function container */
const fn = {
versionCompare: function (v1, v2) {
var regex = new RegExp("(\.0+)+");
v1 = v1.replace(regex, "").split(".");
v2 = v2.replace(regex, "").split(".");
var min = Math.min(v1.length, v2.length);
var diff = 0;
for (var i = 0; i < min; i++) {
diff = parseInt(v1[i], 10) - parseInt(v2[i], 10);
if (diff !== 0) {
return diff;
}
}
return v1.length - v2.length;
},
checkForUpdate: function () {
var version = "";
$.get(INTERNAL_UPDATE_URL).done(function (res) {
var match = atob(res.content).match(/\/\/\s+@version\s+([^\n]+)/);
version = match[1];
if (fn.versionCompare(GM_info.script.version, version) < 0) {
var message = "<li class=\"chat_notification\">Notifications Of Avabur has been updated to version " + version + "! <a href=\"https://github.com/davidmcclelland/notifications-of-avabur/raw/master/notifications-of-avabur.user.js\" target=\"_blank\">Update</a> | <a href=\"https://github.com/davidmcclelland/notifications-of-avabur/commits/master\" target=\"_blank\">Changelog</a></li>";
// TODO: Handle chat direction like ToA does
$("#chatMessageList").prepend(message);
} else {
checkForUpdateTimer = setTimeout(fn.checkForUpdate, 24 * 60 * 60 * 1000);
}
});
},
sendDiscordMessage: function (webhook, target, text) {
if (webhook && target && text) {
let messageContent = text;
if (target && target.length) {
messageContent = target + ' ' + text;
}
if (webhook.includes("discordapp")) {
$.post(webhook, { content: messageContent });
} else {
$.ajax({
data: 'payload=' + JSON.stringify({
"text": messageContent
}),
dataType: 'json',
processData: false,
type: 'POST',
url: webhook
});
}
}
},
/**
* Creates a floaty notification and plays a sound, based on preferences
* @param {String} text Text to display
* @param {String} iconUrl Icon to display in the popup
* @param {object} settings Settings for this type of notification
* @param {number} recurrenceCounter The number of seconds this event has recurred for. Optional, defaults to zero
* @param {Function} [onPopupClick] An optional function to be called back when/if a popup is clicked
*/
notification: function (text, iconUrl, settings, recurrenceCounter, onPopupClick, onPopupClickArgs = []) {
recurrenceCounter = _.defaultTo(recurrenceCounter, 0);
const isFirstRecurrence = (recurrenceCounter === 0);
const recurrenceEnabled = _.defaultTo(settings.recur, false);
const discordRecurrenceEnabled = _.defaultTo(userSettings.recurToDiscord, false);
// It's a good recurrence if it is the first one, or if recurring notifications are on
// and it's been long enough since the previous
const isGoodRecurrence = isFirstRecurrence ||
(recurrenceEnabled && (recurrenceCounter % userSettings.recurringNotificationsTimeout === 0));
// While muted, only log. No sounds, popups, or discord
const isMuted = fn.checkIsMuted();
// Only ever send to discord and log the first instance of a recurrence,j
// even if it's a good recurrence
// Only ever log on the first recurrence.
const doLog = settings.log && isFirstRecurrence;
// Only send to discord if discord is enabled and (it's the first recurrence or (it's a good recurrence and recur to discord is enabled))
const doClanDiscord = !isMuted && settings.clanDiscord && (isFirstRecurrence || (isGoodRecurrence && discordRecurrenceEnabled));
const doPersonalDiscord = !isMuted && settings.personalDiscord && (isFirstRecurrence || (isGoodRecurrence && discordRecurrenceEnabled));
// Recur popup and sound notifications
const doPopup = !isMuted && settings.popup && isGoodRecurrence;
const doSound = !isMuted && settings.sound && isGoodRecurrence;
if (doLog) {
notificationLogEntries.push({
timestamp: new Date(),
text: text
});
}
if (notificationLogEntries.length > 100) {
notificationLogEntries.shift();
}
if (doPopup) {
Notification.requestPermission().then(function () {
var n = new Notification(GM_info.script.name, {
icon: iconUrl,
body: text
});
const popupDurationSec = _.defaultTo(userSettings.popupDurationSec, 5);
setTimeout(n.close.bind(n), popupDurationSec * 1000);
n.addEventListener('click', function (e) {
window.focus();
e.target.close();
if (typeof onPopupClick === 'function') {
if (!Array.isArray(onPopupClickArgs)) {
onPopupClickArgs = [onPopupClickArgs];
}
onPopupClick.apply(null, onPopupClickArgs);
}
}, false);
});
}
if (doSound) {
var soundFileUrl = settings.soundFile;
if (!soundFileUrl || !soundFileUrl.length) {
soundFileUrl = URLS.sfx.message_ding;
}
if (!isSoundPlaying) {
const buzzFile = new buzz.sound(soundFileUrl, { volume: userSettings.soundVolume });
buzzFile.bind('ended', function () {
isSoundPlaying = false;
});
buzzFile.bind('error', function () {
console.log('[NoA] Error playing audio file: ', this.getErrorMessage());
isSoundPlaying = false;
});
buzzFile.play();
isSoundPlaying = true;
}
}
if (doClanDiscord) {
fn.sendDiscordMessage(userSettings.clanDiscord.webhook, userSettings.clanDiscord.target, text);
}
if (doPersonalDiscord) {
fn.sendDiscordMessage(userSettings.personalDiscord.webhook, userSettings.personalDiscord.target, text);
}
},
displaySettingsSavedLabel: function () {
const label = document.getElementById('NoaSettingsSavedLabel');
if (label && label.style) {
label.style.display = 'block';
}
},
debouncedHideSettingsSavedLabel: _.debounce(function () {
const label = document.getElementById('NoaSettingsSavedLabel');
if (label && label.style) {
label.style.display = 'none';
}
}, 3000),
getUpgradedRegexSetting: function (oldSetting) {
const retVal = [];
_.forEach(oldSetting.searchText.split(/\r?\n/), function (singleSearch) {
const newSetting = _.clone(oldSetting);
newSetting.searchText = singleSearch;
retVal.push(newSetting);
});
return retVal;
},
loadUserSettings: function () {
var loadedSettings = JSON.parse(localStorage.getItem(SETTINGS_KEY));
userSettings = _.defaultsDeep(loadedSettings, DEFAULT_USER_SETTINGS);
// Previously, regex searches were stored as a string and then split at text-search time.
if (!_.isArray(userSettings.chatSearch)) {
userSettings.chatSearch = fn.getUpgradedRegexSetting(userSettings.chatSearch);
}
if (!_.isArray(userSettings.craftingSearch)) {
userSettings.craftingSearch = fn.getUpgradedRegexSetting(userSettings.craftingSearch);
}
if (!_.isArray(userSettings.lootSearch)) {
userSettings.lootSearch = fn.getUpgradedRegexSetting(userSettings.lootSearch);
}
// Save settings to store any defaulted settings
fn.storeUserSettings();
},
storeUserSettings: function () {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(userSettings));
fn.displaySettingsSavedLabel();
fn.debouncedHideSettingsSavedLabel();
},
checkIsAfk: function () {
const element = document.getElementById('iAmAFK');
return element && (element.style.display !== 'none');
},
checkIsMuted: function () {
return userSettings.muteWhileAfk && fn.checkIsAfk();
},
checkConstructionVisible: function () {
var div = document.getElementById('constructionNotifier');
if (div && (div.style.display !== 'none')) {
const constructionCallback = function () {
$('#constructionNotifier').click();
};
fn.notification('Construction available!', URLS.img.construction, userSettings.construction, counters.lastConstructionNotification, constructionCallback);
counters.lastConstructionNotification++;
} else {
counters.lastConstructionNotification = 0;
}
},
checkFatigue: function () {
const searchSpan = document.getElementById('autosRemaining');
const staminaRemainingText = searchSpan.innerText || searchSpan.textContent;
const staminaRemainingNumber = parseInt(staminaRemainingText, 10);
if (staminaRemainingNumber <= 0) {
fn.notification('You are fatigued!', URLS.img.fatigued, userSettings.fatigue, counters.lastFatigueNotification);
counters.lastFatigueNotification++;
} else {
counters.lastFatigueNotification = 0;
}
},
checkHarvestronVisible: function () {
var div = document.getElementById('harvestronNotifier');
if (div && (div.style.display !== 'none')) {
const harvestronCallback = function () {
$('#harvestronNotifier').click();
};
fn.notification('Harvestron available!', URLS.img.harvestron, userSettings.harvestron, counters.lastHarvestronNotification, harvestronCallback);
counters.lastHarvestronNotification++;
} else {
counters.lastHarvestronNotification = 0;
}
},
checkQuestComplete: function () {
var visibleQuestDivId;
const possibleQuestDivIds = ['bq_info', 'tq_info', 'pq_info'];
for (var i = 0; i < possibleQuestDivIds.length; i++) {
var questDiv = document.getElementById(possibleQuestDivIds[i]);
if (questDiv) {
var parentDiv = questDiv.parentElement;
if (parentDiv && (parentDiv.style.display !== 'none')) {
visibleQuestDivId = possibleQuestDivIds[i];
break;
}
}
}
if (!visibleQuestDivId) {
return;
}
const visibleQuestDiv = $('#' + visibleQuestDivId);
if (visibleQuestDivId && (visibleQuestDiv.text().startsWith('You have completed your quest!'))) {
const questCallback = function () {
// Find the first <a> sibling of the vibile questDiv and click it
visibleQuestDiv.siblings('a').first().click();
};
const notificationText = visibleQuestDiv.siblings('a').first().text().trim() + ' complete!';
fn.notification(notificationText, URLS.img.quest, userSettings.questComplete, counters.lastQuestNotification, questCallback);
counters.lastQuestNotification++;
} else {
counters.lastQuestNotification = 0;
}
},
checkRecordsVisible: function (records) {
for (var i = 0; i < records.length; i++) {
const target = $(records[i].target);
var style = window.getComputedStyle(target[0]);
if (style.display !== 'none') {
return true;
}
}
return false;
},
findSearchValues: function (text, searchValues) {
// Look for any values in the array
for (var k = 0; k < searchValues.length; k++) {
if (searchValues[k].searchText.length && text.match(new RegExp(searchValues[k].searchText, 'i'))) {
return searchValues[k];
}
}
},
isToAProcessed: function (node) {
return $(node).hasClass('processed');
},
findSearchValuesInRecords: function (records, searchValues) {
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
const text = $(addedNodes[j]).text();
const foundSearchValue = fn.findSearchValues(text, searchValues);
if (!fn.isToAProcessed(addedNodes[j]) && foundSearchValue) {
return {
node: addedNodes[j],
searchValue: foundSearchValue,
}
}
}
}
}
return null;
},
checkEventParticipation: function () {
return document.querySelector('#bossWrapper').style.display !== 'none';
},
setupEventNotifications: function (countdownBadgeText) {
if (!isEventCountdownActive) {
if (countdownBadgeText === '!' || countdownBadgeText.startsWith('*')) {
return;
}
isEventCountdownActive = true;
// First thing's first, figure out how long until the event (in seconds)
/* We handle this a bit odd - if the countdown string doesn't list 'm', then it is displaying
only seconds. This currently only happens on beta when testing events, but NoA shouldn't break on beta.
This could be slightly more elegantly solved with indexof, but I already wrote it this way and it works. */
var minutesString = '0';
var secondsString = '0';
if (countdownBadgeText.includes('m')) {
minutesString = countdownBadgeText.slice(0, 2);
secondsString = countdownBadgeText.slice(3, 5);
} else {
secondsString = countdownBadgeText.slice(0, 2);
}
var secondsUntilEventStart = (parseInt(minutesString, 10) * 60) + parseInt(secondsString, 10);
// This callback is only passed in for the five minute countdown. It would get really annoying otherwise.
const eventCallback = function () {
$('#event_start').click();
};
fn.notification('An event is starting in five minutes!', URLS.img.event, userSettings.eventFiveMinuteCountdown, null, eventCallback);
// 30 second warning
setTimeout(function () {
fn.notification('An event is starting in thirty seconds!', URLS.img.event, userSettings.eventThirtySecondCountdown);
}, (secondsUntilEventStart - 30) * 1000);
// 1 second warning
setTimeout(function () {
fn.notification('An event is starting!', URLS.img.event, userSettings.eventStarting);
}, (secondsUntilEventStart - 1) * 1000);
// 10 minutes remaining
setTimeout(function () {
if (!fn.checkEventParticipation()) {
fn.notification('Ten minutes remaining in the event!', URLS.img.event, userSettings.eventTenMinutesRemaining);
}
}, (secondsUntilEventStart + (60 * 5)) * 1000);
// 5 minutes remaining
setTimeout(function () {
if (!fn.checkEventParticipation()) {
fn.notification('Five minutes remaining in the event!', URLS.img.event, userSettings.eventFiveMinutesRemaining);
}
}, (secondsUntilEventStart + (60 * 10)) * 1000);
// End of the event
setTimeout(function () {
isEventCountdownActive = false;
fn.notification('The event has ended!', URLS.img.event, userSettings.eventEnd);
}, (secondsUntilEventStart + (60 * 15)) * 1000);
}
},
};
/** Collection of mutation observers the script uses */
const OBSERVERS = {
chat_search: new MutationObserver(
/** @param {MutationRecord[]} records */
function (records) {
var searchResults = fn.findSearchValuesInRecords(records, userSettings.chatSearch);
if (searchResults && searchResults.node) {
fn.notification(searchResults.node.textContent, URLS.img.chatSearch, searchResults.searchValue, null, clickToAChannelTab, searchResults.node);
return;
}
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
const text = $(addedNodes[j]).text();
if (!fn.isToAProcessed(addedNodes[j]) && text.match(/^\[[0-9]+:[0-9]+:[0-9]+]\s*Whisper from/)) {
fn.notification(text, URLS.img.whisper, userSettings.whisper, null, clickToAChannelTab, addedNodes[j]);
return;
}
}
}
}
}
),
loot_search: new MutationObserver(
/** @param {MutationRecord[]} records */
function (records) {
var searchResults = fn.findSearchValuesInRecords(records, userSettings.lootSearch);
if (searchResults && searchResults.node) {
fn.notification(searchResults.node.textContent, URLS.img.lootSearch, searchResults.searchValue);
return;
}
}
),
crafting_search: new MutationObserver(
/** @param {MutationRecord[]} records */
function (records) {
var searchResults = fn.findSearchValuesInRecords(records, userSettings.craftingSearch);
// Weird special case, because the crafting progress bar is full of different divs, but it's very useful to search
if (!searchResults) {
const craftingXpCountText = $('#craftingXPCount').text();
searchResults = fn.findSearchValues(craftingXpCountText, userSettings.craftingSearch);
}
if (searchResults) {
fn.notification(searchResults.node.textContent, URLS.img.craftingSearch, searchResults.searchValue);
}
}
),
lowStamina: new MutationObserver(
function (records) {
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
const text = $(addedNodes[j]).text();
if (text === userSettings.lowStaminaThreshold.toString()) {
fn.notification('Your stamina is low!', URLS.img.fatigued, userSettings.fatigue);
}
}
}
}
}
),
event: new MutationObserver(
function (records) {
for (var i = 0; i < records.length; i++) {
const addedNodes = records[i].addedNodes;
if (addedNodes.length) {
for (var j = 0; j < addedNodes.length; j++) {
if (!isEventCountdownActive) {
const text = $(addedNodes[j]).text();
fn.setupEventNotifications(text);
}
}
}
}
}
),
bossFailure: new MutationObserver(
function (records) {
if (fn.checkRecordsVisible(records)) {
fn.notification('You are fighting while weakened!', URLS.img.weakened, userSettings.eventElimination);
}
}
),
};
(function () {
const ON_LOAD = {
"Initializing settings": function () {
GM_addStyle(NOA_STYLES);
fn.loadUserSettings();
},
"Starting script update monitor": function () {
checkForUpdateTimer = setTimeout(fn.checkForUpdate, 10000);
},
"Starting chat monitor": function () {
OBSERVERS.chat_search.observe(document.querySelector("#chatMessageList"), {
childList: true
});
},
"Starting loot monitor": function() {
OBSERVERS.loot_search.observe(document.querySelector("#latestLoot"), {
childList: true
});
},
"Starting crafting monitor": function() {
OBSERVERS.crafting_search.observe(document.querySelector('#craftingGainWrapper'), {
childList: true,
subtree: true
});
},
"Starting fatigue monitor": function () {
setInterval(fn.checkFatigue, 1000);
OBSERVERS.lowStamina.observe(document.querySelector('#autosRemaining'), {
childList: true
});
},
"Starting harvestron monitor": function () {
setInterval(fn.checkHarvestronVisible, 1000);
},
"Starting construction monitor": function () {
setInterval(fn.checkConstructionVisible, 1000);
},
"Starting quest monitor": function () {
setInterval(fn.checkQuestComplete, 1000);
},
"Starting event monitor": function () {
OBSERVERS.event.observe(document.querySelector("#eventCountdown"), { childList: true });
},
"Starting boss failure monitor": function () {
const bossFailureNotifications = document.getElementsByClassName('gauntletWeakened');
// There should be only one of these
if (bossFailureNotifications && bossFailureNotifications.length) {
OBSERVERS.bossFailure.observe(bossFailureNotifications[0], { attributes: true });
} else {
console.log('No boss failure notification divs found!');
}
},
"Adding HTML elements": function () {
const accountSettingsWrapper = $('#accountSettingsWrapper');
var settingsLinksWrapper = $('#settingsLinksWrapper');
var noaSettingsButton = $('<a id="noaPreferences"><button class="btn btn-primary">NoA</button></a>');
var noaSettingsPage = $(SETTINGS_DIALOG_HTML);
accountSettingsWrapper.append(noaSettingsPage);
Object.defineProperty(Vue.prototype, '$lodash', { value: _ });
Vue.component('settings-entry', {
props: ['setting', 'name', 'collection', 'index'],
methods: {
notificationTest: function () {
const description = this.name || this.setting.searchText || 'Setting';
fn.notification('Testing ' + description + ' notifications', URLS.img.icon, this.setting);
},
remove: function() {
this.$delete(this.collection, this.index);
}
},
template: `
<tr>
<th scope="row" v-if="name">{{name}}</th>
<td v-if="!name"><input type="text" v-model="setting.searchText"></td>
<td><input type="checkbox" v-model="setting.popup"></td>
<td><input type="checkbox" v-model="setting.sound"></td>
<td><input type="checkbox" v-model="setting.log"></td>
<td><input type="checkbox" v-model="setting.clanDiscord"></td>
<td><input type="checkbox" v-model="setting.personalDiscord"></td>
<td><input type="checkbox" v-model="setting.recur" v-if="!$lodash.isNil(setting.recur)"></td>
<td><input type="text" v-model="setting.soundFile"></td>
<td><button class="btn btn-primary btn-xs" style="margin-top: 0px;" v-on:click="notificationTest()">Test</button></td>
<td><button class="btn btn-primary btn-xs" style="margin-top: 0px;" v-if="collection" v-on:click="remove()">Remove</button></td>
</tr>
`
});
const settingsApp = new Vue({
el: '#NoASettingsContentWrapper',
data:
{
userSettings: userSettings,
},
methods:
{
addChatSearch: function () {
userSettings.chatSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
},
removeChatSearch: function (toRemove) {
_.pull(userSettings.chatSearch, toRemove);
},
addCraftingSearch: function () {
userSettings.craftingSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
},
removeCraftingSearch: function (toRemove) {
_.pull(userSettings.craftingSearch, toRemove);
},
addLootSearch: function () {
userSettings.lootSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
},
removeLootSearch: function (toRemove) {
_.pull(userSettings.lootSearch, toRemove);
},
},
watch: {
userSettings: {
handler: fn.storeUserSettings,
deep: true,
}
}
});
$('#NoANotificationSettingsButton').click(function () {
$('#NoANotificationSettingsButton').addClass('active').siblings().removeClass('active');
$('#NoANotificationSettingsWrapper').css('display', 'block').siblings().css('display', 'none');
});
$('#NoAAdvancedSettingsButton').click(function () {
$('#NoAAdvancedSettingsButton').addClass('active').siblings().removeClass('active');
$('#NoAAdvancedSettingsWrapper').css('display', 'block').siblings().css('display', 'none');
});
$('#NoALogButton').click(function () {
$('#NoALogButton').addClass('active').siblings().removeClass('active');
$('#NoANotificationLog').css('display', 'block').siblings().css('display', 'none');
populateNotificationLog();
});
$('#NoANotificationSettingsButton').click();
noaSettingsButton.click(function () {
// Remove the active class from all of the buttons in the settings link wrapper, then set the settings button active
noaSettingsButton.addClass('active').siblings().removeClass('active');
// Hide all the children of the settings wrapper, then display only the settings link wrapper and the NoA settings page
accountSettingsWrapper.children().css('display', 'none');
settingsLinksWrapper.css('display', 'block');
$('#NoASettings').css('display', 'block');
});
settingsLinksWrapper.append(noaSettingsButton);
function hideNoaSettings() {
$('#NoASettings').css('display', 'none');
$('#notificationLogItems').empty();
}
noaSettingsButton.siblings().each(function () {
$(this).click(hideNoaSettings);
});
const notificationLogRefreshButton = $('#notificationLogRefresh');
const notificationLogItems = $('#notificationLogItems');
notificationLogRefreshButton.click(populateNotificationLog);
function populateNotificationLog() {
notificationLogItems.empty();
// iterate backwards - display newest first
for (var notificationCounter = notificationLogEntries.length - 1; notificationCounter >= 0; notificationCounter--) {
notificationLogItems.append('<li>' + formatLogEntry(notificationLogEntries[notificationCounter]) + '</li>');
}
}
function formatLogEntry(entry) {
if (!!/^\[\d\d:\d\d:\d\d\]/.exec(entry.text)) {
return entry.text;
} else {
return '[' +
new Date(entry.timestamp).toLocaleTimeString(undefined, { timeZone: 'America/New_York', hour12: false }) +
'] ' +
entry.text;
}
}
},
};
const keys = Object.keys(ON_LOAD);
for (var i = 0; i < keys.length; i++) {
console.log('[' + GM_info.script.name + ' (' + GM_info.script.version + ')] ' + keys[i]);
ON_LOAD[keys[i]]();
}
})();
})(jQuery, MutationObserver, buzz);
}
| 1.12.0-beta2: Adding custom event time notifications
| notifications-of-avabur.user.js | 1.12.0-beta2: Adding custom event time notifications | <ide><path>otifications-of-avabur.user.js
<ide> // @downloadURL https://github.com/davidmcclelland/notifications-of-avabur/raw/master/notifications-of-avabur.user.js
<ide> // @description Never miss another gauntlet again!
<ide> // @match https://*.avabur.com/game*
<del>// @version 1.12.0-beta1
<add>// @version 1.12.0-beta2
<ide> // @icon https://rawgit.com/davidmcclelland/notifications-of-avabur/master/res/img/logo-32.png
<ide> // @run-at document-end
<ide> // @connect githubusercontent.com
<ide> popupDurationSec: 5,
<ide> fatigue: { popup: true, sound: true, log: false, clanDiscord: false, personalDiscord: false, recur: true },
<ide> eventFiveMinuteCountdown: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<del> eventThirtySecondCountdown: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<del> eventStarting: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<del> eventTenMinutesRemaining: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<del> eventFiveMinutesRemaining: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<del> eventEnd: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<del> eventElimination: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<add> eventTimeRemaining: [{popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, timeMinutes: 7.5}],
<ide> harvestron: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
<ide> construction: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, recur: true },
<ide> whisper: { popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false },
<ide> </div>
<ide> </div>
<ide> <hr>
<del> <table id="NoASettingsTable" class="table">
<add> <table id="NoASettingsTable" class="table table-condensed">
<ide> <thead>
<ide> <tr>
<ide> <td></td>
<ide> <tr is="settings-entry" name="Quest Complete" :setting="userSettings.questComplete"></tr>
<ide> <tr is="settings-entry" name="Whisper" :setting="userSettings.whisper"></tr>
<ide> <tr is="settings-entry" name="Event 5 Minute Countdown" :setting="userSettings.eventFiveMinuteCountdown"></tr>
<del> <tr is="settings-entry" name="Event 30 Second Countdown" :setting="userSettings.eventThirtySecondCountdown"></tr>
<del> <tr is="settings-entry" name="Event Starting" :setting="userSettings.eventStarting"></tr>
<del> <tr is="settings-entry" name="Event 10 Minutes Remaining" :setting="userSettings.eventTenMinutesRemaining"></tr>
<del> <tr is="settings-entry" name="Event 5 Minutes Remaining" :setting="userSettings.eventFiveMinutesRemaining"></tr>
<del> <tr is="settings-entry" name="Event End" :setting="userSettings.eventEnd"></tr>
<del> <tr is="settings-entry" name="Event Weakened" :setting="userSettings.eventElimination"></tr>
<ide> </tbody>
<ide> </table>
<ide> </div>
<ide> <div id="NoAAdvancedSettingsWrapper">
<del> <table class="table">
<add> <table class="table table-condensed">
<ide> <thead>
<ide> <tr>
<ide> <td></td>
<ide> </h3>
<ide> </th>
<ide> </tr>
<del> <tr v-for="(chatSearch, index) in userSettings.chatSearch" is="settings-entry" :setting="chatSearch" :collection="userSettings.chatSearch" :index="index"></tr>
<add> <tr v-for="(chatSearch, index) in userSettings.chatSearch" is="settings-entry" :setting="chatSearch" type="regex" :collection="userSettings.chatSearch" :index="index"></tr>
<ide> </tbody>
<ide> <tbody>
<ide> <tr class="header">
<ide> </h3>
<ide> </th>
<ide> </tr>
<del> <tr v-for="(craftingSearch, index) in userSettings.craftingSearch" is="settings-entry" :setting="craftingSearch" :collection="userSettings.craftingSearch" :index="index"></tr>
<add> <tr v-for="(craftingSearch, index) in userSettings.craftingSearch" is="settings-entry" :setting="craftingSearch" type="regex" :collection="userSettings.craftingSearch" :index="index"></tr>
<ide> </tbody>
<ide> <tbody>
<ide> <tr class="header">
<ide> </h3>
<ide> </th>
<ide> </tr>
<del> <tr v-for="(lootSearch, index) in userSettings.lootSearch" is="settings-entry" :setting="lootSearch" :collection="userSettings.lootSearch" :index="index"></tr>
<add> <tr v-for="(lootSearch, index) in userSettings.lootSearch" is="settings-entry" :setting="lootSearch" type="regex" :collection="userSettings.lootSearch" :index="index"></tr>
<add> </tbody>
<add> <tbody>
<add> <tr class="header">
<add> <th colspan="3" scope="col">
<add> <h3 class="nobg">
<add> <span>Event Time Remaining</span>
<add> <button type="button" class="btn btn-primary btn-sm" v-on:click="addEventTime()" style="margin-top: 0;">Add</button>
<add> </h3>
<add> </th>
<add> </tr>
<add> <tr v-for="(eventTime, index) in userSettings.eventTimeRemaining" is="settings-entry" :setting="eventTime" type="eventTime" :collection="userSettings.eventTimeRemaining" :index="index"></tr>
<ide> </tbody>
<ide> </table>
<ide> </div>
<ide> isEventCountdownActive = true;
<ide> // First thing's first, figure out how long until the event (in seconds)
<ide> /* We handle this a bit odd - if the countdown string doesn't list 'm', then it is displaying
<del> only seconds. This currently only happens on beta when testing events, but NoA shouldn't break on beta.
<del> This could be slightly more elegantly solved with indexof, but I already wrote it this way and it works. */
<add> only seconds. This could be slightly more elegantly solved with indexof, but I already wrote it this way and it works. */
<ide> var minutesString = '0';
<ide> var secondsString = '0';
<ide> if (countdownBadgeText.includes('m')) {
<ide> secondsString = countdownBadgeText.slice(0, 2);
<ide> }
<ide> var secondsUntilEventStart = (parseInt(minutesString, 10) * 60) + parseInt(secondsString, 10);
<add> var secondsUntilEventEnd = secondsUntilEventStart + (60*15);
<ide>
<ide> // This callback is only passed in for the five minute countdown. It would get really annoying otherwise.
<ide> const eventCallback = function () {
<ide>
<ide> fn.notification('An event is starting in five minutes!', URLS.img.event, userSettings.eventFiveMinuteCountdown, null, eventCallback);
<ide>
<del> // 30 second warning
<del> setTimeout(function () {
<del> fn.notification('An event is starting in thirty seconds!', URLS.img.event, userSettings.eventThirtySecondCountdown);
<del> }, (secondsUntilEventStart - 30) * 1000);
<del>
<del> // 1 second warning
<del> setTimeout(function () {
<del> fn.notification('An event is starting!', URLS.img.event, userSettings.eventStarting);
<del> }, (secondsUntilEventStart - 1) * 1000);
<del>
<del> // 10 minutes remaining
<del> setTimeout(function () {
<del> if (!fn.checkEventParticipation()) {
<del> fn.notification('Ten minutes remaining in the event!', URLS.img.event, userSettings.eventTenMinutesRemaining);
<del> }
<del> }, (secondsUntilEventStart + (60 * 5)) * 1000);
<del>
<del> // 5 minutes remaining
<del> setTimeout(function () {
<del> if (!fn.checkEventParticipation()) {
<del> fn.notification('Five minutes remaining in the event!', URLS.img.event, userSettings.eventFiveMinutesRemaining);
<del> }
<del> }, (secondsUntilEventStart + (60 * 10)) * 1000);
<del>
<del> // End of the event
<del> setTimeout(function () {
<del> isEventCountdownActive = false;
<del> fn.notification('The event has ended!', URLS.img.event, userSettings.eventEnd);
<del> }, (secondsUntilEventStart + (60 * 15)) * 1000);
<add> userSettings.eventTimeRemaining.forEach(function(timeSetting) {
<add> var notificationSeconds = timeSetting.timeMinutes * 60; // This is seconds from the end of the event
<add> setTimeout(function() {
<add> fn.notification(timeSetting.timeMinutes + ' minute(s) left in the event!', URLS.img.event, timeSetting);
<add> }, (secondsUntilEventEnd - notificationSeconds) * 1000);
<add> });
<ide> }
<ide> },
<ide> };
<ide>
<ide> Object.defineProperty(Vue.prototype, '$lodash', { value: _ });
<ide> Vue.component('settings-entry', {
<del> props: ['setting', 'name', 'collection', 'index'],
<add> props: {
<add> setting: Object,
<add> name: String,
<add> type: {
<add> type: String,
<add> default: 'normal',
<add> validator: function(value) {
<add> return ['normal', 'regex', 'eventTime'].indexOf(value) !== -1;
<add> },
<add> },
<add> collection: Array,
<add> index: Number,
<add> },
<ide> methods: {
<ide> notificationTest: function () {
<ide> const description = this.name || this.setting.searchText || 'Setting';
<ide> },
<ide> template: `
<ide> <tr>
<del> <th scope="row" v-if="name">{{name}}</th>
<del> <td v-if="!name"><input type="text" v-model="setting.searchText"></td>
<add> <th scope="row" v-if="type === 'normal'">{{name}}</th>
<add> <td v-if="type === 'regex'"><input type="text" v-model="setting.searchText"></td>
<add> <td v-if="type === 'eventTime'"><input type="number" v-model="setting.timeMinutes" step="0.5"></td>
<ide> <td><input type="checkbox" v-model="setting.popup"></td>
<ide> <td><input type="checkbox" v-model="setting.sound"></td>
<ide> <td><input type="checkbox" v-model="setting.log"></td>
<ide> addChatSearch: function () {
<ide> userSettings.chatSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
<ide> },
<del> removeChatSearch: function (toRemove) {
<del> _.pull(userSettings.chatSearch, toRemove);
<del> },
<ide> addCraftingSearch: function () {
<ide> userSettings.craftingSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
<del> },
<del> removeCraftingSearch: function (toRemove) {
<del> _.pull(userSettings.craftingSearch, toRemove);
<ide> },
<ide> addLootSearch: function () {
<ide> userSettings.lootSearch.push({ popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, searchText: '', });
<ide> },
<del> removeLootSearch: function (toRemove) {
<del> _.pull(userSettings.lootSearch, toRemove);
<del> },
<add> addEventTime: function() {
<add> userSettings.eventTimeRemaining.push({popup: true, sound: true, log: true, clanDiscord: false, personalDiscord: false, timeMinutes: 1, });
<add> }
<ide> },
<ide> watch: {
<ide> userSettings: { |
|
Java | apache-2.0 | e624324d40e434cb7b970c7d32e0179bbfd4986d | 0 | rodsol/relex-temp,leungmanhin/relex,rodsol/relex,virneo/relex,opencog/relex,ainishdave/relex,virneo/relex,williampma/relex,williampma/relex,anitzkin/relex,rodsol/relex,anitzkin/relex,leungmanhin/relex,anitzkin/relex,rodsol/relex-temp,virneo/relex,opencog/relex,leungmanhin/relex,rodsol/relex,rodsol/relex,ainishdave/relex,AmeBel/relex,virneo/relex,AmeBel/relex,anitzkin/relex,williampma/relex,linas/relex,AmeBel/relex,rodsol/relex-temp,linas/relex,rodsol/relex-temp,ainishdave/relex,rodsol/relex-temp,anitzkin/relex,linas/relex,williampma/relex,ainishdave/relex,opencog/relex | /*
* Copyright 2008 Novamente LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package relex.chunk;
import java.util.ArrayList;
import relex.feature.FeatureNode;
import relex.feature.WordFeature;
import relex.feature.Chunk;
/**
* Holder of lexical chunks
*
* Copyright (C) 2008 Linas Vepstas <[email protected]>
*/
public class LexChunk extends Chunk
{
private static final long serialVersionUID = 8648176749497688526L;
public void addWord(FeatureNode fn)
{
if (WordFeature.isPunctuation(fn)) return;
chunk.add(fn);
}
public void addWords(ArrayList<FeatureNode> words)
{
addNodes(words);
}
/**
* Return true if the other object equals this one, else return false.
* Equals, in the comp-sci sense (e.g. scheme or lisp): compares
* structure to determine if they have congruent structure.
* For lexical object, this means "the same words", and nothing more.
* In particular, equality of the associated truth values is ignored.
*/
public boolean equals(Object other)
{
if (!(other instanceof LexChunk)) return false;
LexChunk oth = (LexChunk) other;
if (oth.chunk.size() != chunk.size()) return false;
for (int i=0; i<chunk.size(); i++)
{
FeatureNode fthis = chunk.get(i);
FeatureNode foth = oth.chunk.get(i);
// Compare string values ..
FeatureNode sfthis = fthis.get("orig_str");
FeatureNode sfoth = foth.get("orig_str");
// If they are *both* null, that's OK, e.g. "New York"
if (!(sfthis == null && sfoth == null))
{
if (sfthis == null || sfoth == null) return false;
String sthis = sfthis.getValue();
String soth = sfoth.getValue();
if (!sthis.equals(soth)) return false;
}
// Make sure that the location in the sentence matches also.
FeatureNode tstart = fthis.get("start_char");
FeatureNode ostart = foth.get("start_char");
String st = tstart.getValue();
String ot = ostart.getValue();
if (st == null || ot == null) return false;
if (!st.equals(ot)) return false;
}
return true;
}
/**
* A very simple output routine. It is meant to provide
* common-sense, human readable output, rahter than a fixed,
* computer-paraable format. It is subject to change from one
* relex release to another.
*/
public String toString()
{
// First, print out the phrase itself.
String str = "Phrase: (";
for (int i=0; i<chunk.size(); i++)
{
FeatureNode fn = chunk.get(i);
// FeatureNode sf = fn.get("str");
FeatureNode sf = fn.get("orig_str");
if (sf != null)
{
if (i != 0) str += " ";
str += sf.getValue();
}
}
str += ")";
// Next, print out the character ranges.
str += " Character ranges: ";
int chunk_start = -1;
int chunk_end = -1;
for (int i=0; i<chunk.size(); i++)
{
FeatureNode fn = chunk.get(i);
// FeatureNode sf = fn.get("str");
FeatureNode sf = fn.get("orig_str");
if (sf != null)
{
FeatureNode start = fn.get("start_char");
FeatureNode orig = fn.get("orig_str");
String st = start.getValue();
String or = orig.getValue();
if (st == null || or == null)
{
System.err.println("Error: chunk is missing feature nodes");
continue;
}
int ist = Integer.parseInt(st);
int len = or.length();
int end = ist+len;
if (chunk_start < 0)
{
chunk_start = ist;
chunk_end = end;
}
else if (ist <= chunk_end+1)
{
chunk_end = end;
}
else
{
str += "["+ chunk_start + "-" + chunk_end + "]";
chunk_start = ist;
chunk_end = end;
}
}
}
if (0 <= chunk_start)
{
str += "["+ chunk_start + "-" + chunk_end + "]";
}
return str;
}
}
| src/java/relex/chunk/LexChunk.java | /*
* Copyright 2008 Novamente LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package relex.chunk;
import java.util.ArrayList;
import relex.feature.FeatureNode;
import relex.feature.WordFeature;
import relex.feature.Chunk;
/**
* Holder of lexical chunks
*
* Copyright (C) 2008 Linas Vepstas <[email protected]>
*/
public class LexChunk extends Chunk
{
private static final long serialVersionUID = 8648176749497688526L;
public void addWord(FeatureNode fn)
{
if (WordFeature.isPunctuation(fn)) return;
chunk.add(fn);
}
public void addWords(ArrayList<FeatureNode> words)
{
addNodes(words);
}
/**
* Return true if the other object equals this one, else return false.
* Equals, in the comp-sci sense (e.g. scheme or lisp): compares
* structure to determine if they have congruent structure.
* For lexical object, this means "the same words", and nothing more.
* In particular, equality of the associated truth values is ignored.
*/
public boolean equals(Object other)
{
if (!(other instanceof LexChunk)) return false;
LexChunk oth = (LexChunk) other;
if (oth.chunk.size() != chunk.size()) return false;
for (int i=0; i<chunk.size(); i++)
{
FeatureNode fthis = chunk.get(i);
FeatureNode foth = oth.chunk.get(i);
// Compare string values ..
FeatureNode sfthis = fthis.get("orig_str");
FeatureNode sfoth = foth.get("orig_str");
if (sfthis == null || sfoth == null) return false;
String sthis = sfthis.getValue();
String soth = sfoth.getValue();
if (!sthis.equals(soth)) return false;
// Make sure that the location in the sentence matches also.
FeatureNode tstart = fthis.get("start_char");
FeatureNode ostart = foth.get("start_char");
String st = tstart.getValue();
String ot = ostart.getValue();
if (st == null || ot == null) return false;
if (!st.equals(ot)) return false;
}
return true;
}
/**
* A very simple output routine. It is meant to provide
* common-sense, human readable output, rahter than a fixed,
* computer-paraable format. It is subject to change from one
* relex release to another.
*/
public String toString()
{
// First, print out the phrase itself.
String str = "Phrase: (";
for (int i=0; i<chunk.size(); i++)
{
FeatureNode fn = chunk.get(i);
// FeatureNode sf = fn.get("str");
FeatureNode sf = fn.get("orig_str");
if (sf != null)
{
if (i != 0) str += " ";
str += sf.getValue();
}
}
str += ")";
// Next, print out the character ranges.
str += " Character ranges: ";
int chunk_start = -1;
int chunk_end = -1;
for (int i=0; i<chunk.size(); i++)
{
FeatureNode fn = chunk.get(i);
// FeatureNode sf = fn.get("str");
FeatureNode sf = fn.get("orig_str");
if (sf != null)
{
FeatureNode start = fn.get("start_char");
FeatureNode orig = fn.get("orig_str");
String st = start.getValue();
String or = orig.getValue();
if (st == null || or == null)
{
System.err.println("Error: chunk is missing feature nodes");
continue;
}
int ist = Integer.parseInt(st);
int len = or.length();
int end = ist+len;
if (chunk_start < 0)
{
chunk_start = ist;
chunk_end = end;
}
else if (ist <= chunk_end+1)
{
chunk_end = end;
}
else
{
str += "["+ chunk_start + "-" + chunk_end + "]";
chunk_start = ist;
chunk_end = end;
}
}
}
if (0 <= chunk_start)
{
str += "["+ chunk_start + "-" + chunk_end + "]";
}
return str;
}
}
| fix up chunk comparison for entities which get cotracted,
e.g. "New York" gets lumped together.
| src/java/relex/chunk/LexChunk.java | fix up chunk comparison for entities which get cotracted, e.g. "New York" gets lumped together. | <ide><path>rc/java/relex/chunk/LexChunk.java
<ide> // Compare string values ..
<ide> FeatureNode sfthis = fthis.get("orig_str");
<ide> FeatureNode sfoth = foth.get("orig_str");
<del> if (sfthis == null || sfoth == null) return false;
<del> String sthis = sfthis.getValue();
<del> String soth = sfoth.getValue();
<del> if (!sthis.equals(soth)) return false;
<add>
<add> // If they are *both* null, that's OK, e.g. "New York"
<add> if (!(sfthis == null && sfoth == null))
<add> {
<add> if (sfthis == null || sfoth == null) return false;
<add> String sthis = sfthis.getValue();
<add> String soth = sfoth.getValue();
<add> if (!sthis.equals(soth)) return false;
<add> }
<ide>
<ide> // Make sure that the location in the sentence matches also.
<ide> FeatureNode tstart = fthis.get("start_char"); |
|
JavaScript | mit | b3ca5f2db78b126d2425af7cd7b463dfc8a0d402 | 0 | viettrung9012/hans-plan,viettrung9012/hans-plan | apiCall = function (method, apiUrl, options) {
try {
var response = HTTP.call(method, apiUrl, options).data;
return response;
} catch (error) {
console.log(error);
var errorCode = 500,
errorMessage = 'Cannot access the API';
if (error.response) {
errorCode = error.response.data.code;
errorMessage = error.response.data.message;
}
var myError = new Meteor.Error(errorCode, errorMessage);
return myError;
}
};
| server/externals/helpers/api_call.js | apiCall = function (method, apiUrl, options) {
try {
var response = HTTP.call(method, apiUrl, options).data;
return response;
} catch (error) {
var errorCode = 500,
errorMessage = 'Cannot access the API';
if (error.response) {
errorCode = error.response.data.code;
errorMessage = error.response.data.message;
}
var myError = new Meteor.Error(errorCode, errorMessage);
return myError;
}
};
| Add console log for original error from http request
| server/externals/helpers/api_call.js | Add console log for original error from http request | <ide><path>erver/externals/helpers/api_call.js
<ide> var response = HTTP.call(method, apiUrl, options).data;
<ide> return response;
<ide> } catch (error) {
<add> console.log(error);
<ide> var errorCode = 500,
<ide> errorMessage = 'Cannot access the API';
<ide> if (error.response) { |
|
Java | apache-2.0 | be28b266d5d85a24f846d1978fc46b9ae1565a93 | 0 | fenik17/netty,artgon/netty,netty/netty,artgon/netty,doom369/netty,ejona86/netty,netty/netty,ejona86/netty,Spikhalskiy/netty,artgon/netty,fenik17/netty,netty/netty,NiteshKant/netty,zer0se7en/netty,Spikhalskiy/netty,doom369/netty,zer0se7en/netty,tbrooks8/netty,zer0se7en/netty,johnou/netty,fenik17/netty,johnou/netty,NiteshKant/netty,ejona86/netty,Spikhalskiy/netty,johnou/netty,tbrooks8/netty,fenik17/netty,andsel/netty,andsel/netty,NiteshKant/netty,andsel/netty,artgon/netty,ejona86/netty,netty/netty,ejona86/netty,Spikhalskiy/netty,artgon/netty,fenik17/netty,zer0se7en/netty,johnou/netty,andsel/netty,tbrooks8/netty,doom369/netty,NiteshKant/netty,zer0se7en/netty,tbrooks8/netty,doom369/netty,tbrooks8/netty,doom369/netty,johnou/netty,NiteshKant/netty,Spikhalskiy/netty,netty/netty,andsel/netty | /*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.json;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.channel.ChannelPipeline;
import java.util.List;
/**
* Splits a byte stream of JSON objects and arrays into individual objects/arrays and passes them up the
* {@link ChannelPipeline}.
* <p>
* The byte stream is expected to be in UTF-8 character encoding or ASCII. The current implementation
* uses direct {@code byte} to {@code char} cast and then compares that {@code char} to a few low range
* ASCII characters like {@code '{'}, {@code '['} or {@code '"'}. UTF-8 is not using low range [0..0x7F]
* byte values for multibyte codepoint representations therefore fully supported by this implementation.
* <p>
* This class does not do any real parsing or validation. A sequence of bytes is considered a JSON object/array
* if it contains a matching number of opening and closing braces/brackets. It's up to a subsequent
* {@link ChannelHandler} to parse the JSON text into a more usable form i.e. a POJO.
*/
public class JsonObjectDecoder extends ByteToMessageDecoder {
private static final int ST_CORRUPTED = -1;
private static final int ST_INIT = 0;
private static final int ST_DECODING_NORMAL = 1;
private static final int ST_DECODING_ARRAY_STREAM = 2;
private int openBraces;
private int idx;
private int lastReaderIndex;
private int state;
private boolean insideString;
private final int maxObjectLength;
private final boolean streamArrayElements;
public JsonObjectDecoder() {
// 1 MB
this(1024 * 1024);
}
public JsonObjectDecoder(int maxObjectLength) {
this(maxObjectLength, false);
}
public JsonObjectDecoder(boolean streamArrayElements) {
this(1024 * 1024, streamArrayElements);
}
/**
* @param maxObjectLength maximum number of bytes a JSON object/array may use (including braces and all).
* Objects exceeding this length are dropped and an {@link TooLongFrameException}
* is thrown.
* @param streamArrayElements if set to true and the "top level" JSON object is an array, each of its entries
* is passed through the pipeline individually and immediately after it was fully
* received, allowing for arrays with "infinitely" many elements.
*
*/
public JsonObjectDecoder(int maxObjectLength, boolean streamArrayElements) {
if (maxObjectLength < 1) {
throw new IllegalArgumentException("maxObjectLength must be a positive int");
}
this.maxObjectLength = maxObjectLength;
this.streamArrayElements = streamArrayElements;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (state == ST_CORRUPTED) {
in.skipBytes(in.readableBytes());
return;
}
if (this.idx > in.readerIndex() && lastReaderIndex != in.readerIndex()) {
this.idx = in.readerIndex() + (idx - lastReaderIndex);
}
// index of next byte to process.
int idx = this.idx;
int wrtIdx = in.writerIndex();
if (wrtIdx > maxObjectLength) {
// buffer size exceeded maxObjectLength; discarding the complete buffer.
in.skipBytes(in.readableBytes());
reset();
throw new TooLongFrameException(
"object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
}
for (/* use current idx */; idx < wrtIdx; idx++) {
byte c = in.getByte(idx);
if (state == ST_DECODING_NORMAL) {
decodeByte(c, in, idx);
// All opening braces/brackets have been closed. That's enough to conclude
// that the JSON object/array is complete.
if (openBraces == 0) {
ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
if (json != null) {
out.add(json);
}
// The JSON object/array was extracted => discard the bytes from
// the input buffer.
in.readerIndex(idx + 1);
// Reset the object state to get ready for the next JSON object/text
// coming along the byte stream.
reset();
}
} else if (state == ST_DECODING_ARRAY_STREAM) {
decodeByte(c, in, idx);
if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
// skip leading spaces. No range check is needed and the loop will terminate
// because the byte at position idx is not a whitespace.
for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
in.skipBytes(1);
}
// skip trailing spaces.
int idxNoSpaces = idx - 1;
while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
idxNoSpaces--;
}
ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
if (json != null) {
out.add(json);
}
in.readerIndex(idx + 1);
if (c == ']') {
reset();
}
}
// JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
} else if (c == '{' || c == '[') {
initDecoding(c);
if (state == ST_DECODING_ARRAY_STREAM) {
// Discard the array bracket
in.skipBytes(1);
}
// Discard leading spaces in front of a JSON object/array.
} else if (Character.isWhitespace(c)) {
in.skipBytes(1);
} else {
state = ST_CORRUPTED;
throw new CorruptedFrameException(
"invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
}
}
if (in.readableBytes() == 0) {
this.idx = 0;
} else {
this.idx = idx;
}
this.lastReaderIndex = in.readerIndex();
}
/**
* Override this method if you want to filter the json objects/arrays that get passed through the pipeline.
*/
@SuppressWarnings("UnusedParameters")
protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
return buffer.retainedSlice(index, length);
}
private void decodeByte(byte c, ByteBuf in, int idx) {
if ((c == '{' || c == '[') && !insideString) {
openBraces++;
} else if ((c == '}' || c == ']') && !insideString) {
openBraces--;
} else if (c == '"') {
// start of a new JSON string. It's necessary to detect strings as they may
// also contain braces/brackets and that could lead to incorrect results.
if (!insideString) {
insideString = true;
} else {
int backslashCount = 0;
idx--;
while (idx >= 0) {
if (in.getByte(idx) == '\\') {
backslashCount++;
idx--;
} else {
break;
}
}
// The double quote isn't escaped only if there are even "\"s.
if (backslashCount % 2 == 0) {
// Since the double quote isn't escaped then this is the end of a string.
insideString = false;
}
}
}
}
private void initDecoding(byte openingBrace) {
openBraces = 1;
if (openingBrace == '[' && streamArrayElements) {
state = ST_DECODING_ARRAY_STREAM;
} else {
state = ST_DECODING_NORMAL;
}
}
private void reset() {
insideString = false;
state = ST_INIT;
openBraces = 0;
}
}
| codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java | /*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.json;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.channel.ChannelPipeline;
import java.util.List;
/**
* Splits a byte stream of JSON objects and arrays into individual objects/arrays and passes them up the
* {@link ChannelPipeline}.
* <p>
* The byte stream is expected to be in UTF-8 character encoding or ASCII. The current implementation
* uses direct {@code byte} to {@code char} cast and then compares that {@code char} to a few low range
* ASCII characters like {@code '{'}, {@code '['} or {@code '"'}. UTF-8 is not using low range [0..0x7F]
* byte values for multibyte codepoint representations therefore fully supported by this implementation.
* <p>
* This class does not do any real parsing or validation. A sequence of bytes is considered a JSON object/array
* if it contains a matching number of opening and closing braces/brackets. It's up to a subsequent
* {@link ChannelHandler} to parse the JSON text into a more usable form i.e. a POJO.
*/
public class JsonObjectDecoder extends ByteToMessageDecoder {
private static final int ST_CORRUPTED = -1;
private static final int ST_INIT = 0;
private static final int ST_DECODING_NORMAL = 1;
private static final int ST_DECODING_ARRAY_STREAM = 2;
private int openBraces;
private int idx;
private int lastReaderIndex;
private int state;
private boolean insideString;
private final int maxObjectLength;
private final boolean streamArrayElements;
public JsonObjectDecoder() {
// 1 MB
this(1024 * 1024);
}
public JsonObjectDecoder(int maxObjectLength) {
this(maxObjectLength, false);
}
public JsonObjectDecoder(boolean streamArrayElements) {
this(1024 * 1024, streamArrayElements);
}
/**
* @param maxObjectLength maximum number of bytes a JSON object/array may use (including braces and all).
* Objects exceeding this length are dropped and an {@link TooLongFrameException}
* is thrown.
* @param streamArrayElements if set to true and the "top level" JSON object is an array, each of its entries
* is passed through the pipeline individually and immediately after it was fully
* received, allowing for arrays with "infinitely" many elements.
*
*/
public JsonObjectDecoder(int maxObjectLength, boolean streamArrayElements) {
if (maxObjectLength < 1) {
throw new IllegalArgumentException("maxObjectLength must be a positive int");
}
this.maxObjectLength = maxObjectLength;
this.streamArrayElements = streamArrayElements;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (state == ST_CORRUPTED) {
in.skipBytes(in.readableBytes());
return;
}
if (this.idx > in.readerIndex() && lastReaderIndex != in.readerIndex()) {
this.idx = in.readerIndex() + (idx - lastReaderIndex);
}
// index of next byte to process.
int idx = this.idx;
int wrtIdx = in.writerIndex();
if (wrtIdx > maxObjectLength) {
// buffer size exceeded maxObjectLength; discarding the complete buffer.
in.skipBytes(in.readableBytes());
reset();
throw new TooLongFrameException(
"object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
}
for (/* use current idx */; idx < wrtIdx; idx++) {
byte c = in.getByte(idx);
if (state == ST_DECODING_NORMAL) {
decodeByte(c, in, idx);
// All opening braces/brackets have been closed. That's enough to conclude
// that the JSON object/array is complete.
if (openBraces == 0) {
ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
if (json != null) {
out.add(json);
}
// The JSON object/array was extracted => discard the bytes from
// the input buffer.
in.readerIndex(idx + 1);
// Reset the object state to get ready for the next JSON object/text
// coming along the byte stream.
reset();
}
} else if (state == ST_DECODING_ARRAY_STREAM) {
decodeByte(c, in, idx);
if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
// skip leading spaces. No range check is needed and the loop will terminate
// because the byte at position idx is not a whitespace.
for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
in.skipBytes(1);
}
// skip trailing spaces.
int idxNoSpaces = idx - 1;
while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
idxNoSpaces--;
}
ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
if (json != null) {
out.add(json);
}
in.readerIndex(idx + 1);
if (c == ']') {
reset();
}
}
// JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
} else if (c == '{' || c == '[') {
initDecoding(c);
if (state == ST_DECODING_ARRAY_STREAM) {
// Discard the array bracket
in.skipBytes(1);
}
// Discard leading spaces in front of a JSON object/array.
} else if (Character.isWhitespace(c)) {
in.skipBytes(1);
} else {
state = ST_CORRUPTED;
throw new CorruptedFrameException(
"invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
}
}
if (in.readableBytes() == 0) {
this.idx = 0;
} else {
this.idx = idx;
}
this.lastReaderIndex = in.readerIndex();
}
/**
* Override this method if you want to filter the json objects/arrays that get passed through the pipeline.
*/
@SuppressWarnings("UnusedParameters")
protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
return buffer.retainedSlice(index, length);
}
private void decodeByte(byte c, ByteBuf in, int idx) {
if ((c == '{' || c == '[') && !insideString) {
openBraces++;
} else if ((c == '}' || c == ']') && !insideString) {
openBraces--;
} else if (c == '"') {
// start of a new JSON string. It's necessary to detect strings as they may
// also contain braces/brackets and that could lead to incorrect results.
if (!insideString) {
insideString = true;
} else {
int backslashCount = 0;
idx--;
while (idx >= 0) {
if (in.getByte(idx) == '\\') {
backslashCount++;
idx--;
} else {
break;
}
}
// The double quote isn't escaped only if there are even "\"s.
if (backslashCount % 2 == 0) {
// Since the double quote isn't escaped then this is the end of a string.
insideString = false;
}
}
}
}
private void initDecoding(byte openingBrace) {
openBraces = 1;
if (openingBrace == '[' && streamArrayElements) {
state = ST_DECODING_ARRAY_STREAM;
} else {
state = ST_DECODING_NORMAL;
}
}
private void reset() {
insideString = false;
state = ST_INIT;
openBraces = 0;
}
}
| Remove unused import in JsonObjectDecoder.java (#10213)
Motivation:
`io.netty.channel.ChannelHandler` is never used in JsonObjectDecoder.java.
Modification:
Just remove this unused import.
Result:
Make the JsonObjectDecoder.java's imports simple and clean.
| codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java | Remove unused import in JsonObjectDecoder.java (#10213) | <ide><path>odec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java
<ide> import io.netty.buffer.ByteBufUtil;
<ide> import io.netty.channel.ChannelHandlerContext;
<ide> import io.netty.handler.codec.ByteToMessageDecoder;
<del>import io.netty.channel.ChannelHandler;
<ide> import io.netty.handler.codec.CorruptedFrameException;
<ide> import io.netty.handler.codec.TooLongFrameException;
<ide> import io.netty.channel.ChannelPipeline; |
|
JavaScript | mit | 360309ede5891dc0ed7d9aba28219c515cc97b4a | 0 | muescha/hutmap,muescha/hutmap,dylanfprice/hutmap,muescha/hutmap,dylanfprice/hutmap,muescha/hutmap,dylanfprice/hutmap,dylanfprice/hutmap | 'use strict';
(function () {
angular.module('google-maps').
/**
* Directive controller which is owned by the googleMap directive and shared
* among all other google maps directives.
*/
factory('googleMapControllerFactory', ['googleMapsUtils', 'googleMapsDefaults', 'googleMapsContainer',
function (googleMapsUtils, googleMapsDefaults, googleMapsContainer) {
/** aliases */
var latLngEqual = googleMapsUtils.latLngEqual;
var boundsEqual = googleMapsUtils.boundsEqual;
var latLngToObj = googleMapsUtils.latLngToObj;
var hasNaN = googleMapsUtils.hasNaN;
var gMDefaults = googleMapsDefaults;
var gMContainer = googleMapsContainer;
/** MapController class **/
/*
* Construct a new controller for the googleMap directive.
* @param {angular.Scope} $scope
* @param {angular.element} $element
* @param {angular.Attributes} $attrs
* @constructor
*/
var MapController = function($scope, $element, $attrs) {
var mapId = $attrs.mapId;
if (!mapId) { throw 'googleMap must have non-empty mapId attribute'; }
var mapDiv = $element.find('[id]');
mapDiv.attr('id', mapId);
var config = this._getConfig($scope, gMDefaults);
// 'private' properties
this._map = this._createMap(mapId, mapDiv, config, gMContainer);
this._markers = {};
// 'public' properties
this.dragging = false;
Object.defineProperties(this, {
'precision': {
value: MapController.precision,
writeable: false,
},
'center': {
configurable: true, // for testing so we can mock
get: function() {
return this._map.getCenter();
},
set: function(center) {
if (hasNaN(center))
throw 'center contains null or NaN';
var changed = !latLngEqual(this.center, center);
if (changed) {
// TODO: change to panTo
//this._map.setCenter(center);
this._map.panTo(center);
}
}
},
'zoom': {
configurable: true, // for testing so we can mock
get: function() {
return this._map.getZoom();
},
set: function(zoom) {
if (!(zoom != null && !isNaN(zoom)))
throw 'zoom was null or NaN';
var changed = this.zoom !== zoom;
if (changed) {
this._map.setZoom(zoom);
}
}
},
'bounds': {
configurable: true, // for testing so we can mock
get: function() {
return this._map.getBounds();
},
set: function(bounds) {
var numbers = !hasNaN(bounds.getSouthWest()) &&
!hasNaN(bounds.getNorthEast());
if (!numbers)
throw 'bounds contains null or NaN';
var changed = !(boundsEqual(this.bounds, bounds));
if (changed) {
this._map.fitBounds(bounds);
}
}
}
});
this._initDragListeners();
};
// used for hashing marker objects
MapController.precision = 3;
// Retrieve google.maps.MapOptions
MapController.prototype._getConfig = function($scope, gMDefaults) {
// Get config or defaults
var defaults = gMDefaults.mapOptions;
var config = {};
angular.extend(config, defaults, $scope.mapOptions());
return config;
};
// Create the map and add to googleMapsContainer
MapController.prototype._createMap = function(id, element, config, gMContainer) {
var map = gMContainer.getMap(id);
if (!map) {
map = new google.maps.Map(element[0], config);
gMContainer.addMap(id, map);
} else {
throw 'A map with id ' + id + ' already exists. You must use' +
' different ids for each instance of the googleMap directive.';
}
return map;
};
// Set up listeners to update this.dragging
MapController.prototype._initDragListeners = function() {
var self = this;
this.addMapListener('dragstart', function () {
self.dragging = true;
});
this.addMapListener('idle', function () {
self.dragging = false;
});
this.addMapListener('drag', function() {
self.dragging = true;
});
};
/**
* Alias for google.maps.event.addListener(map, event, handler)
* @param {string} event an event defined on google.maps.Map
* @param {function} a handler for the event
*/
MapController.prototype.addMapListener = function(event, handler) {
google.maps.event.addListener(this._map,
event, handler);
};
/**
* Alias for google.maps.event.addListenerOnce(map, event, handler)
* @param {string} event an event defined on google.maps.Map
* @param {function} a handler for the event
*/
MapController.prototype.addMapListenerOnce = function(event, handler) {
google.maps.event.addListenerOnce(this._map,
event, handler);
};
/**
* Alias for google.maps.event.addListener(object, event, handler)
*/
MapController.prototype.addListener = function(object, event, handler) {
google.maps.event.addListener(object, event, handler);
};
/**
* Alias for google.maps.event.addListenerOnce(object, event, handler)
*/
MapController.prototype.addListenerOnce = function(object, event, handler) {
google.maps.event.addListenerOnce(object, event, handler);
};
/**
* Adds a new marker to the map.
* @param {google.maps.MarkerOptions} markerOptions
* @return {boolean} true if a marker was added, false if there was already
* a marker at this position. 'at this position' means delta_lat and
* delta_lng are < 0.0005
* @throw if markerOptions does not have all required options (i.e. position)
*/
MapController.prototype.addMarker = function(markerOptions) {
var opts = {};
angular.extend(opts, markerOptions);
if (!(opts.position instanceof google.maps.LatLng)) {
throw 'markerOptions did not contain a position';
}
var marker = new google.maps.Marker(opts);
var position = marker.getPosition();
if (this.hasMarker(position.lat(), position.lng())) {
return false;
}
var hash = position.toUrlValue(this.precision);
this._markers[hash] = marker;
marker.setMap(this._map);
return true;
};
/**
* @param {number} lat
* @param {number} lng
* @return {boolean} true if there is a marker with the given lat and lng
*/
MapController.prototype.hasMarker = function(lat, lng) {
return (this.getMarker(lat, lng) instanceof google.maps.Marker);
};
/**
* @param {number} lat
* @param {number} lng
* @return {google.maps.Marker} the marker at given lat and lng, or null if
* no such marker exists
*/
MapController.prototype.getMarker = function (lat, lng) {
if (lat == null || lng == null)
throw 'lat or lng was null';
var latLng = new google.maps.LatLng(lat, lng);
var hash = latLng.toUrlValue(this.precision);
if (hash in this._markers) {
return this._markers[hash];
} else {
return null;
}
};
/**
* @param {number} lat
* @param {number} lng
* @return {boolean} true if a marker was removed, false if nothing
* happened
*/
MapController.prototype.removeMarker = function(lat, lng) {
if (lat == null || lng == null)
throw 'lat or lng was null';
var latLng = new google.maps.LatLng(lat, lng);
var removed = false;
var hash = latLng.toUrlValue(this.precision);
var marker = this._markers[hash];
if (marker) {
marker.setMap(null);
removed = true;
}
this._markers[hash] = null;
return removed;
};
/**
* Changes bounds of map to view all markers.
*
* Note: after calling this function, this.bounds, this.center, and
* this.zoom may temporarily be null as the map moves. Therefore, use
* this.addMapListenerOnce if you need to access these values immediately
* after calling fitToMarkers.
*/
MapController.prototype.fitToMarkers = function () {
var bounds = new google.maps.LatLngBounds();
this.forEachMarker(function(marker) {
bounds.extend(marker.getPosition());
});
this._map.fitBounds(bounds);
};
/**
* Applies a function to each marker.
* @param {function} fn will called with marker as first argument
* @throw if fn is null or undefined
*/
MapController.prototype.forEachMarker = function(fn) {
if (fn == null) { throw 'fn was null or undefined'; };
angular.forEach(this._markers, function(marker, hash) {
fn(marker);
});
};
return {
MapController: MapController
};
}]);
})();
| src/js/google-maps/directives/googleMapControllerFactory.js | 'use strict';
(function () {
angular.module('google-maps').
/**
* Directive controller which is owned by the googleMap directive and shared
* among all other google maps directives.
*/
factory('googleMapControllerFactory', ['googleMapsUtils', 'googleMapsDefaults', 'googleMapsContainer',
function (googleMapsUtils, googleMapsDefaults, googleMapsContainer) {
/** aliases */
var latLngEqual = googleMapsUtils.latLngEqual;
var boundsEqual = googleMapsUtils.boundsEqual;
var latLngToObj = googleMapsUtils.latLngToObj;
var hasNaN = googleMapsUtils.hasNaN;
var gMDefaults = googleMapsDefaults;
var gMContainer = googleMapsContainer;
/** MapController class **/
/*
* Construct a new controller for the googleMap directive.
* @param {angular.Scope} $scope
* @param {angular.element} $element
* @param {angular.Attributes} $attrs
* @constructor
*/
var MapController = function($scope, $element, $attrs) {
var mapId = $attrs.mapId;
if (!mapId) { throw 'googleMap must have non-empty mapId attribute'; }
var mapDiv = $element.find('[id]');
mapDiv.attr('id', mapId);
var config = this._getConfig($scope, gMDefaults);
// 'private' properties
this._map = this._createMap(mapId, mapDiv, config, gMContainer);
this._markers = {};
// 'public' properties
this.dragging = false;
Object.defineProperties(this, {
'precision': {
value: MapController.precision,
writeable: false,
},
'center': {
get: function() {
return this._map.getCenter();
},
set: function(center) {
if (hasNaN(center))
throw 'center contains null or NaN';
var changed = !latLngEqual(this.center, center);
if (changed) {
// TODO: change to panTo
//this._map.setCenter(center);
this._map.panTo(center);
}
}
},
'zoom': {
get: function() {
return this._map.getZoom();
},
set: function(zoom) {
if (!(zoom != null && !isNaN(zoom)))
throw 'zoom was null or NaN';
var changed = this.zoom !== zoom;
if (changed) {
this._map.setZoom(zoom);
}
}
},
'bounds': {
get: function() {
return this._map.getBounds();
},
set: function(bounds) {
var numbers = !hasNaN(bounds.getSouthWest()) &&
!hasNaN(bounds.getNorthEast());
if (!numbers)
throw 'bounds contains null or NaN';
var changed = !(boundsEqual(this.bounds, bounds));
if (changed) {
this._map.fitBounds(bounds);
}
}
}
});
this._initDragListeners();
};
// used for hashing marker objects
MapController.precision = 3;
// Retrieve google.maps.MapOptions
MapController.prototype._getConfig = function($scope, gMDefaults) {
// Get config or defaults
var defaults = gMDefaults.mapOptions;
var config = {};
angular.extend(config, defaults, $scope.mapOptions());
return config;
};
// Create the map and add to googleMapsContainer
MapController.prototype._createMap = function(id, element, config, gMContainer) {
var map = gMContainer.getMap(id);
if (!map) {
map = new google.maps.Map(element[0], config);
gMContainer.addMap(id, map);
} else {
throw 'A map with id ' + id + ' already exists. You must use' +
' different ids for each instance of the googleMap directive.';
}
return map;
};
// Set up listeners to update this.dragging
MapController.prototype._initDragListeners = function() {
var self = this;
this.addMapListener('dragstart', function () {
self.dragging = true;
});
this.addMapListener('idle', function () {
self.dragging = false;
});
this.addMapListener('drag', function() {
self.dragging = true;
});
};
/**
* Alias for google.maps.event.addListener(map, event, handler)
* @param {string} event an event defined on google.maps.Map
* @param {function} a handler for the event
*/
MapController.prototype.addMapListener = function(event, handler) {
google.maps.event.addListener(this._map,
event, handler);
};
/**
* Alias for google.maps.event.addListenerOnce(map, event, handler)
* @param {string} event an event defined on google.maps.Map
* @param {function} a handler for the event
*/
MapController.prototype.addMapListenerOnce = function(event, handler) {
google.maps.event.addListenerOnce(this._map,
event, handler);
};
/**
* Alias for google.maps.event.addListener(object, event, handler)
*/
MapController.prototype.addListener = function(object, event, handler) {
google.maps.event.addListener(object, event, handler);
};
/**
* Alias for google.maps.event.addListenerOnce(object, event, handler)
*/
MapController.prototype.addListenerOnce = function(object, event, handler) {
google.maps.event.addListenerOnce(object, event, handler);
};
/**
* Adds a new marker to the map.
* @param {google.maps.MarkerOptions} markerOptions
* @return {boolean} true if a marker was added, false if there was already
* a marker at this position. 'at this position' means delta_lat and
* delta_lng are < 0.0005
* @throw if markerOptions does not have all required options (i.e. position)
*/
MapController.prototype.addMarker = function(markerOptions) {
var opts = {};
angular.extend(opts, markerOptions);
if (!(opts.position instanceof google.maps.LatLng)) {
throw 'markerOptions did not contain a position';
}
var marker = new google.maps.Marker(opts);
var position = marker.getPosition();
if (this.hasMarker(position.lat(), position.lng())) {
return false;
}
var hash = position.toUrlValue(this.precision);
this._markers[hash] = marker;
marker.setMap(this._map);
return true;
};
/**
* @param {number} lat
* @param {number} lng
* @return {boolean} true if there is a marker with the given lat and lng
*/
MapController.prototype.hasMarker = function(lat, lng) {
return (this.getMarker(lat, lng) instanceof google.maps.Marker);
};
/**
* @param {number} lat
* @param {number} lng
* @return {google.maps.Marker} the marker at given lat and lng, or null if
* no such marker exists
*/
MapController.prototype.getMarker = function (lat, lng) {
if (lat == null || lng == null)
throw 'lat or lng was null';
var latLng = new google.maps.LatLng(lat, lng);
var hash = latLng.toUrlValue(this.precision);
if (hash in this._markers) {
return this._markers[hash];
} else {
return null;
}
};
/**
* @param {number} lat
* @param {number} lng
* @return {boolean} true if a marker was removed, false if nothing
* happened
*/
MapController.prototype.removeMarker = function(lat, lng) {
if (lat == null || lng == null)
throw 'lat or lng was null';
var latLng = new google.maps.LatLng(lat, lng);
var removed = false;
var hash = latLng.toUrlValue(this.precision);
var marker = this._markers[hash];
if (marker) {
marker.setMap(null);
removed = true;
}
this._markers[hash] = null;
return removed;
};
/**
* Changes bounds of map to view all markers.
*
* Note: after calling this function, this.bounds, this.center, and
* this.zoom may temporarily be null as the map moves. Therefore, use
* this.addMapListenerOnce if you need to access these values immediately
* after calling fitToMarkers.
*/
MapController.prototype.fitToMarkers = function () {
var bounds = new google.maps.LatLngBounds();
this.forEachMarker(function(marker) {
bounds.extend(marker.getPosition());
});
this._map.fitBounds(bounds);
};
/**
* Applies a function to each marker.
* @param {function} fn will called with marker as first argument
* @throw if fn is null or undefined
*/
MapController.prototype.forEachMarker = function(fn) {
if (fn == null) { throw 'fn was null or undefined'; };
angular.forEach(this._markers, function(marker, hash) {
fn(marker);
});
};
return {
MapController: MapController
};
}]);
})();
| Made properties configurable for testing purposes.
--HG--
branch : js-redesign
| src/js/google-maps/directives/googleMapControllerFactory.js | Made properties configurable for testing purposes. | <ide><path>rc/js/google-maps/directives/googleMapControllerFactory.js
<ide> },
<ide>
<ide> 'center': {
<add> configurable: true, // for testing so we can mock
<ide> get: function() {
<ide> return this._map.getCenter();
<ide> },
<ide> },
<ide>
<ide> 'zoom': {
<add> configurable: true, // for testing so we can mock
<ide> get: function() {
<ide> return this._map.getZoom();
<ide> },
<ide> },
<ide>
<ide> 'bounds': {
<add> configurable: true, // for testing so we can mock
<ide> get: function() {
<ide> return this._map.getBounds();
<ide> }, |
|
Java | apache-2.0 | 8a4f103b959ef7f8d1e206a43b83ef268d3800ae | 0 | jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package io.jenetics.prog.op;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static io.jenetics.internal.util.Hashes.hash;
import java.io.Serializable;
import java.util.Objects;
import java.util.function.Supplier;
import io.jenetics.internal.util.Lazy;
/**
* Implementation of an <em>ephemeral</em> constant. It causes the insertion of
* a <em>mutable</em> constant into the operation tree. Every time this terminal
* is chosen a, different value is generated which is then used for that
* particular terminal, and which will remain fixed for the given tree. The main
* usage would be to introduce random terminal values.
*
* <pre>{@code
* final Random random = ...;
* final Op<Double> val = EphemeralConst.of(random::nextDouble);
* }</pre>
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version 4.1
* @since 3.9
*/
public final class EphemeralConst<T> implements Op<T>, Serializable {
private static final long serialVersionUID = 1L;
private final String _name;
private final Supplier<T> _supplier;
private final Lazy<T> _value;
private EphemeralConst(final String name, final Supplier<T> supplier) {
_name = name;
_supplier = requireNonNull(supplier);
_value = Lazy.of(_supplier);
}
@Override
public String name() {
return _name;
}
@Override
public int arity() {
return 0;
}
/**
* Return a newly created, uninitialized constant of type {@code T}.
*
* @return a newly created, uninitialized constant of type {@code T}
*/
@Override
public Op<T> get() {
return new EphemeralConst<>(_name, _supplier);
}
@Override
public T apply(final T[] ts) {
return _value.get();
}
@Override
public int hashCode() {
return hash(_name, hash(_value));
}
@Override
public boolean equals(final Object obj) {
return obj == this ||
obj instanceof EphemeralConst &&
Objects.equals(((EphemeralConst)obj)._name, _name) &&
Objects.equals(((EphemeralConst)obj)._value, _value);
}
@Override
public String toString() {
return _name != null
? format("%s(%s)", _name, _value.get())
: Objects.toString(_value.get());
}
/**
* Create a new ephemeral constant with the given {@code name} and value
* {@code supplier}. For every newly created operation tree, a new constant
* value is chosen for this terminal operation. The value is than kept
* constant for this tree.
*
* @param name the name of the ephemeral constant
* @param supplier the value supplier
* @param <T> the constant type
* @return a new ephemeral constant
* @throws NullPointerException if one of the arguments is {@code null}
*/
public static <T> EphemeralConst<T> of(
final String name,
final Supplier<T> supplier
) {
return new EphemeralConst<>(requireNonNull(name), supplier);
}
/**
* Create a new ephemeral constant with the given value {@code supplier}.
* For every newly created operation tree, a new constant value is chosen
* for this terminal operation. The value is than kept constant for this tree.
*
* @param supplier the value supplier
* @param <T> the constant type
* @return a new ephemeral constant
* @throws NullPointerException if the {@code supplier} is {@code null}
*/
public static <T> EphemeralConst<T> of(final Supplier<T> supplier) {
return new EphemeralConst<>(null, supplier);
}
}
| jenetics.prog/src/main/java/io/jenetics/prog/op/EphemeralConst.java | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author:
* Franz Wilhelmstötter ([email protected])
*/
package io.jenetics.prog.op;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static io.jenetics.internal.util.Hashes.hash;
import java.io.Serializable;
import java.util.Objects;
import java.util.function.Supplier;
import io.jenetics.internal.util.Lazy;
/**
* Implementation of an <em>ephemeral</em> constant. It causes the insertion of
* a <em>mutable</em> constant into the operation tree. Every time this terminal
* is chosen a, different value is generated which is then used for that
* particular terminal, and which will remain fixed for the given tree. The main
* usage would be to introduce random terminal values.
*
* <pre>{@code
* final Random random = ...;
* final Op<Double> val = EphemeralConst.of(random::nextDouble());
* }</pre>
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version 4.1
* @since 3.9
*/
public final class EphemeralConst<T> implements Op<T>, Serializable {
private static final long serialVersionUID = 1L;
private final String _name;
private final Supplier<T> _supplier;
private final Lazy<T> _value;
private EphemeralConst(final String name, final Supplier<T> supplier) {
_name = name;
_supplier = requireNonNull(supplier);
_value = Lazy.of(_supplier);
}
@Override
public String name() {
return _name;
}
@Override
public int arity() {
return 0;
}
/**
* Return a newly created, uninitialized constant of type {@code T}.
*
* @return a newly created, uninitialized constant of type {@code T}
*/
@Override
public Op<T> get() {
return new EphemeralConst<>(_name, _supplier);
}
@Override
public T apply(final T[] ts) {
return _value.get();
}
@Override
public int hashCode() {
return hash(_name, hash(_value));
}
@Override
public boolean equals(final Object obj) {
return obj == this ||
obj instanceof EphemeralConst &&
Objects.equals(((EphemeralConst)obj)._name, _name) &&
Objects.equals(((EphemeralConst)obj)._value, _value);
}
@Override
public String toString() {
return _name != null
? format("%s(%s)", _name, _value.get())
: Objects.toString(_value.get());
}
/**
* Create a new ephemeral constant with the given {@code name} and value
* {@code supplier}. For every newly created operation tree, a new constant
* value is chosen for this terminal operation. The value is than kept
* constant for this tree.
*
* @param name the name of the ephemeral constant
* @param supplier the value supplier
* @param <T> the constant type
* @return a new ephemeral constant
* @throws NullPointerException if one of the arguments is {@code null}
*/
public static <T> EphemeralConst<T> of(
final String name,
final Supplier<T> supplier
) {
return new EphemeralConst<>(requireNonNull(name), supplier);
}
/**
* Create a new ephemeral constant with the given value {@code supplier}.
* For every newly created operation tree, a new constant value is chosen
* for this terminal operation. The value is than kept constant for this tree.
*
* @param supplier the value supplier
* @param <T> the constant type
* @return a new ephemeral constant
* @throws NullPointerException if the {@code supplier} is {@code null}
*/
public static <T> EphemeralConst<T> of(final Supplier<T> supplier) {
return new EphemeralConst<>(null, supplier);
}
}
| Fix Javadoc.
| jenetics.prog/src/main/java/io/jenetics/prog/op/EphemeralConst.java | Fix Javadoc. | <ide><path>enetics.prog/src/main/java/io/jenetics/prog/op/EphemeralConst.java
<ide> *
<ide> * <pre>{@code
<ide> * final Random random = ...;
<del> * final Op<Double> val = EphemeralConst.of(random::nextDouble());
<add> * final Op<Double> val = EphemeralConst.of(random::nextDouble);
<ide> * }</pre>
<ide> *
<ide> * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> |
|
Java | mit | bcfaf32e04a9fe4dfda8a0ea8565aaf1a3edc4c0 | 0 | nbv3/voogasalad_CS308 | package simple.conditions;
import java.util.Collection;
import simple.obj.ISimpleObject;
import simple.obj.SimpleObjectType;
public class PlayerDeathCondition implements ISimpleCondition {
private SimpleConditions type = SimpleConditions.LOSING;
private int playerscounted;
@Override
public boolean isConditionMet() {
return playerscounted <= 0;
}
@Override
public boolean checkObject(Collection<ISimpleObject> universe) {
playerscounted = 0;
for (ISimpleObject object : universe) {
if (object.getType().equals(SimpleObjectType.PLAYER)) {
playerscounted++;
}
}
return isConditionMet();
}
@Override
public SimpleConditions returnType() {
return type;
}
}
| working/simple/conditions/PlayerDeathCondition.java | package simple.conditions;
import java.util.Collection;
import simple.obj.ISimpleObject;
import simple.obj.SimpleObjectType;
public class PlayerDeathCondition implements ISimpleCondition {
private SimpleConditions type = SimpleConditions.LOSING;
private int playerscounted;
@Override
public boolean isConditionMet() {
return playerscounted <= 0;
}
@Override
public boolean checkObject(Collection<ISimpleObject> universe) {
for (ISimpleObject object : universe) {
if (object.getType().equals(SimpleObjectType.PLAYER)) {
playerscounted++;
}
}
return isConditionMet();
}
@Override
public SimpleConditions returnType() {
return type;
}
}
| PlayerDeathCondition bug fixed
| working/simple/conditions/PlayerDeathCondition.java | PlayerDeathCondition bug fixed | <ide><path>orking/simple/conditions/PlayerDeathCondition.java
<ide>
<ide> @Override
<ide> public boolean checkObject(Collection<ISimpleObject> universe) {
<add> playerscounted = 0;
<add>
<ide> for (ISimpleObject object : universe) {
<ide> if (object.getType().equals(SimpleObjectType.PLAYER)) {
<ide> playerscounted++; |
|
Java | mpl-2.0 | a1517eec69dae5020de7706e991d2e84387dd602 | 0 | zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb | /*
* The contents of this file are subject to the MonetDB Public
* License Version 1.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://monetdb.cwi.nl/Legal/MonetDBLicense-1.0.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Monet Database System.
*
* The Initial Developer of the Original Code is CWI.
* Portions created by CWI are Copyright (C) 1997-2004 CWI.
* All Rights Reserved.
*
* Contributor(s):
* Martin Kersten <[email protected]>
* Peter Boncz <[email protected]>
* Niels Nes <[email protected]>
* Stefan Manegold <[email protected]>
*/
/*
The Monet Application Programming Interface
Author M.L. Kersten
The easiest way to extend the functionality of Monet is to construct
an independent Monet application, which communicates with a
running server on a textual basis.
The prime advantage is a secure and debugable interface.
The overhead in command preparation and response decoding is mainly
localized in the workstation of the application.
The Java code base presented here is a 'copy' of the similar C-Mapi interface.
The main differences are that this version does not provide variable
binding to ease interaction.
It is not possible to bind source/destination variables.
Instead, column values should be explicitly extracted from the row cache
and arguments are passed upon query construction.
Furthermore, it uses a simple line-based protocol with the server.
See the corresponding documentation. A synopsis is given only.
bind() & Bind string C-variable to field [NON_JAVA]
bind_var() & Bind typed C-variable to field [NON_JAVA]
bind_numeric() & Bind numeric C-variable to field [NON_JAVA]
cacheLimit() & Set the tuple cache limit
cacheShuffle() & Set the cache shuffle percentage
cacheFreeup() & Empty a fraction of the cache
connect() & Connect to a Mserver
connectSSL() & Connect to a Mserver using SSL [TODO]
disconnect() & Disconnect from server
dup() & Duplicate the connection structure
explain() & Display error message and context on stream
execute() & Execute a query
executeArray() & Execute a query using string arguments
fetchField() & Fetch a field from the current row
fetchFieldArray() & Fetch all fields from the current row
fetchLine() & Retrieve the next line
fetchReset() & Set the cache reader to the begining
fetchRow() & Fetch row of values
fetchAllRows() & Fetch all answers from server into cache
finish() & Terminate the current query
getHost() & Host name of server
getLanguage() & Query language name
getMapiVersion() & Mapi version identifier
getMonetVersion() & Monet version identifier
getMonetId() & Monet version generation number
getUser() & Get current user name
getDBname() & Get current database name
getTable() & Get current table name
getColumnCount()& Number of columns in current row
getColumnName() & Get columns name
getColumnType() & Get columns type
getRowCount() & Number of lines in cache or -1
getTupleCount() & Number of tuples in cache or -1
gotError() & Test for error occurrence
getPort() & Connection IP number
ping() & Test server for accessibility
prepareQuery() & Prepare a query for execution
prepareQueryArray()& Prepare a query for execution using arguments
query() & Send a query for execution
queryArray() & Send a query for execution with arguments
quickQuery() & Send a query for execution
quickQueryArray() & Send a query for execution with arguments
quote() & Escape characters
reconnect() & Restart with a clean session
rows_affected() & Obtain number of rows changed
quickResponse() & Quick pass response to stream
initStream() & Prepare for reading a stream of answers
seekRow() & Move row reader to specific row location in cache
sortColumn() & Sort column by string
timeout() & Set timeout for long-running queries[TODO]
trace() & Set trace flag
traceLog() & Keep log of interaction
unquote() & remove escaped characters
*/
package mapi;
import java.awt.*;
import java.applet.Applet;
import java.applet.*;
import java.io.*;
import java.net.Socket;
public class Mapi
{
public final static int MOK = 0;
public final static int MERROR = -1;
public final static int MEOS = -1;
public final static int MAPIERROR = -4;
public final static char PROMPTBEG= (char) 1;
public final static char PROMPTEND= (char) 2;
static final int MAPIBLKSIZE = 1024;
// public final int SQL_AUTO =0; /* automatic type detection */
// public final int SQL_INT =1;
// public final int SQL_LONG =2;
// public final int SQL_CHAR =3;
// public final int SQL_VARCHAR =4;
// public final int SQL_FLOAT =5;
// public final int SQL_DOUBLE =6;
// public final int SQL_TIME =7;
// public final int SQL_DATE =8;
// public final int SQL_NUMERIC =9;
public final int LANG_MAL =0;
public final int LANG_MIL =1;
public final int LANG_SQL =2;
public final int LANG_XCORE =3;
public final int LANG_XQUERY =4;
public final String PLACEHOLDER ="?";
private String version;
private String mapiversion;
private boolean blocked= false;
private String host = "localhost";
private int port = 50001;
private String username= "anonymous";
private String password="";
private String language= "mil";
private int languageId= LANG_MAL;
private String dbname= "unknown";
private boolean everything = false;
private boolean trace = false;
private boolean connected= false;
private boolean active= false;
private boolean eos = false;
// CacheBlock cache;
IoCache blk= new IoCache();
private int error = MOK;
private String errortext="";
private String action="";
private String query;
private int tableid = -1;
private String qrytemplate;
private String prompt;
// Tabular cache
private int fieldcnt= 1;
private int maxfields= 32;
private int minfields= 0;
private int rows_affected =0;
private RowCache cache= new RowCache();
private Column columns[]= new Column[32];
private Socket socket;
private DataOutputStream toMonet;
//private DataInputStream fromMonet;
private BufferedReader fromMonet;
private PrintStream traceLog = System.err;
private void check(String action){
if( !connected) setError("Connection lost",action);
clrError();
}
/*
The static method hostname gets the hostname from the monetport. The
monetport is defined by 'hostname:portnr'. The static method
portnr will return the port number in this string.
*/
private String hostname( String monetport ){
int pos = monetport.indexOf(':');
if (pos <= 1) return host;
return host= monetport.substring( 0,pos);
}
private int portnr( String monetport ){
int pos = monetport.indexOf(':');
if (pos >= 0 && pos < monetport.length()){
return port=Integer.parseInt(monetport.substring( pos+1 ));
}
return port;
}
// To make life of front-end easier they may call for
// properties to be understood by each running server.
// The actual parameter settings may at a later stage
// be obtained from some system configuration file/ Mguardian
public String getDefaultHost(){ return "localhost";}
public int getDefaultPort(){ return 50000;}
public String getDefaultLanguage(){ return "mil";}
public Mapi(){}
public Mapi( String host, int port, String user, String pwd, String lang)
throws MapiException
{
connect(host,port,user,pwd,lang);
}
//------------------ The actual implementation ---------
/**
* the default communication mode is current line-based
* a future version should also support the more efficient block mode
*/
public void setBlocking(boolean f){
blocked= f;
}
/**
* Toggle the debugging flag for the Mapi interface library
* @param flg the new value
*/
public void trace(boolean flg){
check("trace");
trace= flg;
}
/**
* Open a file to keep a log of the interaction between client and server.
* @param fnme the file name
*/
public void traceLog(String fnme){
check("traceLog");
try {
traceLog = new PrintStream(new FileOutputStream(fnme),true);
} catch(Exception e) {
System.err.println("!ERROR:setTraceLog:couldn't open:"+fnme);
}
}
public void traceLog(PrintStream f){
check("traceLog");
if (f!=null)
traceLog = f;
}
/**
* This method can be used to test for the lifelyness of the database server.
* it creates a new connection and leaves it immediately
* This call is relatively expensive.
* @return the boolean indicating success of failure
*/
public boolean ping(){
//if( language.equals("mal")) query("print(1);");
check("ping");
try{
Mapi m= new Mapi(this);
if(m.gotError())
return false;
m.disconnect();
} catch(MapiException e2){
return false;
}
return true;
}
/**
* This method can be used to set the Mapi descriptor once an error
* has been detected.
* @return the MAPI internal success/failure indicator
*/
private int setError(String msg, String act){
errortext= msg;
error= MERROR;
action= act;
return MERROR;
}
/**
* This method can be used to clear the Mapi error descriptor properties.
*/
private void clrError(){
errortext="";
error= MOK;
action="";
}
/**
* This method can be used to connect to a running server.
* The user can indicate any of the supported query languages, e.g.
* MIL, MAL, or SQL.
* The method throws an exception when a basic IO error is detected.
* @param host - a hostname, e.g. monetdb.cwi.nl
* port - the port to which the server listens, e.g. 50001
* user - user name, defaults to "anonymous"
* pwd - password, defaults to none
* lang - language interpretation required
*/
public Mapi connect( String host, int port, String user, String pwd, String lang )
throws MapiException
{
error = MOK;
this.host =host;
this.port = port;
connected= false;
try{
if(trace)
traceLog.println("setup socket "+host+":"+port);
socket = new Socket( host, port );
fromMonet= new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//fromMonet= new DataInputStream(socket.getInputStream());
toMonet= new DataOutputStream(socket.getOutputStream());
connected = true;
} catch(IOException e) {
error= MERROR;
errortext= "Failed to establish contact\n" ;
throw new MapiException( errortext );
}
if( pwd==null ) pwd="";
blocked=false;
this.mapiversion= "1.0";
this.username= user;
this.password = pwd;
this.active = true;
if(trace) traceLog.println("sent initialization command");
if( pwd.length()>0) pwd= ":"+pwd;
if( blocked)
toMonet(user+pwd+":blocked\n");
else toMonet(user+pwd+"\n");
/*
The rendezvous between client application and server requires
some care. The general approach is to expect a property table
from the server upon succesful connection. An example feedback is:
[ "version", "4.3.12" ]
[ "language", "sql" ]
[ "dbname", "db" ]
[ "user", "anonymous"]
These properties should comply with the parameters passed to connect,
in the sense that non-initialized paramaters are filled by the server.
Moreover, the user and language parameters should match the value returned.
The language property returned should match the required language interaction.
*/
while( !gotError() && active && fetchRow()>0){
if( cache.fldcnt[cache.reader]== 0){
System.out.println("Unexpected reply:"
+ cache.rows[cache.reader]);
continue;
}
String property= fetchField(0);
String value= fetchField(1);
//System.out.println("fields:"+property+","+value);
if( property.equals("language") && !lang.equals("") &&
!value.equals(lang)){
setError("Incompatible language requirement","connect");
System.out.println("exepcted:"+lang);
} else language= lang;
if( property.equals("version")) version= value;
if( property.equals("dbname")) dbname= value;
}
if( gotError()) {
connected = false;
active= false;
if(trace) traceLog.println("Error occurred in initialization");
return this;
}
if(trace) traceLog.println("Connection established");
connected= true;
return this;
}
/**
* Secure communication channels require SSL.
* @param host - a hostname, e.g. monetdb.cwi.nl
* port - the port to which the server listens, e.g. 50001
* user - user name, defaults to "anonymous"
* pwd - password, defaults to none
* lang - language interpretation required
*/
public static Mapi connectSSL( String host, int port, String user, String pwd, String lang )
{
System.out.println("connectSSL not yet implemented");
return null;
}
/**
* Establish a secondary access structure to the same server
*/
public Mapi(Mapi m)
throws MapiException
{
connect(m.host, m.port, m.username, m.password, m.language);
this.traceLog = m.traceLog;
}
/**
* The user can create multiple Mapi objects to keep pre-canned queries around.
* @param src the Mapi connection to be duplicated
* @return a duplicate connection
*/
public Mapi dup(Mapi j){
check("dup");
if( gotError()) return null;
Mapi m= new Mapi();
m.socket = j.socket;
m.fromMonet = j.fromMonet;
m.toMonet = j.toMonet;
return m;
}
/**
* The interaction protocol with the monet database server is very
* simple. Each command (query) is ended with '\n'. The synchronization
* string is recognized by brackets '\1' and '\2'.
*/
private void promptMonet() throws MapiException {
// last line read is in the buffer
int lim = blk.buf.length();
prompt= blk.buf.substring(1,lim-1);
// finding the prompt indicates end of a query
active= false;
if( trace) traceLog.println("promptText:"+prompt);
}
/**
* Disconnect from Monet server.
* The server will notice a broken pipe and terminate.
* The intermediate structurs will be cleared.
*/
public int disconnect() {
check("disconnect");
if( gotError()) return MERROR;
cache= new RowCache();
blk= new IoCache();
connected= active= false;
toMonet = null; fromMonet = null; traceLog = null;
return MOK;
}
/**
* Reset the communication channel, thereby clearing the
* global variable settings
*/
public int reconnect(){
check("reconnect");
if( gotError()) return MERROR;
if( connected) disconnect();
cache= new RowCache();
blk= new IoCache();
try{
connect(host, port,username,password,language);
} catch( MapiException e) {}
return MOK;
}
/**
* Eat away all the remaining lines
*/
private int finish_internal(){
try{
while(active && fetchLineInternal() != null);
} catch( MapiException e) {}
return MOK;
}
public int finish(){
check("finish");
return finish_internal();
}
//======================= Binding parameters ================
private boolean checkColumns(int fnr, String action){
if( fnr<0){
setError("Illegal field nummer:"+fnr,action);
return false;
}
if( fnr >= fieldcnt) extendColumns(fnr);
return true;
}
/**
* Binding an output parameter to an object simplifies transfer,
* values are passed to the receiver using the method setValue();
* @param fnr a valid field index
* obj a reference to an arbitrary receiving object
*/
public int bind(int fnr, Object o){
check("bind");
if( !checkColumns(fnr,"bind")) return MERROR;
System.out.println("bind() yet supported");
//columns[fnr].outparam = o;
return MOK;
}
/**
* Binding an input parameter to an object simplifies transfer,
* values are passed to the receiver using the method setValue();
* @param fnr a valid field index
* obj a reference to an arbitrary receiving object
*/
public int bindVar(int fnr, int tpe, Object o){
check("bindVar");
if( !checkColumns(fnr,"bindVar")) return MERROR;
System.out.println("bindVar() not supported");
//columns[fnr].outparam = o;
return MOK;
}
/**
* Binding an input parameter to an object simplifies transfer,
* values are passed to the receiver using the method setValue();
* @param fnr a valid field index
* scale
* precision
* obj a reference to an arbitrary receiving object
*/
public int bindNumeric(int fnr, int scale, int prec, Object o){
check("bindNumeric");
if( !checkColumns(fnr,"bindVar")) return MERROR;
System.out.println("bindVar() not supported");
columns[fnr].scale = scale;
columns[fnr].precision = prec;
//columns[fnr].outparam = o;
return MOK;
}
// ------------------------ Columns handling
/**
* Columns management realizes the tabular display structure envisioned.
*/
private int extendColumns(int mf){
if(mf<maxfields) return MOK;
int nm= maxfields+32;
if( nm <= mf)
nm= mf+32;
if( trace) traceLog.println("extendColumns:"+nm);
Column nf[]= new Column[nm];
System.arraycopy(columns,0,nf,0,maxfields);
columns= nf;
maxfields= nm;
return MOK;
}
private void extendFields(int cr){
if( trace) traceLog.println("extendFields:"+cr);
if(cache.fields== null ){
String anew[]= new String[maxfields];
if( cache.fields[cr]!= null)
System.arraycopy(cache.fields[cr],0,anew,0,cache.fldcnt[cr]);
cache.fields[cr]= anew;
}
}
/**
* The values of a row are delivered to any bounded variable before
* fetch_row returns. Automatic conversion based on common types
* simplifies the work for the programmers.
*/
private void storeBind(){
System.out.print("storeBind() Not supported");
//int cr= cache.reader;
//for(int i=0; i< fieldcnt; i++)
//if( columns[i].outparam != null){
//columns[i].outparam.setValue(s);
//}
}
/**
* unescape a MIL string
**/
public String unescapeMILstr(String str) {
if (str == null)
return null;
char[] src = str.toCharArray();
char[] dst = new char[src.length];
boolean unescape = false;
int d = 0;
for (int s=0;s<src.length;s++) {
switch (src[s]) {
case '\\':
if (!unescape) {
unescape = true;
continue;
} else
dst[d++] = '\\';
break;
case 'n':
dst[d++] = (unescape?'\n':'n');
break;
case 't':
dst[d++] = (unescape?'\t':'t');
break;
default:
dst[d++] = src[s];
}
unescape = false;
}
return new String(dst);
}
/**
* The slice row constructs a list of string field values.
* It trims the string quotes but nothing else.
*/
public int sliceRow(){
int cr= cache.reader;
if(cr<0 || cr >= cache.writer){
setError("Current row missing","sliceRow");
return 0;
}
String s= cache.rows[cr];
if( s== null){
setError("Current row missing","sliceRow");
return 0;
}
// avoid duplicate slicing
if( cache.fldcnt[cr]>0) return cache.fldcnt[cr];
if( s.length()==0) return 0;
char p[]= s.toCharArray();
int i=0;
int f=1,l;
if( p[0]=='!'){
String olderr= errortext;
clrError();
setError(olderr+s,"sliceRow");
return 0;
}
if( p[0]!='['){
if(trace) traceLog.println("Single field:"+s);
cache.fields[cr][0]= s;
// count filds by counting the type columns in header
// each type looks like (str)\t
i=0;
for(int k=1; k<p.length; k++)
if( p[k]=='\t' && p[k-1]==')') i++;
if( fieldcnt<i) fieldcnt= i;
if(trace) traceLog.println("type cnt:"+i);
return 1;
}
if( trace) traceLog.println("slice:"+(p.length)+":"+s);
do{
// skip leading blancs
while(f<p.length )
if( p[f]=='\t' || p[f] ==' ') f++; else break;
if(f==p.length || p[f]==']') break;
if(i== maxfields){
if( extendColumns(maxfields+32) != MOK)
return 0;
for(int j=0;j<cache.limit;j++)
if( cache.fields[j] != null)
extendFields(j);
}
l=f+1;
// slicing the row should respect the string/char literal
boolean instring=s.charAt(f)=='"' || s.charAt(f)=='\'';
char bracket= instring? s.charAt(f) :'\t';
if(instring) f++;
boolean done =false;
boolean unescape = false;
while(!done && l<p.length ){
switch(p[l]){
case '\t':
case ']':
done = !instring;
if( !done) l++;
break;
case ',':
if(!instring){
done= true;
break;
}
l++;
break;
case '\\': l+=2; unescape=true; break;
case '\'':
case '"':
if(instring ){
//System.out.println("bracket:"+p[l]+l);
if( bracket==p[l]) {
done=true;
break;
}
}
default: l++;
}
}
String fld= s.substring(f,l);
if (unescape)
fld = unescapeMILstr(fld);
if(trace) traceLog.println("field ["+cr+"]["
+i+" "+l+"]"+fld+":"+instring+":");
cache.fields[cr][i]= fld;
// skip any immediate none-space
while(l<p.length )
if( p[l]=='\t' || p[l] ==' ') break; else l++;
if(trace && instring) traceLog.println("skipped to:"+l);
f= l;
i++;
cache.fldcnt[cr]=i;
if(i>fieldcnt) fieldcnt=i;
} while(f< p.length && p[f]!=']');
if(trace) traceLog.println("fields extracted:"+i+" fieldcnt:"+fieldcnt);
return i;
}
/**
* The fetchRow() retrieves a tuple from the server
*/
public int fetchRow(){
check("fetchRow");
if( getRow()==MOK ) return sliceRow();
return 0;
}
public int fetchAllRows(){
check("fetchAllRows");
cacheLimit(-1);
while( getRow()== MOK)
sliceRow();
fetchReset();
return cache.tupleCount;
}
public String fetchField(int fnr){
check("fetchField");
int cr= cache.reader;
if(cr <0 || cr >cache.writer) {
setError("No tuple in cache","fetchField");
return null;
}
if( fnr>=0){
if( cache.fldcnt[cr]==0){
//System.out.println("reslice");
sliceRow();
}
if( fnr < cache.fldcnt[cr])
return cache.fields[cr][fnr];
}
if( fnr== -1)
// fetch complete tuple
return cache.rows[cr];
setError("Illegal field","fetchField");
return null;
}
public String[] fetchFieldArray(int fnr){
check("fetchField");
int cr = cache.reader;
if(cr <0) {
setError("No tuple in cache","fetchFieldArray");
return null;
}
String f[]= new String[cache.fldcnt[cr]];
for(int i=0;i<cache.fldcnt[cr]; i++)
f[i]= cache.fields[cr][i];
return f;
}
public synchronized int getColumnCount(){
check("getColumnCount");
return fieldcnt;
}
public synchronized String getColumnName(int i){
check("getColumnName");
if(i<fieldcnt && columns[i]!= null && columns[i].columnname!= null)
return columns[i].columnname;
return "str";
}
public synchronized String getColumnType(int i){
check("getColumnType");
if(i<fieldcnt && columns[i]!= null && columns[i].columntype!= null)
return columns[i].columntype;
return "";
}
public synchronized int getRowCount(){
check("getRowCount");
return rows_affected;
}
public String getName(int fnr){
check("getName");
int cr= cache.reader;
if(cr <0) {
setError("No tuple in cache","getName");
return null;
}
if( fnr >=0 && fnr < cache.fldcnt[cr]){
if(columns[fnr].columnname== null)
columns[fnr].columnname= "column_"+fnr;
return columns[fnr].columnname;
}
setError("Illegal field","getName");
return null;
}
public String getTable(int fnr){
check("getTable");
int cr= cache.reader;
if(cr <0) {
setError("No tuple in cache","getTable");
return null;
}
if( fnr >=0 && fnr < cache.fldcnt[cr]){
if(columns[fnr].tablename== null)
columns[fnr].tablename= "table_"+fnr;
return columns[fnr].tablename;
}
setError("Illegal field","getName");
return null;
}
public int rows_affected(){
check("rows_affected");
return rows_affected;
}
public String getHost(){
check("getHost");
return host;
}
public String getUser(){
check("getUser");
return username;
}
public String getPassword(){
check("getPassword");
return password;
}
public String getLanguage(){
check("getLanguage");
return language;
}
public String getDBname(){
check("getDBname");
return language;
}
public int getPort(){
check("getPort");
return port;
}
public String getMapiVersion(){
check("getMapiVersion");
return mapiversion;
}
public String getMonetVersion(){
check("getMonetVersion");
return version;
}
public int getMonetId(){
check("getMonetId");
if(version!=null && version.charAt(0)=='4') return 4;
return 4;
}
// ------------------------ Handling queries
/**
* The routine mapi_check_query appends the semicolon and new line if needed.
* Furthermore, it ensures that no 'false' newlines are sent to the server,
* because this may lead to a synchronization error easily.
*/
private void expandQuery(String xtra){
String n= query+xtra;
query = n;
if( qrytemplate != null) qrytemplate= n;
if( trace) traceLog.print("Modified query:"+query);
}
private void checkQuery(){
clrError();
int i = query.indexOf('\n');
if( i>=0 && i < query.length()-1)
setError("Newline in query string not allowed","checkQuery");
query.replace('\n',' ');
// trim white space
int j= query.length()-1;
while(j>0 && (query.charAt(j)==' ' || query.charAt(j)=='\t')) j--;
if( j != query.length()-1) query= query.substring(0,j+1);
// check for unbalanced string quotes
byte qbuf[]= query.getBytes();
boolean instring=false;
char quote=' ';
for(j=0; j<qbuf.length; j++){
switch(qbuf[j]){
case '\\':j++; break;
case '"': if(instring){
if( quote== '"') { instring=false;quote=' ';}
} else{ quote='"'; instring=true;}
break;
case '\'': if(instring){
if( quote== '\'') { instring=false;quote=' ';}
} else{ quote='\''; instring=true;}
} }
if(quote!=' ') expandQuery(""+quote);
if( language.equals("sql")){
i= query.lastIndexOf(';');
if( i != query.length()-1) expandQuery(";");
}
expandQuery("\n");
}
/**
* The query string may contain place holders, which should be replaced
* by the arguments presented
*/
private int prepareQueryInternal(String cmd){
if( cmd == null || cmd.length()==0){
// use previous query
if(query==null) query="";
} else {
query = cmd;
qrytemplate= null;
int i= cmd.indexOf(PLACEHOLDER);
if( i>=0 && i < cmd.length()){
qrytemplate = query;
}
}
checkQuery();
return error;
}
/**
* Move the query to the connection structure. Possibly interact with the
* back-end to prepare the query for execution.
* @param cmd the command string to be executed
*/
public int prepareQuery(String cmd){
check("prepareQuery");
return prepareQueryInternal(cmd);
}
/**
* Move the query to the connection structure. Possibly interact with the
* back-end to prepare the query for execution.
* @param cmd the command string to be executed
* arg replacement strings for each of the placeholders
*/
private int prepareQueryArrayInternal(String cmd, String arg[]){
int ret= prepareQuery(cmd);
if( ret != MOK) return ret;
// get rid of the previous field bindings
for(int i=0; i< fieldcnt; i++) {
//columns[i].inparam= null;
}
int lim= arg.length;
if( lim > fieldcnt)
extendColumns(lim);
for(int i=0; i< lim; i++) {
//columns[i].inparam= arg[i];
}
return error;
}
public int prepareQueryArray(String cmd, String arg[]){
check("prepareQueryArray");
return prepareQueryArrayInternal(cmd,arg);
}
/**
* Before we ship a query, all placeholders should be removed
* and the actual values should take their position.
* Replacement should be able to hangle PLACEHOLDERS in the arguments.
*/
private void paramStore(){
if(qrytemplate == null || qrytemplate.length()==0) return;
query = qrytemplate;
int p, pr=0;
for(int i=0; i< fieldcnt; i++){
String left,right;
p= query.indexOf(PLACEHOLDER,pr);
if( p == pr){
// no more placeholders
setError("Not enough placeholders","paramStore");
break;
}
left = query.substring(0,p-1);
right= query.substring(p+1,query.length());
//query= left+columns[i].inparam.toString()+right;
}
if( trace) traceLog.println("paramStore:"+query);
}
/**
* The command is shipped to the backend for execution. A single answer
* is pre-fetched to detect any runtime error. A NULL command is
* interpreted as taking the previous query. MOK is returned upon success.
* The fake queries '#trace on' and '#trace off' provide an easy means
* to toggle the trace flag.
*/
private int executeInternal(){
try {
if( query.startsWith("#trace on")){
trace= true;
traceLog.println("Set trace on");
}
if( query.startsWith("#trace off")){
traceLog.println("Set trace off");
trace= false;
}
if (tableid >= 0) {
if (trace) traceLog.println("execute: Xclose");
toMonet.writeBytes("Xclose " + tableid + "\n" );
toMonet.flush();
do {
blk.buf = fromMonet.readLine();
if(trace) traceLog.println("gotLine:"+blk.buf);
} while( blk.buf.charAt(0) != PROMPTBEG);
promptMonet();
}
if(trace) traceLog.print("execute:"+query);
paramStore();
cacheResetInternal();
toMonet(query);
} catch(Exception e) {
setError(e.toString(),"execute");
}
return error;
}
public int execute(){
check("execute");
return executeInternal();
}
/**
* The command is shipped to the backend for execution. A single answer
* is pre-fetched to detect any runtime error. A NULL command is
* interpreted as taking the previous query. MOK is returned upon success.
* @param arg the list of place holder values
*/
public int executeArray(String arg[]){
prepareQueryArrayInternal(query,arg);
return error==MOK ? executeInternal(): error;
}
/**
* This routine sends the Command to the database server.
* It is one of the most common operations.
* If Command is null it takes the last query string kept around.
* It returns zero upon success, otherwise it indicates a failure of the request.
* The command response is buffered for consumption, e.g. fetchRow();
* @param cmd - the actual command to be executed
*/
private int answerLookAhead(){
// look ahead to detect errors
int oldrd= cache.reader;
do{
getRow();
} while(error==MOK && active &&
cache.writer+1< cache.limit);
cache.reader= oldrd;
if(trace ) traceLog.println("query return:"+error);
return error;
}
public int query(String cmd){
if (active) {
System.out.println("still active " + query );
}
if(cmd == null) return setError("Null query","query");
prepareQueryInternal(cmd);
if( error== MOK) executeInternal();
if( error== MOK) answerLookAhead();
return error;
}
/**
* This routine sends the Command to the database server.
* It is one of the most common operations.
* If Command is null it takes the last query string kept around.
* It returns zero upon success, otherwise it indicates a failure of the request.
* The command response is buffered for consumption, e.g. fetchRow();
* @param cmd - the actual command to be executed
arg - the place holder values
*/
public int queryArray(String cmd, String arg[]){
if(cmd == null) return setError("Null query","queryArray");
prepareQueryArrayInternal(cmd,arg);
if( error== MOK) executeInternal();
if( error== MOK) answerLookAhead();
return error;
}
/**
* To speed up interaction with a terminal front-end,
* the user can issue the quick_*() variants.
* They will not analyse the result for errors or
* header information, but simply through the output
* received from the server to the stream indicated.
*/
public int quickQuery(String cmd, DataOutputStream fd){
check("quickQuery");
if(cmd == null) return setError("Null query","queryArray");
prepareQueryInternal(cmd);
if( error== MOK) executeInternal();
if( error== MOK) quickResponse(fd);
if(trace && error !=MOK) traceLog.println("query returns error");
return error;
}
public int quickQueryArray(String cmd, String arg[], DataOutputStream fd){
check("quickQueryArray");
if(cmd == null) return setError("Null query","quickQueryArray");
prepareQueryArrayInternal(cmd,arg);
if( error== MOK) executeInternal();
if( error== MOK) quickResponse(fd);
if(trace && error !=MOK) traceLog.println("query returns error");
return error;
}
/**
* Stream queries are request to the database engine that produce a stream
* of answers of indefinite length. Elements are eaten away using the normal way.
* The stream ends with encountering the prompt.
* A stream query can not rely on upfront caching.
* The stream query also ensures that the cache contains a sliding window
* over the stream by shuffling tuples once it is filled.
* @param cmd - the query to be executed
* window- the window size to be maintained in the cache
*/
public int openStream(String cmd, int windowsize){
check("openStream");
if(cmd == null) return setError("Null query","openStream");
query(cmd);
if( gotError()) return error;
// reset the active flag to enable continual reads
// stolen part of cacheResetInternal();
finish_internal();
rows_affected= 0;
active= true;
if( cache.fldcnt==null)
cache.fldcnt = new int[cache.limit];
cache.tupleCount= 0;
cacheFreeup(100);
cacheLimit(windowsize);
cacheShuffle(1);
return error;
}
/**
* A stream can be closed by sending a request to abort the
* further generation of tuples at the server side.
* Note that we do not wait for any reply, because this will
* appear at the stream-reader, a possibly different thread.
*/
public int closeStream(String cmd){
prepareQueryInternal(cmd);
paramStore();
try{
toMonet(query);
} catch( MapiException m){
setError("Write error on stream","execute");
}
return error;
}
// -------------------- Cache Management ------------------
/**
* Empty the cache is controlled by the shuffle percentage.
* It is a factor between 0..100 and indicates the number of space
* to be freed each time the cache should be emptied
* @param percentage - amount to be freed
*/
public int cacheFreeup(int percentage){
if( cache.writer==0 && cache.reader== -1) return MOK;
if( percentage==100){
//System.out.println("allocate new cache struct");
cache= new RowCache();
return MOK;
}
if( percentage <0 || percentage>100) percentage=100;
int k= (cache.writer * percentage) /100;
if( k < 1) k =1;
if(trace) System.out.println("shuffle cache:"+percentage+" tuples:"+k);
for(int i=0; i< cache.writer-k; i++){
cache.rows[i]= cache.rows[i+k];
cache.fldcnt[i]= cache.fldcnt[i+k];
cache.fields[i]= cache.fields[i+k];
}
for(int i=k; i< cache.limit; i++){
cache.rows[i]= null;
cache.fldcnt[i]=0;
cache.fields[i]= new String[maxfields];
for(int j=0;j<maxfields;j++)
cache.fields[i][j]= null;
}
cache.reader -=k;
if(cache.reader < -1) cache.reader= -1;
cache.writer -=k;
if(cache.writer < 0) cache.writer= 0;
if(trace) System.out.println("new reader:"+cache.reader+" writer:"+cache.writer);
//rebuild the tuple index
cache.tupleCount=0;
int i=0;
for(i=0; i<cache.writer; i++){
if( cache.rows[i].indexOf("#")==0 ) continue;
if( cache.rows[i].indexOf("!")==0 ) continue;
cache.tuples[cache.tupleCount++]= i;
}
for(i= cache.tupleCount; i<cache.limit; i++)cache.tuples[i]= -1;
return MOK;
}
/**
* CacheReset throws away any tuples left in the cache and
* prepares it for the next sequence;
* It should re-size the cache too.
* It should retain the field information
*/
private void cacheResetInternal()
{
finish_internal();
rows_affected= 0;
active= true;
if( cache.fldcnt==null)
cache.fldcnt = new int[cache.limit];
// set the default for single columns
for(int i=1;i<fieldcnt;i++) columns[i]=null;
fieldcnt=1;
if(columns[0]!= null){
columns[0].columntype="str";
}
cache.tupleCount= 0;
cacheFreeup(100);
}
/**
* Users may change the cache size limit
* @param limit - new limit to be obeyed
* shuffle - percentage of tuples to be shuffled upon full cache.
*/
public int cacheLimit(int limit){
cache.rowlimit= limit;
return MOK;
}
/**
* Users may change the cache shuffle percentage
* @param shuffle - percentage of tuples to be shuffled upon full cache.
*/
public int cacheShuffle(int shuffle){
if( shuffle< -1 || shuffle>100) {
cache.shuffle=100;
return setError("Illegal shuffle percentage","cacheLimit");
}
cache.shuffle= shuffle;
return MOK;
}
/**
* Reset the row pointer to the first line in the cache.
* This need not be a tuple.
* This is mostly used in combination with fetching all tuples at once.
*/
public int fetchReset(){
check("fetchReset");
cache.reader = -1;
return MOK;
}
/**
* Reset the row pointer to the requested tuple;
* Tuples are those rows that not start with the
* comment bracket. The mapping of tuples to rows
* is maintained during parsing to speedup subsequent
* access in the cache.
* @param rownr - the row of interest
*/
public int seekRow(int rownr){
check("seekRow");
int i, sr=rownr;
cache.reader= -1;
if( rownr<0) return setError("Illegal row number","seekRow");
i= cache.tuples[rownr];
if(i>=0) {
cache.reader= i;
return MOK;
}
/*
for(i=0; rownr>=0 && i<cache.writer; i++){
if( cache.rows[i].indexOf("#")==0 ) continue;
if( cache.rows[i].indexOf("!")==0 ) continue;
if( --rownr <0) break;
}
if( rownr>=0) return setError("Row not found "+sr
+" tuples "+cache.tuples,"seekRow");
cache.reader= i;
return MOK;
*/
return setError("Illegal row number","seekRow");
}
/**
* These are the lowest level operations to retrieve a single line from the
* server. If something goes wrong the application may try to skip input to
* the next synchronization point.
* If the cache is full we reshuffle some tuples to make room.
*/
private void extendCache(){
int oldsize= cache.limit;
if( oldsize == cache.rowlimit){
System.out.println("Row cache limit reached extendCache");
setError("Row cache limit reached","extendCache");
// shuffle the cache content
if( cache.shuffle>0)
System.out.println("Reshuffle the cache ");
}
int incr = oldsize ;
if(incr >200000) incr= 20000;
int newsize = oldsize +incr;
if( newsize >cache.rowlimit && cache.rowlimit>0)
newsize = cache.rowlimit;
String newrows[]= new String[newsize];
int newtuples[]= new int[newsize];
if(oldsize>0){
System.arraycopy(cache.tuples,0,newtuples,0,oldsize);
System.arraycopy(cache.rows,0,newrows,0,oldsize);
cache.rows= newrows;
cache.tuples= newtuples;
//if(trace) traceLog.println("Extend the cache.rows storage");
}
int newfldcnt[]= new int[newsize];
if(oldsize>0){
System.arraycopy(cache.fldcnt,0,newfldcnt,0,oldsize);
cache.fldcnt= newfldcnt;
//if(trace) traceLog.println("Extend the cache.fldcnt storage");
for(int i=oldsize;i<newsize;i++) cache.fldcnt[i]=0;
}
String newfields[][]= new String[newsize][];
if(oldsize>0){
System.arraycopy(cache.fields,0,newfields,0,oldsize);
cache.fields= newfields;
//if(trace) traceLog.println("Extend the cache.fields storage");
for(int i=oldsize;i<newsize;i++)
cache.fields[i]= new String[maxfields];
}
cache.limit= newsize;
}
private int clearCache(){
// remove all left-over fields
if( cache.reader+2<cache.writer){
System.out.println("Cache reset with non-read lines");
System.out.println("reader:"+cache.reader+" writer:"+cache.writer);
setError("Cache reset with non-read lines","clearCache");
}
cacheFreeup(cache.shuffle);
return MOK;
}
// ----------------------- Basic line management ----------------
/**
* The fetchLine() method is the lowest level of interaction with
* the server to acquire results. The lines obtained are stored in
* a cache for further analysis.
*/
public String fetchLine() throws MapiException {
check("fetchLine");
return fetchLineInternal();
}
public String fetchLineInternal() throws MapiException {
if( cache.writer>0 && cache.reader+1<cache.writer){
if( trace) traceLog.println("useCachedLine:"+cache.rows[cache.reader+1]);
return cache.rows[++cache.reader];
}
if( ! active) return null;
error= MOK;
// get rid of the old buffer space
if( cache.writer ==cache.rowlimit){
clearCache();
}
// check if you need to read more blocks to read a line
blk.eos= false;
// fetch one more block or line
int n=0;
int len= 0;
String s="";
blk.buf= null;
if( !connected){
setError("Lost connection with server","fetchLine");
return null;
}
// we should reserve space
// manage the row cache space first
if( cache.writer >= cache.limit)
extendCache();
if( trace) traceLog.println("Start reading from server");
try {
blk.buf = fromMonet.readLine();
if(trace) traceLog.println("gotLine:"+blk.buf);
} catch(IOException e){
connected= false;
error= Mapi.MAPIERROR;
errortext= "Communication broken";
throw new MapiException( errortext);
}
if( blk.buf==null ){
blk.eos= true;
setError("Lost connection with server","fetchLine");
connected= false;
return null;
}
if( blk.buf.length()>0){
switch( blk.buf.charAt(0)){
case PROMPTBEG:
promptMonet();
return null;
case '[': cache.tuples[cache.tupleCount++]= cache.reader+1;
}
}
cache.rows[cache.writer] = blk.buf;
cache.writer++;
return cache.rows[++cache.reader];
}
/**
* If the answer to a query should be simply passed on towards a client,
* i.e. a stream, it pays to use the quickResponse() routine.
* The stream is only checked for occurrence of an error indicator
* and the prompt.
* The best way to use this shortcut execution is calling
* mapi_quick_query(), otherwise we are forced to first
* empy the row cache.
* @param fd - the file destination
*/
public int quickResponse(DataOutputStream fd){
String msg;
if( fd== null)
return setError("File destination missing","response");
try{
while( active && (msg=fetchLineInternal()) != null)
try{
fd.writeBytes(msg.toString());
fd.writeBytes("\n");
fd.flush();
} catch( IOException e){
throw new MapiException("Can not write to destination" );
}
} catch(MapiException e){
}
return error;
}
//------------------- Response analysis --------------
private void keepProp(String name, String colname){
}
// analyse the header row, but make sure it is restored in the end.
// Note that headers received contains an addition column with
// type information. It should be ignored while reading the tuples.
private void headerDecoder() {
String line= cache.rows[cache.reader];
if (trace)
traceLog.println("header:"+line);
int etag= line.lastIndexOf("#");
if(etag==0 || etag== line.length())
return;
String tag= line.substring(etag);
cache.rows[cache.reader]="[ "+cache.rows[cache.reader].substring(1,etag);
int cnt= sliceRow();
if (trace)
traceLog.println("columns "+cnt);
extendColumns(cnt);
if (tag.equals("# name")) {
for (int i=0;i<cnt;i++) {
if(columns[i]==null) columns[i]= new Column();
String s= columns[i].columnname= fetchField(i);
}
} else if (tag.equals("# type")) {
for(int i=0;i<cnt;i++) {
String type = fetchField(i);
if (columns[i]==null)
columns[i] = new Column();
columns[i].columntype = type;
if (trace)
traceLog.println("column["+i+"].type="+columns[i].columntype);
}
} else if (tag.equals("# id")) {
String s = fetchField(0);
try {
tableid = Integer.parseInt(s);
} catch (Exception e) {
//ignore;
}
if (trace)
traceLog.println("got id " + tableid + " \n");
} else if (trace)
traceLog.println("Unrecognized header tag "+tag);
//REST LATER
cache.rows[cache.reader]= line;
}
// Extract the next row from the cache.
private int getRow(){
String reply= "";
//if( trace) traceLog.println("getRow:active:"+active+
//" reader:"+(cache.reader+1)+" writer:"+cache.writer);
while( active ||cache.reader+1< cache.writer){
if( active){
try{
reply= fetchLineInternal();
} catch(MapiException e){
if(trace)
traceLog.print("Got exception in getRow");
reply=null;
}
if( gotError() || reply == null) return MERROR;
} else reply = cache.rows[++cache.reader];
if(trace) traceLog.println("getRow:"+cache.reader);
if( reply.length()>0)
switch(reply.charAt(0)){
case '#':
headerDecoder();
return getRow();
case '!':
// concatenate error messages
String olderr= errortext;
clrError();
setError(olderr+reply.toString(),"getRow");
return getRow();
default:
return MOK;
}
}
return MERROR;
}
// ------------------------------- Utilities
/** The java context provides a table abstraction
* the methods below provide access to the relevant Mapi components
*/
public int getTupleCount(){
//int cnt=0;
return cache.tupleCount;
//for(int i=0;i<cache.writer;i++){
//if(cache.rows[i].charAt(0)=='[') cnt++;
//}
//System.out.println("counted "+cnt+" maintained "+cache.tuples);
//return cnt;
}
/**
* unquoteInternal() squeezes a character array to expand
* all quoted characters. It also removes leading and trailing blancs.
* @param msg - the byte array to be
*/
private int unquoteInternal(char msg[], int first)
{
int f=0, l=0;
for(; f< msg.length; f++)
if( msg[f] != ' ' && msg[f]!= '\t') break;
if( f< msg.length && (msg[f]=='"' || msg[f]=='\'')){
f++;
for(l=f+1; l<msg.length && !(msg[l]=='"' || msg[l]=='\''); l++);
l--;
} else {
}
return f;
}
public String quote(String msg){
System.out.println("Not yet implemented");
return null;
}
/**
* Unquote removes the bounding brackets from strings received
*/
public String unquote(String msg){
char p[]= msg.toCharArray();
int f=0,l=f;
char bracket= ' ';
while(f<p.length && p[f]==' ') f++;
if( f<p.length) bracket = p[f];
if( bracket == '"' || bracket== '\''){
l= msg.lastIndexOf(bracket);
if( l<=f){
if(trace)
traceLog.println("closing '"+bracket+"' not found:"+msg);
return msg;
}
return msg.substring(f+1,l);
} else
// get rid of comma except when it is a literal char
if( p[f]!=',' && p[p.length-1]==',') msg= msg.substring(f,p.length-1);
return msg;
}
/**
* Unescape reconstructs the string by replacing the escaped characters
*/
public String unescape(String msg){
char p[]= msg.toCharArray();
int f=0,l=f;
String newmsg;
for(; f< p.length;f++,l++)
if( p[f]=='\\') {
switch(p[++f]){
case 't':p[l]='\t'; break;
case 'n':p[l]='\n'; break;
default: p[l]=p[f];
}
} else p[l]=p[f];
if( l== p.length) return msg;
newmsg= new String(p,0,l);
//System.out.println("unescaped:"+msg+"->" +newmsg);
return newmsg;
}
public boolean gotError(){
return error!=MOK;
}
public String getErrorMsg(){
return errortext;
}
public String getExplanation(){
return "Mapi:"+dbname+"\nERROR:"+errortext+"\nERRNR:"+error+
"\nACTION:"+action+"\nQUERY:"+query+"\n";
}
public String getPrompt(){
return prompt;
}
public boolean isConnected(){
return connected;
}
/*
The low-level operation toMonet attempts to send a string to the server.
It assumes that the string is properly terminated and a connection to
the server still exists.
*/
private void toMonet(String msg) throws MapiException {
if( ! connected)
throw new MapiException( "Connection was disabled" );
if( msg== null || msg.equals("")){
if(trace)
traceLog.println("Attempt to send an empty message");
return;
}
try{
if( trace) traceLog.println("toMonet:"+msg);
int size= msg.length();
if( language.equals("sql"))
toMonet.writeBytes("S");
toMonet.writeBytes(msg);
toMonet.flush();
} catch( IOException e){
throw new MapiException("Can not write to Monet" );
}
}
/**
* The routine timeout can be used to limit the server handling requests.
* @parem time the timeout in milliseconds
*/
public int timeout(int time){
check("timeout");
System.out.println("timeout() not yet implemented");
return MOK;
}
/**
* The routine explain() dumps the status of the latest query to standard out.
*/
public int explain(){
System.out.println(getExplanation());
return MOK;
}
public void sortColumn(int col){
cache.sortColumn(col);
}
class IoCache
{ String buf="";
boolean eos;
public IoCache(){
eos = false;
}
}
class RowCache{
int rowlimit= -1; /* maximal number of rows to cache */
int shuffle= 100; /* percentage of tuples to shuffle upon overflow */
int limit=10000; /* current storage space limit */
int writer= 0;
int reader= -1;
int fldcnt[] = new int[limit]; /* actual number of columns in each row */
String rows[]= new String[limit]; /* string representation of rows received */
String fields[][]= new String[limit][];
int tuples[]= new int[limit]; /* tuple index */
int tupleCount=0;
public RowCache(){
for(int i=0;i<limit; i++){
fields[i]= new String[maxfields];
rows[i]=null;
tuples[i]= -1;
fldcnt[i]=0;
for(int j=0;j<maxfields;j++) fields[i][j]= null;
}
}
private void dumpLine(int i){
System.out.println("cache["+i+"] fldcnt["+fldcnt[i]+"]");
for(int j=0;j<fldcnt[i];j++)
System.out.println("field["+i+"]["+j+"] "+fields[i][j]);
}
private void dumpCacheStatus(){
System.out.println("cache limit="+rowlimit+
"shuffle="+shuffle+
"limit="+limit+
"writer="+writer+
"reader"+reader+
"tupleCount"+tupleCount);
}
//---------------------- Special features ------------------------
/**
* Retrieving the tuples in a particular value order is a recurring
* situation, which can be accomodated easily through the tuple index.
* Calling sorted on an incomplete cache doesn;t produce the required
* information.
* The sorting function is rather expensive and not type specific.
* This should be improved in the near future
*/
public void sortColumn(int col){
if( col <0 || col > maxfields) return;
// make sure you have all tuples in the cache
// and that they are properly sliced
fetchAllRows();
int direction = columns[col].direction;
columns[col].direction = -direction;
if( columns[col].columntype.equals("int") ||
columns[col].columntype.equals("lng") ||
columns[col].columntype.equals("ptr") ||
columns[col].columntype.equals("oid") ||
columns[col].columntype.equals("void") ||
columns[col].columntype.equals("sht")
){
sortIntColumn(col);
return;
}
if( columns[col].columntype.equals("flt") ||
columns[col].columntype.equals("dbl")
){
sortDblColumn(col);
return;
}
int lim= cache.tupleCount;
for(int i=0;i<lim; i++){
if(fields[tuples[i]][col]== null)
System.out.println("tuple null:"+i+" "+tuples[i]);
for(int j=i+1;j<lim; j++){
String x= fields[tuples[i]][col];
String y= fields[tuples[j]][col];
if( direction>0){
if(y!=null && x!=null && y.compareTo(x) >0 ){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
}
} else
if( direction<0){
if(y!=null && x!=null && y.compareTo(x) <0){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
}
}
}
}
}
private void sortIntColumn(int col){
int direction = columns[col].direction;
int lim= cache.tupleCount;
long val[]= new long[lim];
String sv;
for(int i=0; i<lim; i++){
sv= fields[tuples[i]][col];
if(sv==null){
val[i]= Long.MIN_VALUE;
System.out.println("tuple null:"+i+" "+tuples[i]);
//dumpLine(tuples[i]);
//seekRow(tuples[i]);
//sliceRow();
//dumpLine(tuples[i]);
continue;
}
int k= sv.indexOf("@");
if(k>0) sv= sv.substring(0,k);
try{
val[i]= Long.parseLong(sv);
} catch(NumberFormatException e){
val[i]= Long.MIN_VALUE;}
}
for(int i=0;i<lim; i++){
for(int j=i+1;j<lim; j++){
long x= val[i];
long y= val[j];
if( (direction>0 && y>x) ||
(direction<0 && y<x) ){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
val[i]= y;
val[j]= x;
}
}
}
}
private void sortDblColumn(int col){
int direction = columns[col].direction;
int lim= cache.tupleCount;
double val[]= new double[lim];
String sv;
for(int i=0; i<lim; i++){
sv= fields[tuples[i]][col];
if(sv==null){
System.out.println("tuple null:"+i+" "+tuples[i]);
val[i]= Double.MIN_VALUE;
continue;
}
try{
val[i]= Double.parseDouble(sv);
} catch(NumberFormatException e){
val[i]= Double.MIN_VALUE;}
}
for(int i=0;i<lim; i++){
for(int j=i+1;j<lim; j++){
double x= val[i];
double y= val[j];
if( (direction>0 && y>x) ||
(direction<0 && y<x) ){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
val[i]= y;
val[j]= x;
}
}
}
}
}
class Column{
String tablename=null;
String columnname=null;
String columntype=null;
int colwidth;
int coltype;
int precision;
int scale;
int isnull;
int direction= -1;
//Object inparam; // to application variable
//Object outparam; // both are converted to strings
}
}
| MonetDB/src/mapi/clients/java/mapi/Mapi.java | /*
* The contents of this file are subject to the MonetDB Public
* License Version 1.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://monetdb.cwi.nl/Legal/MonetDBLicense-1.0.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Monet Database System.
*
* The Initial Developer of the Original Code is CWI.
* Portions created by CWI are Copyright (C) 1997-2004 CWI.
* All Rights Reserved.
*
* Contributor(s):
* Martin Kersten <[email protected]>
* Peter Boncz <[email protected]>
* Niels Nes <[email protected]>
* Stefan Manegold <[email protected]>
*/
/*
The Monet Application Programming Interface
Author M.L. Kersten
The easiest way to extend the functionality of Monet is to construct
an independent Monet application, which communicates with a
running server on a textual basis.
The prime advantage is a secure and debugable interface.
The overhead in command preparation and response decoding is mainly
localized in the workstation of the application.
The Java code base presented here is a 'copy' of the similar C-Mapi interface.
The main differences are that this version does not provide variable
binding to ease interaction.
It is not possible to bind source/destination variables.
Instead, column values should be explicitly extracted from the row cache
and arguments are passed upon query construction.
Furthermore, it uses a simple line-based protocol with the server.
See the corresponding documentation. A synopsis is given only.
bind() & Bind string C-variable to field [NON_JAVA]
bind_var() & Bind typed C-variable to field [NON_JAVA]
bind_numeric() & Bind numeric C-variable to field [NON_JAVA]
cacheLimit() & Set the tuple cache limit
cacheShuffle() & Set the cache shuffle percentage
cacheFreeup() & Empty a fraction of the cache
connect() & Connect to a Mserver
connectSSL() & Connect to a Mserver using SSL [TODO]
disconnect() & Disconnect from server
dup() & Duplicate the connection structure
explain() & Display error message and context on stream
execute() & Execute a query
executeArray() & Execute a query using string arguments
fetchField() & Fetch a field from the current row
fetchFieldArray() & Fetch all fields from the current row
fetchLine() & Retrieve the next line
fetchReset() & Set the cache reader to the begining
fetchRow() & Fetch row of values
fetchAllRows() & Fetch all answers from server into cache
finish() & Terminate the current query
getHost() & Host name of server
getLanguage() & Query language name
getMapiVersion() & Mapi version identifier
getMonetVersion() & Monet version identifier
getMonetId() & Monet version generation number
getUser() & Get current user name
getDBname() & Get current database name
getTable() & Get current table name
getColumnCount()& Number of columns in current row
getColumnName() & Get columns name
getColumnType() & Get columns type
getRowCount() & Number of lines in cache or -1
getTupleCount() & Number of tuples in cache or -1
gotError() & Test for error occurrence
getPort() & Connection IP number
ping() & Test server for accessibility
prepareQuery() & Prepare a query for execution
prepareQueryArray()& Prepare a query for execution using arguments
query() & Send a query for execution
queryArray() & Send a query for execution with arguments
quickQuery() & Send a query for execution
quickQueryArray() & Send a query for execution with arguments
quote() & Escape characters
reconnect() & Restart with a clean session
rows_affected() & Obtain number of rows changed
quickResponse() & Quick pass response to stream
initStream() & Prepare for reading a stream of answers
seekRow() & Move row reader to specific row location in cache
sortColumn() & Sort column by string
timeout() & Set timeout for long-running queries[TODO]
trace() & Set trace flag
traceLog() & Keep log of interaction
unquote() & remove escaped characters
*/
package mapi;
import java.awt.*;
import java.applet.Applet;
import java.applet.*;
import java.io.*;
import java.net.Socket;
public class Mapi
{
public final static int MOK = 0;
public final static int MERROR = -1;
public final static int MEOS = -1;
public final static int MAPIERROR = -4;
public final static char PROMPTBEG= (char) 1;
public final static char PROMPTEND= (char) 2;
static final int MAPIBLKSIZE = 1024;
// public final int SQL_AUTO =0; /* automatic type detection */
// public final int SQL_INT =1;
// public final int SQL_LONG =2;
// public final int SQL_CHAR =3;
// public final int SQL_VARCHAR =4;
// public final int SQL_FLOAT =5;
// public final int SQL_DOUBLE =6;
// public final int SQL_TIME =7;
// public final int SQL_DATE =8;
// public final int SQL_NUMERIC =9;
public final int LANG_MAL =0;
public final int LANG_MIL =1;
public final int LANG_SQL =2;
public final int LANG_XCORE =3;
public final int LANG_XQUERY =4;
public final String PLACEHOLDER ="?";
private String version;
private String mapiversion;
private boolean blocked= false;
private String host = "localhost";
private int port = 50001;
private String username= "anonymous";
private String password="";
private String language= "mil";
private int languageId= LANG_MAL;
private String dbname= "unknown";
private boolean everything = false;
private boolean trace = false;
private boolean connected= false;
private boolean active= false;
private boolean eos = false;
// CacheBlock cache;
IoCache blk= new IoCache();
private int error = MOK;
private String errortext="";
private String action="";
private String query;
private int tableid = -1;
private String qrytemplate;
private String prompt;
// Tabular cache
private int fieldcnt= 1;
private int maxfields= 32;
private int minfields= 0;
private int rows_affected =0;
private RowCache cache= new RowCache();
private Column columns[]= new Column[32];
private Socket socket;
private DataOutputStream toMonet;
//private DataInputStream fromMonet;
private BufferedReader fromMonet;
private PrintStream traceLog = System.err;
private void check(String action){
if( !connected) setError("Connection lost",action);
clrError();
}
/*
The static method hostname gets the hostname from the monetport. The
monetport is defined by 'hostname:portnr'. The static method
portnr will return the port number in this string.
*/
private String hostname( String monetport ){
int pos = monetport.indexOf(':');
if (pos <= 1) return host;
return host= monetport.substring( 0,pos);
}
private int portnr( String monetport ){
int pos = monetport.indexOf(':');
if (pos >= 0 && pos < monetport.length()){
return port=Integer.parseInt(monetport.substring( pos+1 ));
}
return port;
}
// To make life of front-end easier they may call for
// properties to be understood by each running server.
// The actual parameter settings may at a later stage
// be obtained from some system configuration file/ Mguardian
public String getDefaultHost(){ return "localhost";}
public int getDefaultPort(){ return 50000;}
public String getDefaultLanguage(){ return "mil";}
public Mapi(){}
public Mapi( String host, int port, String user, String pwd, String lang)
throws MapiException
{
connect(host,port,user,pwd,lang);
}
//------------------ The actual implementation ---------
/**
* the default communication mode is current line-based
* a future version should also support the more efficient block mode
*/
public void setBlocking(boolean f){
blocked= f;
}
/**
* Toggle the debugging flag for the Mapi interface library
* @param flg the new value
*/
public void trace(boolean flg){
check("trace");
trace= flg;
}
/**
* Open a file to keep a log of the interaction between client and server.
* @param fnme the file name
*/
public void traceLog(String fnme){
check("traceLog");
try {
traceLog = new PrintStream(new FileOutputStream(fnme),true);
} catch(Exception e) {
System.err.println("!ERROR:setTraceLog:couldn't open:"+fnme);
}
}
public void traceLog(PrintStream f){
check("traceLog");
if (f!=null)
traceLog = f;
}
/**
* This method can be used to test for the lifelyness of the database server.
* it creates a new connection and leaves it immediately
* This call is relatively expensive.
* @return the boolean indicating success of failure
*/
public boolean ping(){
//if( language.equals("mal")) query("print(1);");
check("ping");
try{
Mapi m= new Mapi(this);
if(m.gotError())
return false;
m.disconnect();
} catch(MapiException e2){
return false;
}
return true;
}
/**
* This method can be used to set the Mapi descriptor once an error
* has been detected.
* @return the MAPI internal success/failure indicator
*/
private int setError(String msg, String act){
errortext= msg;
error= MERROR;
action= act;
return MERROR;
}
/**
* This method can be used to clear the Mapi error descriptor properties.
*/
private void clrError(){
errortext="";
error= MOK;
action="";
}
/**
* This method can be used to connect to a running server.
* The user can indicate any of the supported query languages, e.g.
* MIL, MAL, or SQL.
* The method throws an exception when a basic IO error is detected.
* @param host - a hostname, e.g. monetdb.cwi.nl
* port - the port to which the server listens, e.g. 50001
* user - user name, defaults to "anonymous"
* pwd - password, defaults to none
* lang - language interpretation required
*/
public Mapi connect( String host, int port, String user, String pwd, String lang )
throws MapiException
{
error = MOK;
this.host =host;
this.port = port;
connected= false;
try{
if(trace)
traceLog.println("setup socket "+host+":"+port);
socket = new Socket( host, port );
fromMonet= new BufferedReader(
new InputStreamReader(socket.getInputStream()));
//fromMonet= new DataInputStream(socket.getInputStream());
toMonet= new DataOutputStream(socket.getOutputStream());
connected = true;
} catch(IOException e) {
error= MERROR;
errortext= "Failed to establish contact\n" ;
throw new MapiException( errortext );
}
if( pwd==null ) pwd="";
blocked=false;
this.mapiversion= "1.0";
this.username= user;
this.password = pwd;
this.active = true;
if(trace) traceLog.println("sent initialization command");
if( pwd.length()>0) pwd= ":"+pwd;
if( blocked)
toMonet(user+pwd+":blocked\n");
else toMonet(user+pwd+"\n");
/*
The rendezvous between client application and server requires
some care. The general approach is to expect a property table
from the server upon succesful connection. An example feedback is:
[ "version", "4.3.12" ]
[ "language", "sql" ]
[ "dbname", "db" ]
[ "user", "anonymous"]
These properties should comply with the parameters passed to connect,
in the sense that non-initialized paramaters are filled by the server.
Moreover, the user and language parameters should match the value returned.
The language property returned should match the required language interaction.
*/
while( !gotError() && active && fetchRow()>0){
if( cache.fldcnt[cache.reader]== 0){
System.out.println("Unexpected reply:"
+ cache.rows[cache.reader]);
continue;
}
String property= fetchField(0);
String value= fetchField(1);
//System.out.println("fields:"+property+","+value);
if( property.equals("language") && !lang.equals("") &&
!value.equals(lang)){
setError("Incompatible language requirement","connect");
System.out.println("exepcted:"+lang);
} else language= lang;
if( property.equals("version")) version= value;
if( property.equals("dbname")) dbname= value;
}
if( gotError()) {
connected = false;
active= false;
if(trace) traceLog.println("Error occurred in initialization");
return this;
}
if(trace) traceLog.println("Connection established");
connected= true;
return this;
}
/**
* Secure communication channels require SSL.
* @param host - a hostname, e.g. monetdb.cwi.nl
* port - the port to which the server listens, e.g. 50001
* user - user name, defaults to "anonymous"
* pwd - password, defaults to none
* lang - language interpretation required
*/
public static Mapi connectSSL( String host, int port, String user, String pwd, String lang )
{
System.out.println("connectSSL not yet implemented");
return null;
}
/**
* Establish a secondary access structure to the same server
*/
public Mapi(Mapi m)
throws MapiException
{
connect(m.host, m.port, m.username, m.password, m.language);
this.traceLog = m.traceLog;
}
/**
* The user can create multiple Mapi objects to keep pre-canned queries around.
* @param src the Mapi connection to be duplicated
* @return a duplicate connection
*/
public Mapi dup(Mapi j){
check("dup");
if( gotError()) return null;
Mapi m= new Mapi();
m.socket = j.socket;
m.fromMonet = j.fromMonet;
m.toMonet = j.toMonet;
return m;
}
/**
* The interaction protocol with the monet database server is very
* simple. Each command (query) is ended with '\n'. The synchronization
* string is recognized by brackets '\1' and '\2'.
*/
private void promptMonet() throws MapiException {
// last line read is in the buffer
int lim = blk.buf.length();
prompt= blk.buf.substring(1,lim-1);
// finding the prompt indicates end of a query
active= false;
if( trace) traceLog.println("promptText:"+prompt);
}
/**
* Disconnect from Monet server.
* The server will notice a broken pipe and terminate.
* The intermediate structurs will be cleared.
*/
public int disconnect() {
check("disconnect");
if( gotError()) return MERROR;
cache= new RowCache();
blk= new IoCache();
connected= active= false;
toMonet = null; fromMonet = null; traceLog = null;
return MOK;
}
/**
* Reset the communication channel, thereby clearing the
* global variable settings
*/
public int reconnect(){
check("reconnect");
if( gotError()) return MERROR;
if( connected) disconnect();
cache= new RowCache();
blk= new IoCache();
try{
connect(host, port,username,password,language);
} catch( MapiException e) {}
return MOK;
}
/**
* Eat away all the remaining lines
*/
private int finish_internal(){
try{
while(active && fetchLineInternal() != null);
} catch( MapiException e) {}
return MOK;
}
public int finish(){
check("finish");
return finish_internal();
}
//======================= Binding parameters ================
private boolean checkColumns(int fnr, String action){
if( fnr<0){
setError("Illegal field nummer:"+fnr,action);
return false;
}
if( fnr >= fieldcnt) extendColumns(fnr);
return true;
}
/**
* Binding an output parameter to an object simplifies transfer,
* values are passed to the receiver using the method setValue();
* @param fnr a valid field index
* obj a reference to an arbitrary receiving object
*/
public int bind(int fnr, Object o){
check("bind");
if( !checkColumns(fnr,"bind")) return MERROR;
System.out.println("bind() yet supported");
//columns[fnr].outparam = o;
return MOK;
}
/**
* Binding an input parameter to an object simplifies transfer,
* values are passed to the receiver using the method setValue();
* @param fnr a valid field index
* obj a reference to an arbitrary receiving object
*/
public int bindVar(int fnr, int tpe, Object o){
check("bindVar");
if( !checkColumns(fnr,"bindVar")) return MERROR;
System.out.println("bindVar() not supported");
//columns[fnr].outparam = o;
return MOK;
}
/**
* Binding an input parameter to an object simplifies transfer,
* values are passed to the receiver using the method setValue();
* @param fnr a valid field index
* scale
* precision
* obj a reference to an arbitrary receiving object
*/
public int bindNumeric(int fnr, int scale, int prec, Object o){
check("bindNumeric");
if( !checkColumns(fnr,"bindVar")) return MERROR;
System.out.println("bindVar() not supported");
columns[fnr].scale = scale;
columns[fnr].precision = prec;
//columns[fnr].outparam = o;
return MOK;
}
// ------------------------ Columns handling
/**
* Columns management realizes the tabular display structure envisioned.
*/
private int extendColumns(int mf){
if(mf<maxfields) return MOK;
int nm= maxfields+32;
if( nm <= mf)
nm= mf+32;
if( trace) traceLog.println("extendColumns:"+nm);
Column nf[]= new Column[nm];
System.arraycopy(columns,0,nf,0,maxfields);
columns= nf;
maxfields= nm;
return MOK;
}
private void extendFields(int cr){
if( trace) traceLog.println("extendFields:"+cr);
if(cache.fields== null ){
String anew[]= new String[maxfields];
if( cache.fields[cr]!= null)
System.arraycopy(cache.fields[cr],0,anew,0,cache.fldcnt[cr]);
cache.fields[cr]= anew;
}
}
/**
* The values of a row are delivered to any bounded variable before
* fetch_row returns. Automatic conversion based on common types
* simplifies the work for the programmers.
*/
private void storeBind(){
System.out.print("storeBind() Not supported");
//int cr= cache.reader;
//for(int i=0; i< fieldcnt; i++)
//if( columns[i].outparam != null){
//columns[i].outparam.setValue(s);
//}
}
/**
* The slice row constructs a list of string field values.
* It trims the string quotes but nothing else.
*/
public int sliceRow(){
int cr= cache.reader;
if(cr<0 || cr >= cache.writer){
setError("Current row missing","sliceRow");
return 0;
}
String s= cache.rows[cr];
if( s== null){
setError("Current row missing","sliceRow");
return 0;
}
// avoid duplicate slicing
if( cache.fldcnt[cr]>0) return cache.fldcnt[cr];
if( s.length()==0) return 0;
char p[]= s.toCharArray();
int i=0;
int f=1,l;
if( p[0]=='!'){
String olderr= errortext;
clrError();
setError(olderr+s,"sliceRow");
return 0;
}
if( p[0]!='['){
if(trace) traceLog.println("Single field:"+s);
cache.fields[cr][0]= s;
// count filds by counting the type columns in header
// each type looks like (str)\t
i=0;
for(int k=1; k<p.length; k++)
if( p[k]=='\t' && p[k-1]==')') i++;
if( fieldcnt<i) fieldcnt= i;
if(trace) traceLog.println("type cnt:"+i);
return 1;
}
if( trace) traceLog.println("slice:"+(p.length)+":"+s);
do{
// skip leading blancs
while(f<p.length )
if( p[f]=='\t' || p[f] ==' ') f++; else break;
if(f==p.length || p[f]==']') break;
if(i== maxfields){
if( extendColumns(maxfields+32) != MOK)
return 0;
for(int j=0;j<cache.limit;j++)
if( cache.fields[j] != null)
extendFields(j);
}
l=f+1;
// slicing the row should respect the string/char literal
boolean instring=s.charAt(f)=='"' || s.charAt(f)=='\'';
char bracket= instring? s.charAt(f) :'\t';
if(instring) f++;
boolean done =false;
boolean unescape = false;
while(!done && l<p.length ){
switch(p[l]){
case '\t':
case ']':
done = !instring;
if( !done) l++;
break;
case ',':
if(!instring){
done= true;
break;
}
l++;
break;
case '\\': l+=2; unescape=true; break;
case '\'':
case '"':
if(instring ){
//System.out.println("bracket:"+p[l]+l);
if( bracket==p[l]) {
done=true;
break;
}
}
default: l++;
}
}
String fld= s.substring(f,l);
if (unescape) {
fld = fld.replaceAll("\\\\n","\n");
fld = fld.replaceAll("\\\\t","\t");
fld = fld.replaceAll("\\\\","\\");
}
if(trace) traceLog.println("field ["+cr+"]["
+i+" "+l+"]"+fld+":"+instring+":");
cache.fields[cr][i]= fld;
// skip any immediate none-space
while(l<p.length )
if( p[l]=='\t' || p[l] ==' ') break; else l++;
if(trace && instring) traceLog.println("skipped to:"+l);
f= l;
i++;
cache.fldcnt[cr]=i;
if(i>fieldcnt) fieldcnt=i;
} while(f< p.length && p[f]!=']');
if(trace) traceLog.println("fields extracted:"+i+" fieldcnt:"+fieldcnt);
return i;
}
/**
* The fetchRow() retrieves a tuple from the server
*/
public int fetchRow(){
check("fetchRow");
if( getRow()==MOK ) return sliceRow();
return 0;
}
public int fetchAllRows(){
check("fetchAllRows");
cacheLimit(-1);
while( getRow()== MOK)
sliceRow();
fetchReset();
return cache.tupleCount;
}
public String fetchField(int fnr){
check("fetchField");
int cr= cache.reader;
if(cr <0 || cr >cache.writer) {
setError("No tuple in cache","fetchField");
return null;
}
if( fnr>=0){
if( cache.fldcnt[cr]==0){
//System.out.println("reslice");
sliceRow();
}
if( fnr < cache.fldcnt[cr])
return cache.fields[cr][fnr];
}
if( fnr== -1)
// fetch complete tuple
return cache.rows[cr];
setError("Illegal field","fetchField");
return null;
}
public String[] fetchFieldArray(int fnr){
check("fetchField");
int cr = cache.reader;
if(cr <0) {
setError("No tuple in cache","fetchFieldArray");
return null;
}
String f[]= new String[cache.fldcnt[cr]];
for(int i=0;i<cache.fldcnt[cr]; i++)
f[i]= cache.fields[cr][i];
return f;
}
public synchronized int getColumnCount(){
check("getColumnCount");
return fieldcnt;
}
public synchronized String getColumnName(int i){
check("getColumnName");
if(i<fieldcnt && columns[i]!= null && columns[i].columnname!= null)
return columns[i].columnname;
return "str";
}
public synchronized String getColumnType(int i){
check("getColumnType");
if(i<fieldcnt && columns[i]!= null && columns[i].columntype!= null)
return columns[i].columntype;
return "";
}
public synchronized int getRowCount(){
check("getRowCount");
return rows_affected;
}
public String getName(int fnr){
check("getName");
int cr= cache.reader;
if(cr <0) {
setError("No tuple in cache","getName");
return null;
}
if( fnr >=0 && fnr < cache.fldcnt[cr]){
if(columns[fnr].columnname== null)
columns[fnr].columnname= "column_"+fnr;
return columns[fnr].columnname;
}
setError("Illegal field","getName");
return null;
}
public String getTable(int fnr){
check("getTable");
int cr= cache.reader;
if(cr <0) {
setError("No tuple in cache","getTable");
return null;
}
if( fnr >=0 && fnr < cache.fldcnt[cr]){
if(columns[fnr].tablename== null)
columns[fnr].tablename= "table_"+fnr;
return columns[fnr].tablename;
}
setError("Illegal field","getName");
return null;
}
public int rows_affected(){
check("rows_affected");
return rows_affected;
}
public String getHost(){
check("getHost");
return host;
}
public String getUser(){
check("getUser");
return username;
}
public String getPassword(){
check("getPassword");
return password;
}
public String getLanguage(){
check("getLanguage");
return language;
}
public String getDBname(){
check("getDBname");
return language;
}
public int getPort(){
check("getPort");
return port;
}
public String getMapiVersion(){
check("getMapiVersion");
return mapiversion;
}
public String getMonetVersion(){
check("getMonetVersion");
return version;
}
public int getMonetId(){
check("getMonetId");
if(version!=null && version.charAt(0)=='4') return 4;
return 4;
}
// ------------------------ Handling queries
/**
* The routine mapi_check_query appends the semicolon and new line if needed.
* Furthermore, it ensures that no 'false' newlines are sent to the server,
* because this may lead to a synchronization error easily.
*/
private void expandQuery(String xtra){
String n= query+xtra;
query = n;
if( qrytemplate != null) qrytemplate= n;
if( trace) traceLog.print("Modified query:"+query);
}
private void checkQuery(){
clrError();
int i = query.indexOf('\n');
if( i>=0 && i < query.length()-1)
setError("Newline in query string not allowed","checkQuery");
query.replace('\n',' ');
// trim white space
int j= query.length()-1;
while(j>0 && (query.charAt(j)==' ' || query.charAt(j)=='\t')) j--;
if( j != query.length()-1) query= query.substring(0,j+1);
// check for unbalanced string quotes
byte qbuf[]= query.getBytes();
boolean instring=false;
char quote=' ';
for(j=0; j<qbuf.length; j++){
switch(qbuf[j]){
case '\\':j++; break;
case '"': if(instring){
if( quote== '"') { instring=false;quote=' ';}
} else{ quote='"'; instring=true;}
break;
case '\'': if(instring){
if( quote== '\'') { instring=false;quote=' ';}
} else{ quote='\''; instring=true;}
} }
if(quote!=' ') expandQuery(""+quote);
if( language.equals("sql")){
i= query.lastIndexOf(';');
if( i != query.length()-1) expandQuery(";");
}
expandQuery("\n");
}
/**
* The query string may contain place holders, which should be replaced
* by the arguments presented
*/
private int prepareQueryInternal(String cmd){
if( cmd == null || cmd.length()==0){
// use previous query
if(query==null) query="";
} else {
query = cmd;
qrytemplate= null;
int i= cmd.indexOf(PLACEHOLDER);
if( i>=0 && i < cmd.length()){
qrytemplate = query;
}
}
checkQuery();
return error;
}
/**
* Move the query to the connection structure. Possibly interact with the
* back-end to prepare the query for execution.
* @param cmd the command string to be executed
*/
public int prepareQuery(String cmd){
check("prepareQuery");
return prepareQueryInternal(cmd);
}
/**
* Move the query to the connection structure. Possibly interact with the
* back-end to prepare the query for execution.
* @param cmd the command string to be executed
* arg replacement strings for each of the placeholders
*/
private int prepareQueryArrayInternal(String cmd, String arg[]){
int ret= prepareQuery(cmd);
if( ret != MOK) return ret;
// get rid of the previous field bindings
for(int i=0; i< fieldcnt; i++) {
//columns[i].inparam= null;
}
int lim= arg.length;
if( lim > fieldcnt)
extendColumns(lim);
for(int i=0; i< lim; i++) {
//columns[i].inparam= arg[i];
}
return error;
}
public int prepareQueryArray(String cmd, String arg[]){
check("prepareQueryArray");
return prepareQueryArrayInternal(cmd,arg);
}
/**
* Before we ship a query, all placeholders should be removed
* and the actual values should take their position.
* Replacement should be able to hangle PLACEHOLDERS in the arguments.
*/
private void paramStore(){
if(qrytemplate == null || qrytemplate.length()==0) return;
query = qrytemplate;
int p, pr=0;
for(int i=0; i< fieldcnt; i++){
String left,right;
p= query.indexOf(PLACEHOLDER,pr);
if( p == pr){
// no more placeholders
setError("Not enough placeholders","paramStore");
break;
}
left = query.substring(0,p-1);
right= query.substring(p+1,query.length());
//query= left+columns[i].inparam.toString()+right;
}
if( trace) traceLog.println("paramStore:"+query);
}
/**
* The command is shipped to the backend for execution. A single answer
* is pre-fetched to detect any runtime error. A NULL command is
* interpreted as taking the previous query. MOK is returned upon success.
* The fake queries '#trace on' and '#trace off' provide an easy means
* to toggle the trace flag.
*/
private int executeInternal(){
try {
if( query.startsWith("#trace on")){
trace= true;
traceLog.println("Set trace on");
}
if( query.startsWith("#trace off")){
traceLog.println("Set trace off");
trace= false;
}
if (tableid >= 0) {
if (trace) traceLog.println("execute: Xclose");
toMonet.writeBytes("Xclose " + tableid + "\n" );
toMonet.flush();
do {
blk.buf = fromMonet.readLine();
if(trace) traceLog.println("gotLine:"+blk.buf);
} while( blk.buf.charAt(0) != PROMPTBEG);
promptMonet();
}
if(trace) traceLog.print("execute:"+query);
paramStore();
cacheResetInternal();
toMonet(query);
} catch(Exception e) {
setError(e.toString(),"execute");
}
return error;
}
public int execute(){
check("execute");
return executeInternal();
}
/**
* The command is shipped to the backend for execution. A single answer
* is pre-fetched to detect any runtime error. A NULL command is
* interpreted as taking the previous query. MOK is returned upon success.
* @param arg the list of place holder values
*/
public int executeArray(String arg[]){
prepareQueryArrayInternal(query,arg);
return error==MOK ? executeInternal(): error;
}
/**
* This routine sends the Command to the database server.
* It is one of the most common operations.
* If Command is null it takes the last query string kept around.
* It returns zero upon success, otherwise it indicates a failure of the request.
* The command response is buffered for consumption, e.g. fetchRow();
* @param cmd - the actual command to be executed
*/
private int answerLookAhead(){
// look ahead to detect errors
int oldrd= cache.reader;
do{
getRow();
} while(error==MOK && active &&
cache.writer+1< cache.limit);
cache.reader= oldrd;
if(trace ) traceLog.println("query return:"+error);
return error;
}
public int query(String cmd){
if (active) {
System.out.println("still active " + query );
}
if(cmd == null) return setError("Null query","query");
prepareQueryInternal(cmd);
if( error== MOK) executeInternal();
if( error== MOK) answerLookAhead();
return error;
}
/**
* This routine sends the Command to the database server.
* It is one of the most common operations.
* If Command is null it takes the last query string kept around.
* It returns zero upon success, otherwise it indicates a failure of the request.
* The command response is buffered for consumption, e.g. fetchRow();
* @param cmd - the actual command to be executed
arg - the place holder values
*/
public int queryArray(String cmd, String arg[]){
if(cmd == null) return setError("Null query","queryArray");
prepareQueryArrayInternal(cmd,arg);
if( error== MOK) executeInternal();
if( error== MOK) answerLookAhead();
return error;
}
/**
* To speed up interaction with a terminal front-end,
* the user can issue the quick_*() variants.
* They will not analyse the result for errors or
* header information, but simply through the output
* received from the server to the stream indicated.
*/
public int quickQuery(String cmd, DataOutputStream fd){
check("quickQuery");
if(cmd == null) return setError("Null query","queryArray");
prepareQueryInternal(cmd);
if( error== MOK) executeInternal();
if( error== MOK) quickResponse(fd);
if(trace && error !=MOK) traceLog.println("query returns error");
return error;
}
public int quickQueryArray(String cmd, String arg[], DataOutputStream fd){
check("quickQueryArray");
if(cmd == null) return setError("Null query","quickQueryArray");
prepareQueryArrayInternal(cmd,arg);
if( error== MOK) executeInternal();
if( error== MOK) quickResponse(fd);
if(trace && error !=MOK) traceLog.println("query returns error");
return error;
}
/**
* Stream queries are request to the database engine that produce a stream
* of answers of indefinite length. Elements are eaten away using the normal way.
* The stream ends with encountering the prompt.
* A stream query can not rely on upfront caching.
* The stream query also ensures that the cache contains a sliding window
* over the stream by shuffling tuples once it is filled.
* @param cmd - the query to be executed
* window- the window size to be maintained in the cache
*/
public int openStream(String cmd, int windowsize){
check("openStream");
if(cmd == null) return setError("Null query","openStream");
query(cmd);
if( gotError()) return error;
// reset the active flag to enable continual reads
// stolen part of cacheResetInternal();
finish_internal();
rows_affected= 0;
active= true;
if( cache.fldcnt==null)
cache.fldcnt = new int[cache.limit];
cache.tupleCount= 0;
cacheFreeup(100);
cacheLimit(windowsize);
cacheShuffle(1);
return error;
}
/**
* A stream can be closed by sending a request to abort the
* further generation of tuples at the server side.
* Note that we do not wait for any reply, because this will
* appear at the stream-reader, a possibly different thread.
*/
public int closeStream(String cmd){
prepareQueryInternal(cmd);
paramStore();
try{
toMonet(query);
} catch( MapiException m){
setError("Write error on stream","execute");
}
return error;
}
// -------------------- Cache Management ------------------
/**
* Empty the cache is controlled by the shuffle percentage.
* It is a factor between 0..100 and indicates the number of space
* to be freed each time the cache should be emptied
* @param percentage - amount to be freed
*/
public int cacheFreeup(int percentage){
if( cache.writer==0 && cache.reader== -1) return MOK;
if( percentage==100){
//System.out.println("allocate new cache struct");
cache= new RowCache();
return MOK;
}
if( percentage <0 || percentage>100) percentage=100;
int k= (cache.writer * percentage) /100;
if( k < 1) k =1;
if(trace) System.out.println("shuffle cache:"+percentage+" tuples:"+k);
for(int i=0; i< cache.writer-k; i++){
cache.rows[i]= cache.rows[i+k];
cache.fldcnt[i]= cache.fldcnt[i+k];
cache.fields[i]= cache.fields[i+k];
}
for(int i=k; i< cache.limit; i++){
cache.rows[i]= null;
cache.fldcnt[i]=0;
cache.fields[i]= new String[maxfields];
for(int j=0;j<maxfields;j++)
cache.fields[i][j]= null;
}
cache.reader -=k;
if(cache.reader < -1) cache.reader= -1;
cache.writer -=k;
if(cache.writer < 0) cache.writer= 0;
if(trace) System.out.println("new reader:"+cache.reader+" writer:"+cache.writer);
//rebuild the tuple index
cache.tupleCount=0;
int i=0;
for(i=0; i<cache.writer; i++){
if( cache.rows[i].indexOf("#")==0 ) continue;
if( cache.rows[i].indexOf("!")==0 ) continue;
cache.tuples[cache.tupleCount++]= i;
}
for(i= cache.tupleCount; i<cache.limit; i++)cache.tuples[i]= -1;
return MOK;
}
/**
* CacheReset throws away any tuples left in the cache and
* prepares it for the next sequence;
* It should re-size the cache too.
* It should retain the field information
*/
private void cacheResetInternal()
{
finish_internal();
rows_affected= 0;
active= true;
if( cache.fldcnt==null)
cache.fldcnt = new int[cache.limit];
// set the default for single columns
for(int i=1;i<fieldcnt;i++) columns[i]=null;
fieldcnt=1;
if(columns[0]!= null){
columns[0].columntype="str";
}
cache.tupleCount= 0;
cacheFreeup(100);
}
/**
* Users may change the cache size limit
* @param limit - new limit to be obeyed
* shuffle - percentage of tuples to be shuffled upon full cache.
*/
public int cacheLimit(int limit){
cache.rowlimit= limit;
return MOK;
}
/**
* Users may change the cache shuffle percentage
* @param shuffle - percentage of tuples to be shuffled upon full cache.
*/
public int cacheShuffle(int shuffle){
if( shuffle< -1 || shuffle>100) {
cache.shuffle=100;
return setError("Illegal shuffle percentage","cacheLimit");
}
cache.shuffle= shuffle;
return MOK;
}
/**
* Reset the row pointer to the first line in the cache.
* This need not be a tuple.
* This is mostly used in combination with fetching all tuples at once.
*/
public int fetchReset(){
check("fetchReset");
cache.reader = -1;
return MOK;
}
/**
* Reset the row pointer to the requested tuple;
* Tuples are those rows that not start with the
* comment bracket. The mapping of tuples to rows
* is maintained during parsing to speedup subsequent
* access in the cache.
* @param rownr - the row of interest
*/
public int seekRow(int rownr){
check("seekRow");
int i, sr=rownr;
cache.reader= -1;
if( rownr<0) return setError("Illegal row number","seekRow");
i= cache.tuples[rownr];
if(i>=0) {
cache.reader= i;
return MOK;
}
/*
for(i=0; rownr>=0 && i<cache.writer; i++){
if( cache.rows[i].indexOf("#")==0 ) continue;
if( cache.rows[i].indexOf("!")==0 ) continue;
if( --rownr <0) break;
}
if( rownr>=0) return setError("Row not found "+sr
+" tuples "+cache.tuples,"seekRow");
cache.reader= i;
return MOK;
*/
return setError("Illegal row number","seekRow");
}
/**
* These are the lowest level operations to retrieve a single line from the
* server. If something goes wrong the application may try to skip input to
* the next synchronization point.
* If the cache is full we reshuffle some tuples to make room.
*/
private void extendCache(){
int oldsize= cache.limit;
if( oldsize == cache.rowlimit){
System.out.println("Row cache limit reached extendCache");
setError("Row cache limit reached","extendCache");
// shuffle the cache content
if( cache.shuffle>0)
System.out.println("Reshuffle the cache ");
}
int incr = oldsize ;
if(incr >200000) incr= 20000;
int newsize = oldsize +incr;
if( newsize >cache.rowlimit && cache.rowlimit>0)
newsize = cache.rowlimit;
String newrows[]= new String[newsize];
int newtuples[]= new int[newsize];
if(oldsize>0){
System.arraycopy(cache.tuples,0,newtuples,0,oldsize);
System.arraycopy(cache.rows,0,newrows,0,oldsize);
cache.rows= newrows;
cache.tuples= newtuples;
//if(trace) traceLog.println("Extend the cache.rows storage");
}
int newfldcnt[]= new int[newsize];
if(oldsize>0){
System.arraycopy(cache.fldcnt,0,newfldcnt,0,oldsize);
cache.fldcnt= newfldcnt;
//if(trace) traceLog.println("Extend the cache.fldcnt storage");
for(int i=oldsize;i<newsize;i++) cache.fldcnt[i]=0;
}
String newfields[][]= new String[newsize][];
if(oldsize>0){
System.arraycopy(cache.fields,0,newfields,0,oldsize);
cache.fields= newfields;
//if(trace) traceLog.println("Extend the cache.fields storage");
for(int i=oldsize;i<newsize;i++)
cache.fields[i]= new String[maxfields];
}
cache.limit= newsize;
}
private int clearCache(){
// remove all left-over fields
if( cache.reader+2<cache.writer){
System.out.println("Cache reset with non-read lines");
System.out.println("reader:"+cache.reader+" writer:"+cache.writer);
setError("Cache reset with non-read lines","clearCache");
}
cacheFreeup(cache.shuffle);
return MOK;
}
// ----------------------- Basic line management ----------------
/**
* The fetchLine() method is the lowest level of interaction with
* the server to acquire results. The lines obtained are stored in
* a cache for further analysis.
*/
public String fetchLine() throws MapiException {
check("fetchLine");
return fetchLineInternal();
}
public String fetchLineInternal() throws MapiException {
if( cache.writer>0 && cache.reader+1<cache.writer){
if( trace) traceLog.println("useCachedLine:"+cache.rows[cache.reader+1]);
return cache.rows[++cache.reader];
}
if( ! active) return null;
error= MOK;
// get rid of the old buffer space
if( cache.writer ==cache.rowlimit){
clearCache();
}
// check if you need to read more blocks to read a line
blk.eos= false;
// fetch one more block or line
int n=0;
int len= 0;
String s="";
blk.buf= null;
if( !connected){
setError("Lost connection with server","fetchLine");
return null;
}
// we should reserve space
// manage the row cache space first
if( cache.writer >= cache.limit)
extendCache();
if( trace) traceLog.println("Start reading from server");
try {
blk.buf = fromMonet.readLine();
if(trace) traceLog.println("gotLine:"+blk.buf);
} catch(IOException e){
connected= false;
error= Mapi.MAPIERROR;
errortext= "Communication broken";
throw new MapiException( errortext);
}
if( blk.buf==null ){
blk.eos= true;
setError("Lost connection with server","fetchLine");
connected= false;
return null;
}
if( blk.buf.length()>0){
switch( blk.buf.charAt(0)){
case PROMPTBEG:
promptMonet();
return null;
case '[': cache.tuples[cache.tupleCount++]= cache.reader+1;
}
}
cache.rows[cache.writer] = blk.buf;
cache.writer++;
return cache.rows[++cache.reader];
}
/**
* If the answer to a query should be simply passed on towards a client,
* i.e. a stream, it pays to use the quickResponse() routine.
* The stream is only checked for occurrence of an error indicator
* and the prompt.
* The best way to use this shortcut execution is calling
* mapi_quick_query(), otherwise we are forced to first
* empy the row cache.
* @param fd - the file destination
*/
public int quickResponse(DataOutputStream fd){
String msg;
if( fd== null)
return setError("File destination missing","response");
try{
while( active && (msg=fetchLineInternal()) != null)
try{
fd.writeBytes(msg.toString());
fd.writeBytes("\n");
fd.flush();
} catch( IOException e){
throw new MapiException("Can not write to destination" );
}
} catch(MapiException e){
}
return error;
}
//------------------- Response analysis --------------
private void keepProp(String name, String colname){
}
// analyse the header row, but make sure it is restored in the end.
// Note that headers received contains an addition column with
// type information. It should be ignored while reading the tuples.
private void headerDecoder() {
String line= cache.rows[cache.reader];
if (trace)
traceLog.println("header:"+line);
int etag= line.lastIndexOf("#");
if(etag==0 || etag== line.length())
return;
String tag= line.substring(etag);
cache.rows[cache.reader]="[ "+cache.rows[cache.reader].substring(1,etag);
int cnt= sliceRow();
if (trace)
traceLog.println("columns "+cnt);
extendColumns(cnt);
if (tag.equals("# name")) {
for (int i=0;i<cnt;i++) {
if(columns[i]==null) columns[i]= new Column();
String s= columns[i].columnname= fetchField(i);
}
} else if (tag.equals("# type")) {
for(int i=0;i<cnt;i++) {
String type = fetchField(i);
if (columns[i]==null)
columns[i] = new Column();
columns[i].columntype = type;
if (trace)
traceLog.println("column["+i+"].type="+columns[i].columntype);
}
} else if (tag.equals("# id")) {
String s = fetchField(0);
try {
tableid = Integer.parseInt(s);
} catch (Exception e) {
//ignore;
}
if (trace)
traceLog.println("got id " + tableid + " \n");
} else if (trace)
traceLog.println("Unrecognized header tag "+tag);
//REST LATER
cache.rows[cache.reader]= line;
}
// Extract the next row from the cache.
private int getRow(){
String reply= "";
//if( trace) traceLog.println("getRow:active:"+active+
//" reader:"+(cache.reader+1)+" writer:"+cache.writer);
while( active ||cache.reader+1< cache.writer){
if( active){
try{
reply= fetchLineInternal();
} catch(MapiException e){
if(trace)
traceLog.print("Got exception in getRow");
reply=null;
}
if( gotError() || reply == null) return MERROR;
} else reply = cache.rows[++cache.reader];
if(trace) traceLog.println("getRow:"+cache.reader);
if( reply.length()>0)
switch(reply.charAt(0)){
case '#':
headerDecoder();
return getRow();
case '!':
// concatenate error messages
String olderr= errortext;
clrError();
setError(olderr+reply.toString(),"getRow");
return getRow();
default:
return MOK;
}
}
return MERROR;
}
// ------------------------------- Utilities
/** The java context provides a table abstraction
* the methods below provide access to the relevant Mapi components
*/
public int getTupleCount(){
//int cnt=0;
return cache.tupleCount;
//for(int i=0;i<cache.writer;i++){
//if(cache.rows[i].charAt(0)=='[') cnt++;
//}
//System.out.println("counted "+cnt+" maintained "+cache.tuples);
//return cnt;
}
/**
* unquoteInternal() squeezes a character array to expand
* all quoted characters. It also removes leading and trailing blancs.
* @param msg - the byte array to be
*/
private int unquoteInternal(char msg[], int first)
{
int f=0, l=0;
for(; f< msg.length; f++)
if( msg[f] != ' ' && msg[f]!= '\t') break;
if( f< msg.length && (msg[f]=='"' || msg[f]=='\'')){
f++;
for(l=f+1; l<msg.length && !(msg[l]=='"' || msg[l]=='\''); l++);
l--;
} else {
}
return f;
}
public String quote(String msg){
System.out.println("Not yet implemented");
return null;
}
/**
* Unquote removes the bounding brackets from strings received
*/
public String unquote(String msg){
char p[]= msg.toCharArray();
int f=0,l=f;
char bracket= ' ';
while(f<p.length && p[f]==' ') f++;
if( f<p.length) bracket = p[f];
if( bracket == '"' || bracket== '\''){
l= msg.lastIndexOf(bracket);
if( l<=f){
if(trace)
traceLog.println("closing '"+bracket+"' not found:"+msg);
return msg;
}
return msg.substring(f+1,l);
} else
// get rid of comma except when it is a literal char
if( p[f]!=',' && p[p.length-1]==',') msg= msg.substring(f,p.length-1);
return msg;
}
/**
* Unescape reconstructs the string by replacing the escaped characters
*/
public String unescape(String msg){
char p[]= msg.toCharArray();
int f=0,l=f;
String newmsg;
for(; f< p.length;f++,l++)
if( p[f]=='\\') {
switch(p[++f]){
case 't':p[l]='\t'; break;
case 'n':p[l]='\n'; break;
default: p[l]=p[f];
}
} else p[l]=p[f];
if( l== p.length) return msg;
newmsg= new String(p,0,l);
//System.out.println("unescaped:"+msg+"->" +newmsg);
return newmsg;
}
public boolean gotError(){
return error!=MOK;
}
public String getErrorMsg(){
return errortext;
}
public String getExplanation(){
return "Mapi:"+dbname+"\nERROR:"+errortext+"\nERRNR:"+error+
"\nACTION:"+action+"\nQUERY:"+query+"\n";
}
public String getPrompt(){
return prompt;
}
public boolean isConnected(){
return connected;
}
/*
The low-level operation toMonet attempts to send a string to the server.
It assumes that the string is properly terminated and a connection to
the server still exists.
*/
private void toMonet(String msg) throws MapiException {
if( ! connected)
throw new MapiException( "Connection was disabled" );
if( msg== null || msg.equals("")){
if(trace)
traceLog.println("Attempt to send an empty message");
return;
}
try{
if( trace) traceLog.println("toMonet:"+msg);
int size= msg.length();
if( language.equals("sql"))
toMonet.writeBytes("S");
toMonet.writeBytes(msg);
toMonet.flush();
} catch( IOException e){
throw new MapiException("Can not write to Monet" );
}
}
/**
* The routine timeout can be used to limit the server handling requests.
* @parem time the timeout in milliseconds
*/
public int timeout(int time){
check("timeout");
System.out.println("timeout() not yet implemented");
return MOK;
}
/**
* The routine explain() dumps the status of the latest query to standard out.
*/
public int explain(){
System.out.println(getExplanation());
return MOK;
}
public void sortColumn(int col){
cache.sortColumn(col);
}
class IoCache
{ String buf="";
boolean eos;
public IoCache(){
eos = false;
}
}
class RowCache{
int rowlimit= -1; /* maximal number of rows to cache */
int shuffle= 100; /* percentage of tuples to shuffle upon overflow */
int limit=10000; /* current storage space limit */
int writer= 0;
int reader= -1;
int fldcnt[] = new int[limit]; /* actual number of columns in each row */
String rows[]= new String[limit]; /* string representation of rows received */
String fields[][]= new String[limit][];
int tuples[]= new int[limit]; /* tuple index */
int tupleCount=0;
public RowCache(){
for(int i=0;i<limit; i++){
fields[i]= new String[maxfields];
rows[i]=null;
tuples[i]= -1;
fldcnt[i]=0;
for(int j=0;j<maxfields;j++) fields[i][j]= null;
}
}
private void dumpLine(int i){
System.out.println("cache["+i+"] fldcnt["+fldcnt[i]+"]");
for(int j=0;j<fldcnt[i];j++)
System.out.println("field["+i+"]["+j+"] "+fields[i][j]);
}
private void dumpCacheStatus(){
System.out.println("cache limit="+rowlimit+
"shuffle="+shuffle+
"limit="+limit+
"writer="+writer+
"reader"+reader+
"tupleCount"+tupleCount);
}
//---------------------- Special features ------------------------
/**
* Retrieving the tuples in a particular value order is a recurring
* situation, which can be accomodated easily through the tuple index.
* Calling sorted on an incomplete cache doesn;t produce the required
* information.
* The sorting function is rather expensive and not type specific.
* This should be improved in the near future
*/
public void sortColumn(int col){
if( col <0 || col > maxfields) return;
// make sure you have all tuples in the cache
// and that they are properly sliced
fetchAllRows();
int direction = columns[col].direction;
columns[col].direction = -direction;
if( columns[col].columntype.equals("int") ||
columns[col].columntype.equals("lng") ||
columns[col].columntype.equals("ptr") ||
columns[col].columntype.equals("oid") ||
columns[col].columntype.equals("void") ||
columns[col].columntype.equals("sht")
){
sortIntColumn(col);
return;
}
if( columns[col].columntype.equals("flt") ||
columns[col].columntype.equals("dbl")
){
sortDblColumn(col);
return;
}
int lim= cache.tupleCount;
for(int i=0;i<lim; i++){
if(fields[tuples[i]][col]== null)
System.out.println("tuple null:"+i+" "+tuples[i]);
for(int j=i+1;j<lim; j++){
String x= fields[tuples[i]][col];
String y= fields[tuples[j]][col];
if( direction>0){
if(y!=null && x!=null && y.compareTo(x) >0 ){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
}
} else
if( direction<0){
if(y!=null && x!=null && y.compareTo(x) <0){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
}
}
}
}
}
private void sortIntColumn(int col){
int direction = columns[col].direction;
int lim= cache.tupleCount;
long val[]= new long[lim];
String sv;
for(int i=0; i<lim; i++){
sv= fields[tuples[i]][col];
if(sv==null){
val[i]= Long.MIN_VALUE;
System.out.println("tuple null:"+i+" "+tuples[i]);
//dumpLine(tuples[i]);
//seekRow(tuples[i]);
//sliceRow();
//dumpLine(tuples[i]);
continue;
}
int k= sv.indexOf("@");
if(k>0) sv= sv.substring(0,k);
try{
val[i]= Long.parseLong(sv);
} catch(NumberFormatException e){
val[i]= Long.MIN_VALUE;}
}
for(int i=0;i<lim; i++){
for(int j=i+1;j<lim; j++){
long x= val[i];
long y= val[j];
if( (direction>0 && y>x) ||
(direction<0 && y<x) ){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
val[i]= y;
val[j]= x;
}
}
}
}
private void sortDblColumn(int col){
int direction = columns[col].direction;
int lim= cache.tupleCount;
double val[]= new double[lim];
String sv;
for(int i=0; i<lim; i++){
sv= fields[tuples[i]][col];
if(sv==null){
System.out.println("tuple null:"+i+" "+tuples[i]);
val[i]= Double.MIN_VALUE;
continue;
}
try{
val[i]= Double.parseDouble(sv);
} catch(NumberFormatException e){
val[i]= Double.MIN_VALUE;}
}
for(int i=0;i<lim; i++){
for(int j=i+1;j<lim; j++){
double x= val[i];
double y= val[j];
if( (direction>0 && y>x) ||
(direction<0 && y<x) ){
int z= tuples[i];
tuples[i]= tuples[j];
tuples[j]= z;
val[i]= y;
val[j]= x;
}
}
}
}
}
class Column{
String tablename=null;
String columnname=null;
String columntype=null;
int colwidth;
int coltype;
int precision;
int scale;
int isnull;
int direction= -1;
//Object inparam; // to application variable
//Object outparam; // both are converted to strings
}
}
| src/mapi/clients/java/mapi/Mapi.java:
- replaced replaceALL calls, which made Mapi depend on Java 1.4.x and a
buggy regexp implementation, by a call to the new unescapeMILstr method
| MonetDB/src/mapi/clients/java/mapi/Mapi.java | src/mapi/clients/java/mapi/Mapi.java: - replaced replaceALL calls, which made Mapi depend on Java 1.4.x and a buggy regexp implementation, by a call to the new unescapeMILstr method | <ide><path>onetDB/src/mapi/clients/java/mapi/Mapi.java
<ide> }
<ide>
<ide> /**
<add> * unescape a MIL string
<add> **/
<add>public String unescapeMILstr(String str) {
<add> if (str == null)
<add> return null;
<add> char[] src = str.toCharArray();
<add> char[] dst = new char[src.length];
<add> boolean unescape = false;
<add> int d = 0;
<add> for (int s=0;s<src.length;s++) {
<add> switch (src[s]) {
<add> case '\\':
<add> if (!unescape) {
<add> unescape = true;
<add> continue;
<add> } else
<add> dst[d++] = '\\';
<add> break;
<add> case 'n':
<add> dst[d++] = (unescape?'\n':'n');
<add> break;
<add> case 't':
<add> dst[d++] = (unescape?'\t':'t');
<add> break;
<add> default:
<add> dst[d++] = src[s];
<add> }
<add> unescape = false;
<add> }
<add> return new String(dst);
<add>}
<add>
<add>/**
<ide> * The slice row constructs a list of string field values.
<ide> * It trims the string quotes but nothing else.
<ide> */
<ide> }
<ide>
<ide> String fld= s.substring(f,l);
<del> if (unescape) {
<del> fld = fld.replaceAll("\\\\n","\n");
<del> fld = fld.replaceAll("\\\\t","\t");
<del> fld = fld.replaceAll("\\\\","\\");
<del> }
<add> if (unescape)
<add> fld = unescapeMILstr(fld);
<ide>
<ide> if(trace) traceLog.println("field ["+cr+"]["
<ide> +i+" "+l+"]"+fld+":"+instring+":"); |
|
Java | mit | e135d631a656a6fc7a4dda97e5b7fb243bdad007 | 0 | chr-krenn/chr-krenn-fhj-ws2016-sd14-pse,chr-krenn/chr-krenn-fhj-ws2016-sd14-pse,chr-krenn/chr-krenn-fhj-ws2016-sd14-pse | package at.fhj.swd14.pse.person;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import at.fhj.swd14.pse.base.IntegrationTestUtil;
import at.fhj.swd14.pse.database.DatabaseTestUtil;
import at.fhj.swd14.pse.user.UserConverter;
public class PersonServiceIntegrationTest {
private PersonService service;
private EntityManager manager;
@Before
public void setup()
{
service = IntegrationTestUtil.getService(PersonService.class);
manager = DatabaseTestUtil.getEntityManager();
}
private Person getAnyPerson()
{
List<Person> persons = manager.createQuery("SELECT p FROM Person p", Person.class).getResultList();
Assert.assertTrue(persons.size()>0);
return persons.get(0);
}
private void validatePerson(Person expected, PersonDto actual)
{
Assert.assertNotNull(actual);
PersonDtoTester.assertEquals(PersonConverter.convert(expected), actual);
}
@Test
public void testFind()
{
Person person = getAnyPerson();
PersonDto foundPerson = service.find(person.getId());
validatePerson(person,foundPerson);
}
@Test
public void testFindByUser()
{
Person person = getAnyPerson();
PersonDto foundPerson = service.findByUser(UserConverter.convert(person.getUser()));
validatePerson(person,foundPerson);
}
@Test
public void testSaveLoggedInPerson()
{
EntityTransaction trans = manager.getTransaction();
trans.begin();
Person person = getAnyPerson();
//just modify a field in the person
String oldAddress = person.getAddress();
String expectedAddress = person.getAddress()!=null?person.getAddress()+"Test":"Test";
person.setAddress(expectedAddress);
service.saveLoggedInPerson(PersonConverter.convert(person));
trans.rollback();
//manager.refresh(person);
person = manager.find(Person.class, person.getId());
trans.begin();
String actualAddress = person.getAddress();
person.setAddress(oldAddress);
manager.merge(person);
manager.flush();
trans.commit();
Assert.assertEquals(expectedAddress, actualAddress);
}
@Test
public void testFindAllStati()
{
final String[] stati = new String[]{"online","offline","abwesend"};
Collection<StatusDto> svcStati = service.findAllStati();
Assert.assertNotNull(svcStati);
Assert.assertEquals(3, svcStati.size());
int found = 0;
for(StatusDto status : svcStati)
{
for(int i = 0;i<stati.length;i++)
{
if(status.getName().equals(stati[i]))
{
found|=(int)Math.pow(2, i);
}
}
}
Assert.assertEquals((int)Math.pow(2, stati.length)-1, found);
}
@Test
public void testPersonImage()
{
EntityTransaction trans = manager.getTransaction();
trans.begin();
Person person = getAnyPerson();
//save any existing images
List<PersonImage> existingImgs = manager.createQuery("SELECT i FROM PersonImage i "
+ " WHERE i.person.id=:personid",PersonImage.class)
.setParameter("personid", person.getId())
.getResultList();
byte[] data = new byte[]{1,2,3,4};
service.savePersonImage(PersonConverter.convert(person), data,"image/jpeg");
trans.rollback();
List<PersonImage> newImgs=null;
newImgs = manager.createQuery("SELECT i FROM PersonImage i "
+ " WHERE i.person.id=:personid",PersonImage.class)
.setParameter("personid", person.getId())
.getResultList();
byte[] newData = newImgs.get(0).getData();
String newType = newImgs.get(0).getContentType();
trans.begin();
//restore the state
if(newImgs.size()>0)
manager.remove(newImgs.get(0));
if(existingImgs.size()>0)
manager.persist(existingImgs.get(0));
manager.flush();
trans.commit();
Assert.assertEquals(1, newImgs.size());
Assert.assertArrayEquals(data, newData);
Assert.assertEquals("image/jpeg", newType);
}
@Test
public void testGetPersonImage()
{
Person person = getAnyPerson();
//check if an image already exists, if not create one
List<PersonImage> existingImgs = manager.createQuery("SELECT i FROM PersonImage i "
+ " WHERE i.person.id=:personid",PersonImage.class)
.setParameter("personid", person.getId())
.getResultList();
EntityTransaction trans = manager.getTransaction();
PersonImage img = null;
if(existingImgs.size()==0)
{
trans.begin();
img = new PersonImage();
img.setId(null);
img.setContentType("image/jpeg");
img.setData(new byte[]{1,2,3,4});
img.setPerson(person);
manager.persist(img);
manager.flush();
trans.commit();
}
else
{
img = existingImgs.get(0);
}
PersonImageDto dto = service.getPersonImage(person.getId());
//restore original state
if(existingImgs.size()==0)
{
trans.begin();
manager.remove(img);
manager.flush();
trans.commit();
}
Assert.assertNotNull(dto);
Assert.assertEquals(img.getContentType(),dto.getContentType());
PersonDtoTester.assertEquals(PersonConverter.convert(person), dto.getPerson());
Assert.assertArrayEquals(img.getData(), dto.getData());
}
}
| backend/backend-impl/src/test/java/at/fhj/swd14/pse/person/PersonServiceIntegrationTest.java | package at.fhj.swd14.pse.person;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import at.fhj.swd14.pse.base.IntegrationTestUtil;
import at.fhj.swd14.pse.database.DatabaseTestUtil;
import at.fhj.swd14.pse.user.UserConverter;
public class PersonServiceIntegrationTest {
private PersonService service;
private EntityManager manager;
@Before
public void setup()
{
service = IntegrationTestUtil.getService(PersonService.class);
manager = DatabaseTestUtil.getEntityManager();
}
private Person getAnyPerson()
{
List<Person> persons = manager.createQuery("SELECT p FROM Person p", Person.class).getResultList();
Assert.assertTrue(persons.size()>0);
return persons.get(0);
}
private void validatePerson(Person expected, PersonDto actual)
{
Assert.assertNotNull(actual);
PersonDtoTester.assertEquals(PersonConverter.convert(expected), actual);
}
@Test
public void testFind()
{
Person person = getAnyPerson();
PersonDto foundPerson = service.find(person.getId());
validatePerson(person,foundPerson);
}
@Test
public void testFindByUser()
{
Person person = getAnyPerson();
PersonDto foundPerson = service.findByUser(UserConverter.convert(person.getUser()));
validatePerson(person,foundPerson);
}
@Test
public void testSaveLoggedInPerson()
{
EntityTransaction trans = manager.getTransaction();
trans.begin();
Person person = getAnyPerson();
//just modify a field in the person
String oldAddress = person.getAddress();
String expectedAddress = person.getAddress()!=null?person.getAddress()+"Test":"Test";
person.setAddress(expectedAddress);
service.saveLoggedInPerson(PersonConverter.convert(person));
trans.rollback();
//manager.refresh(person);
person = manager.find(Person.class, person.getId());
trans.begin();
String actualAddress = person.getAddress();
person.setAddress(oldAddress);
manager.merge(person);
manager.flush();
trans.commit();
Assert.assertEquals(expectedAddress, actualAddress);
}
@Test
public void testFindAllStati()
{
final String[] stati = new String[]{"online","offline","abwesend"};
Collection<StatusDto> svcStati = service.findAllStati();
Assert.assertNotNull(svcStati);
Assert.assertEquals(3, svcStati.size());
int found = 0;
for(StatusDto status : svcStati)
{
for(int i = 0;i<stati.length;i++)
{
if(status.getName().equals(stati[i]))
{
found|=(int)Math.pow(2, i);
}
}
}
Assert.assertEquals((int)Math.pow(2, stati.length)-1, found);
}
@Test
public void testPersonImage()
{
Person person = getAnyPerson();
//save any existing images
List<PersonImage> existingImgs = manager.createQuery("SELECT i FROM PersonImage i "
+ " WHERE i.person.id=:personid",PersonImage.class)
.setParameter("personid", person.getId())
.getResultList();
byte[] data = new byte[]{1,2,3,4};
service.savePersonImage(PersonConverter.convert(person), data,"image/jpeg");
List<PersonImage> newImgs=null;
newImgs = manager.createQuery("SELECT i FROM PersonImage i "
+ " WHERE i.person.id=:personid",PersonImage.class)
.setParameter("personid", person.getId())
.getResultList();
byte[] newData = newImgs.get(0).getData();
String newType = newImgs.get(0).getContentType();
EntityTransaction trans = manager.getTransaction();
trans.begin();
//restore the state
if(newImgs.size()>0)
manager.remove(newImgs.get(0));
if(existingImgs.size()>0)
manager.persist(existingImgs.get(0));
manager.flush();
trans.commit();
Assert.assertEquals(1, newImgs.size());
Assert.assertArrayEquals(data, newData);
Assert.assertEquals("image/jpeg", newType);
}
@Test
public void testGetPersonImage()
{
Person person = getAnyPerson();
//check if an image already exists, if not create one
List<PersonImage> existingImgs = manager.createQuery("SELECT i FROM PersonImage i "
+ " WHERE i.person.id=:personid",PersonImage.class)
.setParameter("personid", person.getId())
.getResultList();
EntityTransaction trans = manager.getTransaction();
PersonImage img = null;
if(existingImgs.size()==0)
{
trans.begin();
img = new PersonImage();
img.setId(null);
img.setContentType("image/jpeg");
img.setData(new byte[]{1,2,3,4});
img.setPerson(person);
manager.persist(img);
manager.flush();
trans.commit();
}
else
{
img = existingImgs.get(0);
}
PersonImageDto dto = service.getPersonImage(person.getId());
//restore original state
if(existingImgs.size()==0)
{
trans.begin();
manager.remove(img);
manager.flush();
trans.commit();
}
Assert.assertNotNull(dto);
Assert.assertEquals(img.getContentType(),dto.getContentType());
PersonDtoTester.assertEquals(PersonConverter.convert(person), dto.getPerson());
Assert.assertArrayEquals(img.getData(), dto.getData());
}
}
| added more transaction black magic i can't explain | backend/backend-impl/src/test/java/at/fhj/swd14/pse/person/PersonServiceIntegrationTest.java | added more transaction black magic i can't explain | <ide><path>ackend/backend-impl/src/test/java/at/fhj/swd14/pse/person/PersonServiceIntegrationTest.java
<ide> @Test
<ide> public void testPersonImage()
<ide> {
<add> EntityTransaction trans = manager.getTransaction();
<add> trans.begin();
<ide> Person person = getAnyPerson();
<ide>
<ide> //save any existing images
<ide>
<ide> service.savePersonImage(PersonConverter.convert(person), data,"image/jpeg");
<ide>
<add> trans.rollback();
<add>
<ide> List<PersonImage> newImgs=null;
<ide> newImgs = manager.createQuery("SELECT i FROM PersonImage i "
<ide> + " WHERE i.person.id=:personid",PersonImage.class)
<ide> byte[] newData = newImgs.get(0).getData();
<ide> String newType = newImgs.get(0).getContentType();
<ide>
<del> EntityTransaction trans = manager.getTransaction();
<ide> trans.begin();
<ide> //restore the state
<ide> if(newImgs.size()>0) |
|
Java | mit | error: pathspec '1-algorithm/13-leetcode/java/src/fundamentals/stack/evaluation/lc224_basiccalculator/Solution.java' did not match any file(s) known to git
| 70d7f7aeaea668966f32ed82059eb236d3e8098d | 1 | cdai/interview | package fundamentals.stack.evaluation.lc224_basiccalculator;
import java.util.Stack;
/**
* Implement a basic calculator to evaluate a simple expression string.
* The expression string may contain open ( and closing parentheses ), the plus + or minus sign -,
* non-negative integers and empty spaces. You may assume that the given expression is always valid.
* Some examples:
* "1 + 1" = 2
* " 2-1 + 2 " = 3
* "(1+(4+5+2)-3)+(6+8)" = 23
* Note: Do not use the eval built-in library function.
*/
public class Solution {
// Inspired by solution from leetcode discuss
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(0); // Always keep most recent sum at top
for (int i = 0, sign = 1; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
int num = s.charAt(i) - '0'; // Be aware of outer loop boundary and i++
for (; i < s.length() - 1 && Character.isDigit(s.charAt(i + 1)); i++) {
num = num * 10 + (s.charAt(i + 1) - '0');
}
stack.push(stack.pop() + sign * num);
} else if (s.charAt(i) == '+') {
sign = 1;
} else if (s.charAt(i) == '-') {
sign = -1;
} else if (s.charAt(i) == '(') {
stack.push(sign);
stack.push(0);
sign = 1; // Don't forget to reset
} else if (s.charAt(i) == ')') { // Update last sum = current sum * sign
stack.push(stack.pop() * stack.pop() + stack.pop());
} /* else whitespace*/
}
return stack.pop();
}
}
| 1-algorithm/13-leetcode/java/src/fundamentals/stack/evaluation/lc224_basiccalculator/Solution.java | leetcode-224 basic calculator
| 1-algorithm/13-leetcode/java/src/fundamentals/stack/evaluation/lc224_basiccalculator/Solution.java | leetcode-224 basic calculator | <ide><path>-algorithm/13-leetcode/java/src/fundamentals/stack/evaluation/lc224_basiccalculator/Solution.java
<add>package fundamentals.stack.evaluation.lc224_basiccalculator;
<add>
<add>import java.util.Stack;
<add>
<add>/**
<add> * Implement a basic calculator to evaluate a simple expression string.
<add> * The expression string may contain open ( and closing parentheses ), the plus + or minus sign -,
<add> * non-negative integers and empty spaces. You may assume that the given expression is always valid.
<add> * Some examples:
<add> * "1 + 1" = 2
<add> * " 2-1 + 2 " = 3
<add> * "(1+(4+5+2)-3)+(6+8)" = 23
<add> * Note: Do not use the eval built-in library function.
<add> */
<add>public class Solution {
<add>
<add> // Inspired by solution from leetcode discuss
<add> public int calculate(String s) {
<add> Stack<Integer> stack = new Stack<>();
<add> stack.push(0); // Always keep most recent sum at top
<add> for (int i = 0, sign = 1; i < s.length(); i++) {
<add> if (Character.isDigit(s.charAt(i))) {
<add> int num = s.charAt(i) - '0'; // Be aware of outer loop boundary and i++
<add> for (; i < s.length() - 1 && Character.isDigit(s.charAt(i + 1)); i++) {
<add> num = num * 10 + (s.charAt(i + 1) - '0');
<add> }
<add> stack.push(stack.pop() + sign * num);
<add> } else if (s.charAt(i) == '+') {
<add> sign = 1;
<add> } else if (s.charAt(i) == '-') {
<add> sign = -1;
<add> } else if (s.charAt(i) == '(') {
<add> stack.push(sign);
<add> stack.push(0);
<add> sign = 1; // Don't forget to reset
<add> } else if (s.charAt(i) == ')') { // Update last sum = current sum * sign
<add> stack.push(stack.pop() * stack.pop() + stack.pop());
<add> } /* else whitespace*/
<add> }
<add> return stack.pop();
<add> }
<add>
<add>} |
|
JavaScript | mit | 9c6d73c94ef8d91015581af1101f32f9fb25a48f | 0 | finkhq/fink-www,finkhq/fink,finkhq/fink,finkhq/fink-www | 'use strict'
;(function (Fink, fetch, _isURI) {
Fink.isURI = function (uri) {
return _isURI(uri, window.location.hostname)
}
Fink.register = function (uri) {
return fetch(Fink.endpoint, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
uri: uri
})
}).then(function (response) {
return response.json()
})
}
Fink.buzz = function () {
var elem = document.getElementById('fink-logo')
elem.classList.add('toggleBuzz')
setTimeout(function () {
elem.classList.remove('toggleBuzz')
}, 750)
}
})(window.Fink, window.fetch, window.isURI); // eslint-disable-line
| app/client/js/fink.js | 'use strict'
;(function (Fink, fetch, _isURI, parseURI) {
Fink.isURI = function (uri) {
return _isURI(uri, window.location.hostname)
}
Fink.register = function (uri) {
return fetch(Fink.endpoint, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
uri: uri
})
}).then(function (response) {
return response.json()
})
}
Fink.buzz = function () {
var elem = document.getElementById('fink-logo')
elem.classList.add('toggleBuzz')
setTimeout(function () {
elem.classList.remove('toggleBuzz')
}, 750)
}
})(window.Fink, window.fetch, require('fink-is-uri')); // eslint-disable-line
| Fix typo
| app/client/js/fink.js | Fix typo | <ide><path>pp/client/js/fink.js
<ide> 'use strict'
<ide>
<del>;(function (Fink, fetch, _isURI, parseURI) {
<add>;(function (Fink, fetch, _isURI) {
<ide> Fink.isURI = function (uri) {
<ide> return _isURI(uri, window.location.hostname)
<ide> }
<ide> elem.classList.remove('toggleBuzz')
<ide> }, 750)
<ide> }
<del>})(window.Fink, window.fetch, require('fink-is-uri')); // eslint-disable-line
<add>})(window.Fink, window.fetch, window.isURI); // eslint-disable-line |
|
JavaScript | apache-2.0 | 82d94abd7a2f9d629d967619aefc9570d1788e69 | 0 | zzo/sivart-slave,zzo/sivart-slave | var fs = require('fs');
var path = require('path');
var uuid = require('uuid');
var projectId = 'focal-inquiry-92622';
var gcloud = require('gcloud')({
projectId: projectId
});
var dataset = gcloud.datastore.dataset({
projectId: projectId
// keyFilename: '/Users/trostler/Downloads/sivart-6ddd2fa23c3b.json'
});
var storage = gcloud.storage({
projectId: projectId
// keyFilename: '/Users/trostler/Downloads/sivart-6ddd2fa23c3b.json'
});
//Get metadata
var logDir = process.argv[2];
var metadata = JSON.parse(fs.readFileSync(path.join(logDir, 'metadata')));
// Generate bucket name
metadata.bucket = ['sivart', uuid.v1()].join('.');
metadata.stored = new Date().getTime();
// Store metadata
var key = dataset.key({ namespace: 'sivart', path: [ metadata.name, metadata.branch ] });
dataset.get(key, function(err, entity) {
if (err) {
console.log('Error getting entity');
return;
}
if (!entity) {
dataset.save({ key: key, data: { runs: [ metadata ] }}, function(err) {
if (err) {
console.log('Error saving new entity');
}
});
} else {
entity.data.runs.unshift(metadata);
dataset.save({ key: key, data: entity }, function(err) {
if (err) {
console.log('Error saving new entity');
}
});
}
});
// Store files
storage.createBucket(metadata.bucket, function(err, bucket) {
if (err) {
console.log(err);
return;
}
var files = fs.readdirSync(logDir);
files.forEach(function(file) {
fs.createReadStream(path.join(logDir, file)).pipe(bucket.file(file).createWriteStream());
});
fs.createReadStream('/tmp/user-script').pipe(bucket.file('user-script').createWriteStream());
fs.createReadStream('/tmp/user-script.log').pipe(bucket.file('user-script.log').createWriteStream());
fs.createReadStream('/var/log/startupscript.log').pipe(bucket.file('startupscript.log').createWriteStream());
fs.createReadStream('/var/run/google.startup.script').pipe(bucket.file('google.startup.script').createWriteStream());
})
| saveLogs.js | var fs = require('fs');
var path = require('path');
var uuid = require('uuid');
var projectId = 'focal-inquiry-92622';
var gcloud = require('gcloud')({
projectId: projectId
});
var dataset = gcloud.datastore.dataset({
projectId: projectId
// keyFilename: '/Users/trostler/Downloads/sivart-6ddd2fa23c3b.json'
});
var storage = gcloud.storage({
projectId: projectId
// keyFilename: '/Users/trostler/Downloads/sivart-6ddd2fa23c3b.json'
});
//Get metadata
var logDir = process.argv[2];
var metadata = JSON.parse(fs.readFileSync(path.join(logDir, 'metadata')));
// Generate bucket name
metadata.bucket = ['sivart', uuid.v1()].join('.');
metadata.stored = new Date().getTime();
// Store metadata
var key = dataset.key({ namespace: 'sivart', path: [ metadata.name, metadata.branch ] });
dataset.get(key, function(err, entity) {
if (err) {
console.log('Error getting entity');
return;
}
if (!entity) {
dataset.save({ key: key, data: { runs: [ metadata ] }}, function(err) {
if (err) {
console.log('Error saving new entity');
}
});
} else {
entity.data.runs.unshift(metadata);
dataset.save({ key: key, data: entity }, function(err) {
if (err) {
console.log('Error saving new entity');
}
});
}
});
// Store files
storage.createBucket(metadata.bucket, function(err, bucket) {
if (err) {
console.log(err);
return;
}
var files = fs.readdirSync(logDir);
files.forEach(function(file) {
fs.createReadStream(path.join(logDir, file)).pipe(bucket.file(file).createWriteStream());
});
fs.createReadStream('/tmp/user-script').pipe(bucket.file('user-script').createWriteStream());
fs.createReadStream('/var/log/startupscript.log').pipe(bucket.file('startupscript.log').createWriteStream());
fs.createReadStream('/var/run/google.startup.script').pipe(bucket.file('google.startup.script').createWriteStream());
})
| add user-script.log
| saveLogs.js | add user-script.log | <ide><path>aveLogs.js
<ide> fs.createReadStream(path.join(logDir, file)).pipe(bucket.file(file).createWriteStream());
<ide> });
<ide> fs.createReadStream('/tmp/user-script').pipe(bucket.file('user-script').createWriteStream());
<add> fs.createReadStream('/tmp/user-script.log').pipe(bucket.file('user-script.log').createWriteStream());
<ide> fs.createReadStream('/var/log/startupscript.log').pipe(bucket.file('startupscript.log').createWriteStream());
<ide> fs.createReadStream('/var/run/google.startup.script').pipe(bucket.file('google.startup.script').createWriteStream());
<ide> }) |
|
Java | mit | aa6d1cf7e7dc5aac44325f6a69a83ca4e15f4820 | 0 | AzureAD/azure-activedirectory-library-for-android,AzureAD/azure-activedirectory-library-for-android | // Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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.microsoft.aad.adal;
import android.content.Context;
import com.microsoft.aad.adal.AuthenticationResult.AuthenticationStatus;
import com.microsoft.identity.common.adal.internal.AuthenticationConstants;
import com.microsoft.identity.common.adal.internal.util.StringExtensions;
import com.microsoft.identity.common.internal.cache.ADALOAuth2TokenCache;
import com.microsoft.identity.common.internal.cache.AccountCredentialCache;
import com.microsoft.identity.common.internal.cache.CacheKeyValueDelegate;
import com.microsoft.identity.common.internal.cache.IAccountCredentialCache;
import com.microsoft.identity.common.internal.cache.IShareSingleSignOnState;
import com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter;
import com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectory;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAuthorizationRequest;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Configuration;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Strategy;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryTokenResponse;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static com.microsoft.aad.adal.TokenEntryType.FRT_TOKEN_ENTRY;
import static com.microsoft.aad.adal.TokenEntryType.MRRT_TOKEN_ENTRY;
import static com.microsoft.aad.adal.TokenEntryType.REGULAR_TOKEN_ENTRY;
/**
* Internal class handling the interaction with {@link AcquireTokenSilentHandler} and {@link ITokenCacheStore}.
*/
class TokenCacheAccessor {
private static final String TAG = TokenCacheAccessor.class.getSimpleName();
private final ITokenCacheStore mTokenCacheStore;
private String mAuthority; // Remove final to update the authority when preferred cache location is not the same as passed in authority
private final String mTelemetryRequestId;
private boolean mUseCommonCache = false;
private ADALOAuth2TokenCache mCommonCache = null;
private boolean mValidateAuthorityHost = true;
TokenCacheAccessor(final Context appContext, final ITokenCacheStore tokenCacheStore, final String authority, final String telemetryRequestId) {
if (tokenCacheStore == null) {
throw new IllegalArgumentException("tokenCacheStore");
}
if (StringExtensions.isNullOrBlank(authority)) {
throw new IllegalArgumentException("authority");
}
if (StringExtensions.isNullOrBlank(telemetryRequestId)) {
throw new IllegalArgumentException("requestId");
}
mTokenCacheStore = tokenCacheStore;
mAuthority = authority;
mTelemetryRequestId = telemetryRequestId;
//Setup common cache implementation
List<IShareSingleSignOnState> sharedSSOCaches = new ArrayList<IShareSingleSignOnState>();
// Set up the MsalAuth2TokenCache
final IAccountCredentialCache accountCredentialCache = new AccountCredentialCache(
appContext,
new CacheKeyValueDelegate()
);
final MsalOAuth2TokenCache msalOAuth2TokenCache =
new MsalOAuth2TokenCache(
appContext,
accountCredentialCache,
new MicrosoftStsAccountCredentialAdapter()
);
sharedSSOCaches.add(msalOAuth2TokenCache);
mCommonCache = new ADALOAuth2TokenCache(appContext, sharedSSOCaches);
if (mTokenCacheStore instanceof DefaultTokenCacheStore) {
//If the default token cache is in use... delegate token operations to unified cache in common
//If not using default token cache then sharing SSO state between ADAL & MSAL cache implementations will not be possible anyway
mUseCommonCache = true;
}
}
public boolean isValidateAuthorityHost() {
return mValidateAuthorityHost;
}
public void setValidateAuthorityHost(boolean mValidateAuthorityHost) {
this.mValidateAuthorityHost = mValidateAuthorityHost;
}
/**
* @return Access token from cache. Could be null if AT does not exist or expired.
* This will be a strict match with the user passed in, could be unique userid,
* displayable id, or null user.
* @throws AuthenticationException
*/
TokenCacheItem getATFromCache(final String resource, final String clientId, final String user)
throws AuthenticationException {
final String methodName = ":getATFromCache";
final TokenCacheItem accessTokenItem;
try {
accessTokenItem = getRegularRefreshTokenCacheItem(resource, clientId, user);
} catch (final MalformedURLException ex) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, ex.getMessage(), ex);
}
if (accessTokenItem == null) {
Logger.v(TAG + methodName, "No access token exists.");
return null;
}
throwIfMultipleATExisted(clientId, resource, user);
if (!StringExtensions.isNullOrBlank(accessTokenItem.getAccessToken())) {
if (TokenCacheItem.isTokenExpired(accessTokenItem.getExpiresOn())) {
Logger.v(TAG + methodName, "Access token exists, but already expired.");
return null;
}
// To support backward-compatibility, for old token entry, user stored in
// token cache item could be different from the one in cachekey.
if (isUserMisMatch(user, accessTokenItem)) {
throw new AuthenticationException(ADALError.AUTH_FAILED_USER_MISMATCH);
}
}
return accessTokenItem;
}
/**
* @return {@link TokenCacheItem} for regular token cache entry.
*/
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) throws MalformedURLException {
final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_RT);
// try preferred cache location first
final String cacheKey = CacheKey.createCacheKeyForRTEntry(getAuthorityUrlWithPreferredCache(), resource, clientId, user);
TokenCacheItem item = mTokenCacheStore.getItem(cacheKey);
// try all the alias
if (item == null) {
item = performAdditionalCacheLookup(resource, clientId, null, user, REGULAR_TOKEN_ENTRY);
}
if (item != null) {
cacheEvent.setTokenTypeRT(true);
cacheEvent.setSpeRing(item.getSpeRing());
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return item;
}
/**
* @return {@link TokenCacheItem} for MRRT token cache entry.
*/
TokenCacheItem getMRRTItem(final String clientId, final String user) throws MalformedURLException {
final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_MRRT);
final String cacheKey = CacheKey.createCacheKeyForMRRT(getAuthorityUrlWithPreferredCache(), clientId, user);
TokenCacheItem item = mTokenCacheStore.getItem(cacheKey);
if (item == null) {
item = performAdditionalCacheLookup(null, clientId, null, user, MRRT_TOKEN_ENTRY);
}
if (item != null) {
cacheEvent.setTokenTypeMRRT(true);
cacheEvent.setTokenTypeFRT(item.isFamilyToken());
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return item;
}
/**
* @return {@link TokenCacheItem} for FRT token cache entry.
*/
TokenCacheItem getFRTItem(final String familyClientId, final String user) throws MalformedURLException {
final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_FRT);
if (StringExtensions.isNullOrBlank(user)) {
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return null;
}
final String cacheKey = CacheKey.createCacheKeyForFRT(getAuthorityUrlWithPreferredCache(), familyClientId, user);
TokenCacheItem item = mTokenCacheStore.getItem(cacheKey);
if (item == null) {
item = performAdditionalCacheLookup(null, null, familyClientId, user, FRT_TOKEN_ENTRY);
}
if (item != null) {
cacheEvent.setTokenTypeFRT(true);
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return item;
}
TokenCacheItem getStaleToken(AuthenticationRequest authRequest) throws AuthenticationException {
final String methodName = ":getStaleToken";
final TokenCacheItem accessTokenItem;
try {
accessTokenItem = getRegularRefreshTokenCacheItem(authRequest.getResource(),
authRequest.getClientId(), authRequest.getUserFromRequest());
} catch (final MalformedURLException ex) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, ex.getMessage(), ex);
}
if (accessTokenItem != null
&& !StringExtensions.isNullOrBlank(accessTokenItem.getAccessToken())
&& accessTokenItem.getExtendedExpiresOn() != null
&& !TokenCacheItem.isTokenExpired(accessTokenItem.getExtendedExpiresOn())) {
throwIfMultipleATExisted(authRequest.getClientId(), authRequest.getResource(), authRequest.getUserFromRequest());
Logger.i(TAG + methodName, "The stale access token is returned.", "");
return accessTokenItem;
}
Logger.i(TAG + methodName, "The stale access token is not found.", "");
return null;
}
/**
* Update token cache with returned auth result.
*
* @throws AuthenticationException
* @throws IllegalArgumentException If {@link AuthenticationResult} is null.
*/
void updateCachedItemWithResult(final String resource, final String clientId, final AuthenticationResult result,
final TokenCacheItem cachedItem) throws AuthenticationException {
final String methodName = ":updateCachedItemWithResult";
if (result == null) {
Logger.v(TAG + methodName, "AuthenticationResult is null, cannot update cache.");
throw new IllegalArgumentException("result");
}
//Moving this such that the correct authority is available to all code paths
if (!StringExtensions.isNullOrBlank(result.getAuthority())) {
mAuthority = result.getAuthority();
}
if (result.getStatus() == AuthenticationStatus.Succeeded) {
Logger.v(TAG + methodName, "Save returned AuthenticationResult into cache.");
if (cachedItem != null && cachedItem.getUserInfo() != null && result.getUserInfo() == null) {
result.setUserInfo(cachedItem.getUserInfo());
result.setIdToken(cachedItem.getRawIdToken());
result.setTenantId(cachedItem.getTenantId());
}
try {
if (mUseCommonCache && !UrlExtensions.isADFSAuthority(new URL(mAuthority))) {
updateTokenCacheUsingCommonCache(resource, clientId, result);
} else {
updateTokenCache(resource, clientId, result);
}
} catch (MalformedURLException e) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, e.getMessage(), e);
}
} else if (AuthenticationConstants.OAuth2ErrorCode.INVALID_GRANT.equalsIgnoreCase(result.getErrorCode())) {
// remove Item if oauth2_error is invalid_grant
Logger.v(TAG + methodName, "Received INVALID_GRANT error code, remove existing cache entry.");
removeTokenCacheItem(cachedItem, resource);
}
}
/**
* Update token cache with returned auth result.
*/
void updateTokenCache(final String resource, final String clientId, final AuthenticationResult result) throws MalformedURLException {
if (result == null || StringExtensions.isNullOrBlank(result.getAccessToken())) {
return;
}
if (mUseCommonCache && !UrlExtensions.isADFSAuthority(new URL(mAuthority))) {
updateTokenCacheUsingCommonCache(resource, clientId, result);
return;
}
if (result.getUserInfo() != null) {
// update cache entry with displayableId
if (!StringExtensions.isNullOrBlank(result.getUserInfo().getDisplayableId())) {
setItemToCacheForUser(resource, clientId, result, result.getUserInfo().getDisplayableId());
}
// update cache entry with userId
if (!StringExtensions.isNullOrBlank(result.getUserInfo().getUserId())) {
setItemToCacheForUser(resource, clientId, result, result.getUserInfo().getUserId());
}
}
// update for empty userid
setItemToCacheForUser(resource, clientId, result, null);
}
void updateTokenCacheUsingCommonCache(final String resource, final String clientId, final AuthenticationResult result) throws MalformedURLException {
AzureActiveDirectory ad = new AzureActiveDirectory();
AzureActiveDirectoryTokenResponse tokenResponse = CoreAdapter.asAadTokenResponse(result);
AzureActiveDirectoryOAuth2Configuration config = new AzureActiveDirectoryOAuth2Configuration();
config.setAuthorityHostValidationEnabled(this.isValidateAuthorityHost());
AzureActiveDirectoryOAuth2Strategy strategy = ad.createOAuth2Strategy(config);
AzureActiveDirectoryAuthorizationRequest request = new AzureActiveDirectoryAuthorizationRequest();
request.setClientId(clientId);
request.setScope(resource);
request.setAuthority(new URL(mAuthority));
mCommonCache.saveTokens(strategy, request, tokenResponse);
}
/**
* Remove token from cache.
* 1) If refresh with resource specific token cache entry, clear RT with key(R,C,U,A)
* 2) If refresh with MRRT, clear RT (C,U,A) and (R,C,U,A)
* 3) if refresh with FRT, clear RT with (U,A)
*
* @throws AuthenticationException
*/
void removeTokenCacheItem(final TokenCacheItem tokenCacheItem, final String resource)
throws AuthenticationException {
final String methodName = ":removeTokenCacheItem";
final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_DELETE);
cacheEvent.setRequestId(mTelemetryRequestId);
Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_DELETE);
final List<String> keys;
final TokenEntryType tokenEntryType = tokenCacheItem.getTokenEntryType();
switch (tokenEntryType) {
case REGULAR_TOKEN_ENTRY:
cacheEvent.setTokenTypeRT(true);
Logger.v(TAG + methodName, "Regular RT was used to get access token, remove entries "
+ "for regular RT entries.");
keys = getKeyListToRemoveForRT(tokenCacheItem);
break;
case MRRT_TOKEN_ENTRY:
// We delete both MRRT and RT in this case.
cacheEvent.setTokenTypeMRRT(true);
Logger.v(TAG + methodName, "MRRT was used to get access token, remove entries for both "
+ "MRRT entries and regular RT entries.");
keys = getKeyListToRemoveForMRRTOrFRT(tokenCacheItem, false);
final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem);
regularRTItem.setResource(resource);
keys.addAll(getKeyListToRemoveForRT(regularRTItem));
break;
case FRT_TOKEN_ENTRY:
cacheEvent.setTokenTypeFRT(true);
Logger.v(TAG + methodName, "FRT was used to get access token, remove entries for "
+ "FRT entries.");
keys = getKeyListToRemoveForMRRTOrFRT(tokenCacheItem, true);
break;
default:
throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM);
}
for (final String key : keys) {
mTokenCacheStore.removeItem(key);
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent,
EventStrings.TOKEN_CACHE_DELETE);
}
boolean isMultipleRTsMatchingGivenAppAndResource(final String clientId, final String resource) {
final Iterator<TokenCacheItem> allItems = mTokenCacheStore.getAll();
final List<TokenCacheItem> regularRTsMatchingRequest = new ArrayList<>();
while (allItems.hasNext()) {
final TokenCacheItem tokenCacheItem = allItems.next();
if (mAuthority.equalsIgnoreCase(tokenCacheItem.getAuthority()) && clientId.equalsIgnoreCase(tokenCacheItem.getClientId())
&& resource.equalsIgnoreCase(tokenCacheItem.getResource()) && !tokenCacheItem.getIsMultiResourceRefreshToken()) {
regularRTsMatchingRequest.add(tokenCacheItem);
}
}
return regularRTsMatchingRequest.size() > 1;
}
boolean isMultipleMRRTsMatchingGivenApp(final String clientId) {
final Iterator<TokenCacheItem> allItems = mTokenCacheStore.getAll();
final List<TokenCacheItem> mrrtsMatchingRequest = new ArrayList<>();
while (allItems.hasNext()) {
final TokenCacheItem tokenCacheItem = allItems.next();
if (tokenCacheItem.getAuthority().equalsIgnoreCase(mAuthority) && tokenCacheItem.getClientId().equalsIgnoreCase(clientId)
&& (tokenCacheItem.getIsMultiResourceRefreshToken() || StringExtensions.isNullOrBlank(tokenCacheItem.getResource()))) {
mrrtsMatchingRequest.add(tokenCacheItem);
}
}
return mrrtsMatchingRequest.size() > 1;
}
/**
* Update token cache for a given user. If token is MRRT, store two separate entries for regular RT entry and MRRT entry.
* Ideally, if returned token is MRRT, we should not store RT along with AT. However, there may be caller taking dependency
* on RT.
* If the token is FRT, store three separate entries.
*/
private void setItemToCacheForUser(final String resource, final String clientId, final AuthenticationResult result, final String userId) throws MalformedURLException {
final String methodName = ":setItemToCacheForUser";
logReturnedToken(result);
Logger.v(TAG + methodName, "Save regular token into cache.");
final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_WRITE);
cacheEvent.setRequestId(mTelemetryRequestId);
Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_WRITE);
// new tokens will only be saved into preferred cache location
mTokenCacheStore.setItem(CacheKey.createCacheKeyForRTEntry(getAuthorityUrlWithPreferredCache(), resource, clientId, userId),
TokenCacheItem.createRegularTokenCacheItem(getAuthorityUrlWithPreferredCache(), resource, clientId, result));
cacheEvent.setTokenTypeRT(true);
// Store separate entries for MRRT.
if (result.getIsMultiResourceRefreshToken()) {
Logger.v(TAG + methodName, "Save Multi Resource Refresh token to cache.");
mTokenCacheStore.setItem(CacheKey.createCacheKeyForMRRT(getAuthorityUrlWithPreferredCache(), clientId, userId),
TokenCacheItem.createMRRTTokenCacheItem(getAuthorityUrlWithPreferredCache(), clientId, result));
cacheEvent.setTokenTypeMRRT(true);
}
// Store separate entries for FRT.
if (!StringExtensions.isNullOrBlank(result.getFamilyClientId()) && !StringExtensions.isNullOrBlank(userId)) {
Logger.v(TAG + methodName, "Save Family Refresh token into cache.");
final TokenCacheItem familyTokenCacheItem = TokenCacheItem.createFRRTTokenCacheItem(getAuthorityUrlWithPreferredCache(), result);
mTokenCacheStore.setItem(CacheKey.createCacheKeyForFRT(getAuthorityUrlWithPreferredCache(), result.getFamilyClientId(), userId), familyTokenCacheItem);
cacheEvent.setTokenTypeFRT(true);
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent,
EventStrings.TOKEN_CACHE_WRITE);
}
/**
* @return List of keys to remove when using regular RT to send refresh token request.
*/
private List<String> getKeyListToRemoveForRT(final TokenCacheItem cachedItem) {
final List<String> keysToRemove = new ArrayList<>();
try {
final String preferredAuthority = getAuthorityUrlWithPreferredCache();
if (preferredAuthority != null) {
addDeletionKeysForRTEntry(preferredAuthority, cachedItem, keysToRemove);
}
} catch (final MalformedURLException exception) {
com.microsoft.identity.common.internal.logging.Logger.error(TAG, "Authority from preferred cache is invalid", null);
com.microsoft.identity.common.internal.logging.Logger.errorPII(TAG, "Failed with exception", exception);
}
addDeletionKeysForRTEntry(mAuthority, cachedItem, keysToRemove);
// For back compatibility, remove the cache key with the passed-in request authority.
if (!mAuthority.equalsIgnoreCase(cachedItem.getAuthority())) {
addDeletionKeysForRTEntry(cachedItem.getAuthority(), cachedItem, keysToRemove);
}
return keysToRemove;
}
/**
* @return List of keys to remove when using MRRT or FRT to send refresh token request.
*/
private List<String> getKeyListToRemoveForMRRTOrFRT(final TokenCacheItem cachedItem, final boolean isFRT) {
final List<String> keysToRemove = new ArrayList<>();
final KeyMakerStrategy keymaker = new KeyMakerStrategy() {
@Override
public boolean isFrt() {
return isFRT;
}
@Override
public String makeKey(String authority, String clientId, String userId) {
if (isFRT) {
return CacheKey.createCacheKeyForFRT(authority, clientId, userId);
}
return CacheKey.createCacheKeyForMRRT(authority, clientId, userId);
}
};
// Remove the cache key with preferred authority.
try {
final String preferredAuthority = getAuthorityUrlWithPreferredCache();
if (preferredAuthority != null) {
addDeletionKeysForMRRTOrFRTEntry(preferredAuthority, cachedItem, keysToRemove, keymaker);
}
} catch (final MalformedURLException exception) {
com.microsoft.identity.common.internal.logging.Logger.error(TAG, "Authority from preferred cache is invalid", null);
com.microsoft.identity.common.internal.logging.Logger.errorPII(TAG, "Failed with exception", exception);
}
addDeletionKeysForMRRTOrFRTEntry(mAuthority, cachedItem, keysToRemove, keymaker);
// For back compatibility, remove the cache key with the passed-in request authority.
if (!mAuthority.equalsIgnoreCase(cachedItem.getAuthority())) {
addDeletionKeysForMRRTOrFRTEntry(cachedItem.getAuthority(), cachedItem, keysToRemove, keymaker);
}
return keysToRemove;
}
interface KeyMakerStrategy {
boolean isFrt();
String makeKey(final String authority, final String clientId, final String userId);
}
private void addDeletionKeysForRTEntry(final String authority, final TokenCacheItem item, final List<String> keys) {
final String resource = item.getResource();
final String clientId = item.getClientId();
final UserInfo userInfo = item.getUserInfo();
keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, null));
if (userInfo != null) {
if (userInfo.getDisplayableId() != null) {
keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, userInfo.getDisplayableId()));
}
if (userInfo.getUserId() != null) {
keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, userInfo.getUserId()));
if (item.getTenantId() != null) {
String uniqueId = getUniqueIdentifierForCacheKey(userInfo.getUserId(), item.getTenantId());
keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, uniqueId));
}
}
}
}
private void addDeletionKeysForMRRTOrFRTEntry(final String authority, final TokenCacheItem item, final List<String> keys, final KeyMakerStrategy strategy) {
final UserInfo userInfo = item.getUserInfo();
String clientId = item.getClientId();
if (strategy.isFrt()) {
clientId = item.getFamilyClientId();
}
final List<String> userIds = new ArrayList<>();
userIds.add(null); // no user affinity
if (userInfo != null) {
if (userInfo.getDisplayableId() != null) {
userIds.add(userInfo.getDisplayableId());
}
if (userInfo.getUserId() != null) {
userIds.add(userInfo.getUserId());
if (item.getTenantId() != null) {
userIds.add(getUniqueIdentifierForCacheKey(userInfo.getUserId(), item.getTenantId()));
}
}
}
// Iterate over the userId permutations and, in the FRT-case, conditionally delete them if they match.
// Non-FRTs are unconditionally cleared.
for (final String userId : userIds) {
addDeletionKeyForMRRTOrFRTEntry(keys, item, authority, clientId, userId, strategy);
}
}
private void addDeletionKeyForMRRTOrFRTEntry(final List<String> keysToRemove,
final TokenCacheItem deletionTarget,
final String authority,
final String clientId,
final String userId,
final KeyMakerStrategy strategy) {
final String keyToAdd = strategy.makeKey(authority, clientId, userId);
if (strategy.isFrt()) {
addDeletionKeyForFRTIfRTValueIsStale(keysToRemove, deletionTarget, keyToAdd);
} else {
keysToRemove.add(keyToAdd);
}
}
private void addDeletionKeyForFRTIfRTValueIsStale(final List<String> keysToRemove,
final TokenCacheItem deletionTarget,
final String deletionCandidateKey) {
final TokenCacheItem fociCacheItem = mTokenCacheStore.getItem(deletionCandidateKey);
if (null != fociCacheItem && deletionTarget.getRefreshToken().equalsIgnoreCase(fociCacheItem.getRefreshToken())) {
keysToRemove.add(deletionCandidateKey);
}
}
private String getUniqueIdentifierForCacheKey(final String userId, final String tenantId) {
return StringExtensions.base64UrlEncodeToString(userId) + "." + StringExtensions.base64UrlEncodeToString(tenantId);
}
private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) {
// If user is not passed in the request or userInfo does not exist in the token cache item,
// it's a match case. We do wildcard find, return whatever match with cache key.
if (StringExtensions.isNullOrBlank(user) || tokenCacheItem.getUserInfo() == null) {
return false;
}
// If user if provided, it needs to match either displayId or userId.
return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId())
&& !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId());
}
private void throwIfMultipleATExisted(final String clientId, final String resource, final String user) throws AuthenticationException {
if (StringExtensions.isNullOrBlank(user) && isMultipleRTsMatchingGivenAppAndResource(clientId, resource)) {
throw new AuthenticationException(ADALError.AUTH_FAILED_USER_MISMATCH, "No user is provided and multiple access tokens "
+ "exist for the given app and resource.");
}
}
/**
* Calculate hash for accessToken and log that.
*/
private void logReturnedToken(final AuthenticationResult result) {
if (result != null && result.getAccessToken() != null) {
Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", null);
}
}
private CacheEvent startCacheTelemetryRequest(String tokenType) {
final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_LOOKUP);
cacheEvent.setTokenType(tokenType);
cacheEvent.setRequestId(mTelemetryRequestId);
Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_LOOKUP);
return cacheEvent;
}
private TokenCacheItem performAdditionalCacheLookup(final String resource, final String clientid, final String familyClientId,
final String user, final TokenEntryType type) throws MalformedURLException {
TokenCacheItem item = getTokenCacheItemFromPassedInAuthority(resource, clientid, familyClientId, user, type);
if (item == null) {
item = getTokenCacheItemFromAliasedHost(resource, clientid, familyClientId, user, type);
}
return item;
}
private TokenCacheItem getTokenCacheItemFromPassedInAuthority(final String resource, final String clientId, final String familyClientId,
final String user, final TokenEntryType type) throws MalformedURLException {
if (getAuthorityUrlWithPreferredCache().equalsIgnoreCase(mAuthority)) {
return null;
}
final String cacheKeyWithPassedInAuthority = getCacheKey(mAuthority, resource, clientId, user, familyClientId, type);
return mTokenCacheStore.getItem(cacheKeyWithPassedInAuthority);
}
private TokenCacheItem getTokenCacheItemFromAliasedHost(final String resource, final String clientId, final String familyClientId,
final String user, final TokenEntryType type) throws MalformedURLException {
final InstanceDiscoveryMetadata instanceDiscoveryMetadata = getInstanceDiscoveryMetadata();
if (instanceDiscoveryMetadata == null) {
return null;
}
TokenCacheItem tokenCacheItemForAliasedHost = null;
final List<String> aliasHosts = instanceDiscoveryMetadata.getAliases();
for (final String aliasHost : aliasHosts) {
final String authority = constructAuthorityUrl(aliasHost);
// Already looked cache with preferred cache location and passed in authority, needs to look through other
// aliased host.
if (authority.equalsIgnoreCase(mAuthority) || authority.equalsIgnoreCase(getAuthorityUrlWithPreferredCache())) {
continue;
}
final String cacheKeyForAliasedHost = getCacheKey(authority, resource, clientId, user, familyClientId, type);
final TokenCacheItem item = mTokenCacheStore.getItem(cacheKeyForAliasedHost);
if (item != null) {
tokenCacheItemForAliasedHost = item;
break;
}
}
return tokenCacheItemForAliasedHost;
}
private String getCacheKey(final String authority, final String resource, final String clientId, final String user,
final String familyClientId, final TokenEntryType type) {
final String cacheKey;
switch (type) {
case REGULAR_TOKEN_ENTRY:
cacheKey = CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, user);
break;
case MRRT_TOKEN_ENTRY:
cacheKey = CacheKey.createCacheKeyForMRRT(authority, clientId, user);
break;
case FRT_TOKEN_ENTRY:
cacheKey = CacheKey.createCacheKeyForFRT(authority, familyClientId, user);
break;
default:
return null;
}
return cacheKey;
}
String getAuthorityUrlWithPreferredCache() throws MalformedURLException {
final InstanceDiscoveryMetadata instanceDiscoveryMetadata = getInstanceDiscoveryMetadata();
if (instanceDiscoveryMetadata == null || !instanceDiscoveryMetadata.isValidated()) {
return mAuthority;
}
final String preferredLocation = instanceDiscoveryMetadata.getPreferredCache();
// mAuthority can be updated to preferred location.
return constructAuthorityUrl(preferredLocation);
}
private String constructAuthorityUrl(final String host) throws MalformedURLException {
final URL passedInAuthority = new URL(mAuthority);
if (passedInAuthority.getHost().equalsIgnoreCase(host)) {
return mAuthority;
}
return Discovery.constructAuthorityUrl(passedInAuthority, host).toString();
}
private InstanceDiscoveryMetadata getInstanceDiscoveryMetadata() throws MalformedURLException {
final URL passedInAuthority = new URL(mAuthority);
return AuthorityValidationMetadataCache.getCachedInstanceDiscoveryMetadata(passedInAuthority);
}
}
| adal/src/main/java/com/microsoft/aad/adal/TokenCacheAccessor.java | // Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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.microsoft.aad.adal;
import android.content.Context;
import com.microsoft.aad.adal.AuthenticationResult.AuthenticationStatus;
import com.microsoft.identity.common.adal.internal.AuthenticationConstants;
import com.microsoft.identity.common.adal.internal.util.StringExtensions;
import com.microsoft.identity.common.internal.cache.ADALOAuth2TokenCache;
import com.microsoft.identity.common.internal.cache.AccountCredentialCache;
import com.microsoft.identity.common.internal.cache.CacheKeyValueDelegate;
import com.microsoft.identity.common.internal.cache.IAccountCredentialCache;
import com.microsoft.identity.common.internal.cache.IShareSingleSignOnState;
import com.microsoft.identity.common.internal.cache.MicrosoftStsAccountCredentialAdapter;
import com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectory;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAuthorizationRequest;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Configuration;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryOAuth2Strategy;
import com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryTokenResponse;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static com.microsoft.aad.adal.TokenEntryType.FRT_TOKEN_ENTRY;
import static com.microsoft.aad.adal.TokenEntryType.MRRT_TOKEN_ENTRY;
import static com.microsoft.aad.adal.TokenEntryType.REGULAR_TOKEN_ENTRY;
/**
* Internal class handling the interaction with {@link AcquireTokenSilentHandler} and {@link ITokenCacheStore}.
*/
class TokenCacheAccessor {
private static final String TAG = TokenCacheAccessor.class.getSimpleName();
private final ITokenCacheStore mTokenCacheStore;
private String mAuthority; // Remove final to update the authority when preferred cache location is not the same as passed in authority
private final String mTelemetryRequestId;
private boolean mUseCommonCache = false;
private ADALOAuth2TokenCache mCommonCache = null;
private boolean mValidateAuthorityHost = true;
TokenCacheAccessor(final Context appContext, final ITokenCacheStore tokenCacheStore, final String authority, final String telemetryRequestId) {
if (tokenCacheStore == null) {
throw new IllegalArgumentException("tokenCacheStore");
}
if (StringExtensions.isNullOrBlank(authority)) {
throw new IllegalArgumentException("authority");
}
if (StringExtensions.isNullOrBlank(telemetryRequestId)) {
throw new IllegalArgumentException("requestId");
}
mTokenCacheStore = tokenCacheStore;
mAuthority = authority;
mTelemetryRequestId = telemetryRequestId;
//Setup common cache implementation
List<IShareSingleSignOnState> sharedSSOCaches = new ArrayList<IShareSingleSignOnState>();
// Set up the MsalAuth2TokenCache
final IAccountCredentialCache accountCredentialCache = new AccountCredentialCache(
appContext,
new CacheKeyValueDelegate()
);
final MsalOAuth2TokenCache msalOAuth2TokenCache =
new MsalOAuth2TokenCache(
appContext,
accountCredentialCache,
new MicrosoftStsAccountCredentialAdapter()
);
sharedSSOCaches.add(msalOAuth2TokenCache);
mCommonCache = new ADALOAuth2TokenCache(appContext, sharedSSOCaches);
if (mTokenCacheStore instanceof DefaultTokenCacheStore) {
//If the default token cache is in use... delegate token operations to unified cache in common
//If not using default token cache then sharing SSO state between ADAL & MSAL cache implementations will not be possible anyway
mUseCommonCache = true;
}
}
public boolean isValidateAuthorityHost() {
return mValidateAuthorityHost;
}
public void setValidateAuthorityHost(boolean mValidateAuthorityHost) {
this.mValidateAuthorityHost = mValidateAuthorityHost;
}
/**
* @return Access token from cache. Could be null if AT does not exist or expired.
* This will be a strict match with the user passed in, could be unique userid,
* displayable id, or null user.
* @throws AuthenticationException
*/
TokenCacheItem getATFromCache(final String resource, final String clientId, final String user)
throws AuthenticationException {
final String methodName = ":getATFromCache";
final TokenCacheItem accessTokenItem;
try {
accessTokenItem = getRegularRefreshTokenCacheItem(resource, clientId, user);
} catch (final MalformedURLException ex) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, ex.getMessage(), ex);
}
if (accessTokenItem == null) {
Logger.v(TAG + methodName, "No access token exists.");
return null;
}
throwIfMultipleATExisted(clientId, resource, user);
if (!StringExtensions.isNullOrBlank(accessTokenItem.getAccessToken())) {
if (TokenCacheItem.isTokenExpired(accessTokenItem.getExpiresOn())) {
Logger.v(TAG + methodName, "Access token exists, but already expired.");
return null;
}
// To support backward-compatibility, for old token entry, user stored in
// token cache item could be different from the one in cachekey.
if (isUserMisMatch(user, accessTokenItem)) {
throw new AuthenticationException(ADALError.AUTH_FAILED_USER_MISMATCH);
}
}
return accessTokenItem;
}
/**
* @return {@link TokenCacheItem} for regular token cache entry.
*/
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) throws MalformedURLException {
final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_RT);
// try preferred cache location first
final String cacheKey = CacheKey.createCacheKeyForRTEntry(getAuthorityUrlWithPreferredCache(), resource, clientId, user);
TokenCacheItem item = mTokenCacheStore.getItem(cacheKey);
// try all the alias
if (item == null) {
item = performAdditionalCacheLookup(resource, clientId, null, user, REGULAR_TOKEN_ENTRY);
}
if (item != null) {
cacheEvent.setTokenTypeRT(true);
cacheEvent.setSpeRing(item.getSpeRing());
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return item;
}
/**
* @return {@link TokenCacheItem} for MRRT token cache entry.
*/
TokenCacheItem getMRRTItem(final String clientId, final String user) throws MalformedURLException {
final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_MRRT);
final String cacheKey = CacheKey.createCacheKeyForMRRT(getAuthorityUrlWithPreferredCache(), clientId, user);
TokenCacheItem item = mTokenCacheStore.getItem(cacheKey);
if (item == null) {
item = performAdditionalCacheLookup(null, clientId, null, user, MRRT_TOKEN_ENTRY);
}
if (item != null) {
cacheEvent.setTokenTypeMRRT(true);
cacheEvent.setTokenTypeFRT(item.isFamilyToken());
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return item;
}
/**
* @return {@link TokenCacheItem} for FRT token cache entry.
*/
TokenCacheItem getFRTItem(final String familyClientId, final String user) throws MalformedURLException {
final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_FRT);
if (StringExtensions.isNullOrBlank(user)) {
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return null;
}
final String cacheKey = CacheKey.createCacheKeyForFRT(getAuthorityUrlWithPreferredCache(), familyClientId, user);
TokenCacheItem item = mTokenCacheStore.getItem(cacheKey);
if (item == null) {
item = performAdditionalCacheLookup(null, null, familyClientId, user, FRT_TOKEN_ENTRY);
}
if (item != null) {
cacheEvent.setTokenTypeFRT(true);
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP);
return item;
}
TokenCacheItem getStaleToken(AuthenticationRequest authRequest) throws AuthenticationException {
final String methodName = ":getStaleToken";
final TokenCacheItem accessTokenItem;
try {
accessTokenItem = getRegularRefreshTokenCacheItem(authRequest.getResource(),
authRequest.getClientId(), authRequest.getUserFromRequest());
} catch (final MalformedURLException ex) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, ex.getMessage(), ex);
}
if (accessTokenItem != null
&& !StringExtensions.isNullOrBlank(accessTokenItem.getAccessToken())
&& accessTokenItem.getExtendedExpiresOn() != null
&& !TokenCacheItem.isTokenExpired(accessTokenItem.getExtendedExpiresOn())) {
throwIfMultipleATExisted(authRequest.getClientId(), authRequest.getResource(), authRequest.getUserFromRequest());
Logger.i(TAG + methodName, "The stale access token is returned.", "");
return accessTokenItem;
}
Logger.i(TAG + methodName, "The stale access token is not found.", "");
return null;
}
/**
* Update token cache with returned auth result.
*
* @throws AuthenticationException
* @throws IllegalArgumentException If {@link AuthenticationResult} is null.
*/
void updateCachedItemWithResult(final String resource, final String clientId, final AuthenticationResult result,
final TokenCacheItem cachedItem) throws AuthenticationException {
final String methodName = ":updateCachedItemWithResult";
if (result == null) {
Logger.v(TAG + methodName, "AuthenticationResult is null, cannot update cache.");
throw new IllegalArgumentException("result");
}
//Moving this such that the correct authority is available to all code paths
if (!StringExtensions.isNullOrBlank(result.getAuthority())) {
mAuthority = result.getAuthority();
}
if (result.getStatus() == AuthenticationStatus.Succeeded) {
Logger.v(TAG + methodName, "Save returned AuthenticationResult into cache.");
if (cachedItem != null && cachedItem.getUserInfo() != null && result.getUserInfo() == null) {
result.setUserInfo(cachedItem.getUserInfo());
result.setIdToken(cachedItem.getRawIdToken());
result.setTenantId(cachedItem.getTenantId());
}
try {
if (mUseCommonCache && !UrlExtensions.isADFSAuthority(new URL(mAuthority))) {
updateTokenCacheUsingCommonCache(resource, clientId, result);
} else {
updateTokenCache(resource, clientId, result);
}
} catch (MalformedURLException e) {
throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, e.getMessage(), e);
}
} else if (AuthenticationConstants.OAuth2ErrorCode.INVALID_GRANT.equalsIgnoreCase(result.getErrorCode())) {
// remove Item if oauth2_error is invalid_grant
Logger.v(TAG + methodName, "Received INVALID_GRANT error code, remove existing cache entry.");
removeTokenCacheItem(cachedItem, resource);
}
}
/**
* Update token cache with returned auth result.
*/
void updateTokenCache(final String resource, final String clientId, final AuthenticationResult result) throws MalformedURLException {
if (result == null || StringExtensions.isNullOrBlank(result.getAccessToken())) {
return;
}
if (mUseCommonCache && !UrlExtensions.isADFSAuthority(new URL(mAuthority))) {
updateTokenCacheUsingCommonCache(resource, clientId, result);
return;
}
if (result.getUserInfo() != null) {
// update cache entry with displayableId
if (!StringExtensions.isNullOrBlank(result.getUserInfo().getDisplayableId())) {
setItemToCacheForUser(resource, clientId, result, result.getUserInfo().getDisplayableId());
}
// update cache entry with userId
if (!StringExtensions.isNullOrBlank(result.getUserInfo().getUserId())) {
setItemToCacheForUser(resource, clientId, result, result.getUserInfo().getUserId());
}
}
// update for empty userid
setItemToCacheForUser(resource, clientId, result, null);
}
void updateTokenCacheUsingCommonCache(final String resource, final String clientId, final AuthenticationResult result) throws MalformedURLException {
AzureActiveDirectory ad = new AzureActiveDirectory();
AzureActiveDirectoryTokenResponse tokenResponse = CoreAdapter.asAadTokenResponse(result);
AzureActiveDirectoryOAuth2Configuration config = new AzureActiveDirectoryOAuth2Configuration();
config.setAuthorityHostValidationEnabled(this.isValidateAuthorityHost());
AzureActiveDirectoryOAuth2Strategy strategy = ad.createOAuth2Strategy(config);
AzureActiveDirectoryAuthorizationRequest request = new AzureActiveDirectoryAuthorizationRequest();
request.setClientId(clientId);
request.setScope(resource);
request.setAuthority(new URL(mAuthority));
mCommonCache.saveTokens(strategy, request, tokenResponse);
}
/**
* Remove token from cache.
* 1) If refresh with resource specific token cache entry, clear RT with key(R,C,U,A)
* 2) If refresh with MRRT, clear RT (C,U,A) and (R,C,U,A)
* 3) if refresh with FRT, clear RT with (U,A)
*
* @throws AuthenticationException
*/
void removeTokenCacheItem(final TokenCacheItem tokenCacheItem, final String resource)
throws AuthenticationException {
final String methodName = ":removeTokenCacheItem";
final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_DELETE);
cacheEvent.setRequestId(mTelemetryRequestId);
Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_DELETE);
final List<String> keys;
final TokenEntryType tokenEntryType = tokenCacheItem.getTokenEntryType();
switch (tokenEntryType) {
case REGULAR_TOKEN_ENTRY:
cacheEvent.setTokenTypeRT(true);
Logger.v(TAG + methodName, "Regular RT was used to get access token, remove entries "
+ "for regular RT entries.");
keys = getKeyListToRemoveForRT(tokenCacheItem);
break;
case MRRT_TOKEN_ENTRY:
// We delete both MRRT and RT in this case.
cacheEvent.setTokenTypeMRRT(true);
Logger.v(TAG + methodName, "MRRT was used to get access token, remove entries for both "
+ "MRRT entries and regular RT entries.");
keys = getKeyListToRemoveForMRRT(tokenCacheItem);
final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem);
regularRTItem.setResource(resource);
keys.addAll(getKeyListToRemoveForRT(regularRTItem));
break;
case FRT_TOKEN_ENTRY:
cacheEvent.setTokenTypeFRT(true);
Logger.v(TAG + methodName, "FRT was used to get access token, remove entries for "
+ "FRT entries.");
keys = getKeyListToRemoveForFRT(tokenCacheItem);
break;
default:
throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM);
}
for (final String key : keys) {
mTokenCacheStore.removeItem(key);
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent,
EventStrings.TOKEN_CACHE_DELETE);
}
boolean isMultipleRTsMatchingGivenAppAndResource(final String clientId, final String resource) {
final Iterator<TokenCacheItem> allItems = mTokenCacheStore.getAll();
final List<TokenCacheItem> regularRTsMatchingRequest = new ArrayList<>();
while (allItems.hasNext()) {
final TokenCacheItem tokenCacheItem = allItems.next();
if (mAuthority.equalsIgnoreCase(tokenCacheItem.getAuthority()) && clientId.equalsIgnoreCase(tokenCacheItem.getClientId())
&& resource.equalsIgnoreCase(tokenCacheItem.getResource()) && !tokenCacheItem.getIsMultiResourceRefreshToken()) {
regularRTsMatchingRequest.add(tokenCacheItem);
}
}
return regularRTsMatchingRequest.size() > 1;
}
boolean isMultipleMRRTsMatchingGivenApp(final String clientId) {
final Iterator<TokenCacheItem> allItems = mTokenCacheStore.getAll();
final List<TokenCacheItem> mrrtsMatchingRequest = new ArrayList<>();
while (allItems.hasNext()) {
final TokenCacheItem tokenCacheItem = allItems.next();
if (tokenCacheItem.getAuthority().equalsIgnoreCase(mAuthority) && tokenCacheItem.getClientId().equalsIgnoreCase(clientId)
&& (tokenCacheItem.getIsMultiResourceRefreshToken() || StringExtensions.isNullOrBlank(tokenCacheItem.getResource()))) {
mrrtsMatchingRequest.add(tokenCacheItem);
}
}
return mrrtsMatchingRequest.size() > 1;
}
/**
* Update token cache for a given user. If token is MRRT, store two separate entries for regular RT entry and MRRT entry.
* Ideally, if returned token is MRRT, we should not store RT along with AT. However, there may be caller taking dependency
* on RT.
* If the token is FRT, store three separate entries.
*/
private void setItemToCacheForUser(final String resource, final String clientId, final AuthenticationResult result, final String userId) throws MalformedURLException {
final String methodName = ":setItemToCacheForUser";
logReturnedToken(result);
Logger.v(TAG + methodName, "Save regular token into cache.");
final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_WRITE);
cacheEvent.setRequestId(mTelemetryRequestId);
Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_WRITE);
// new tokens will only be saved into preferred cache location
mTokenCacheStore.setItem(CacheKey.createCacheKeyForRTEntry(getAuthorityUrlWithPreferredCache(), resource, clientId, userId),
TokenCacheItem.createRegularTokenCacheItem(getAuthorityUrlWithPreferredCache(), resource, clientId, result));
cacheEvent.setTokenTypeRT(true);
// Store separate entries for MRRT.
if (result.getIsMultiResourceRefreshToken()) {
Logger.v(TAG + methodName, "Save Multi Resource Refresh token to cache.");
mTokenCacheStore.setItem(CacheKey.createCacheKeyForMRRT(getAuthorityUrlWithPreferredCache(), clientId, userId),
TokenCacheItem.createMRRTTokenCacheItem(getAuthorityUrlWithPreferredCache(), clientId, result));
cacheEvent.setTokenTypeMRRT(true);
}
// Store separate entries for FRT.
if (!StringExtensions.isNullOrBlank(result.getFamilyClientId()) && !StringExtensions.isNullOrBlank(userId)) {
Logger.v(TAG + methodName, "Save Family Refresh token into cache.");
final TokenCacheItem familyTokenCacheItem = TokenCacheItem.createFRRTTokenCacheItem(getAuthorityUrlWithPreferredCache(), result);
mTokenCacheStore.setItem(CacheKey.createCacheKeyForFRT(getAuthorityUrlWithPreferredCache(), result.getFamilyClientId(), userId), familyTokenCacheItem);
cacheEvent.setTokenTypeFRT(true);
}
Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent,
EventStrings.TOKEN_CACHE_WRITE);
}
/**
* @return List of keys to remove when using regular RT to send refresh token request.
*/
private List<String> getKeyListToRemoveForRT(final TokenCacheItem cachedItem) {
final List<String> keysToRemove = new ArrayList<>();
keysToRemove.add(CacheKey.createCacheKeyForRTEntry(mAuthority, cachedItem.getResource(), cachedItem.getClientId(), null));
if (cachedItem.getUserInfo() != null) {
keysToRemove.add(CacheKey.createCacheKeyForRTEntry(mAuthority, cachedItem.getResource(), cachedItem.getClientId(), cachedItem.getUserInfo().getDisplayableId()));
keysToRemove.add(CacheKey.createCacheKeyForRTEntry(mAuthority, cachedItem.getResource(), cachedItem.getClientId(), cachedItem.getUserInfo().getUserId()));
}
return keysToRemove;
}
/**
* @return List of keys to remove when using MRRT to send refresh token request.
*/
private List<String> getKeyListToRemoveForMRRT(final TokenCacheItem cachedItem) {
final List<String> keysToRemove = new ArrayList<>();
keysToRemove.add(CacheKey.createCacheKeyForMRRT(mAuthority, cachedItem.getClientId(), null));
if (cachedItem.getUserInfo() != null) {
keysToRemove.add(CacheKey.createCacheKeyForMRRT(mAuthority, cachedItem.getClientId(), cachedItem.getUserInfo().getDisplayableId()));
keysToRemove.add(CacheKey.createCacheKeyForMRRT(mAuthority, cachedItem.getClientId(), cachedItem.getUserInfo().getUserId()));
}
return keysToRemove;
}
/**
* @return List of keys to remove when using FRT to send refresh token request.
*/
private List<String> getKeyListToRemoveForFRT(final TokenCacheItem cachedItem) {
final List<String> keysToRemove = new ArrayList<>();
if (cachedItem.getUserInfo() != null) {
keysToRemove.add(CacheKey.createCacheKeyForFRT(mAuthority, cachedItem.getFamilyClientId(), cachedItem.getUserInfo().getDisplayableId()));
keysToRemove.add(CacheKey.createCacheKeyForFRT(mAuthority, cachedItem.getFamilyClientId(), cachedItem.getUserInfo().getUserId()));
}
return keysToRemove;
}
private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) {
// If user is not passed in the request or userInfo does not exist in the token cache item,
// it's a match case. We do wildcard find, return whatever match with cache key.
if (StringExtensions.isNullOrBlank(user) || tokenCacheItem.getUserInfo() == null) {
return false;
}
// If user if provided, it needs to match either displayId or userId.
return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId())
&& !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId());
}
private void throwIfMultipleATExisted(final String clientId, final String resource, final String user) throws AuthenticationException {
if (StringExtensions.isNullOrBlank(user) && isMultipleRTsMatchingGivenAppAndResource(clientId, resource)) {
throw new AuthenticationException(ADALError.AUTH_FAILED_USER_MISMATCH, "No user is provided and multiple access tokens "
+ "exist for the given app and resource.");
}
}
/**
* Calculate hash for accessToken and log that.
*/
private void logReturnedToken(final AuthenticationResult result) {
if (result != null && result.getAccessToken() != null) {
Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", null);
}
}
/*
//No usages found... commenting out to make PMD happy.
private String getTokenHash(String token) {
try {
return StringExtensions.createHash(token);
} catch (NoSuchAlgorithmException e) {
Logger.e(TAG, "Digest error", "", ADALError.DEVICE_NO_SUCH_ALGORITHM, e);
} catch (UnsupportedEncodingException e) {
Logger.e(TAG, "Digest error", "", ADALError.ENCODING_IS_NOT_SUPPORTED, e);
}
return "";
}
*/
private CacheEvent startCacheTelemetryRequest(String tokenType) {
final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_LOOKUP);
cacheEvent.setTokenType(tokenType);
cacheEvent.setRequestId(mTelemetryRequestId);
Telemetry.getInstance().startEvent(mTelemetryRequestId, EventStrings.TOKEN_CACHE_LOOKUP);
return cacheEvent;
}
private TokenCacheItem performAdditionalCacheLookup(final String resource, final String clientid, final String familyClientId,
final String user, final TokenEntryType type) throws MalformedURLException {
TokenCacheItem item = getTokenCacheItemFromPassedInAuthority(resource, clientid, familyClientId, user, type);
if (item == null) {
item = getTokenCacheItemFromAliasedHost(resource, clientid, familyClientId, user, type);
}
return item;
}
private TokenCacheItem getTokenCacheItemFromPassedInAuthority(final String resource, final String clientId, final String familyClientId,
final String user, final TokenEntryType type) throws MalformedURLException {
if (getAuthorityUrlWithPreferredCache().equalsIgnoreCase(mAuthority)) {
return null;
}
final String cacheKeyWithPassedInAuthority = getCacheKey(mAuthority, resource, clientId, user, familyClientId, type);
return mTokenCacheStore.getItem(cacheKeyWithPassedInAuthority);
}
private TokenCacheItem getTokenCacheItemFromAliasedHost(final String resource, final String clientId, final String familyClientId,
final String user, final TokenEntryType type) throws MalformedURLException {
final InstanceDiscoveryMetadata instanceDiscoveryMetadata = getInstanceDiscoveryMetadata();
if (instanceDiscoveryMetadata == null) {
return null;
}
TokenCacheItem tokenCacheItemForAliasedHost = null;
final List<String> aliasHosts = instanceDiscoveryMetadata.getAliases();
for (final String aliasHost : aliasHosts) {
final String authority = constructAuthorityUrl(aliasHost);
// Already looked cache with preferred cache location and passed in authority, needs to look through other
// aliased host.
if (authority.equalsIgnoreCase(mAuthority) || authority.equalsIgnoreCase(getAuthorityUrlWithPreferredCache())) {
continue;
}
final String cacheKeyForAliasedHost = getCacheKey(authority, resource, clientId, user, familyClientId, type);
final TokenCacheItem item = mTokenCacheStore.getItem(cacheKeyForAliasedHost);
if (item != null) {
tokenCacheItemForAliasedHost = item;
break;
}
}
return tokenCacheItemForAliasedHost;
}
private String getCacheKey(final String authority, final String resource, final String clientId, final String user,
final String familyClientId, final TokenEntryType type) {
final String cacheKey;
switch (type) {
case REGULAR_TOKEN_ENTRY:
cacheKey = CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, user);
break;
case MRRT_TOKEN_ENTRY:
cacheKey = CacheKey.createCacheKeyForMRRT(authority, clientId, user);
break;
case FRT_TOKEN_ENTRY:
cacheKey = CacheKey.createCacheKeyForFRT(authority, familyClientId, user);
break;
default:
return null;
}
return cacheKey;
}
String getAuthorityUrlWithPreferredCache() throws MalformedURLException {
final InstanceDiscoveryMetadata instanceDiscoveryMetadata = getInstanceDiscoveryMetadata();
if (instanceDiscoveryMetadata == null || !instanceDiscoveryMetadata.isValidated()) {
return mAuthority;
}
final String preferredLocation = instanceDiscoveryMetadata.getPreferredCache();
// mAuthority can be updated to preferred location.
return constructAuthorityUrl(preferredLocation);
}
private String constructAuthorityUrl(final String host) throws MalformedURLException {
final URL passedInAuthority = new URL(mAuthority);
if (passedInAuthority.getHost().equalsIgnoreCase(host)) {
return mAuthority;
}
return Discovery.constructAuthorityUrl(passedInAuthority, host).toString();
}
private InstanceDiscoveryMetadata getInstanceDiscoveryMetadata() throws MalformedURLException {
final URL passedInAuthority = new URL(mAuthority);
return AuthorityValidationMetadataCache.getCachedInstanceDiscoveryMetadata(passedInAuthority);
}
}
| Changes to delete all tokens with all authority combinations for legacy and common (#1220)
* Changes to delete all tokens with all authority combinations for legacy
and common
(cherry picked from commit 56c65a2932eaa801edc500992ed59c4381a23d41)
* Minor Log line modification
* Minor formatting nits
| adal/src/main/java/com/microsoft/aad/adal/TokenCacheAccessor.java | Changes to delete all tokens with all authority combinations for legacy and common (#1220) | <ide><path>dal/src/main/java/com/microsoft/aad/adal/TokenCacheAccessor.java
<ide> request.setAuthority(new URL(mAuthority));
<ide>
<ide> mCommonCache.saveTokens(strategy, request, tokenResponse);
<del>
<ide> }
<ide>
<ide>
<ide> cacheEvent.setTokenTypeMRRT(true);
<ide> Logger.v(TAG + methodName, "MRRT was used to get access token, remove entries for both "
<ide> + "MRRT entries and regular RT entries.");
<del> keys = getKeyListToRemoveForMRRT(tokenCacheItem);
<add> keys = getKeyListToRemoveForMRRTOrFRT(tokenCacheItem, false);
<ide>
<ide> final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem);
<ide> regularRTItem.setResource(resource);
<ide> cacheEvent.setTokenTypeFRT(true);
<ide> Logger.v(TAG + methodName, "FRT was used to get access token, remove entries for "
<ide> + "FRT entries.");
<del> keys = getKeyListToRemoveForFRT(tokenCacheItem);
<add> keys = getKeyListToRemoveForMRRTOrFRT(tokenCacheItem, true);
<ide> break;
<ide> default:
<ide> throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM);
<ide> */
<ide> private List<String> getKeyListToRemoveForRT(final TokenCacheItem cachedItem) {
<ide> final List<String> keysToRemove = new ArrayList<>();
<del> keysToRemove.add(CacheKey.createCacheKeyForRTEntry(mAuthority, cachedItem.getResource(), cachedItem.getClientId(), null));
<del> if (cachedItem.getUserInfo() != null) {
<del> keysToRemove.add(CacheKey.createCacheKeyForRTEntry(mAuthority, cachedItem.getResource(), cachedItem.getClientId(), cachedItem.getUserInfo().getDisplayableId()));
<del> keysToRemove.add(CacheKey.createCacheKeyForRTEntry(mAuthority, cachedItem.getResource(), cachedItem.getClientId(), cachedItem.getUserInfo().getUserId()));
<del> }
<del>
<add> try {
<add> final String preferredAuthority = getAuthorityUrlWithPreferredCache();
<add> if (preferredAuthority != null) {
<add> addDeletionKeysForRTEntry(preferredAuthority, cachedItem, keysToRemove);
<add> }
<add> } catch (final MalformedURLException exception) {
<add> com.microsoft.identity.common.internal.logging.Logger.error(TAG, "Authority from preferred cache is invalid", null);
<add> com.microsoft.identity.common.internal.logging.Logger.errorPII(TAG, "Failed with exception", exception);
<add>
<add> }
<add> addDeletionKeysForRTEntry(mAuthority, cachedItem, keysToRemove);
<add>
<add> // For back compatibility, remove the cache key with the passed-in request authority.
<add> if (!mAuthority.equalsIgnoreCase(cachedItem.getAuthority())) {
<add> addDeletionKeysForRTEntry(cachedItem.getAuthority(), cachedItem, keysToRemove);
<add> }
<ide> return keysToRemove;
<ide> }
<ide>
<ide> /**
<del> * @return List of keys to remove when using MRRT to send refresh token request.
<del> */
<del> private List<String> getKeyListToRemoveForMRRT(final TokenCacheItem cachedItem) {
<add> * @return List of keys to remove when using MRRT or FRT to send refresh token request.
<add> */
<add> private List<String> getKeyListToRemoveForMRRTOrFRT(final TokenCacheItem cachedItem, final boolean isFRT) {
<add>
<ide> final List<String> keysToRemove = new ArrayList<>();
<del>
<del> keysToRemove.add(CacheKey.createCacheKeyForMRRT(mAuthority, cachedItem.getClientId(), null));
<del> if (cachedItem.getUserInfo() != null) {
<del> keysToRemove.add(CacheKey.createCacheKeyForMRRT(mAuthority, cachedItem.getClientId(), cachedItem.getUserInfo().getDisplayableId()));
<del> keysToRemove.add(CacheKey.createCacheKeyForMRRT(mAuthority, cachedItem.getClientId(), cachedItem.getUserInfo().getUserId()));
<add> final KeyMakerStrategy keymaker = new KeyMakerStrategy() {
<add> @Override
<add> public boolean isFrt() {
<add> return isFRT;
<add> }
<add>
<add> @Override
<add> public String makeKey(String authority, String clientId, String userId) {
<add> if (isFRT) {
<add> return CacheKey.createCacheKeyForFRT(authority, clientId, userId);
<add> }
<add> return CacheKey.createCacheKeyForMRRT(authority, clientId, userId);
<add> }
<add> };
<add> // Remove the cache key with preferred authority.
<add> try {
<add> final String preferredAuthority = getAuthorityUrlWithPreferredCache();
<add> if (preferredAuthority != null) {
<add> addDeletionKeysForMRRTOrFRTEntry(preferredAuthority, cachedItem, keysToRemove, keymaker);
<add> }
<add> } catch (final MalformedURLException exception) {
<add> com.microsoft.identity.common.internal.logging.Logger.error(TAG, "Authority from preferred cache is invalid", null);
<add> com.microsoft.identity.common.internal.logging.Logger.errorPII(TAG, "Failed with exception", exception);
<add> }
<add>
<add> addDeletionKeysForMRRTOrFRTEntry(mAuthority, cachedItem, keysToRemove, keymaker);
<add>
<add> // For back compatibility, remove the cache key with the passed-in request authority.
<add> if (!mAuthority.equalsIgnoreCase(cachedItem.getAuthority())) {
<add> addDeletionKeysForMRRTOrFRTEntry(cachedItem.getAuthority(), cachedItem, keysToRemove, keymaker);
<ide> }
<ide>
<ide> return keysToRemove;
<ide> }
<ide>
<del> /**
<del> * @return List of keys to remove when using FRT to send refresh token request.
<del> */
<del> private List<String> getKeyListToRemoveForFRT(final TokenCacheItem cachedItem) {
<del> final List<String> keysToRemove = new ArrayList<>();
<del> if (cachedItem.getUserInfo() != null) {
<del> keysToRemove.add(CacheKey.createCacheKeyForFRT(mAuthority, cachedItem.getFamilyClientId(), cachedItem.getUserInfo().getDisplayableId()));
<del> keysToRemove.add(CacheKey.createCacheKeyForFRT(mAuthority, cachedItem.getFamilyClientId(), cachedItem.getUserInfo().getUserId()));
<del> }
<del>
<del> return keysToRemove;
<add> interface KeyMakerStrategy {
<add> boolean isFrt();
<add>
<add> String makeKey(final String authority, final String clientId, final String userId);
<add> }
<add>
<add> private void addDeletionKeysForRTEntry(final String authority, final TokenCacheItem item, final List<String> keys) {
<add> final String resource = item.getResource();
<add> final String clientId = item.getClientId();
<add> final UserInfo userInfo = item.getUserInfo();
<add>
<add> keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, null));
<add>
<add> if (userInfo != null) {
<add> if (userInfo.getDisplayableId() != null) {
<add> keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, userInfo.getDisplayableId()));
<add> }
<add> if (userInfo.getUserId() != null) {
<add> keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, userInfo.getUserId()));
<add> if (item.getTenantId() != null) {
<add> String uniqueId = getUniqueIdentifierForCacheKey(userInfo.getUserId(), item.getTenantId());
<add> keys.add(CacheKey.createCacheKeyForRTEntry(authority, resource, clientId, uniqueId));
<add> }
<add> }
<add> }
<add> }
<add>
<add> private void addDeletionKeysForMRRTOrFRTEntry(final String authority, final TokenCacheItem item, final List<String> keys, final KeyMakerStrategy strategy) {
<add> final UserInfo userInfo = item.getUserInfo();
<add> String clientId = item.getClientId();
<add>
<add> if (strategy.isFrt()) {
<add> clientId = item.getFamilyClientId();
<add> }
<add>
<add> final List<String> userIds = new ArrayList<>();
<add> userIds.add(null); // no user affinity
<add>
<add> if (userInfo != null) {
<add> if (userInfo.getDisplayableId() != null) {
<add> userIds.add(userInfo.getDisplayableId());
<add> }
<add> if (userInfo.getUserId() != null) {
<add> userIds.add(userInfo.getUserId());
<add> if (item.getTenantId() != null) {
<add> userIds.add(getUniqueIdentifierForCacheKey(userInfo.getUserId(), item.getTenantId()));
<add> }
<add> }
<add> }
<add> // Iterate over the userId permutations and, in the FRT-case, conditionally delete them if they match.
<add> // Non-FRTs are unconditionally cleared.
<add> for (final String userId : userIds) {
<add> addDeletionKeyForMRRTOrFRTEntry(keys, item, authority, clientId, userId, strategy);
<add> }
<add> }
<add>
<add> private void addDeletionKeyForMRRTOrFRTEntry(final List<String> keysToRemove,
<add> final TokenCacheItem deletionTarget,
<add> final String authority,
<add> final String clientId,
<add> final String userId,
<add> final KeyMakerStrategy strategy) {
<add> final String keyToAdd = strategy.makeKey(authority, clientId, userId);
<add> if (strategy.isFrt()) {
<add> addDeletionKeyForFRTIfRTValueIsStale(keysToRemove, deletionTarget, keyToAdd);
<add> } else {
<add> keysToRemove.add(keyToAdd);
<add> }
<add> }
<add>
<add> private void addDeletionKeyForFRTIfRTValueIsStale(final List<String> keysToRemove,
<add> final TokenCacheItem deletionTarget,
<add> final String deletionCandidateKey) {
<add> final TokenCacheItem fociCacheItem = mTokenCacheStore.getItem(deletionCandidateKey);
<add> if (null != fociCacheItem && deletionTarget.getRefreshToken().equalsIgnoreCase(fociCacheItem.getRefreshToken())) {
<add> keysToRemove.add(deletionCandidateKey);
<add> }
<add> }
<add>
<add> private String getUniqueIdentifierForCacheKey(final String userId, final String tenantId) {
<add> return StringExtensions.base64UrlEncodeToString(userId) + "." + StringExtensions.base64UrlEncodeToString(tenantId);
<ide> }
<ide>
<ide> private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) {
<ide> Logger.i(TAG, "Access tokenID and refresh tokenID returned. ", null);
<ide> }
<ide> }
<del>
<del> /*
<del> //No usages found... commenting out to make PMD happy.
<del> private String getTokenHash(String token) {
<del> try {
<del> return StringExtensions.createHash(token);
<del> } catch (NoSuchAlgorithmException e) {
<del> Logger.e(TAG, "Digest error", "", ADALError.DEVICE_NO_SUCH_ALGORITHM, e);
<del> } catch (UnsupportedEncodingException e) {
<del> Logger.e(TAG, "Digest error", "", ADALError.ENCODING_IS_NOT_SUPPORTED, e);
<del> }
<del>
<del> return "";
<del> }
<del> */
<del>
<ide>
<ide> private CacheEvent startCacheTelemetryRequest(String tokenType) {
<ide> final CacheEvent cacheEvent = new CacheEvent(EventStrings.TOKEN_CACHE_LOOKUP); |
|
Java | mit | a0f0a0eaee8d04282a93c71f8aa65ba3077244de | 0 | katzenpapst/amunra | package de.katzenpapst.amunra.world;
import java.util.Random;
import javax.vecmath.Color4f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import com.sun.prism.paint.Color;
import cpw.mods.fml.client.FMLClientHandler;
import de.katzenpapst.amunra.AmunRa;
import micdoodle8.mods.galacticraft.api.galaxies.CelestialBody;
import micdoodle8.mods.galacticraft.api.galaxies.GalaxyRegistry;
import micdoodle8.mods.galacticraft.api.galaxies.Moon;
import micdoodle8.mods.galacticraft.api.galaxies.Planet;
import micdoodle8.mods.galacticraft.api.galaxies.SolarSystem;
import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider;
import micdoodle8.mods.galacticraft.core.GalacticraftCore;
import micdoodle8.mods.galacticraft.core.util.ColorUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import net.minecraftforge.client.IRenderHandler;
public class SkyProviderDynamic extends IRenderHandler {
private static final ResourceLocation overworldTexture = new ResourceLocation(GalacticraftCore.ASSET_PREFIX, "textures/gui/celestialbodies/earth.png");
private static final ResourceLocation sunTexture = new ResourceLocation("textures/environment/sun.png");
public int starList;
public int glSkyList;
public int glSkyList2;
private float sunSize;
protected double yearFactor = 40000L; // technically, 8640000L would be true
protected double moonFactor = 2000L;//192000L;
// angle of the system in the sky
protected float systemAngle = 24;
// angle of the moons' orbits relative to the equator
protected float moonAngle = 19;
// system to render in the sky
protected SolarSystem curSystem;
// the body to render it around
protected CelestialBody curBody;
// this is either the same as curBody, or it's parent, if its a moon
protected Planet curBodyPlanet;
// the distance of this body or it's parent from the sun
protected float curBodyDistance;
private float boxWidthHalf = 311;
public SkyProviderDynamic(IGalacticraftWorldProvider worldProvider) {
this.sunSize = 2*worldProvider.getSolarSize();
curBody = worldProvider.getCelestialBody();
// find the current system
if(curBody instanceof Planet) {
curBodyPlanet = ((Planet)curBody);
curSystem = curBodyPlanet.getParentSolarSystem();
} else if(curBody instanceof Moon) {
curBodyPlanet = ((Moon)curBody).getParentPlanet();
curSystem = curBodyPlanet.getParentSolarSystem();
} else {
// todo do somethign
}
curBodyDistance = curBodyPlanet.getRelativeDistanceFromCenter().unScaledDistance;
//curSystem = curBody.getPhaseShift(
int displayLists = GLAllocation.generateDisplayLists(3);
this.starList = displayLists;
this.glSkyList = displayLists + 1;
this.glSkyList2 = displayLists + 2;
// Bind stars to display list
GL11.glPushMatrix();
GL11.glNewList(this.starList, GL11.GL_COMPILE);
this.renderStars();
GL11.glEndList();
GL11.glPopMatrix();
final Tessellator tessellator = Tessellator.instance;
GL11.glNewList(this.glSkyList, GL11.GL_COMPILE);
final byte byte2 = 64;
final int i = 256 / byte2 + 2;
float f = 16F;
for (int j = -byte2 * i; j <= byte2 * i; j += byte2)
{
for (int l = -byte2 * i; l <= byte2 * i; l += byte2)
{
tessellator.startDrawingQuads();
tessellator.addVertex(j + 0, f, l + 0);
tessellator.addVertex(j + byte2, f, l + 0);
tessellator.addVertex(j + byte2, f, l + byte2);
tessellator.addVertex(j + 0, f, l + byte2);
tessellator.draw();
}
}
GL11.glEndList();
GL11.glNewList(this.glSkyList2, GL11.GL_COMPILE);
f = -16F;
tessellator.startDrawingQuads();
for (int k = -byte2 * i; k <= byte2 * i; k += byte2)
{
for (int i1 = -byte2 * i; i1 <= byte2 * i; i1 += byte2)
{
tessellator.addVertex(k + byte2, f, i1 + 0);
tessellator.addVertex(k + 0, f, i1 + 0);
tessellator.addVertex(k + 0, f, i1 + byte2);
tessellator.addVertex(k + byte2, f, i1 + byte2);
}
}
tessellator.draw();
GL11.glEndList();
}
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableStandardItemLighting();
Vec3 vec3 = world.getSkyColor(mc.renderViewEntity, partialTicks);
float f1 = (float) vec3.xCoord;
float f2 = (float) vec3.yCoord;
float f3 = (float) vec3.zCoord;
float f6;
if (mc.gameSettings.anaglyph)
{
float f4 = (f1 * 30.0F + f2 * 59.0F + f3 * 11.0F) / 100.0F;
float f5 = (f1 * 30.0F + f2 * 70.0F) / 100.0F;
f6 = (f1 * 30.0F + f3 * 70.0F) / 100.0F;
f1 = f4;
f2 = f5;
f3 = f6;
}
GL11.glColor3f(f1, f2, f3);
Tessellator tessellator1 = Tessellator.instance;
GL11.glDepthMask(false);
GL11.glEnable(GL11.GL_FOG);
GL11.glColor3f(f1, f2, f3);
GL11.glCallList(this.glSkyList);
GL11.glDisable(GL11.GL_FOG);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
RenderHelper.disableStandardItemLighting();
float f7;
float f8;
float f9;
float f10;
float f18 = world.getStarBrightness(partialTicks);
if (f18 > 0.0F)
{
GL11.glColor4f(f18, f18, f18, f18);
GL11.glCallList(this.starList);
}
float[] afloat = new float[4];
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glPushMatrix();
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(world.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F);
afloat[0] = 255 / 255.0F;
afloat[1] = 194 / 255.0F;
afloat[2] = 180 / 255.0F;
afloat[3] = 0.3F;
f6 = afloat[0];
f7 = afloat[1];
f8 = afloat[2];
float f11;
if (mc.gameSettings.anaglyph)
{
f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F;
f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F;
f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F;
f6 = f9;
f7 = f10;
f8 = f11;
}
f18 = 1.0F - f18;
GL11.glPopMatrix();
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_TEXTURE_2D);
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
GL11.glPushMatrix();
f7 = 0.0F;
f8 = 0.0F;
f9 = 0.0F;
GL11.glTranslatef(f7, f8, f9);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
// rotates the sky by the celestial angle on the x axis
// this seems to mean that the x-axis is the rotational axis of the planet
// does the sun move from -z to z or the other way round?
GL11.glRotatef(world.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F);
// so at this point, I'm where the sun is supposed to be. This is where I have to start.
// Render system
renderSystem(partialTicks, world, tessellator1, mc);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_FOG);
GL11.glPopMatrix();
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor3f(0.0F, 0.0F, 0.0F);
double d0 = mc.thePlayer.getPosition(partialTicks).yCoord - world.getHorizon();
if (d0 < 0.0D)
{
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, 12.0F, 0.0F);
GL11.glCallList(this.glSkyList2);
GL11.glPopMatrix();
f8 = 1.0F;
f9 = -((float) (d0 + 65.0D));
f10 = -f8;
tessellator1.startDrawingQuads();
tessellator1.setColorRGBA_I(0, 255);
tessellator1.addVertex(-f8, f9, f8);
tessellator1.addVertex(f8, f9, f8);
tessellator1.addVertex(f8, f10, f8);
tessellator1.addVertex(-f8, f10, f8);
tessellator1.addVertex(-f8, f10, -f8);
tessellator1.addVertex(f8, f10, -f8);
tessellator1.addVertex(f8, f9, -f8);
tessellator1.addVertex(-f8, f9, -f8);
tessellator1.addVertex(f8, f10, -f8);
tessellator1.addVertex(f8, f10, f8);
tessellator1.addVertex(f8, f9, f8);
tessellator1.addVertex(f8, f9, -f8);
tessellator1.addVertex(-f8, f9, -f8);
tessellator1.addVertex(-f8, f9, f8);
tessellator1.addVertex(-f8, f10, f8);
tessellator1.addVertex(-f8, f10, -f8);
tessellator1.addVertex(-f8, f10, -f8);
tessellator1.addVertex(-f8, f10, f8);
tessellator1.addVertex(f8, f10, f8);
tessellator1.addVertex(f8, f10, -f8);
tessellator1.draw();
}
if (world.provider.isSkyColored())
{
GL11.glColor3f(f1 * 0.2F + 0.04F, f2 * 0.2F + 0.04F, f3 * 0.6F + 0.1F);
}
else
{
GL11.glColor3f(f1, f2, f3);
}
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, -((float) (d0 - 16.0D)), 0.0F);
GL11.glCallList(this.glSkyList2);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(true);
}
protected void renderSunAura(Tessellator tessellator1, Vector3f color, float size, float brightness) {
// Vector3f basecolor = new Vector3f(0.94890916F, 0.72191525F, 0.6698182F);
GL11.glShadeModel(GL11.GL_SMOOTH);
// Color4f color1 = new Color4f(0.5, 0, 0.5, arg3)
// f18 = sunbrightness
/*tessellator1.setColorRGBA_F(f6 * f18, f7 * f18, f8 * f18, afloat[3] * 2 / f18);
tessellator1.addVertex(0.0D, 100.0D, 0.0D);
byte b0 = 16;
tessellator1.setColorRGBA_F(afloat[0] * f18, afloat[1] * f18, afloat[2] * f18, 0.0F);*/
// small sun aura START
double y = 80.0D;
tessellator1.startDrawing(GL11.GL_TRIANGLE_FAN);
tessellator1.setColorRGBA_F(color.x, color.y, color.z, 0.8F / brightness);
tessellator1.addVertex(0.0D, y, 0.0D);
byte b0 = 16;
tessellator1.setColorRGBA_F(color.x, color.y, color.z, 0.0F);
// Render sun aura
tessellator1.addVertex(-size, y, -size);
tessellator1.addVertex(0, y, (double) -size * 1.5F);
tessellator1.addVertex(size, y, -size);
tessellator1.addVertex((double) size * 1.5F, y, 0);
tessellator1.addVertex(size, y, size);
tessellator1.addVertex(0, y, (double) size * 1.5F);
tessellator1.addVertex(-size, y, size);
tessellator1.addVertex((double) -size * 1.5F, y, 0);
tessellator1.addVertex(-size, y, -size);
tessellator1.draw();
}
protected void renderSystem(float partialTicks, WorldClient world, Tessellator tess, Minecraft mc) {
// assume we are at the position of the sun
GL11.glPushMatrix();
// try to rotate it
GL11.glRotatef(25, 0, 1.0F, 0);
GL11.glPushMatrix();
// sun aura
renderSunAura(tess, new Vector3f(0.7F, 0.2F, 0.0F), this.sunSize*5, this.sunSize);
// render the sun first
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(0.0F, 0.0F, 0.0F, 1.0F);
//Some blanking to conceal the stars
float f10 = this.sunSize / 3.5F;
tess.startDrawingQuads();
tess.addVertex(-f10, 99.9D, -f10);
tess.addVertex(f10, 99.9D, -f10);
tess.addVertex(f10, 99.9D, f10);
tess.addVertex(-f10, 99.9D, f10);
tess.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
f10 = this.sunSize;
mc.renderEngine.bindTexture(this.curSystem.getMainStar().getBodyIcon());
tess.startDrawingQuads();
tess.addVertexWithUV(-f10, 100.0D, -f10, 0.0D, 0.0D);
tess.addVertexWithUV(f10, 100.0D, -f10, 1.0D, 0.0D);
tess.addVertexWithUV(f10, 100.0D, f10, 1.0D, 1.0D);
tess.addVertexWithUV(-f10, 100.0D, f10, 0.0D, 1.0D);
tess.draw();
GL11.glPopMatrix();
GL11.glDisable(GL11.GL_TEXTURE_2D);
//renderHalfArch(tess);
// protected void renderSunAura(Tessellator tessellator1, Vector3f color, float size, float brightness) {
long curWorldTime = world.getWorldTime();
// get my own angle
double curBodyOrbitalAngle = getOrbitalAngle(curBodyPlanet.getRelativeDistanceFromCenter().unScaledDistance, curBodyPlanet.getPhaseShift(), curWorldTime , partialTicks, yearFactor);
// now render planets. wait wat. you can't just iterate through all the planets in a system?!
for (Planet planet : GalaxyRegistry.getRegisteredPlanets().values()) {
// oh well I hope this doesn't kill the performance
if(planet.getParentSolarSystem() != curSystem) {
continue;
}
float dist = planet.getRelativeDistanceFromCenter().unScaledDistance;
// try do my own
if(dist == curBodyDistance) {
// so seems like the skybox is some 622 across
//i++;
continue;
}
if(planet.equals(AmunRa.instance.asteroidBeltMehen)) {
continue; // for now don't render it
}
// orbital angle of the planet
double curOrbitalAngle = getOrbitalAngle(planet.getRelativeOrbitTime(), planet.getPhaseShift(), curWorldTime, partialTicks, yearFactor);
// but I need it relative to curOrbitalAngle, or actually to curOrbitalAngle rotated by 180,
// just because that's how I calculated that stuff
curOrbitalAngle -= (Math.PI*2-curBodyOrbitalAngle);
// angle between connection line curBody<-->sun and planet<-->sun
double innerAngle = Math.PI-curOrbitalAngle;
// distance between curBody<-->planet, also needed for scaling
double distanceToPlanet = getDistanceToBody(innerAngle, dist);
double projectedAngle = projectAngle(innerAngle, dist, distanceToPlanet, curBodyDistance);
renderPlanetByAngle(tess, planet, (float)projectedAngle, 0, 1.0F / (float)distanceToPlanet);
}
GL11.glPopMatrix();
// now do moons
GL11.glPushMatrix();
// try to rotate it
GL11.glRotatef(-19, 0, 1.0F, 0);
if(this.curBody instanceof Planet) {
// oh my...
double curOrbitalAngle;
for (Moon moon : GalaxyRegistry.getRegisteredMoons().values()) {
if(!moon.getParentPlanet().equals(curBody)) {
continue;
}
curOrbitalAngle = getOrbitalAngle(moon.getRelativeOrbitTime()/100, moon.getPhaseShift(), curWorldTime, partialTicks, moonFactor);
// not projecting the angle here
renderPlanetByAngle(tess, moon, (float) curOrbitalAngle, 0, 20/moon.getRelativeDistanceFromCenter().unScaledDistance);
}
} else {
double distanceToParent = curBody.getRelativeDistanceFromCenter().unScaledDistance;
double curOrbitalAngle = getOrbitalAngle(curBody.getRelativeOrbitTime()/100, curBody.getPhaseShift(), curWorldTime, partialTicks, moonFactor);
// render my parent body
// 180-my angle around my parent, should be it's angle in my sky
double mainBodyOrbitalAngle = Math.PI-curOrbitalAngle;
renderPlanetByAngle(tess, curBodyPlanet, (float) mainBodyOrbitalAngle, 0, (float) (20/distanceToParent));
// now do my sibling moons
for (Moon moon : GalaxyRegistry.getRegisteredMoons().values()) {
if(!moon.getParentPlanet().equals(curBodyPlanet) || moon.equals(curBody)) {
continue;
}
// this is what I do for planets
float dist = moon.getRelativeDistanceFromCenter().unScaledDistance;
/*if(dist < distanceToParent) {
continue; // DEBUG
}*/
// orbital angle of the moon
double moonOrbitalAngle = getOrbitalAngle(moon.getRelativeOrbitTime(), moon.getPhaseShift(), curWorldTime, partialTicks, moonFactor);
// but I need it relative to curOrbitalAngle, or actually to curOrbitalAngle rotated by 180,
// just because that's how I calculated that stuff
moonOrbitalAngle -= (Math.PI*2-curOrbitalAngle);
// angle between connection line curBody<-->parent and moon<-->parent
double innerAngle = Math.PI-moonOrbitalAngle;
// distance between curBody<-->moon, also needed for scaling
double distanceToPlanet = getDistanceToBody(innerAngle, dist);
double projectedAngle = projectAngle(innerAngle, dist, distanceToPlanet, distanceToParent);
renderPlanetByAngle(tess, moon, (float)projectedAngle, 0, 10.0F / (float)distanceToPlanet);
}
}
GL11.glPopMatrix();
}
protected double getOrbitalAngle(double relOrbitTime, double phaseShift, long worldTime, double partialTicks, double orbitFactor) {
double curYearLength = relOrbitTime * orbitFactor;
int j = (int)(worldTime % (long)curYearLength);
double orbitPos = (j + partialTicks) / curYearLength - 0.25F;
return orbitPos*2*Math.PI + phaseShift;
}
private double getDistanceToBody(double innerAngle, double otherBodyDistance) {
return Math.sqrt(
Math.pow(otherBodyDistance, 2) +
Math.pow(curBodyDistance, 2) -
2 * otherBodyDistance * curBodyDistance * Math.cos(innerAngle));
}
/**
* Should convert an angle around the sun into an angle around this body
*
*
* @param innerAngle in radians, the angle between curBody<-->sun and otherBody<-->sun
* @param otherBodyDistance other body's orbital radius
* @param distFromThisToOtherBody
* @return
*/
private double projectAngle(double innerAngle, double otherBodyDistance, double distFromThisToOtherBody, double curBodyDistance) {
// omg now do dark mathemagic
/*if(angleAroundSun < 0) {
angleAroundSun = Math.PI*2+angleAroundSun;
}*/
//double beta = Math.PI-angleAroundSun;
// innerAngle = beta
double sinBeta = Math.sin(innerAngle);
// distFromThisToOtherBody = x
// curBodyDistance = d
// otherBodyDistance = r
// gamma
double angleAroundCurBody = Math.asin(
otherBodyDistance * sinBeta / distFromThisToOtherBody
);
if ( curBodyDistance > otherBodyDistance) {
return angleAroundCurBody;
}
// now fix this angle...
// for this, I need the third angle, too
double delta = Math.asin(sinBeta / distFromThisToOtherBody * curBodyDistance);
double angleSum = innerAngle+delta+angleAroundCurBody;
double otherAngleSum =innerAngle+delta+(Math.PI-angleAroundCurBody);
if(Math.abs(Math.abs(angleSum)/Math.PI - 1) < 0.001) {
// aka angleSUm = 180 or -180
return angleAroundCurBody;
} else {
return Math.PI-angleAroundCurBody;
}
}
private void renderPlanetByAngle(Tessellator tessellator1, CelestialBody body, float angle, float zIndex, float scale) {
// we start at the sun
GL11.glPushMatrix();
//GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F); // change this for your colour
//GL11.glLineWidth(2.0F);
// rotate on x
GL11.glRotatef((float) (angle/Math.PI*180), 1.0F, 0.0F, 0.0F);
if(body.equals(AmunRa.instance.starAmun)) {
renderSunAura(tessellator1, new Vector3f(0.0F, 0.2F, 0.7F), scale*5, scale);
}
//renderPlanet(tessellator1,texture,0,offset);
// BEGIN
GL11.glDisable(GL11.GL_BLEND);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F);
FMLClientHandler.instance().getClient().renderEngine.bindTexture(body.getBodyIcon());
tessellator1.startDrawingQuads();
// final float scale = 2;
// go to the position
GL11.glTranslatef(0, 95.0F+zIndex, 0);
tessellator1.addVertexWithUV(-scale, 0, -scale, 0, 0);
tessellator1.addVertexWithUV(scale, 0, -scale, 1, 0);
tessellator1.addVertexWithUV(scale, 0, scale, 1, 1);
tessellator1.addVertexWithUV(-scale, 0, scale, 0, 1);
tessellator1.draw();
GL11.glDisable(GL11.GL_TEXTURE_2D);
// END
GL11.glEnable(GL11.GL_BLEND);
// TODO figure this out: http://wiki.delphigl.com/index.php/glBlendFunc
GL11.glPopMatrix();
}
/*private void renderOrbit(Tessellator tessellator1 , float scale) {
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F); // change this for your colour
GL11.glLineWidth(2.0F);
tessellator1.startDrawing(GL11.GL_LINE_LOOP);
float x = -scale;
float y = scale;
float temp;
final float theta = (float) (2 * Math.PI / 90);
final float cos = (float) Math.cos(theta);
final float sin = (float) Math.sin(theta);
for (int i = 0; i < 90; i++)
{
tessellator1.addVertex(x, -90F, -y);
temp = x;
x = cos * x - sin * y;
y = sin * temp + cos * y;
}
tessellator1.draw();
}*/
private void renderStars()
{
final Random rand = new Random(10842L);
final Tessellator var2 = Tessellator.instance;
var2.startDrawingQuads();
for (int starIndex = 0; starIndex < (6000); ++starIndex)
{
double var4 = rand.nextFloat() * 2.0F - 1.0F;
double var6 = rand.nextFloat() * 2.0F - 1.0F;
double var8 = rand.nextFloat() * 2.0F - 1.0F;
final double var10 = 0.15F + rand.nextFloat() * 0.1F;
double var12 = var4 * var4 + var6 * var6 + var8 * var8;
if (var12 < 1.0D && var12 > 0.01D)
{
var12 = 1.0D / Math.sqrt(var12);
var4 *= var12;
var6 *= var12;
var8 *= var12;
final double var14 = var4 * 100.0D;//(ConfigManagerCore.moreStars ? rand.nextDouble() * 150D + 130D : 100.0D);
final double var16 = var6 * 100.0D;//(ConfigManagerCore.moreStars ? rand.nextDouble() * 150D + 130D : 100.0D);
final double var18 = var8 * 100.0D;//(ConfigManagerCore.moreStars ? rand.nextDouble() * 150D + 130D : 100.0D);
final double var20 = Math.atan2(var4, var8);
final double var22 = Math.sin(var20);
final double var24 = Math.cos(var20);
final double var26 = Math.atan2(Math.sqrt(var4 * var4 + var8 * var8), var6);
final double var28 = Math.sin(var26);
final double var30 = Math.cos(var26);
final double var32 = rand.nextDouble() * Math.PI * 2.0D;
final double var34 = Math.sin(var32);
final double var36 = Math.cos(var32);
for (int var38 = 0; var38 < 4; ++var38)
{
final double var39 = 0.0D;
final double var41 = ((var38 & 2) - 1) * var10;
final double var43 = ((var38 + 1 & 2) - 1) * var10;
final double var47 = var41 * var36 - var43 * var34;
final double var49 = var43 * var36 + var41 * var34;
final double var53 = var47 * var28 + var39 * var30;
final double var55 = var39 * var28 - var47 * var30;
final double var57 = var55 * var22 - var49 * var24;
final double var61 = var49 * var22 + var55 * var24;
var2.addVertex(var14 + var57, var16 + var53, var18 + var61);
}
}
}
var2.draw();
}
private Vec3 getCustomSkyColor()
{
return Vec3.createVectorHelper(0.26796875D, 0.1796875D, 0.0D);
}
public float getSkyBrightness(float par1)
{
final float var2 = FMLClientHandler.instance().getClient().theWorld.getCelestialAngle(par1);
float var3 = 1.0F - (MathHelper.sin(var2 * (float) Math.PI * 2.0F) * 2.0F + 0.25F);
if (var3 < 0.0F)
{
var3 = 0.0F;
}
if (var3 > 1.0F)
{
var3 = 1.0F;
}
return var3 * var3 * 1F;
}
}
| src/main/java/de/katzenpapst/amunra/world/SkyProviderDynamic.java | package de.katzenpapst.amunra.world;
import java.util.Random;
import javax.vecmath.Color4f;
import javax.vecmath.Vector3f;
import javax.vecmath.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import com.sun.prism.paint.Color;
import cpw.mods.fml.client.FMLClientHandler;
import de.katzenpapst.amunra.AmunRa;
import micdoodle8.mods.galacticraft.api.galaxies.CelestialBody;
import micdoodle8.mods.galacticraft.api.galaxies.GalaxyRegistry;
import micdoodle8.mods.galacticraft.api.galaxies.Moon;
import micdoodle8.mods.galacticraft.api.galaxies.Planet;
import micdoodle8.mods.galacticraft.api.galaxies.SolarSystem;
import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider;
import micdoodle8.mods.galacticraft.core.GalacticraftCore;
import micdoodle8.mods.galacticraft.core.util.ColorUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import net.minecraftforge.client.IRenderHandler;
public class SkyProviderDynamic extends IRenderHandler {
private static final ResourceLocation overworldTexture = new ResourceLocation(GalacticraftCore.ASSET_PREFIX, "textures/gui/celestialbodies/earth.png");
private static final ResourceLocation sunTexture = new ResourceLocation("textures/environment/sun.png");
public int starList;
public int glSkyList;
public int glSkyList2;
private float sunSize;
protected double yearFactor = 40000L; // technically, 8640000L would be true
protected double moonFactor = 2000L;//192000L;
// angle of the system in the sky
protected float systemAngle = 24;
// angle of the moons' orbits relative to the equator
protected float moonAngle = 19;
// system to render in the sky
protected SolarSystem curSystem;
// the body to render it around
protected CelestialBody curBody;
// this is either the same as curBody, or it's parent, if its a moon
protected Planet curBodyPlanet;
// the distance of this body or it's parent from the sun
protected float curBodyDistance;
private float boxWidthHalf = 311;
public SkyProviderDynamic(IGalacticraftWorldProvider worldProvider) {
this.sunSize = 2*worldProvider.getSolarSize();
curBody = worldProvider.getCelestialBody();
// find the current system
if(curBody instanceof Planet) {
curBodyPlanet = ((Planet)curBody);
curSystem = curBodyPlanet.getParentSolarSystem();
} else if(curBody instanceof Moon) {
curBodyPlanet = ((Moon)curBody).getParentPlanet();
curSystem = curBodyPlanet.getParentSolarSystem();
} else {
// todo do somethign
}
curBodyDistance = curBodyPlanet.getRelativeDistanceFromCenter().unScaledDistance;
//curSystem = curBody.getPhaseShift(
int displayLists = GLAllocation.generateDisplayLists(3);
this.starList = displayLists;
this.glSkyList = displayLists + 1;
this.glSkyList2 = displayLists + 2;
// Bind stars to display list
GL11.glPushMatrix();
GL11.glNewList(this.starList, GL11.GL_COMPILE);
this.renderStars();
GL11.glEndList();
GL11.glPopMatrix();
final Tessellator tessellator = Tessellator.instance;
GL11.glNewList(this.glSkyList, GL11.GL_COMPILE);
final byte byte2 = 64;
final int i = 256 / byte2 + 2;
float f = 16F;
for (int j = -byte2 * i; j <= byte2 * i; j += byte2)
{
for (int l = -byte2 * i; l <= byte2 * i; l += byte2)
{
tessellator.startDrawingQuads();
tessellator.addVertex(j + 0, f, l + 0);
tessellator.addVertex(j + byte2, f, l + 0);
tessellator.addVertex(j + byte2, f, l + byte2);
tessellator.addVertex(j + 0, f, l + byte2);
tessellator.draw();
}
}
GL11.glEndList();
GL11.glNewList(this.glSkyList2, GL11.GL_COMPILE);
f = -16F;
tessellator.startDrawingQuads();
for (int k = -byte2 * i; k <= byte2 * i; k += byte2)
{
for (int i1 = -byte2 * i; i1 <= byte2 * i; i1 += byte2)
{
tessellator.addVertex(k + byte2, f, i1 + 0);
tessellator.addVertex(k + 0, f, i1 + 0);
tessellator.addVertex(k + 0, f, i1 + byte2);
tessellator.addVertex(k + byte2, f, i1 + byte2);
}
}
tessellator.draw();
GL11.glEndList();
}
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
RenderHelper.enableStandardItemLighting();
Vec3 vec3 = world.getSkyColor(mc.renderViewEntity, partialTicks);
float f1 = (float) vec3.xCoord;
float f2 = (float) vec3.yCoord;
float f3 = (float) vec3.zCoord;
float f6;
if (mc.gameSettings.anaglyph)
{
float f4 = (f1 * 30.0F + f2 * 59.0F + f3 * 11.0F) / 100.0F;
float f5 = (f1 * 30.0F + f2 * 70.0F) / 100.0F;
f6 = (f1 * 30.0F + f3 * 70.0F) / 100.0F;
f1 = f4;
f2 = f5;
f3 = f6;
}
GL11.glColor3f(f1, f2, f3);
Tessellator tessellator1 = Tessellator.instance;
GL11.glDepthMask(false);
GL11.glEnable(GL11.GL_FOG);
GL11.glColor3f(f1, f2, f3);
GL11.glCallList(this.glSkyList);
GL11.glDisable(GL11.GL_FOG);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
RenderHelper.disableStandardItemLighting();
float f7;
float f8;
float f9;
float f10;
float f18 = world.getStarBrightness(partialTicks);
if (f18 > 0.0F)
{
GL11.glColor4f(f18, f18, f18, f18);
GL11.glCallList(this.starList);
}
float[] afloat = new float[4];
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glPushMatrix();
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(world.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F);
afloat[0] = 255 / 255.0F;
afloat[1] = 194 / 255.0F;
afloat[2] = 180 / 255.0F;
afloat[3] = 0.3F;
f6 = afloat[0];
f7 = afloat[1];
f8 = afloat[2];
float f11;
if (mc.gameSettings.anaglyph)
{
f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F;
f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F;
f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F;
f6 = f9;
f7 = f10;
f8 = f11;
}
f18 = 1.0F - f18;
GL11.glPopMatrix();
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_TEXTURE_2D);
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
GL11.glPushMatrix();
f7 = 0.0F;
f8 = 0.0F;
f9 = 0.0F;
GL11.glTranslatef(f7, f8, f9);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
// rotates the sky by the celestial angle on the x axis
// this seems to mean that the x-axis is the rotational axis of the planet
// does the sun move from -z to z or the other way round?
GL11.glRotatef(world.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F);
// so at this point, I'm where the sun is supposed to be. This is where I have to start.
// Render system
renderSystem(partialTicks, world, tessellator1, mc);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_FOG);
GL11.glPopMatrix();
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor3f(0.0F, 0.0F, 0.0F);
double d0 = mc.thePlayer.getPosition(partialTicks).yCoord - world.getHorizon();
if (d0 < 0.0D)
{
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, 12.0F, 0.0F);
GL11.glCallList(this.glSkyList2);
GL11.glPopMatrix();
f8 = 1.0F;
f9 = -((float) (d0 + 65.0D));
f10 = -f8;
tessellator1.startDrawingQuads();
tessellator1.setColorRGBA_I(0, 255);
tessellator1.addVertex(-f8, f9, f8);
tessellator1.addVertex(f8, f9, f8);
tessellator1.addVertex(f8, f10, f8);
tessellator1.addVertex(-f8, f10, f8);
tessellator1.addVertex(-f8, f10, -f8);
tessellator1.addVertex(f8, f10, -f8);
tessellator1.addVertex(f8, f9, -f8);
tessellator1.addVertex(-f8, f9, -f8);
tessellator1.addVertex(f8, f10, -f8);
tessellator1.addVertex(f8, f10, f8);
tessellator1.addVertex(f8, f9, f8);
tessellator1.addVertex(f8, f9, -f8);
tessellator1.addVertex(-f8, f9, -f8);
tessellator1.addVertex(-f8, f9, f8);
tessellator1.addVertex(-f8, f10, f8);
tessellator1.addVertex(-f8, f10, -f8);
tessellator1.addVertex(-f8, f10, -f8);
tessellator1.addVertex(-f8, f10, f8);
tessellator1.addVertex(f8, f10, f8);
tessellator1.addVertex(f8, f10, -f8);
tessellator1.draw();
}
if (world.provider.isSkyColored())
{
GL11.glColor3f(f1 * 0.2F + 0.04F, f2 * 0.2F + 0.04F, f3 * 0.6F + 0.1F);
}
else
{
GL11.glColor3f(f1, f2, f3);
}
GL11.glPushMatrix();
GL11.glTranslatef(0.0F, -((float) (d0 - 16.0D)), 0.0F);
GL11.glCallList(this.glSkyList2);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDepthMask(true);
}
protected void renderSunAura(Tessellator tessellator1, Vector3f color, float size, float brightness) {
// Vector3f basecolor = new Vector3f(0.94890916F, 0.72191525F, 0.6698182F);
GL11.glShadeModel(GL11.GL_SMOOTH);
// Color4f color1 = new Color4f(0.5, 0, 0.5, arg3)
// f18 = sunbrightness
/*tessellator1.setColorRGBA_F(f6 * f18, f7 * f18, f8 * f18, afloat[3] * 2 / f18);
tessellator1.addVertex(0.0D, 100.0D, 0.0D);
byte b0 = 16;
tessellator1.setColorRGBA_F(afloat[0] * f18, afloat[1] * f18, afloat[2] * f18, 0.0F);*/
// small sun aura START
double y = 80.0D;
tessellator1.startDrawing(GL11.GL_TRIANGLE_FAN);
tessellator1.setColorRGBA_F(color.x, color.y, color.z, 0.8F / brightness);
tessellator1.addVertex(0.0D, y, 0.0D);
byte b0 = 16;
tessellator1.setColorRGBA_F(color.x, color.y, color.z, 0.0F);
// Render sun aura
tessellator1.addVertex(-size, y, -size);
tessellator1.addVertex(0, y, (double) -size * 1.5F);
tessellator1.addVertex(size, y, -size);
tessellator1.addVertex((double) size * 1.5F, y, 0);
tessellator1.addVertex(size, y, size);
tessellator1.addVertex(0, y, (double) size * 1.5F);
tessellator1.addVertex(-size, y, size);
tessellator1.addVertex((double) -size * 1.5F, y, 0);
tessellator1.addVertex(-size, y, -size);
tessellator1.draw();
}
protected void renderSystem(float partialTicks, WorldClient world, Tessellator tess, Minecraft mc) {
// assume we are at the position of the sun
GL11.glPushMatrix();
// try to rotate it
GL11.glRotatef(25, 0, 1.0F, 0);
GL11.glPushMatrix();
// sun aura
renderSunAura(tess, new Vector3f(0.7F, 0.2F, 0.0F), this.sunSize*5, this.sunSize);
// render the sun first
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(0.0F, 0.0F, 0.0F, 1.0F);
//Some blanking to conceal the stars
float f10 = this.sunSize / 3.5F;
tess.startDrawingQuads();
tess.addVertex(-f10, 99.9D, -f10);
tess.addVertex(f10, 99.9D, -f10);
tess.addVertex(f10, 99.9D, f10);
tess.addVertex(-f10, 99.9D, f10);
tess.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
f10 = this.sunSize;
mc.renderEngine.bindTexture(this.curSystem.getMainStar().getBodyIcon());
tess.startDrawingQuads();
tess.addVertexWithUV(-f10, 100.0D, -f10, 0.0D, 0.0D);
tess.addVertexWithUV(f10, 100.0D, -f10, 1.0D, 0.0D);
tess.addVertexWithUV(f10, 100.0D, f10, 1.0D, 1.0D);
tess.addVertexWithUV(-f10, 100.0D, f10, 0.0D, 1.0D);
tess.draw();
GL11.glPopMatrix();
GL11.glDisable(GL11.GL_TEXTURE_2D);
//renderHalfArch(tess);
// protected void renderSunAura(Tessellator tessellator1, Vector3f color, float size, float brightness) {
long curWorldTime = world.getWorldTime();
// get my own angle
double curBodyOrbitalAngle = getOrbitalAngle(curBodyPlanet.getRelativeDistanceFromCenter().unScaledDistance, curBodyPlanet.getPhaseShift(), curWorldTime , partialTicks, yearFactor);
// now render planets. wait wat. you can't just iterate through all the planets in a system?!
/*
for (Planet planet : GalaxyRegistry.getRegisteredPlanets().values()) {
// oh well I hope this doesn't kill the performance
if(planet.getParentSolarSystem() != curSystem) {
continue;
}
float dist = planet.getRelativeDistanceFromCenter().unScaledDistance;
// try do my own
if(dist == curBodyDistance) {
// so seems like the skybox is some 622 across
//i++;
continue;
}
if(planet.equals(AmunRa.instance.asteroidBeltMehen)) {
continue; // for now don't render it
}
// orbital angle of the planet
double curOrbitalAngle = getOrbitalAngle(planet.getRelativeOrbitTime(), planet.getPhaseShift(), curWorldTime, partialTicks, yearFactor);
// but I need it relative to curOrbitalAngle, or actually to curOrbitalAngle rotated by 180,
// just because that's how I calculated that stuff
curOrbitalAngle -= (Math.PI*2-curBodyOrbitalAngle);
// angle between connection line curBody<-->sun and planet<-->sun
double innerAngle = Math.PI-curOrbitalAngle;
// distance between curBody<-->planet, also needed for scaling
double distanceToPlanet = getDistanceToBody(innerAngle, dist);
double projectedAngle = projectAngle(innerAngle, dist, distanceToPlanet, curBodyDistance);
renderPlanetByAngle(tess, planet, (float)projectedAngle, 0, 1.0F / (float)distanceToPlanet);
}*/
GL11.glPopMatrix();
// now do moons
GL11.glPushMatrix();
// try to rotate it
GL11.glRotatef(-19, 0, 1.0F, 0);
if(this.curBody instanceof Planet) {
// oh my...
double curOrbitalAngle;
for (Moon moon : GalaxyRegistry.getRegisteredMoons().values()) {
if(!moon.getParentPlanet().equals(curBody)) {
continue;
}
curOrbitalAngle = getOrbitalAngle(moon.getRelativeOrbitTime()/100, moon.getPhaseShift(), curWorldTime, partialTicks, moonFactor);
// not projecting the angle here
renderPlanetByAngle(tess, moon, (float) curOrbitalAngle, 0, 20/moon.getRelativeDistanceFromCenter().unScaledDistance);
}
} else {
double distanceToParent = curBody.getRelativeDistanceFromCenter().unScaledDistance;
double curOrbitalAngle = getOrbitalAngle(curBody.getRelativeOrbitTime()/100, curBody.getPhaseShift(), curWorldTime, partialTicks, moonFactor);
// render my parent body
// 180-my angle around my parent, should be it's angle in my sky
double mainBodyOrbitalAngle = Math.PI-curOrbitalAngle;
renderPlanetByAngle(tess, curBodyPlanet, (float) mainBodyOrbitalAngle, 0, (float) (20/distanceToParent));
// now do my sibling moons
for (Moon moon : GalaxyRegistry.getRegisteredMoons().values()) {
if(!moon.getParentPlanet().equals(curBodyPlanet) || moon.equals(curBody)) {
continue;
}
// this is what I do for planets
float dist = moon.getRelativeDistanceFromCenter().unScaledDistance;
/*if(dist < distanceToParent) {
continue; // DEBUG
}*/
// orbital angle of the moon
double moonOrbitalAngle = getOrbitalAngle(moon.getRelativeOrbitTime(), moon.getPhaseShift(), curWorldTime, partialTicks, moonFactor);
// but I need it relative to curOrbitalAngle, or actually to curOrbitalAngle rotated by 180,
// just because that's how I calculated that stuff
moonOrbitalAngle -= (Math.PI*2-curOrbitalAngle);
// angle between connection line curBody<-->parent and moon<-->parent
double innerAngle = Math.PI-moonOrbitalAngle;
// distance between curBody<-->moon, also needed for scaling
double distanceToPlanet = getDistanceToBody(innerAngle, dist);
double projectedAngle = projectAngle(innerAngle, dist, distanceToPlanet, distanceToParent);
renderPlanetByAngle(tess, moon, (float)projectedAngle, 0, 10.0F / (float)distanceToPlanet);
}
}
GL11.glPopMatrix();
}
protected double getOrbitalAngle(double relOrbitTime, double phaseShift, long worldTime, double partialTicks, double orbitFactor) {
double curYearLength = relOrbitTime * orbitFactor;
int j = (int)(worldTime % (long)curYearLength);
double orbitPos = (j + partialTicks) / curYearLength - 0.25F;
return orbitPos*2*Math.PI + phaseShift;
}
private double getDistanceToBody(double innerAngle, double otherBodyDistance) {
return Math.sqrt(
Math.pow(otherBodyDistance, 2) +
Math.pow(curBodyDistance, 2) -
2 * otherBodyDistance * curBodyDistance * Math.cos(innerAngle));
}
/**
* Should convert an angle around the sun into an angle around this body
*
*
* @param innerAngle in radians, the angle between curBody<-->sun and otherBody<-->sun
* @param otherBodyDistance other body's orbital radius
* @param distFromThisToOtherBody
* @return
*/
private double projectAngle(double innerAngle, double otherBodyDistance, double distFromThisToOtherBody, double curBodyDistance) {
// omg now do dark mathemagic
/*if(angleAroundSun < 0) {
angleAroundSun = Math.PI*2+angleAroundSun;
}*/
//double beta = Math.PI-angleAroundSun;
// innerAngle = beta
double sinBeta = Math.sin(innerAngle);
// distFromThisToOtherBody = x
// curBodyDistance = d
// otherBodyDistance = r
// gamma
double angleAroundCurBody = Math.asin(
otherBodyDistance * sinBeta / distFromThisToOtherBody
);
if ( curBodyDistance > otherBodyDistance) {
return angleAroundCurBody;
}
// now fix this angle...
// for this, I need the third angle, too
double delta = Math.asin(sinBeta / distFromThisToOtherBody * curBodyDistance);
double angleSum = innerAngle+delta+angleAroundCurBody;
double otherAngleSum =innerAngle+delta+(Math.PI-angleAroundCurBody);
if(Math.abs(Math.abs(angleSum)/Math.PI - 1) < 0.001) {
// aka angleSUm = 180 or -180
return angleAroundCurBody;
} else {
return Math.PI-angleAroundCurBody;
}
}
private void renderPlanetByAngle(Tessellator tessellator1, CelestialBody body, float angle, float zIndex, float scale) {
// we start at the sun
GL11.glPushMatrix();
//GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F); // change this for your colour
//GL11.glLineWidth(2.0F);
// rotate on x
GL11.glRotatef((float) (angle/Math.PI*180), 1.0F, 0.0F, 0.0F);
if(body.equals(AmunRa.instance.starAmun)) {
renderSunAura(tessellator1, new Vector3f(0.0F, 0.2F, 0.7F), scale*5, scale);
}
//renderPlanet(tessellator1,texture,0,offset);
// BEGIN
GL11.glDisable(GL11.GL_BLEND);
GL11.glShadeModel(GL11.GL_SMOOTH);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F);
FMLClientHandler.instance().getClient().renderEngine.bindTexture(body.getBodyIcon());
tessellator1.startDrawingQuads();
// final float scale = 2;
// go to the position
GL11.glTranslatef(0, 95.0F+zIndex, 0);
tessellator1.addVertexWithUV(-scale, 0, -scale, 0, 0);
tessellator1.addVertexWithUV(scale, 0, -scale, 1, 0);
tessellator1.addVertexWithUV(scale, 0, scale, 1, 1);
tessellator1.addVertexWithUV(-scale, 0, scale, 0, 1);
tessellator1.draw();
GL11.glDisable(GL11.GL_TEXTURE_2D);
// END
GL11.glEnable(GL11.GL_BLEND);
// TODO figure this out: http://wiki.delphigl.com/index.php/glBlendFunc
GL11.glPopMatrix();
}
/*private void renderOrbit(Tessellator tessellator1 , float scale) {
// GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1F); // change this for your colour
GL11.glLineWidth(2.0F);
tessellator1.startDrawing(GL11.GL_LINE_LOOP);
float x = -scale;
float y = scale;
float temp;
final float theta = (float) (2 * Math.PI / 90);
final float cos = (float) Math.cos(theta);
final float sin = (float) Math.sin(theta);
for (int i = 0; i < 90; i++)
{
tessellator1.addVertex(x, -90F, -y);
temp = x;
x = cos * x - sin * y;
y = sin * temp + cos * y;
}
tessellator1.draw();
}*/
private void renderStars()
{
final Random rand = new Random(10842L);
final Tessellator var2 = Tessellator.instance;
var2.startDrawingQuads();
for (int starIndex = 0; starIndex < (6000); ++starIndex)
{
double var4 = rand.nextFloat() * 2.0F - 1.0F;
double var6 = rand.nextFloat() * 2.0F - 1.0F;
double var8 = rand.nextFloat() * 2.0F - 1.0F;
final double var10 = 0.15F + rand.nextFloat() * 0.1F;
double var12 = var4 * var4 + var6 * var6 + var8 * var8;
if (var12 < 1.0D && var12 > 0.01D)
{
var12 = 1.0D / Math.sqrt(var12);
var4 *= var12;
var6 *= var12;
var8 *= var12;
final double var14 = var4 * 100.0D;//(ConfigManagerCore.moreStars ? rand.nextDouble() * 150D + 130D : 100.0D);
final double var16 = var6 * 100.0D;//(ConfigManagerCore.moreStars ? rand.nextDouble() * 150D + 130D : 100.0D);
final double var18 = var8 * 100.0D;//(ConfigManagerCore.moreStars ? rand.nextDouble() * 150D + 130D : 100.0D);
final double var20 = Math.atan2(var4, var8);
final double var22 = Math.sin(var20);
final double var24 = Math.cos(var20);
final double var26 = Math.atan2(Math.sqrt(var4 * var4 + var8 * var8), var6);
final double var28 = Math.sin(var26);
final double var30 = Math.cos(var26);
final double var32 = rand.nextDouble() * Math.PI * 2.0D;
final double var34 = Math.sin(var32);
final double var36 = Math.cos(var32);
for (int var38 = 0; var38 < 4; ++var38)
{
final double var39 = 0.0D;
final double var41 = ((var38 & 2) - 1) * var10;
final double var43 = ((var38 + 1 & 2) - 1) * var10;
final double var47 = var41 * var36 - var43 * var34;
final double var49 = var43 * var36 + var41 * var34;
final double var53 = var47 * var28 + var39 * var30;
final double var55 = var39 * var28 - var47 * var30;
final double var57 = var55 * var22 - var49 * var24;
final double var61 = var49 * var22 + var55 * var24;
var2.addVertex(var14 + var57, var16 + var53, var18 + var61);
}
}
}
var2.draw();
}
private Vec3 getCustomSkyColor()
{
return Vec3.createVectorHelper(0.26796875D, 0.1796875D, 0.0D);
}
public float getSkyBrightness(float par1)
{
final float var2 = FMLClientHandler.instance().getClient().theWorld.getCelestialAngle(par1);
float var3 = 1.0F - (MathHelper.sin(var2 * (float) Math.PI * 2.0F) * 2.0F + 0.25F);
if (var3 < 0.0F)
{
var3 = 0.0F;
}
if (var3 > 1.0F)
{
var3 = 1.0F;
}
return var3 * var3 * 1F;
}
}
| commented planets back in
| src/main/java/de/katzenpapst/amunra/world/SkyProviderDynamic.java | commented planets back in | <ide><path>rc/main/java/de/katzenpapst/amunra/world/SkyProviderDynamic.java
<ide>
<ide>
<ide> // now render planets. wait wat. you can't just iterate through all the planets in a system?!
<del> /*
<add>
<ide> for (Planet planet : GalaxyRegistry.getRegisteredPlanets().values()) {
<ide> // oh well I hope this doesn't kill the performance
<ide> if(planet.getParentSolarSystem() != curSystem) {
<ide>
<ide> renderPlanetByAngle(tess, planet, (float)projectedAngle, 0, 1.0F / (float)distanceToPlanet);
<ide>
<del> }*/
<add> }
<ide>
<ide> GL11.glPopMatrix();
<ide> |
|
Java | apache-2.0 | 1031081fa6b00df9fa6fa1d274afe54f92cb9454 | 0 | google/thread-weaver | /*
* Copyright 2009 Weaver authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.testing.instrumentation;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
/**
* A custom ClassLoader that performs byte-code instrumentation on all loaded
* classes.
*
* @author [email protected] (Alasdair Mackintosh)
*/
public final class InstrumentedClassLoader extends ClassLoader {
/** Initial size of buffer used to read class data. */
/* Note: should be enough for most classes, and is not a hard limit. */
private static final int BUF_SIZE = 4096;
private final Instrumenter instrumenter;
/**
* List of class prefixes that this loader doesn't load, but delegates to the
* parent.
*/
/* Note - we run into various obscure errors with on-the-fly classes if we try
* to load sun packages, so delegate these to the parent class loader. Also
* delegate java and javax packages, on the assumption that we don't want to
* instrument these.
*
* We also exclude classes from the JUnit and EasyMock test frameworks, from
* Objenesis, and from org.w3c.dom, on the grounds that we are not likely to
* test these directly.
*
* TODO(alasdair): determine if we want to provide an interface that lets
* callers specify this.
*/
private static final List<String> excludedClassPrefixes =
Arrays.asList("java.", "javax.", "sun.", "net.sf.cglib", "junit.",
"org.junit.", "org.objenesis.", "org.easymock.", "org.w3c.dom");
/**
* Creates a new instrumented class loader using the given {@link
* Instrumenter}. All classes loaded by this loader will have their byte-code
* passed through the {@link Instrumenter#instrument} method.
*
* @param instrumenter the instrumenter
*/
public InstrumentedClassLoader(Instrumenter instrumenter){
super(InstrumentedClassLoader.class.getClassLoader());
if (instrumenter == null) {
throw new IllegalArgumentException("instrumenter cannot be null");
}
this.instrumenter = instrumenter;
}
/**
* Returns true if this class should be loaded by this classloader. If not,
* then loading delegates to the parent.
*/
private boolean shouldLoad(String className) {
for (String excluded : excludedClassPrefixes) {
if (className.startsWith(excluded)) {
return false;
}
}
return true;
}
/**
* Loads a class, and throws an IllegalArgumentException if the class cannot
* be loaded. Useful for classes which we expect to be able to find, e.g. for
* currently loaded classes that are being reloaded by this
* InstrumentedClassLoader.
*
* @param name the full name of the class
*
* @return the loaded class
*/
public Class<?> getExpectedClass(String name) {
try {
return findClass(name);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot find " + e);
}
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// First, check if the class has already been loaded. If not, load it
// ourselves or delegate to the parent.
Class<?> result = findLoadedClass(name);
if (result == null) {
if (shouldLoad(name)) {
result = findClass(name);
} else {
return super.loadClass(name, resolve);
}
}
if (resolve) {
resolveClass(result);
}
return result;
}
@Override
public Class<?> findClass(String className) throws ClassNotFoundException {
try {
// Create a package for this class, unless it's in the default package.
int dotpos = className.lastIndexOf('.');
if (dotpos != -1) {
String pkgname = className.substring(0, dotpos);
if (getPackage(pkgname) == null) {
definePackage(pkgname, null, null, null, null, null, null, null);
}
}
String resourceName = className.replace('.', '/') + ".class";
InputStream input = getSystemResourceAsStream(resourceName);
byte[] classData = instrumenter.instrument(className, loadClassData(input));
Class<?> result = defineClass(className, classData, 0, classData.length, null);
return result;
} catch (IOException e) {
throw new ClassNotFoundException("Cannot load " + className, e);
}
}
/**
* Load class data from a given input stream.
*/
private byte[] loadClassData(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream(BUF_SIZE);
byte[] buffer = new byte[BUF_SIZE];
int readCount;
while ((readCount = input.read(buffer, 0, BUF_SIZE)) >= 0) {
output.write(buffer, 0, readCount);
}
return output.toByteArray();
}
}
| main/com/google/testing/instrumentation/InstrumentedClassLoader.java | /*
* Copyright 2009 Weaver authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.testing.instrumentation;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
/**
* A custom ClassLoader that performs byte-code instrumentation on all loaded
* classes.
*
* @author [email protected] (Alasdair Mackintosh)
*/
public final class InstrumentedClassLoader extends ClassLoader {
/** Initial size of buffer used to read class data. */
/* Note: should be enough for most classes, and is not a hard limit. */
private static final int BUF_SIZE = 4096;
private final Instrumenter instrumenter;
/**
* List of class prefixes that this loader doesn't load, but delegates to the
* parent.
*/
/* Note - we run into various obscure errors with on-the-fly classes if we try
* to load sun packages, so delegate these to the parent class loader. Also
* delegate java and javax packages, on the assumption that we don't want to
* instrument these.
*
* We also exclude classes from the JUnit and EasyMock test frameworks, from
* Objenesis, and from org.w3c.dom, on the grounds that we are not likely to
* test these directly.
*
* TODO(alasdair): determine if we want to provide an interface that lets
* callers specify this.
*/
private static final List<String> excludedClassPrefixes =
Arrays.asList("java.", "javax.", "sun.", "net.sf.cglib", "junit.",
"org.junit.", "org.objenesis.", "org.easymock.", "org.w3c.dom");
/**
* Creates a new instrumented class loader using the given {@link
* Instrumenter}. All classes loaded by this loader will have their byte-code
* passed through the {@link Instrumenter#instrument} method.
*
* @param instrumenter the instrumenter
*/
public InstrumentedClassLoader(Instrumenter instrumenter){
super(InstrumentedClassLoader.class.getClassLoader());
if (instrumenter == null) {
throw new IllegalArgumentException("instrumenter cannot be null");
}
this.instrumenter = instrumenter;
}
/**
* Returns true if this class should be loaded by this classloader. If not,
* then loading delegates to the parent.
*/
private boolean shouldLoad(String className) {
for (String excluded : excludedClassPrefixes) {
if (className.startsWith(excluded)) {
return false;
}
}
return true;
}
/**
* Loads a class, and throws an IllegalArgumentException if the class cannot
* be loaded. Useful for classes which we expect to be able to find, e.g. for
* currently loaded classes that are being reloaded by this
* InstrumentedClassLoader.
*
* @param name the full name of the class
*
* @return the loaded class
*/
public Class<?> getExpectedClass(String name) {
try {
return findClass(name);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Cannot find " + e);
}
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// First, check if the class has already been loaded. If not, load it
// ourselves or delegate to the parent.
Class<?> result = findLoadedClass(name);
if (result == null) {
if (shouldLoad(name)) {
result = findClass(name);
} else {
return super.loadClass(name, resolve);
}
}
if (resolve) {
resolveClass(result);
}
return result;
}
@Override
public Class<?> findClass(String className) throws ClassNotFoundException {
try {
// Create a package for this class, unless it's in the default package.
int dotpos = className.lastIndexOf('.');
if (dotpos != -1) {
String pkgname = className.substring(0, dotpos);
if (getPackage(pkgname) == null) {
definePackage(pkgname, null, null, null, null, null, null, null);
}
}
String resourceName = className.replace('.', File.separatorChar) + ".class";
InputStream input = getSystemResourceAsStream(resourceName);
byte[] classData = instrumenter.instrument(className, loadClassData(input));
Class<?> result = defineClass(className, classData, 0, classData.length, null);
return result;
} catch (IOException e) {
throw new ClassNotFoundException("Cannot load " + className, e);
}
}
/**
* Load class data from a given input stream.
*/
private byte[] loadClassData(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream(BUF_SIZE);
byte[] buffer = new byte[BUF_SIZE];
int readCount;
while ((readCount = input.read(buffer, 0, BUF_SIZE)) >= 0) {
output.write(buffer, 0, readCount);
}
return output.toByteArray();
}
}
| Use '/' character instead of File.separatorChar()
| main/com/google/testing/instrumentation/InstrumentedClassLoader.java | Use '/' character instead of File.separatorChar() | <ide><path>ain/com/google/testing/instrumentation/InstrumentedClassLoader.java
<ide> definePackage(pkgname, null, null, null, null, null, null, null);
<ide> }
<ide> }
<del> String resourceName = className.replace('.', File.separatorChar) + ".class";
<add> String resourceName = className.replace('.', '/') + ".class";
<ide> InputStream input = getSystemResourceAsStream(resourceName);
<ide> byte[] classData = instrumenter.instrument(className, loadClassData(input));
<ide> Class<?> result = defineClass(className, classData, 0, classData.length, null); |
|
Java | apache-2.0 | 4732a8e32802a25591cc54d8bcbf77a6c73a4890 | 0 | juanchel/BackendCI | package edu.cmu.sv.ws.ssnoc.data.dao;
import edu.cmu.sv.ws.ssnoc.common.utils.ConverterUtils;
import edu.cmu.sv.ws.ssnoc.data.util.DBUtils;
import edu.cmu.sv.ws.ssnoc.dto.Message;
import edu.cmu.sv.ws.ssnoc.dto.User;
import edu.cmu.sv.ws.ssnoc.rest.MessagesService;
import edu.cmu.sv.ws.ssnoc.rest.UserService;
import junit.framework.TestCase;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MessageDAOImplTest extends TestCase {
public void setUp() throws Exception {
super.setUp();
File file = new File(System.getProperty("user.home") + "/h2db.mv.db");
File file2 = new File(System.getProperty("user.home") + "/h2db.mv.db.backup");
if (!file2.exists()) {
file.renameTo(file2);
} else {
file2.delete();
file.renameTo(file2);
}
}
public void tearDown() throws Exception {
File file = new File(System.getProperty("user.home") + "/h2db.mv.db");
File file2 = new File(System.getProperty("user.home") + "/h2db.mv.db.backup");
file.delete();
file2.renameTo(file);
}
public void testCanSavePubicMessage() throws Exception {
DBUtils.initializeDatabase();
UserService us = new UserService();
User u = new User();
u.setUserName("demo");
u.setPassword("asdf");
us.addUser(u);
Message message = new Message();
message.setContent("test");
message.setAuthor("demo");
message.setPublic(true);
message.setTimestamp("1970-01-01 12:00:00");
DAOFactory.getInstance().getMessageDAO().save(ConverterUtils.convert(message));
MessagesService mss = new MessagesService();
List<Message> ret = mss.getWallPosts();
List<String> contents = new ArrayList<String>();
for (Message m : ret) {
contents.add(m.getContent());
}
boolean passed = false;
for (String content : contents) {
if (content.equals("test")) {
passed = true;
break;
}
}
assertTrue(passed);
}
public void testCanSavePM() throws Exception {
DBUtils.initializeDatabase();
UserService us = new UserService();
User u = new User();
u.setUserName("jc");
u.setPassword("asdf");
User u2 = new User();
u2.setUserName("vinay");
u2.setPassword("asdf");
us.addUser(u);
Message message = new Message();
message.setContent("test");
message.setAuthor("jc");
message.setTarget("vinay");
message.setPublic(false);
message.setTimestamp("1970-01-01 12:00:00");
DAOFactory.getInstance().getMessageDAO().save(ConverterUtils.convert(message));
MessagesService mss = new MessagesService();
List<Message> ret = mss.getPMs("jc", "vinay");
List<String> contents = new ArrayList<String>();
for (Message m : ret) {
contents.add(m.getContent());
}
boolean passed = false;
for (String content : contents) {
if (content.equals("test")) {
passed = true;
break;
}
}
assertTrue(passed);
}
} | src/it/java/edu/cmu/sv/ws/ssnoc/data/dao/MessageDAOImplTest.java | package edu.cmu.sv.ws.ssnoc.data.dao;
import edu.cmu.sv.ws.ssnoc.common.utils.ConverterUtils;
import edu.cmu.sv.ws.ssnoc.data.util.DBUtils;
import edu.cmu.sv.ws.ssnoc.dto.Message;
import edu.cmu.sv.ws.ssnoc.dto.User;
import edu.cmu.sv.ws.ssnoc.rest.MessagesService;
import edu.cmu.sv.ws.ssnoc.rest.UserService;
import junit.framework.TestCase;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MessageDAOImplTest extends TestCase {
public void setUp() throws Exception {
super.setUp();
File file = new File(System.getProperty("user.home") + "/h2db.mv.db");
File file2 = new File(System.getProperty("user.home") + "/h2db.mv.db.backup");
if (!file2.exists()) {
file.renameTo(file2);
} else {
file2.delete();
file.renameTo(file2);
}
}
public void tearDown() throws Exception {
File file = new File(System.getProperty("user.home") + "/h2db.mv.db");
File file2 = new File(System.getProperty("user.home") + "/h2db.mv.db.backup");
file.delete();
file2.renameTo(file);
}
public void testSavePublic() throws Exception {
DBUtils.initializeDatabase();
UserService us = new UserService();
User u = new User();
u.setUserName("demo");
u.setPassword("asdf");
us.addUser(u);
Message message = new Message();
message.setContent("test");
message.setAuthor("demo");
message.setPublic(true);
message.setTimestamp("1970-01-01 12:00:00");
DAOFactory.getInstance().getMessageDAO().save(ConverterUtils.convert(message));
MessagesService mss = new MessagesService();
List<Message> ret = mss.getWallPosts();
List<String> contents = new ArrayList<String>();
for (Message m : ret) {
contents.add(m.getContent());
}
boolean passed = false;
for (String content : contents) {
if (content.equals("test")) {
passed = true;
break;
}
}
assertTrue(passed);
}
} | added test case for pms
| src/it/java/edu/cmu/sv/ws/ssnoc/data/dao/MessageDAOImplTest.java | added test case for pms | <ide><path>rc/it/java/edu/cmu/sv/ws/ssnoc/data/dao/MessageDAOImplTest.java
<ide> file2.renameTo(file);
<ide> }
<ide>
<del> public void testSavePublic() throws Exception {
<add> public void testCanSavePubicMessage() throws Exception {
<ide> DBUtils.initializeDatabase();
<ide>
<ide> UserService us = new UserService();
<ide> assertTrue(passed);
<ide> }
<ide>
<add> public void testCanSavePM() throws Exception {
<add> DBUtils.initializeDatabase();
<add>
<add> UserService us = new UserService();
<add> User u = new User();
<add> u.setUserName("jc");
<add> u.setPassword("asdf");
<add> User u2 = new User();
<add> u2.setUserName("vinay");
<add> u2.setPassword("asdf");
<add> us.addUser(u);
<add>
<add> Message message = new Message();
<add> message.setContent("test");
<add> message.setAuthor("jc");
<add> message.setTarget("vinay");
<add> message.setPublic(false);
<add> message.setTimestamp("1970-01-01 12:00:00");
<add>
<add> DAOFactory.getInstance().getMessageDAO().save(ConverterUtils.convert(message));
<add>
<add> MessagesService mss = new MessagesService();
<add> List<Message> ret = mss.getPMs("jc", "vinay");
<add> List<String> contents = new ArrayList<String>();
<add> for (Message m : ret) {
<add> contents.add(m.getContent());
<add> }
<add> boolean passed = false;
<add> for (String content : contents) {
<add> if (content.equals("test")) {
<add> passed = true;
<add> break;
<add> }
<add> }
<add> assertTrue(passed);
<add> }
<add>
<ide> } |
|
JavaScript | apache-2.0 | f8b4b53aada53dae3dfe7b7ff27cf3af6ffc32c0 | 0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var ColumnChart = require( '@stdlib/plot/sparklines/unicode/column' );
var LineChart = require( '@stdlib/plot/sparklines/unicode/line' );
var TristateChart = require( '@stdlib/plot/sparklines/unicode/tristate' );
var UpDownChart = require( '@stdlib/plot/sparklines/unicode/up-down' );
var WinLossChart = require( '@stdlib/plot/sparklines/unicode/win-loss' );
// VARIABLES //
var debug = logger( 'sparkline:unicode:render' );
// MAIN //
/**
* Renders a chart.
*
* @private
* @returns {string} rendered chart
*/
function render() {
/* eslint-disable no-invalid-this */
var out;
debug( 'Rendering...' );
switch ( this._type ) { // eslint-disable-line default-case
case 'column':
out = ColumnChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'line':
out = LineChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'tristate':
out = TristateChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'up-down':
out = UpDownChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'win-loss':
out = WinLossChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
}
this.emit( 'render', out );
return out;
}
// EXPORTS //
module.exports = render;
| lib/node_modules/@stdlib/plot/sparklines/unicode/lib/render.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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.
*/
'use strict';
// MODULES //
var logger = require( 'debug' );
var ColumnChart = require( '@stdlib/plot/sparklines/unicode/column' );
var LineChart = require( '@stdlib/plot/sparklines/unicode/line' );
var TristateChart = require( '@stdlib/plot/sparklines/unicode/tristate' );
var UpDownChart = require( '@stdlib/plot/sparklines/unicode/up-down' );
var WinLossChart = require( '@stdlib/plot/sparklines/unicode/win-loss' );
// VARIABLES //
var debug = logger( 'sparkline:unicode:render' );
// MAIN //
/**
* Renders a chart.
*
* @private
* @returns {string} rendered chart
*/
function render() {
/* eslint-disable no-invalid-this */
var out;
debug( 'Rendering...' );
switch ( this._type ) { // eslint-disable-line default-case
case 'column':
out = ColumnChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'line':
out = LineChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'tristate':
out = TristateChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'up-down':
out = UpDownChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
case 'WinLoss':
out = WinLossChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
break;
}
this.emit( 'render', out );
return out;
}
// EXPORTS //
module.exports = render;
| Fix chart type
| lib/node_modules/@stdlib/plot/sparklines/unicode/lib/render.js | Fix chart type | <ide><path>ib/node_modules/@stdlib/plot/sparklines/unicode/lib/render.js
<ide> case 'up-down':
<ide> out = UpDownChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
<ide> break;
<del> case 'WinLoss':
<add> case 'win-loss':
<ide> out = WinLossChart.prototype._render.call( this ); // eslint-disable-line no-underscore-dangle
<ide> break;
<ide> } |
|
Java | apache-2.0 | cb63778369a4f86861e23b0c78aeee2d808a8e57 | 0 | SachinMali/acs-aem-commons,dfoerderreuther/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,bstopp/acs-aem-commons,dfoerderreuther/acs-aem-commons,bstopp/acs-aem-commons,bstopp/acs-aem-commons,SachinMali/acs-aem-commons,SachinMali/acs-aem-commons,SachinMali/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,dfoerderreuther/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,dfoerderreuther/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,bstopp/acs-aem-commons | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2017 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.dispatcher.impl;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import static junitx.framework.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class PermissionSensitiveCacheServletTest {
public static final String TEST_PAGE = "/content/test.html";
@Rule
public SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
@InjectMocks
private PermissionSensitiveCacheServlet servlet = new PermissionSensitiveCacheServlet();
MockSlingHttpServletRequest request;
@Before
public void setup() throws Exception {
Map<String, String> config = new HashMap<>();
config.put( "removable-extensions", "html");
servlet.activate( config );
}
@Test
public void getUriShouldRemoveExtension() throws Exception {
String requestUri = TEST_PAGE;
String uri = servlet.getUri( requestUri );
assertEquals( "/content/test", uri );
}
@Test
public void getUriShouldNotRemoveExtension() throws Exception {
String requestUri = "/content/dam/test.jpg";
String uri = servlet.getUri( requestUri );
assertEquals( requestUri, uri );
}
@Test
public void doHeadShouldAllowAccess() throws Exception {
context.create().resource( "/content/test" );
request = context.request();
Map<String,Object> requestMap = new HashMap<>();
requestMap.put( "uri", TEST_PAGE );
request.setParameterMap( requestMap );
MockSlingHttpServletResponse response = context.response();
servlet.doHeadRequest( request, response );
assertEquals( HttpServletResponse.SC_OK, response.getStatus() );
}
@Test
public void doHeadShouldNotAllowAccess() throws Exception {
request = context.request();
Map<String,Object> requestMap = new HashMap<>();
requestMap.put( "uri", TEST_PAGE );
request.setParameterMap( requestMap );
MockSlingHttpServletResponse response = context.response();
servlet.doHeadRequest( request, response );
assertEquals( HttpServletResponse.SC_UNAUTHORIZED, response.getStatus() );
}
}
| bundle/src/test/java/com/adobe/acs/commons/dispatcher/impl/PermissionSensitiveCacheServletTest.java | /*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2017 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.dispatcher.impl;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import static junitx.framework.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class PermissionSensitiveCacheServletTest {
public static final String TEST_PAGE = "/content/test.html";
@Rule
public SlingContext context = new SlingContext(ResourceResolverType.JCR_OAK);
@InjectMocks
private PermissionSensitiveCacheServlet servlet = new PermissionSensitiveCacheServlet();
MockSlingHttpServletRequest request;
@Before
public void setup() throws Exception {
Map<String, String> config = new HashMap<>();
config.put( "removable-extensions", "html");
servlet.activate( config );
context.create().resource( "/content/test" );
}
@Test
public void getUriShouldRemoveExtension() throws Exception {
String requestUri = TEST_PAGE;
String uri = servlet.getUri( requestUri );
assertEquals( "/content/test", uri );
}
@Test
public void getUriShouldNotRemoveExtension() throws Exception {
String requestUri = "/content/dam/test.jpg";
String uri = servlet.getUri( requestUri );
assertEquals( requestUri, uri );
}
@Test
public void doHeadShouldAllowAccess() throws Exception {
request = context.request();
Map<String,Object> requestMap = new HashMap<>();
requestMap.put( "uri", TEST_PAGE );
request.setParameterMap( requestMap );
MockSlingHttpServletResponse response = context.response();
servlet.doHeadRequest( request, response );
assertEquals( HttpServletResponse.SC_OK, response.getStatus() );
}
@Test
public void doHeadShouldNotAllowAccess() throws Exception {
}
}
| instead of mocking a request w/ no admin rights, testing with the case when resource == null to simulate the same behavior as the session not seeing a resource.
| bundle/src/test/java/com/adobe/acs/commons/dispatcher/impl/PermissionSensitiveCacheServletTest.java | instead of mocking a request w/ no admin rights, testing with the case when resource == null to simulate the same behavior as the session not seeing a resource. | <ide><path>undle/src/test/java/com/adobe/acs/commons/dispatcher/impl/PermissionSensitiveCacheServletTest.java
<ide> config.put( "removable-extensions", "html");
<ide> servlet.activate( config );
<ide>
<del> context.create().resource( "/content/test" );
<del>
<ide> }
<ide>
<ide> @Test
<ide> @Test
<ide> public void doHeadShouldAllowAccess() throws Exception {
<ide>
<add> context.create().resource( "/content/test" );
<add>
<ide> request = context.request();
<ide>
<ide> Map<String,Object> requestMap = new HashMap<>();
<ide> @Test
<ide> public void doHeadShouldNotAllowAccess() throws Exception {
<ide>
<add> request = context.request();
<add>
<add> Map<String,Object> requestMap = new HashMap<>();
<add> requestMap.put( "uri", TEST_PAGE );
<add>
<add> request.setParameterMap( requestMap );
<add>
<add> MockSlingHttpServletResponse response = context.response();
<add>
<add> servlet.doHeadRequest( request, response );
<add>
<add> assertEquals( HttpServletResponse.SC_UNAUTHORIZED, response.getStatus() );
<add>
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 0764195e7382be164a0503a25a509259a8dd9f69 | 0 | foundation-runtime/service-directory,foundation-runtime/service-directory | /**
* Copyright 2014 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.oss.foundation.directory.impl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_CREATED;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.cisco.oss.foundation.directory.Configurations;
import com.cisco.oss.foundation.directory.entity.ModelMetadataKey;
import com.cisco.oss.foundation.directory.entity.ModelService;
import com.cisco.oss.foundation.directory.entity.ModelServiceInstance;
import com.cisco.oss.foundation.directory.entity.OperationResult;
import com.cisco.oss.foundation.directory.entity.OperationalStatus;
import com.cisco.oss.foundation.directory.entity.ProvidedServiceInstance;
import com.cisco.oss.foundation.directory.entity.ServiceInstanceHeartbeat;
import com.cisco.oss.foundation.directory.exception.DirectoryServerClientException;
import com.cisco.oss.foundation.directory.exception.ErrorCode;
import com.cisco.oss.foundation.directory.exception.ServiceDirectoryError;
import com.cisco.oss.foundation.directory.exception.ServiceException;
import com.cisco.oss.foundation.directory.utils.HttpResponse;
import com.cisco.oss.foundation.directory.utils.HttpUtils.HttpMethod;
import com.cisco.oss.foundation.directory.utils.JsonSerializer;
/**
* This is the client object to invoke the remote service in ServiceDirectory Server Node.
*
* It implements the HTTP transportation for ServiceDirectoryService,
* and hides the HTTPClient details from the upper application layer.
*
*
*/
public class DirectoryServiceClient{
/**
* The http client read timeout property.
*/
public static final String SD_API_HTTPCLIENT_READ_TIMEOUT_PROPERTY = "httpclient.read.timeout";
/**
* The http client default read timeout value.
*/
public static final int SD_API_HTTPCLIENT_READ_TIMEOUT_DEFAULT = 5;
/**
* The Service Directory server FQDN property name.
*/
public static final String SD_API_SD_SERVER_FQDN_PROPERTY = "server.fqdn";
/**
* The default Service Directory server FQDN name.
*/
public static final String SD_API_SD_SERVER_FQDN_DEFAULT = "vcsdirsvc";
/**
* The Service Directory server port property name.
*/
public static final String SD_API_SD_SERVER_PORT_PROPERTY = "server.port";
/**
* The default Service Directory server port.
*/
public static final int SD_API_SD_SERVER_PORT_DEFAULT = 2013;
/**
* The HTTP invoker to access remote ServiceDirectory node.
*/
private final DirectoryInvoker invoker;
private final JsonSerializer serializer;
/**
* Constructor.
*/
public DirectoryServiceClient() {
serializer = new JsonSerializer();
String sdFQDN = Configurations.getString(SD_API_SD_SERVER_FQDN_PROPERTY, SD_API_SD_SERVER_FQDN_DEFAULT);
int port = Configurations.getInt(SD_API_SD_SERVER_PORT_PROPERTY, SD_API_SD_SERVER_PORT_DEFAULT);
String directoryAddresses = "http://" + sdFQDN + ":" + port;
this.invoker = new DirectoryInvoker(directoryAddresses, serializer);
}
/**
* Register a ServiceInstance.
*
* @param instance
* the ProvidedServiceInstance.
* @throws ServiceException
*/
public void registerInstance(ProvidedServiceInstance instance){
String body = serialize(instance);
HttpResponse result = invoker.invoke("/service/" + instance.getServiceName() + "/" + instance.getProviderId(), body,
HttpMethod.POST);
if (result.getHttpCode() != HTTP_CREATED) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
"HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Update a ServiceInstance.
*
* @param instance
* the ProvidedServiceInstance.
*/
public void updateInstance(ProvidedServiceInstance instance){
String body = serialize(instance);
HttpResponse result = invoker.invoke("/service/" + instance.getServiceName() + "/" + instance.getProviderId(), body,
HttpMethod.PUT);
if (result.getHttpCode() != HTTP_CREATED) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
"HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Update the ServiceInstance OperationalStatus by serviceName and instanceId.
*
* @param serviceName
* the service name.
* @param instanceId
* the instance id.
* @param status
* the ServiceInstance OperationalStatus.
* @param isOwned
* whether the DirectoryAPI owns this ServiceProvider.
*/
public void updateInstanceStatus(String serviceName, String instanceId, OperationalStatus status, boolean isOwned){
String uri = "/service/" + serviceName + "/" + instanceId + "/status";
String body = null;
try {
body = "status=" + URLEncoder.encode(status.toString(), "UTF-8") + "&isOwned=" + isOwned;
} catch (UnsupportedEncodingException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.SERVICE_INSTANCE_URI_FORMAT_ERROR);
throw new DirectoryServerClientException(sde);
}
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
HttpResponse result = invoker.invoke(uri, body,
HttpMethod.PUT, headers);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Update the ServiceInstance URI by serviceName and instanceId.
*
* @param serviceName
* the service name.
* @param instanceId
* the instance id.
* @param uri
* the ServiceInstance URI.
* @param isOwned
* whether the DirectoryAPI owns this ServiceProvider.
*/
public void updateInstanceUri(String serviceName, String instanceId, String uri, boolean isOwned){
String serviceUri = "/service/" + serviceName + "/" + instanceId + "/uri" ;
String body = null;
try {
body = "uri=" + URLEncoder.encode(uri, "UTF-8") + "&isOwned=" + isOwned;
} catch (UnsupportedEncodingException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.SERVICE_INSTANCE_URI_FORMAT_ERROR);
throw new DirectoryServerClientException(sde);
}
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
HttpResponse result = invoker.invoke(serviceUri, body,
HttpMethod.PUT, headers);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Unregister a ServiceInstance.
*
* @param serviceName
* service name.
* @param instanceId
* the instance id.
* @param isOwned
* whether the DirectoryAPI owns this ServiceProvider.
*/
public void unregisterInstance(String serviceName, String instanceId, boolean isOwned){
String uri = "/service/" + serviceName + "/" + instanceId + "/" + isOwned;
HttpResponse result = invoker.invoke(uri, null,
HttpMethod.DELETE);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Send ServiceInstance heartbeats.
*
* @param heartbeatMap
* the ServiceInstances heartbeat Map.
*/
public Map<String, OperationResult<String>> sendHeartBeat(Map<String, ServiceInstanceHeartbeat> heartbeatMap){
String body = serialize(heartbeatMap);
HttpResponse result = invoker.invoke("/service/heartbeat", body,
HttpMethod.PUT);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
Map<String, OperationResult<String>> operateRsult = deserialize(
result.getRetBody(), new TypeReference<Map<String, OperationResult<String>>>(){});
return operateRsult;
}
/**
* Lookup a Service by serviceName.
*
* @param serviceName
* the service name.
* @return
* the ModelService.
*/
public ModelService lookupService(String serviceName){
HttpResponse result = invoker.invoke("/service/" + serviceName , null, HttpMethod.GET);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
ModelService service = deserialize(result.getRetBody(), ModelService.class);
return service;
}
/**
* Get all service instances.
*
* @return
* the ModelServiceInstance list.
*/
public List<ModelServiceInstance> getAllInstances(){
HttpResponse result = invoker.invoke("/service" , null, HttpMethod.GET);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
List<ModelServiceInstance> allInstances = deserialize(result.getRetBody(), new TypeReference<List<ModelServiceInstance>>(){});
return allInstances;
}
/**
* Get the MetadataKey by key name.
*
* @param keyName
* the key name.
* @return
* the ModelMetadataKey.
*/
public ModelMetadataKey getMetadataKey(String keyName){
HttpResponse result = invoker.invoke("/metadatakey/" + keyName , null, HttpMethod.GET);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
ModelMetadataKey key = deserialize(
result.getRetBody(), ModelMetadataKey.class);
return key;
}
/**
* Get the changed services for Services list.
*
* @param services
* the Service list.
* @return
* the Service list that has modification.
* @throws ServiceException
*/
public Map<String, OperationResult<ModelService>> getServiceChanging(Map<String, ModelService> services){
String body = serialize(services);
HttpResponse result = invoker.invoke("/service/changing" , body, HttpMethod.POST);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
Map<String, OperationResult<ModelService>> newservices = deserialize(
result.getRetBody(), new TypeReference<Map<String, OperationResult<ModelService>>>(){});
return newservices;
}
/**
* Get the changed MetadataKey.
*
* @param keys
* the MetadataKey List.
* @return
* the ModelMetadataKey that has been changed.
*/
public Map<String, OperationResult<ModelMetadataKey>> getMetadataKeyChanging(Map<String, ModelMetadataKey> keys) {
String body = serialize(keys);
HttpResponse result = invoker.invoke("/metadatakey/changing" , body, HttpMethod.POST);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
Map<String, OperationResult<ModelMetadataKey>> newkeys = deserialize(
result.getRetBody(), new TypeReference<Map<String, OperationResult<ModelMetadataKey>>>(){});
return newkeys;
}
/**
* Deserialize a JSON String to the target object.
*
* @param body
* the JSON String.
* @param clazz
* the Object class name deserialized to.
* @return
* the deserialized Object instance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@SuppressWarnings("unchecked")
private <T> T deserialize(String body, Class<T> clazz) {
if(body == null || body.isEmpty()){
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "the message body is empty");
throw new DirectoryServerClientException(sde);
}
try {
return (T) serializer.deserialize(body.getBytes(), clazz);
} catch (IOException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "unrecognized message, deserialize failed.");
throw new DirectoryServerClientException(sde, e);
}
}
/**
* Deserialize a JSON String to a generic object.
*
* This method is used when the target object is generic.
*
* @param body
* the JSON String.
* @param typeRef
* the generic type.
* @return
* the deserialized object instance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@SuppressWarnings("unchecked")
private <T> T deserialize(String body, TypeReference<T> typeRef){
if(body == null || body.isEmpty()){
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "the message body is empty");
throw new DirectoryServerClientException(sde);
}
try {
return (T) serializer.deserialize(body.getBytes(), typeRef);
} catch (IOException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "unrecognized message, deserialize failed.");
throw new DirectoryServerClientException(sde, e);
}
}
/**
* Serialize a object to JSON String.
*
* @param o
* the target object.
* @return
* the JSON String.
*/
private String serialize(Object o) {
String body = null;
try {
body = new String(serializer.serialize(o));
} catch (IOException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.HTTP_CLIENT_ERROR, "serialize failed.");
throw new DirectoryServerClientException(sde, e);
}
return body;
}
/**
* Keep it default for unit test.
* @return
* the DirectoryInvoker
*/
DirectoryInvoker getDirectoryInvoker(){
return invoker;
}
}
| 1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java | /**
* Copyright 2014 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cisco.oss.foundation.directory.impl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_CREATED;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.cisco.oss.foundation.directory.Configurations;
import com.cisco.oss.foundation.directory.entity.ModelMetadataKey;
import com.cisco.oss.foundation.directory.entity.ModelService;
import com.cisco.oss.foundation.directory.entity.ModelServiceInstance;
import com.cisco.oss.foundation.directory.entity.OperationResult;
import com.cisco.oss.foundation.directory.entity.OperationalStatus;
import com.cisco.oss.foundation.directory.entity.ProvidedServiceInstance;
import com.cisco.oss.foundation.directory.entity.ServiceInstanceHeartbeat;
import com.cisco.oss.foundation.directory.exception.DirectoryServerClientException;
import com.cisco.oss.foundation.directory.exception.ErrorCode;
import com.cisco.oss.foundation.directory.exception.ServiceDirectoryError;
import com.cisco.oss.foundation.directory.exception.ServiceException;
import com.cisco.oss.foundation.directory.utils.HttpResponse;
import com.cisco.oss.foundation.directory.utils.HttpUtils.HttpMethod;
import com.cisco.oss.foundation.directory.utils.JsonSerializer;
/**
* This is the client object to invoke the remote service in ServiceDirectory Server Node.
*
* It implements the HTTP transportation for ServiceDirectoryService,
* and hides the HTTPClient details from the upper application layer.
*
*
*/
public class DirectoryServiceClient{
/**
* The http client read timeout property.
*/
public static final String SD_API_HTTPCLIENT_READ_TIMEOUT_PROPERTY = "httpclient.read.timeout";
/**
* The http client default read timeout value.
*/
public static final int SD_API_HTTPCLIENT_READ_TIMEOUT_DEFAULT = 5;
/**
* The Service Directory server FQDN property name.
*/
public static final String SD_API_SD_SERVER_FQDN_PROPERTY = "server.fqdn";
/**
* The default Service Directory server FQDN name.
*/
public static final String SD_API_SD_SERVER_FQDN_DEFAULT = "vcsdirsvc";
/**
* The Service Directory server port property name.
*/
public static final String SD_API_SD_SERVER_PORT_PROPERTY = "server.port";
/**
* The default Service Directory server port.
*/
public static final int SD_API_SD_SERVER_PORT_DEFAULT = 2013;
/**
* The HTTP invoker to access remote ServiceDirectory node.
*/
private DirectoryInvoker invoker;
private JsonSerializer serializer;
/**
* Constructor.
*/
public DirectoryServiceClient() {
serializer = new JsonSerializer();
String sdFQDN = Configurations.getString(SD_API_SD_SERVER_FQDN_PROPERTY, SD_API_SD_SERVER_FQDN_DEFAULT);
int port = Configurations.getInt(SD_API_SD_SERVER_PORT_PROPERTY, SD_API_SD_SERVER_PORT_DEFAULT);
String directoryAddresses = "http://" + sdFQDN + ":" + port;
this.invoker = new DirectoryInvoker(directoryAddresses, serializer);
}
/**
* Register a ServiceInstance.
*
* @param instance
* the ProvidedServiceInstance.
* @throws ServiceException
*/
public void registerInstance(ProvidedServiceInstance instance){
String body = serialize(instance);
HttpResponse result = invoker.invoke("/service/" + instance.getServiceName() + "/" + instance.getProviderId(), body,
HttpMethod.POST);
if (result.getHttpCode() != HTTP_CREATED) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
"HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Update a ServiceInstance.
*
* @param instance
* the ProvidedServiceInstance.
*/
public void updateInstance(ProvidedServiceInstance instance){
String body = serialize(instance);
HttpResponse result = invoker.invoke("/service/" + instance.getServiceName() + "/" + instance.getProviderId(), body,
HttpMethod.PUT);
if (result.getHttpCode() != HTTP_CREATED) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR,
"HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Update the ServiceInstance OperationalStatus by serviceName and instanceId.
*
* @param serviceName
* the service name.
* @param instanceId
* the instance id.
* @param status
* the ServiceInstance OperationalStatus.
* @param isOwned
* whether the DirectoryAPI owns this ServiceProvider.
*/
public void updateInstanceStatus(String serviceName, String instanceId, OperationalStatus status, boolean isOwned){
String uri = "/service/" + serviceName + "/" + instanceId + "/status";
String body = null;
try {
body = "status=" + URLEncoder.encode(status.toString(), "UTF-8") + "&isOwned=" + isOwned;
} catch (UnsupportedEncodingException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.SERVICE_INSTANCE_URI_FORMAT_ERROR);
throw new DirectoryServerClientException(sde);
}
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
HttpResponse result = invoker.invoke(uri, body,
HttpMethod.PUT, headers);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Update the ServiceInstance URI by serviceName and instanceId.
*
* @param serviceName
* the service name.
* @param instanceId
* the instance id.
* @param uri
* the ServiceInstance URI.
* @param isOwned
* whether the DirectoryAPI owns this ServiceProvider.
*/
public void updateInstanceUri(String serviceName, String instanceId, String uri, boolean isOwned){
String serviceUri = "/service/" + serviceName + "/" + instanceId + "/uri" ;
String body = null;
try {
body = "uri=" + URLEncoder.encode(uri, "UTF-8") + "&isOwned=" + isOwned;
} catch (UnsupportedEncodingException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.SERVICE_INSTANCE_URI_FORMAT_ERROR);
throw new DirectoryServerClientException(sde);
}
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
HttpResponse result = invoker.invoke(serviceUri, body,
HttpMethod.PUT, headers);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Unregister a ServiceInstance.
*
* @param serviceName
* service name.
* @param instanceId
* the instance id.
* @param isOwned
* whether the DirectoryAPI owns this ServiceProvider.
*/
public void unregisterInstance(String serviceName, String instanceId, boolean isOwned){
String uri = "/service/" + serviceName + "/" + instanceId + "/" + isOwned;
HttpResponse result = invoker.invoke(uri, null,
HttpMethod.DELETE);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
}
/**
* Send ServiceInstance heartbeats.
*
* @param heartbeatMap
* the ServiceInstances heartbeat Map.
*/
public Map<String, OperationResult<String>> sendHeartBeat(Map<String, ServiceInstanceHeartbeat> heartbeatMap){
String body = serialize(heartbeatMap);
HttpResponse result = invoker.invoke("/service/heartbeat", body,
HttpMethod.PUT);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
Map<String, OperationResult<String>> operateRsult = deserialize(
result.getRetBody(), new TypeReference<Map<String, OperationResult<String>>>(){});
return operateRsult;
}
/**
* Lookup a Service by serviceName.
*
* @param serviceName
* the service name.
* @return
* the ModelService.
*/
public ModelService lookupService(String serviceName){
HttpResponse result = invoker.invoke("/service/" + serviceName , null, HttpMethod.GET);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
ModelService service = deserialize(result.getRetBody(), ModelService.class);
return service;
}
/**
* Get all service instances.
*
* @return
* the ModelServiceInstance list.
*/
public List<ModelServiceInstance> getAllInstances(){
HttpResponse result = invoker.invoke("/service" , null, HttpMethod.GET);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
List<ModelServiceInstance> allInstances = deserialize(result.getRetBody(), new TypeReference<List<ModelServiceInstance>>(){});
return allInstances;
}
/**
* Get the MetadataKey by key name.
*
* @param keyName
* the key name.
* @return
* the ModelMetadataKey.
*/
public ModelMetadataKey getMetadataKey(String keyName){
HttpResponse result = invoker.invoke("/metadatakey/" + keyName , null, HttpMethod.GET);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
ModelMetadataKey key = deserialize(
result.getRetBody(), ModelMetadataKey.class);
return key;
}
/**
* Get the changed services for Services list.
*
* @param services
* the Service list.
* @return
* the Service list that has modification.
* @throws ServiceException
*/
public Map<String, OperationResult<ModelService>> getServiceChanging(Map<String, ModelService> services){
String body = serialize(services);
HttpResponse result = invoker.invoke("/service/changing" , body, HttpMethod.POST);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
Map<String, OperationResult<ModelService>> newservices = deserialize(
result.getRetBody(), new TypeReference<Map<String, OperationResult<ModelService>>>(){});
return newservices;
}
/**
* Get the changed MetadataKey.
*
* @param keys
* the MetadataKey List.
* @return
* the ModelMetadataKey that has been changed.
*/
public Map<String, OperationResult<ModelMetadataKey>> getMetadataKeyChanging(Map<String, ModelMetadataKey> keys) {
String body = serialize(keys);
HttpResponse result = invoker.invoke("/metadatakey/changing" , body, HttpMethod.POST);
if (result.getHttpCode() != HTTP_OK) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "HTTP Code is not OK, code=" + result.getHttpCode());
throw new DirectoryServerClientException(sde);
}
Map<String, OperationResult<ModelMetadataKey>> newkeys = deserialize(
result.getRetBody(), new TypeReference<Map<String, OperationResult<ModelMetadataKey>>>(){});
return newkeys;
}
/**
* Deserialize a JSON String to the target object.
*
* @param body
* the JSON String.
* @param clazz
* the Object class name deserialized to.
* @return
* the deserialized Object instance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@SuppressWarnings("unchecked")
private <T> T deserialize(String body, Class<T> clazz) {
if(body == null || body.isEmpty()){
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "the message body is empty");
throw new DirectoryServerClientException(sde);
}
try {
return (T) serializer.deserialize(body.getBytes(), clazz);
} catch (IOException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "unrecognized message, deserialize failed.");
throw new DirectoryServerClientException(sde, e);
}
}
/**
* Deserialize a JSON String to a generic object.
*
* This method is used when the target object is generic.
*
* @param body
* the JSON String.
* @param typeRef
* the generic type.
* @return
* the deserialized object instance.
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@SuppressWarnings("unchecked")
private <T> T deserialize(String body, TypeReference<T> typeRef){
if(body == null || body.isEmpty()){
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "the message body is empty");
throw new DirectoryServerClientException(sde);
}
try {
return (T) serializer.deserialize(body.getBytes(), typeRef);
} catch (IOException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, "unrecognized message, deserialize failed.");
throw new DirectoryServerClientException(sde, e);
}
}
/**
* Serialize a object to JSON String.
*
* @param o
* the target object.
* @return
* the JSON String.
*/
private String serialize(Object o) {
String body = null;
try {
body = new String(serializer.serialize(o));
} catch (IOException e) {
ServiceDirectoryError sde = new ServiceDirectoryError(
ErrorCode.HTTP_CLIENT_ERROR, "serialize failed.");
throw new DirectoryServerClientException(sde, e);
}
return body;
}
/**
* Keep it default for unit test.
* @return
* the DirectoryInvoker
*/
DirectoryInvoker getDirectoryInvoker(){
return invoker;
}
}
| immutable field should be final
| 1.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java | immutable field should be final | <ide><path>.1/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DirectoryServiceClient.java
<ide> /**
<ide> * The HTTP invoker to access remote ServiceDirectory node.
<ide> */
<del> private DirectoryInvoker invoker;
<del>
<del> private JsonSerializer serializer;
<add> private final DirectoryInvoker invoker;
<add>
<add> private final JsonSerializer serializer;
<ide>
<ide> /**
<ide> * Constructor. |
|
Java | mit | 18f2a20019bf78ba1588f9c312cf8047c79664df | 0 | luizgrp/SectionedRecyclerViewAdapter | package io.github.luizgrp.sectionedrecyclerviewadapter;
import org.junit.Before;
import org.junit.Test;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedStatelessSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedStatelessSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedStatelessSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.SectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.StatelessSectionStub;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* Unit tests for {@link SectionedRecyclerViewAdapter}
*/
public class SectionedRecyclerViewAdapterTest {
private final int ITEMS_QTY = 10;
private final String SECTION_TAG = "tag";
private final String SECTION_TAG2 = "tag2";
private SectionedRecyclerViewAdapter sectionAdapter;
@Before
public void setup() {
sectionAdapter = new SectionedRecyclerViewAdapter();
}
@Test(expected = IndexOutOfBoundsException.class)
public void getPositionInSection_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getPositionInSection(0);
}
@Test
public void getPositionInSection_withAdapterWithInvisibleSection_returnsCorrectPosition() {
// Given
addHeadedFootedStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
// When
int result = sectionAdapter.getPositionInSection(13);
int result2 = sectionAdapter.getPositionInSection(22);
// Then
assertThat(result, is(0));
assertThat(result2, is(9));
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingTag_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionPosition(SECTION_TAG);
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingTag_withInvalidTag_throwsException() {
// Given
addStatelessSectionStubToAdapter();
addStatelessSectionStubToAdapter();
// When
sectionAdapter.getSectionPosition(SECTION_TAG);
}
@Test
public void getSectionPositionUsingTag_withAdapterWithInvisibleSection_returnsCorrectPosition() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
int result = sectionAdapter.getSectionPosition(SECTION_TAG);
// Then
assertThat(result, is(10));
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingSection_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY));
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingSection_withInvalidSection_throwsException() {
// Given
addStatelessSectionStubToAdapter();
addStatelessSectionStubToAdapter();
// When
sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY));
}
@Test
public void getSectionPositionUsingSection_withAdapterWithInvisibleSection_returnsCorrectPosition() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(statelessSectionStub);
// When
int result = sectionAdapter.getSectionPosition(statelessSectionStub);
// Then
assertThat(result, is(10));
}
@Test(expected = IndexOutOfBoundsException.class)
public void onBindViewHolder_withEmptyAdapter_throwsException() {
// When
sectionAdapter.onBindViewHolder(null, 0);
}
@Test
public void addSection_withEmptyAdapter_succeeds() {
// Given
Section section = new StatelessSectionStub(ITEMS_QTY);
// When
sectionAdapter.addSection(SECTION_TAG, section);
// Then
assertSame(sectionAdapter.getSection(SECTION_TAG), section);
assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section);
}
@Test
public void addSectionWithTag_withEmptyAdapter_succeeds() {
// Given
Section section = new StatelessSectionStub(ITEMS_QTY);
// When
sectionAdapter.addSection(SECTION_TAG, section);
// Then
assertSame(sectionAdapter.getSection(SECTION_TAG), section);
assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section);
}
@Test
public void getSectionWithTag_withRemovedSection_returnsNull() {
// Given
sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
sectionAdapter.removeSection(SECTION_TAG);
// Then
assertNull(sectionAdapter.getSection(SECTION_TAG));
}
@Test
public void getSectionWithTag_withEmptyAdapter_returnsNull() {
// When
Section result = sectionAdapter.getSection(SECTION_TAG);
// Then
assertNull(result);
}
@Test
public void getItemCount_withEmptyAdapter_isZero() {
// When
int result = sectionAdapter.getItemCount();
// Then
assertThat(result, is(0));
}
@Test
public void getItemCount_withAdapterWithInvisibleSection_returnsCorrectQuantity() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
// When
int result = sectionAdapter.getItemCount();
// Then
assertThat(result, is(ITEMS_QTY));
}
@Test
public void getSectionsMap_withEmptyAdapter_isEmpty() {
// When
boolean result = sectionAdapter.getSectionsMap().isEmpty();
// Then
assertTrue(result);
}
@Test
public void getSectionsMap_withAdapterWithInvisibleSection_hasCorrectSize() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
// When
int result = sectionAdapter.getSectionsMap().size();
// Then
assertThat(result, is(2));
}
@Test
public void getSection_withEmptyAdapter_isNull() {
// When
Section result = sectionAdapter.getSection(SECTION_TAG);
// Then
assertNull(result);
}
@Test
public void getSection_withAdapterWithManySections_returnsCorrectSection() {
// Given
addStatelessSectionStubToAdapter();
Section section = new StatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(SECTION_TAG, section);
addStatelessSectionStubToAdapter();
// When
Section result = sectionAdapter.getSection(SECTION_TAG);
// Then
assertSame(result, section);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getSectionForPosition_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionForPosition(0);
}
@Test
public void getSectionForPosition_withAdapterWithManySections_returnsCorrectSection() {
// Given
Section sectionStub1 = addStatelessSectionStubToAdapter();
Section sectionStub2 = addStatelessSectionStubToAdapter();
Section sectionStub3 = addStatelessSectionStubToAdapter();
// When
Section result = sectionAdapter.getSectionForPosition(0);
Section result2 = sectionAdapter.getSectionForPosition(9);
Section result3 = sectionAdapter.getSectionForPosition(10);
Section result4 = sectionAdapter.getSectionForPosition(19);
Section result5 = sectionAdapter.getSectionForPosition(20);
Section result6 = sectionAdapter.getSectionForPosition(29);
// Then
assertSame(result, sectionStub1);
assertSame(result2, sectionStub1);
assertSame(result3, sectionStub2);
assertSame(result4, sectionStub2);
assertSame(result5, sectionStub3);
assertSame(result6, sectionStub3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getSectionItemViewType_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionItemViewType(0);
}
@Test
public void getSectionItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() {
// Given
addFourStatelessSectionsAndFourSectionsToAdapter();
// When
int positionHeader = sectionAdapter.getSectionItemViewType(32);
int positionItemStart = sectionAdapter.getSectionItemViewType(33);
int positionItemEnd = sectionAdapter.getSectionItemViewType(42);
int positionFooter = sectionAdapter.getSectionItemViewType(43);
// Then
assertThat(positionHeader, is(SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER));
assertThat(positionItemStart, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED));
assertThat(positionItemEnd, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED));
assertThat(positionFooter, is(SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getItemViewType_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getItemViewType(0);
}
@Test
public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() {
// Given
addFourStatelessSectionsAndFourSectionsToAdapter();
// When
int positionHeader = sectionAdapter.getItemViewType(32);
int positionItemStart = sectionAdapter.getItemViewType(33);
int positionItemEnd = sectionAdapter.getItemViewType(42);
int positionFooter = sectionAdapter.getItemViewType(43);
// Then
assertThat(positionHeader, is(15));
assertThat(positionItemStart, is(17));
assertThat(positionItemEnd, is(17));
assertThat(positionFooter, is(16));
}
@Test
public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithLoadingState() {
// Given
addStatelessSectionStubToAdapter();
addHeadedStatelessSectionStubToAdapter();
addFootedStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
Section section = addSectionStubToAdapter();
section.setState(Section.State.LOADING);
addHeadedSectionStubToAdapter();
addFootedSectionStubToAdapter();
addHeadedFootedSectionStubToAdapter();
// When
int positionLoading = sectionAdapter.getItemViewType(44);
// Then
assertThat(positionLoading, is(23));
}
@Test
public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithFailedState() {
// Given
addStatelessSectionStubToAdapter();
addHeadedStatelessSectionStubToAdapter();
addFootedStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
Section section = addSectionStubToAdapter();
section.setState(Section.State.FAILED);
addHeadedSectionStubToAdapter();
addFootedSectionStubToAdapter();
addHeadedFootedSectionStubToAdapter();
// When
int positionFailed = sectionAdapter.getItemViewType(44);
// Then
assertThat(positionFailed, is(24));
}
@Test
public void onCreateViewHolder_withEmptyAdapter_returnsNull() {
// When
Object result = sectionAdapter.onCreateViewHolder(null, 0);
// Then
assertNull(result);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForHeader() {
// Given
addStatelessSectionStubToAdapter();
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForFooter() {
// Given
addStatelessSectionStubToAdapter();
// When
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForLoading() {
// Given
addStatelessSectionStubToAdapter();
// When
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_LOADING);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForFailed() {
// Given
addStatelessSectionStubToAdapter();
// When
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FAILED);
}
@Test
public void removeAllSections_withAdapterWithManySections_succeeds() {
// Given
addFourStatelessSectionsAndFourSectionsToAdapter();
// When
sectionAdapter.removeAllSections();
// Then
assertThat(sectionAdapter.getItemCount(), is(0));
assertTrue(sectionAdapter.getSectionsMap().isEmpty());
}
@Test
public void getPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(SECTION_TAG, 0);
// Then
assertThat(result, is(11));
}
@Test
public void getPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(headedFootedStatelessSectionStub, 0);
// Then
assertThat(result, is(11));
}
@Test
public void getHeaderPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterHeaderPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG2, new StatelessSectionStub(ITEMS_QTY));
// When
int result = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_TAG);
int result2 = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_TAG2);
// Then
assertThat(result, is(10));
assertThat(result2, is(-1));
}
@Test
public void getHeaderPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterHeaderPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(statelessSectionStub);
// When
int result = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(headedFootedStatelessSectionStub);
int result2 = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(statelessSectionStub);
// Then
assertThat(result, is(10));
assertThat(result2, is(-1));
}
@Test
public void getFooterPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterFooterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG2, new StatelessSectionStub(ITEMS_QTY));
// When
int result = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_TAG);
int result2 = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_TAG2);
// Then
assertThat(result, is(21));
assertThat(result2, is(-1));
}
@Test
public void getFooterPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterFooterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(statelessSectionStub);
// When
int result = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(headedFootedStatelessSectionStub);
int result2 = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(statelessSectionStub);
// Then
assertThat(result, is(21));
assertThat(result2, is(-1));
}
@Test
public void notifyItemInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(SECTION_TAG, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11);
}
@Test
public void notifyItemInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(headedFootedStatelessSectionStub, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11);
}
@Test
public void notifyItemRangeInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4);
}
@Test
public void notifyItemRangeInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4);
}
@Test
public void notifyItemRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(SECTION_TAG, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11);
}
@Test
public void notifyItemRemovedFromSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(headedFootedStatelessSectionStub, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11);
}
@Test
public void notifyItemRangeRemovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4);
}
@Test
public void notifyItemRangeRemovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4);
}
@Test
public void notifyItemChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemChangedInSection(SECTION_TAG, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11);
}
@Test
public void notifyItemChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemChangedInSection(headedFootedStatelessSectionStub, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11);
}
@Test
public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(SECTION_TAG);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(10);
}
@Test
public void notifyHeaderChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(headedFootedStatelessSectionStub);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(10);
}
@Test
public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_neverCallsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(SECTION_TAG);
// Then
verify(spySectionedRecyclerViewAdapter, never()).callSuperNotifyItemChanged(-1);
}
@Test
public void notifyHeaderChangedInSectionUsingSection_withAdapterWithManySections_neverCallsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(statelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(statelessSectionStub);
// Then
verify(spySectionedRecyclerViewAdapter, never()).callSuperNotifyItemChanged(-1);
}
@Test
public void notifyItemRangeChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4);
}
@Test
public void notifyItemRangeChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4);
}
@Test
public void notifyItemRangeChangedInSectionWithPayloadUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4, null);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null);
}
@Test
public void notifyItemRangeChangedInSectionWithPayloadUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4, null);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null);
}
@Test
public void notifyItemMovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemMoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemMovedInSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15);
}
@Test
public void notifyItemMovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemMoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemMovedInSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15);
}
private void addFourStatelessSectionsAndFourSectionsToAdapter() {
addStatelessSectionStubToAdapter();
addHeadedStatelessSectionStubToAdapter();
addFootedStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
addSectionStubToAdapter();
addHeadedSectionStubToAdapter();
addFootedSectionStubToAdapter();
addHeadedFootedSectionStubToAdapter();
}
private StatelessSectionStub addStatelessSectionStubToAdapter() {
StatelessSectionStub sectionStub = new StatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(sectionStub);
return sectionStub;
}
private void addInvisibleStatelessSectionStubToAdapter() {
Section sectionStub = addStatelessSectionStubToAdapter();
sectionStub.setVisible(false);
}
private SectionStub addSectionStubToAdapter() {
SectionStub sectionStub = new SectionStub(ITEMS_QTY);
sectionAdapter.addSection(sectionStub);
return sectionStub;
}
private HeadedStatelessSectionStub addHeadedStatelessSectionStubToAdapter() {
HeadedStatelessSectionStub headedSectionSub = new HeadedStatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedSectionSub);
return headedSectionSub;
}
private HeadedSectionStub addHeadedSectionStubToAdapter() {
HeadedSectionStub headedSectionSub = new HeadedSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedSectionSub);
return headedSectionSub;
}
private FootedStatelessSectionStub addFootedStatelessSectionStubToAdapter() {
FootedStatelessSectionStub footedSectionSub = new FootedStatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(footedSectionSub);
return footedSectionSub;
}
private FootedSectionStub addFootedSectionStubToAdapter() {
FootedSectionStub footedSectionSub = new FootedSectionStub(ITEMS_QTY);
sectionAdapter.addSection(footedSectionSub);
return footedSectionSub;
}
private HeadedFootedStatelessSectionStub addHeadedFootedStatelessSectionStubToAdapter() {
HeadedFootedStatelessSectionStub headedFootedSectionSub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedFootedSectionSub);
return headedFootedSectionSub;
}
private HeadedFootedSectionStub addHeadedFootedSectionStubToAdapter() {
HeadedFootedSectionStub headedFootedSectionSub = new HeadedFootedSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedFootedSectionSub);
return headedFootedSectionSub;
}
}
| library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/SectionedRecyclerViewAdapterTest.java | package io.github.luizgrp.sectionedrecyclerviewadapter;
import org.junit.Before;
import org.junit.Test;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.FootedStatelessSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedFootedStatelessSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.HeadedStatelessSectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.SectionStub;
import io.github.luizgrp.sectionedrecyclerviewadapter.testdoubles.stub.StatelessSectionStub;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* Unit tests for {@link SectionedRecyclerViewAdapter}
*/
public class SectionedRecyclerViewAdapterTest {
private final int ITEMS_QTY = 10;
private final String SECTION_TAG = "tag";
private final String SECTION_HEADER_TAG = "header_tag";
private final String SECTION_FOOTER_TAG = "footer_tag";
private SectionedRecyclerViewAdapter sectionAdapter;
@Before
public void setup() {
sectionAdapter = new SectionedRecyclerViewAdapter();
}
@Test(expected = IndexOutOfBoundsException.class)
public void getPositionInSection_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getPositionInSection(0);
}
@Test
public void getPositionInSection_withAdapterWithInvisibleSection_returnsCorrectPosition() {
// Given
addHeadedFootedStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
// When
int result = sectionAdapter.getPositionInSection(13);
int result2 = sectionAdapter.getPositionInSection(22);
// Then
assertThat(result, is(0));
assertThat(result2, is(9));
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingTag_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionPosition(SECTION_TAG);
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingTag_withInvalidTag_throwsException() {
// Given
addStatelessSectionStubToAdapter();
addStatelessSectionStubToAdapter();
// When
sectionAdapter.getSectionPosition(SECTION_TAG);
}
@Test
public void getSectionPositionUsingTag_withAdapterWithInvisibleSection_returnsCorrectPosition() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
int result = sectionAdapter.getSectionPosition(SECTION_TAG);
// Then
assertThat(result, is(10));
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingSection_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY));
}
@Test(expected = IllegalArgumentException.class)
public void getSectionPositionUsingSection_withInvalidSection_throwsException() {
// Given
addStatelessSectionStubToAdapter();
addStatelessSectionStubToAdapter();
// When
sectionAdapter.getSectionPosition(new StatelessSectionStub(ITEMS_QTY));
}
@Test
public void getSectionPositionUsingSection_withAdapterWithInvisibleSection_returnsCorrectPosition() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(statelessSectionStub);
// When
int result = sectionAdapter.getSectionPosition(statelessSectionStub);
// Then
assertThat(result, is(10));
}
@Test(expected = IndexOutOfBoundsException.class)
public void onBindViewHolder_withEmptyAdapter_throwsException() {
// When
sectionAdapter.onBindViewHolder(null, 0);
}
@Test
public void addSection_withEmptyAdapter_succeeds() {
// Given
Section section = new StatelessSectionStub(ITEMS_QTY);
// When
sectionAdapter.addSection(SECTION_TAG, section);
// Then
assertSame(sectionAdapter.getSection(SECTION_TAG), section);
assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section);
}
@Test
public void addSectionWithTag_withEmptyAdapter_succeeds() {
// Given
Section section = new StatelessSectionStub(ITEMS_QTY);
// When
sectionAdapter.addSection(SECTION_TAG, section);
// Then
assertSame(sectionAdapter.getSection(SECTION_TAG), section);
assertSame(sectionAdapter.getSectionsMap().get(SECTION_TAG), section);
}
@Test
public void getSectionWithTag_withRemovedSection_returnsNull() {
// Given
sectionAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
sectionAdapter.removeSection(SECTION_TAG);
// Then
assertNull(sectionAdapter.getSection(SECTION_TAG));
}
@Test
public void getSectionWithTag_withEmptyAdapter_returnsNull() {
// When
Section result = sectionAdapter.getSection(SECTION_TAG);
// Then
assertNull(result);
}
@Test
public void getItemCount_withEmptyAdapter_isZero() {
// When
int result = sectionAdapter.getItemCount();
// Then
assertThat(result, is(0));
}
@Test
public void getItemCount_withAdapterWithInvisibleSection_returnsCorrectQuantity() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
// When
int result = sectionAdapter.getItemCount();
// Then
assertThat(result, is(ITEMS_QTY));
}
@Test
public void getSectionsMap_withEmptyAdapter_isEmpty() {
// When
boolean result = sectionAdapter.getSectionsMap().isEmpty();
// Then
assertTrue(result);
}
@Test
public void getSectionsMap_withAdapterWithInvisibleSection_hasCorrectSize() {
// Given
addStatelessSectionStubToAdapter();
addInvisibleStatelessSectionStubToAdapter();
// When
int result = sectionAdapter.getSectionsMap().size();
// Then
assertThat(result, is(2));
}
@Test
public void getSection_withEmptyAdapter_isNull() {
// When
Section result = sectionAdapter.getSection(SECTION_TAG);
// Then
assertNull(result);
}
@Test
public void getSection_withAdapterWithManySections_returnsCorrectSection() {
// Given
addStatelessSectionStubToAdapter();
Section section = new StatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(SECTION_TAG, section);
addStatelessSectionStubToAdapter();
// When
Section result = sectionAdapter.getSection(SECTION_TAG);
// Then
assertSame(result, section);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getSectionForPosition_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionForPosition(0);
}
@Test
public void getSectionForPosition_withAdapterWithManySections_returnsCorrectSection() {
// Given
Section sectionStub1 = addStatelessSectionStubToAdapter();
Section sectionStub2 = addStatelessSectionStubToAdapter();
Section sectionStub3 = addStatelessSectionStubToAdapter();
// When
Section result = sectionAdapter.getSectionForPosition(0);
Section result2 = sectionAdapter.getSectionForPosition(9);
Section result3 = sectionAdapter.getSectionForPosition(10);
Section result4 = sectionAdapter.getSectionForPosition(19);
Section result5 = sectionAdapter.getSectionForPosition(20);
Section result6 = sectionAdapter.getSectionForPosition(29);
// Then
assertSame(result, sectionStub1);
assertSame(result2, sectionStub1);
assertSame(result3, sectionStub2);
assertSame(result4, sectionStub2);
assertSame(result5, sectionStub3);
assertSame(result6, sectionStub3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getSectionItemViewType_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getSectionItemViewType(0);
}
@Test
public void getSectionItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() {
// Given
addFourStatelessSectionsAndFourSectionsToAdapter();
// When
int positionHeader = sectionAdapter.getSectionItemViewType(32);
int positionItemStart = sectionAdapter.getSectionItemViewType(33);
int positionItemEnd = sectionAdapter.getSectionItemViewType(42);
int positionFooter = sectionAdapter.getSectionItemViewType(43);
// Then
assertThat(positionHeader, is(SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER));
assertThat(positionItemStart, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED));
assertThat(positionItemEnd, is(SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED));
assertThat(positionFooter, is(SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getItemViewType_withEmptyAdapter_throwsException() {
// When
sectionAdapter.getItemViewType(0);
}
@Test
public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForHeadedFootedStatelessSection() {
// Given
addFourStatelessSectionsAndFourSectionsToAdapter();
// When
int positionHeader = sectionAdapter.getItemViewType(32);
int positionItemStart = sectionAdapter.getItemViewType(33);
int positionItemEnd = sectionAdapter.getItemViewType(42);
int positionFooter = sectionAdapter.getItemViewType(43);
// Then
assertThat(positionHeader, is(15));
assertThat(positionItemStart, is(17));
assertThat(positionItemEnd, is(17));
assertThat(positionFooter, is(16));
}
@Test
public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithLoadingState() {
// Given
addStatelessSectionStubToAdapter();
addHeadedStatelessSectionStubToAdapter();
addFootedStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
Section section = addSectionStubToAdapter();
section.setState(Section.State.LOADING);
addHeadedSectionStubToAdapter();
addFootedSectionStubToAdapter();
addHeadedFootedSectionStubToAdapter();
// When
int positionLoading = sectionAdapter.getItemViewType(44);
// Then
assertThat(positionLoading, is(23));
}
@Test
public void getItemViewType_withAdapterWithManySections_returnsCorrectValuesForSectionWithFailedState() {
// Given
addStatelessSectionStubToAdapter();
addHeadedStatelessSectionStubToAdapter();
addFootedStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
Section section = addSectionStubToAdapter();
section.setState(Section.State.FAILED);
addHeadedSectionStubToAdapter();
addFootedSectionStubToAdapter();
addHeadedFootedSectionStubToAdapter();
// When
int positionFailed = sectionAdapter.getItemViewType(44);
// Then
assertThat(positionFailed, is(24));
}
@Test
public void onCreateViewHolder_withEmptyAdapter_returnsNull() {
// When
Object result = sectionAdapter.onCreateViewHolder(null, 0);
// Then
assertNull(result);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForHeader() {
// Given
addStatelessSectionStubToAdapter();
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForFooter() {
// Given
addStatelessSectionStubToAdapter();
// When
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForLoading() {
// Given
addStatelessSectionStubToAdapter();
// When
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_LOADING);
}
@Test(expected = NullPointerException.class)
public void onCreateViewHolder_withStatelessSection_throwsExceptionForFailed() {
// Given
addStatelessSectionStubToAdapter();
// When
sectionAdapter.onCreateViewHolder(null, SectionedRecyclerViewAdapter.VIEW_TYPE_FAILED);
}
@Test
public void removeAllSections_withAdapterWithManySections_succeeds() {
// Given
addFourStatelessSectionsAndFourSectionsToAdapter();
// When
sectionAdapter.removeAllSections();
// Then
assertThat(sectionAdapter.getItemCount(), is(0));
assertTrue(sectionAdapter.getSectionsMap().isEmpty());
}
@Test
public void getPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(SECTION_TAG, 0);
// Then
assertThat(result, is(11));
}
@Test
public void getPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
int result = spySectionedRecyclerViewAdapter.getPositionInAdapter(headedFootedStatelessSectionStub, 0);
// Then
assertThat(result, is(11));
}
@Test
public void getHeaderPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterHeaderPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_HEADER_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
int result = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_TAG);
int result2 = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_HEADER_TAG);
// Then
assertThat(result, is(10));
assertThat(result2, is(-1));
}
@Test
public void getHeaderPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterHeaderPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(statelessSectionStub);
// When
int result = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(headedFootedStatelessSectionStub);
int result2 = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(statelessSectionStub);
// Then
assertThat(result, is(10));
assertThat(result2, is(-1));
}
@Test
public void getFooterPositionInAdapterUsingTag_withAdapterWithManySections_returnsCorrectAdapterFooterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_FOOTER_TAG, new StatelessSectionStub(ITEMS_QTY));
// When
int result = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_TAG);
int result2 = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_FOOTER_TAG);
// Then
assertThat(result, is(21));
assertThat(result2, is(-1));
}
@Test
public void getFooterPositionInAdapterUsingSection_withAdapterWithManySections_returnsCorrectAdapterFooterPosition() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(statelessSectionStub);
// When
int result = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(headedFootedStatelessSectionStub);
int result2 = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(statelessSectionStub);
// Then
assertThat(result, is(21));
assertThat(result2, is(-1));
}
@Test
public void notifyItemInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(SECTION_TAG, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11);
}
@Test
public void notifyItemInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemInsertedInSection(headedFootedStatelessSectionStub, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemInserted(11);
}
@Test
public void notifyItemRangeInsertedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4);
}
@Test
public void notifyItemRangeInsertedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeInserted() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeInsertedInSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeInserted(11, 4);
}
@Test
public void notifyItemRemovedFromSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(SECTION_TAG, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11);
}
@Test
public void notifyItemRemovedFromSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRemovedFromSection(headedFootedStatelessSectionStub, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRemoved(11);
}
@Test
public void notifyItemRangeRemovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4);
}
@Test
public void notifyItemRangeRemovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeRemoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeRemovedFromSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeRemoved(11, 4);
}
@Test
public void notifyItemChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemChangedInSection(SECTION_TAG, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11);
}
@Test
public void notifyItemChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemChangedInSection(headedFootedStatelessSectionStub, 0);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11);
}
@Test
public void notifyItemRangeChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4);
}
@Test
public void notifyItemRangeChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4);
}
@Test
public void notifyItemRangeChangedInSectionWithPayloadUsingTag_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(SECTION_TAG, 0, 4, null);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null);
}
@Test
public void notifyItemRangeChangedInSectionWithPayloadUsingSection_withAdapterWithManySections_callsSuperNotifyItemRangeChanged() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(anyInt(), anyInt(), any());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemRangeChangedInSection(headedFootedStatelessSectionStub, 0, 4, null);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemRangeChanged(11, 4, null);
}
@Test
public void notifyItemMovedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemMoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
// When
spySectionedRecyclerViewAdapter.notifyItemMovedInSection(SECTION_TAG, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15);
}
@Test
public void notifyItemMovedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemMoved() {
// Given
SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(anyInt(), anyInt());
spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
// When
spySectionedRecyclerViewAdapter.notifyItemMovedInSection(headedFootedStatelessSectionStub, 0, 4);
// Then
verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemMoved(11, 15);
}
private void addFourStatelessSectionsAndFourSectionsToAdapter() {
addStatelessSectionStubToAdapter();
addHeadedStatelessSectionStubToAdapter();
addFootedStatelessSectionStubToAdapter();
addHeadedFootedStatelessSectionStubToAdapter();
addSectionStubToAdapter();
addHeadedSectionStubToAdapter();
addFootedSectionStubToAdapter();
addHeadedFootedSectionStubToAdapter();
}
private StatelessSectionStub addStatelessSectionStubToAdapter() {
StatelessSectionStub sectionStub = new StatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(sectionStub);
return sectionStub;
}
private void addInvisibleStatelessSectionStubToAdapter() {
Section sectionStub = addStatelessSectionStubToAdapter();
sectionStub.setVisible(false);
}
private SectionStub addSectionStubToAdapter() {
SectionStub sectionStub = new SectionStub(ITEMS_QTY);
sectionAdapter.addSection(sectionStub);
return sectionStub;
}
private HeadedStatelessSectionStub addHeadedStatelessSectionStubToAdapter() {
HeadedStatelessSectionStub headedSectionSub = new HeadedStatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedSectionSub);
return headedSectionSub;
}
private HeadedSectionStub addHeadedSectionStubToAdapter() {
HeadedSectionStub headedSectionSub = new HeadedSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedSectionSub);
return headedSectionSub;
}
private FootedStatelessSectionStub addFootedStatelessSectionStubToAdapter() {
FootedStatelessSectionStub footedSectionSub = new FootedStatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(footedSectionSub);
return footedSectionSub;
}
private FootedSectionStub addFootedSectionStubToAdapter() {
FootedSectionStub footedSectionSub = new FootedSectionStub(ITEMS_QTY);
sectionAdapter.addSection(footedSectionSub);
return footedSectionSub;
}
private HeadedFootedStatelessSectionStub addHeadedFootedStatelessSectionStubToAdapter() {
HeadedFootedStatelessSectionStub headedFootedSectionSub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedFootedSectionSub);
return headedFootedSectionSub;
}
private HeadedFootedSectionStub addHeadedFootedSectionStubToAdapter() {
HeadedFootedSectionStub headedFootedSectionSub = new HeadedFootedSectionStub(ITEMS_QTY);
sectionAdapter.addSection(headedFootedSectionSub);
return headedFootedSectionSub;
}
}
| More unit test.
| library/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/SectionedRecyclerViewAdapterTest.java | More unit test. | <ide><path>ibrary/src/test/java/io/github/luizgrp/sectionedrecyclerviewadapter/SectionedRecyclerViewAdapterTest.java
<ide> import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.ArgumentMatchers.anyInt;
<ide> import static org.mockito.Mockito.doNothing;
<add>import static org.mockito.Mockito.never;
<ide> import static org.mockito.Mockito.spy;
<ide> import static org.mockito.Mockito.verify;
<ide>
<ide>
<ide> private final int ITEMS_QTY = 10;
<ide> private final String SECTION_TAG = "tag";
<del> private final String SECTION_HEADER_TAG = "header_tag";
<del> private final String SECTION_FOOTER_TAG = "footer_tag";
<add> private final String SECTION_TAG2 = "tag2";
<ide>
<ide> private SectionedRecyclerViewAdapter sectionAdapter;
<ide>
<ide>
<ide> spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
<ide> spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
<del> spySectionedRecyclerViewAdapter.addSection(SECTION_HEADER_TAG, new StatelessSectionStub(ITEMS_QTY));
<add> spySectionedRecyclerViewAdapter.addSection(SECTION_TAG2, new StatelessSectionStub(ITEMS_QTY));
<ide>
<ide> // When
<ide> int result = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_TAG);
<del> int result2 = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_HEADER_TAG);
<add> int result2 = spySectionedRecyclerViewAdapter.getHeaderPositionInAdapter(SECTION_TAG2);
<ide>
<ide> // Then
<ide> assertThat(result, is(10));
<ide>
<ide> spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
<ide> spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
<del> spySectionedRecyclerViewAdapter.addSection(SECTION_FOOTER_TAG, new StatelessSectionStub(ITEMS_QTY));
<add> spySectionedRecyclerViewAdapter.addSection(SECTION_TAG2, new StatelessSectionStub(ITEMS_QTY));
<ide>
<ide> // When
<ide> int result = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_TAG);
<del> int result2 = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_FOOTER_TAG);
<add> int result2 = spySectionedRecyclerViewAdapter.getFooterPositionInAdapter(SECTION_TAG2);
<ide>
<ide> // Then
<ide> assertThat(result, is(21));
<ide>
<ide> // Then
<ide> verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(11);
<add> }
<add>
<add> @Test
<add> public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
<add> // Given
<add> SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
<add> doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
<add>
<add> spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
<add> spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new HeadedFootedStatelessSectionStub(ITEMS_QTY));
<add>
<add> // When
<add> spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(SECTION_TAG);
<add>
<add> // Then
<add> verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(10);
<add> }
<add>
<add> @Test
<add> public void notifyHeaderChangedInSectionUsingSection_withAdapterWithManySections_callsSuperNotifyItemChangedInSection() {
<add> // Given
<add> SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
<add> doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
<add>
<add> spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
<add> HeadedFootedStatelessSectionStub headedFootedStatelessSectionStub = new HeadedFootedStatelessSectionStub(ITEMS_QTY);
<add> spySectionedRecyclerViewAdapter.addSection(headedFootedStatelessSectionStub);
<add>
<add> // When
<add> spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(headedFootedStatelessSectionStub);
<add>
<add> // Then
<add> verify(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(10);
<add> }
<add>
<add> @Test
<add> public void notifyHeaderChangedInSectionUsingTag_withAdapterWithManySections_neverCallsSuperNotifyItemChangedInSection() {
<add> // Given
<add> SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
<add> doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
<add>
<add> spySectionedRecyclerViewAdapter.addSection(new StatelessSectionStub(ITEMS_QTY));
<add> spySectionedRecyclerViewAdapter.addSection(SECTION_TAG, new StatelessSectionStub(ITEMS_QTY));
<add>
<add> // When
<add> spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(SECTION_TAG);
<add>
<add> // Then
<add> verify(spySectionedRecyclerViewAdapter, never()).callSuperNotifyItemChanged(-1);
<add> }
<add>
<add> @Test
<add> public void notifyHeaderChangedInSectionUsingSection_withAdapterWithManySections_neverCallsSuperNotifyItemChangedInSection() {
<add> // Given
<add> SectionedRecyclerViewAdapter spySectionedRecyclerViewAdapter = spy(SectionedRecyclerViewAdapter.class);
<add> doNothing().when(spySectionedRecyclerViewAdapter).callSuperNotifyItemChanged(anyInt());
<add>
<add> StatelessSectionStub statelessSectionStub = new StatelessSectionStub(ITEMS_QTY);
<add> spySectionedRecyclerViewAdapter.addSection(statelessSectionStub);
<add>
<add> // When
<add> spySectionedRecyclerViewAdapter.notifyHeaderChangedInSection(statelessSectionStub);
<add>
<add> // Then
<add> verify(spySectionedRecyclerViewAdapter, never()).callSuperNotifyItemChanged(-1);
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | error: pathspec 'dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java' did not match any file(s) known to git
| 3274db89224fe97c7147eeea468577e7690b8f7a | 1 | apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev | /*
* 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.felix.dm.test.integration.api;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Random;
import java.util.Set;
import junit.framework.Assert;
import org.apache.felix.dm.Component;
import org.apache.felix.dm.DependencyManager;
import org.apache.felix.dm.ServiceUtil;
import org.apache.felix.dm.test.components.Ensure;
import org.apache.felix.dm.test.integration.common.TestBase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
/**
* Test for aspects with service properties propagations.
*
* @author <a href="mailto:[email protected]">Felix Project Team</a>
*/
@RunWith(PaxExam.class)
public class AspectWithPropagationTest extends TestBase {
private final static int ASPECTS = 2;
private final Set<Integer> _randoms = new HashSet<Integer>();
private final Random _rnd = new Random();
private static Ensure m_invokeStep;
private static Ensure m_changeStep;
@Test
public void testAspectsWithPropagation() {
DependencyManager m = new DependencyManager(context);
// helper class that ensures certain steps get executed in sequence
m_invokeStep = new Ensure();
// Create our original "S" service.
Dictionary props = new Hashtable();
props.put("foo", "bar");
Component s = m.createComponent()
.setImplementation(new SImpl())
.setInterface(S.class.getName(), props);
// Create an aspect aware client, depending on "S" service.
Client clientImpl;
Component client = m.createComponent()
.setImplementation((clientImpl = new Client()))
.add(m.createServiceDependency()
.setService(S.class)
.setRequired(true)
.setDebug("client")
.setCallbacks("add", "change", "remove", "swap"));
// Create some "S" aspects
Component[] aspects = new Component[ASPECTS];
for (int rank = 1; rank <= ASPECTS; rank ++) {
aspects[rank-1] = m.createAspectService(S.class, null, rank, "add", "change", "remove", "swap")
.setImplementation(new A("A" + rank, rank));
props = new Hashtable();
props.put("a" + rank, "v" + rank);
aspects[rank-1].setServiceProperties(props);
}
// Register client
m.add(client);
// Randomly register aspects and original service
boolean originalServiceAdded = false;
for (int i = 0; i < ASPECTS; i ++) {
int index = getRandomAspect();
m.add(aspects[index]);
if (_rnd.nextBoolean()) {
m.add(s);
originalServiceAdded = true;
}
}
if (! originalServiceAdded) {
m.add(s);
}
// All set, check if client has inherited from all aspect properties + original service properties
Dictionary check = new Hashtable();
check.put("foo", "bar");
for (int i = 1; i <= ASPECTS; i ++) {
check.put("a" + i, "v" + i);
}
checkServiceProperties(check, clientImpl.getServiceProperties());
// Now invoke client, which orderly calls all aspects in the chain, and finally the original service "S".
System.out.println("-------------------------- Invoking client.");
clientImpl.invoke();
m_invokeStep.waitForStep(ASPECTS+1, 5000);
// Now, change original service "S" properties: this will orderly trigger "change" callbacks on aspects, and on client.
System.out.println("-------------------------- Modifying original service properties.");
m_changeStep = new Ensure();
props = new Hashtable();
props.put("foo", "barModified");
s.setServiceProperties(props);
// Check if aspects and client have been orderly called in their "changed" callback
m_changeStep.waitForStep(ASPECTS+1, 5000);
// Check if modified "foo" original service property has been propagated
check = new Hashtable();
check.put("foo", "barModified");
for (int i = 1; i <= ASPECTS; i ++) {
check.put("a" + i, "v" + i);
}
checkServiceProperties(check, clientImpl.getServiceProperties());
// Now, change the lower ranked aspect: it must propagate to all upper aspects, as well as to the client
System.out.println("-------------------------- Modifying First aspect service properties.");
m_changeStep = new Ensure();
m_changeStep.step(1); // skip the first lower-ranked aspect, only upper aspects (rank >= 2) will be changed.
props = new Hashtable();
props.put("a1", "v1Modified");
aspects[0].setServiceProperties(props); // That triggers change callbacks for upper aspects (with rank >= 2)
m_changeStep.waitForStep(ASPECTS+1, 5000); // check if Aspects with rank > 1 and the clients have been changed.
// Check if first aspect service properties have been propagated up to the client.
check = new Hashtable();
check.put("foo", "barModified");
check.put("a1", "v1Modified");
for (int i = 2; i <= ASPECTS; i ++) {
check.put("a" + i, "v" + i);
}
checkServiceProperties(check, clientImpl.getServiceProperties());
// Clear all components.
m.clear();
}
private void checkServiceProperties(Dictionary check, Dictionary properties) {
Enumeration e = check.keys();
while (e.hasMoreElements()) {
Object key = e.nextElement();
Object val = check.get(key);
Assert.assertEquals(val, properties.get(key));
}
}
// S Service
public static interface S {
public void invoke();
}
// S ServiceImpl
static class SImpl implements S {
public SImpl() {
}
public String toString() {
return "S";
}
public void invoke() {
m_invokeStep.step(ASPECTS+1);
}
}
// S Aspect
static class A implements S {
private final String m_name;
private volatile ServiceRegistration m_registration;
private volatile S m_next;
private final int m_rank;
public A(String name, int rank) {
m_name = name;
m_rank = rank;
}
public String toString() {
return m_name;
}
public void invoke() {
int rank = ServiceUtil.getRanking(m_registration.getReference());
m_invokeStep.step(ASPECTS - rank + 1);
m_next.invoke();
}
public void add(ServiceReference ref, S s) {
System.out.println("+++ A" + m_rank + ".add:" + s + "/" + ServiceUtil.toString(ref));
m_next = s;
}
public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
System.out.println("+++ A" + m_rank + ".swap: new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
Assert.assertTrue(m_next == oldS);
m_next = newS;
}
public void change(ServiceReference props, S s) {
System.out.println("+++ A" + m_rank + ".change: s=" + s + ", props=" + ServiceUtil.toString(props));
if (m_changeStep != null) {
int rank = ServiceUtil.getRanking(m_registration.getReference());
m_changeStep.step(rank);
}
}
public void remove(ServiceReference props, S s) {
System.out.println("+++ A" + m_rank + ".remove: " + s + ", props=" + ServiceUtil.toString(props));
}
}
// Aspect aware client, depending of "S" service aspects.
static class Client {
private volatile S m_s;
private volatile ServiceReference m_sRef;
public Client() {
}
public Dictionary getServiceProperties() {
Dictionary props = new Hashtable();
for (String key : m_sRef.getPropertyKeys()) {
props.put(key, m_sRef.getProperty(key));
}
return props;
}
public void invoke() {
m_s.invoke();
}
public String toString() {
return "Client";
}
public void add(ServiceReference ref, S s) {
System.out.println("+++ Client.add: " + s + "/" + ServiceUtil.toString(ref));
m_s = s;
m_sRef = ref;
}
public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
System.out.println("+++ Client.swap: new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
Assert.assertTrue(m_s == oldS);
m_s = newS;
m_sRef = newSRef;
}
public void change(ServiceReference properties, S s) {
System.out.println("+++ Client.change: s=" + s + ", props=" + ServiceUtil.toString(properties));
if (m_changeStep != null) {
m_changeStep.step(ASPECTS+1);
}
}
public void remove(ServiceReference props, S s) {
System.out.println("+++ Client.remove: " + s + ", props=" + ServiceUtil.toString(props));
}
}
private int getRandomAspect() {
int index = 0;
do {
index = _rnd.nextInt(ASPECTS);
} while (_randoms.contains(new Integer(index)));
_randoms.add(new Integer(index));
return index;
}
}
| dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java | [FELIX-4305] Added a testcase for Aspect service properties propagation.
git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@1542753 13f79535-47bb-0310-9956-ffa450edef68
| dependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java | [FELIX-4305] Added a testcase for Aspect service properties propagation. | <ide><path>ependencymanager/test/src/test/java/org/apache/felix/dm/test/integration/api/AspectWithPropagationTest.java
<add>/*
<add> * Licensed to the Apache Software Foundation (ASF) under one
<add> * or more contributor license agreements. See the NOTICE file
<add> * distributed with this work for additional information
<add> * regarding copyright ownership. The ASF licenses this file
<add> * to you under the Apache License, Version 2.0 (the
<add> * "License"); you may not use this file except in compliance
<add> * with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing,
<add> * software distributed under the License is distributed on an
<add> * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add> * KIND, either express or implied. See the License for the
<add> * specific language governing permissions and limitations
<add> * under the License.
<add> */
<add>package org.apache.felix.dm.test.integration.api;
<add>
<add>import java.util.Dictionary;
<add>import java.util.Enumeration;
<add>import java.util.HashSet;
<add>import java.util.Hashtable;
<add>import java.util.Random;
<add>import java.util.Set;
<add>
<add>import junit.framework.Assert;
<add>
<add>import org.apache.felix.dm.Component;
<add>import org.apache.felix.dm.DependencyManager;
<add>import org.apache.felix.dm.ServiceUtil;
<add>import org.apache.felix.dm.test.components.Ensure;
<add>import org.apache.felix.dm.test.integration.common.TestBase;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.ops4j.pax.exam.junit.PaxExam;
<add>import org.osgi.framework.ServiceReference;
<add>import org.osgi.framework.ServiceRegistration;
<add>
<add>/**
<add> * Test for aspects with service properties propagations.
<add> *
<add> * @author <a href="mailto:[email protected]">Felix Project Team</a>
<add> */
<add>@RunWith(PaxExam.class)
<add>public class AspectWithPropagationTest extends TestBase {
<add> private final static int ASPECTS = 2;
<add> private final Set<Integer> _randoms = new HashSet<Integer>();
<add> private final Random _rnd = new Random();
<add> private static Ensure m_invokeStep;
<add> private static Ensure m_changeStep;
<add>
<add> @Test
<add> public void testAspectsWithPropagation() {
<add> DependencyManager m = new DependencyManager(context);
<add> // helper class that ensures certain steps get executed in sequence
<add> m_invokeStep = new Ensure();
<add>
<add> // Create our original "S" service.
<add> Dictionary props = new Hashtable();
<add> props.put("foo", "bar");
<add> Component s = m.createComponent()
<add> .setImplementation(new SImpl())
<add> .setInterface(S.class.getName(), props);
<add>
<add> // Create an aspect aware client, depending on "S" service.
<add> Client clientImpl;
<add> Component client = m.createComponent()
<add> .setImplementation((clientImpl = new Client()))
<add> .add(m.createServiceDependency()
<add> .setService(S.class)
<add> .setRequired(true)
<add> .setDebug("client")
<add> .setCallbacks("add", "change", "remove", "swap"));
<add>
<add> // Create some "S" aspects
<add> Component[] aspects = new Component[ASPECTS];
<add> for (int rank = 1; rank <= ASPECTS; rank ++) {
<add> aspects[rank-1] = m.createAspectService(S.class, null, rank, "add", "change", "remove", "swap")
<add> .setImplementation(new A("A" + rank, rank));
<add> props = new Hashtable();
<add> props.put("a" + rank, "v" + rank);
<add> aspects[rank-1].setServiceProperties(props);
<add> }
<add>
<add> // Register client
<add> m.add(client);
<add>
<add> // Randomly register aspects and original service
<add> boolean originalServiceAdded = false;
<add> for (int i = 0; i < ASPECTS; i ++) {
<add> int index = getRandomAspect();
<add> m.add(aspects[index]);
<add> if (_rnd.nextBoolean()) {
<add> m.add(s);
<add> originalServiceAdded = true;
<add> }
<add> }
<add> if (! originalServiceAdded) {
<add> m.add(s);
<add> }
<add>
<add> // All set, check if client has inherited from all aspect properties + original service properties
<add> Dictionary check = new Hashtable();
<add> check.put("foo", "bar");
<add> for (int i = 1; i <= ASPECTS; i ++) {
<add> check.put("a" + i, "v" + i);
<add> }
<add> checkServiceProperties(check, clientImpl.getServiceProperties());
<add>
<add> // Now invoke client, which orderly calls all aspects in the chain, and finally the original service "S".
<add> System.out.println("-------------------------- Invoking client.");
<add> clientImpl.invoke();
<add> m_invokeStep.waitForStep(ASPECTS+1, 5000);
<add>
<add> // Now, change original service "S" properties: this will orderly trigger "change" callbacks on aspects, and on client.
<add> System.out.println("-------------------------- Modifying original service properties.");
<add> m_changeStep = new Ensure();
<add> props = new Hashtable();
<add> props.put("foo", "barModified");
<add> s.setServiceProperties(props);
<add>
<add> // Check if aspects and client have been orderly called in their "changed" callback
<add> m_changeStep.waitForStep(ASPECTS+1, 5000);
<add>
<add> // Check if modified "foo" original service property has been propagated
<add> check = new Hashtable();
<add> check.put("foo", "barModified");
<add> for (int i = 1; i <= ASPECTS; i ++) {
<add> check.put("a" + i, "v" + i);
<add> }
<add> checkServiceProperties(check, clientImpl.getServiceProperties());
<add>
<add> // Now, change the lower ranked aspect: it must propagate to all upper aspects, as well as to the client
<add> System.out.println("-------------------------- Modifying First aspect service properties.");
<add>
<add> m_changeStep = new Ensure();
<add> m_changeStep.step(1); // skip the first lower-ranked aspect, only upper aspects (rank >= 2) will be changed.
<add> props = new Hashtable();
<add> props.put("a1", "v1Modified");
<add> aspects[0].setServiceProperties(props); // That triggers change callbacks for upper aspects (with rank >= 2)
<add> m_changeStep.waitForStep(ASPECTS+1, 5000); // check if Aspects with rank > 1 and the clients have been changed.
<add>
<add> // Check if first aspect service properties have been propagated up to the client.
<add> check = new Hashtable();
<add> check.put("foo", "barModified");
<add> check.put("a1", "v1Modified");
<add> for (int i = 2; i <= ASPECTS; i ++) {
<add> check.put("a" + i, "v" + i);
<add> }
<add> checkServiceProperties(check, clientImpl.getServiceProperties());
<add>
<add> // Clear all components.
<add> m.clear();
<add> }
<add>
<add> private void checkServiceProperties(Dictionary check, Dictionary properties) {
<add> Enumeration e = check.keys();
<add> while (e.hasMoreElements()) {
<add> Object key = e.nextElement();
<add> Object val = check.get(key);
<add> Assert.assertEquals(val, properties.get(key));
<add> }
<add> }
<add>
<add> // S Service
<add> public static interface S {
<add> public void invoke();
<add> }
<add>
<add> // S ServiceImpl
<add> static class SImpl implements S {
<add> public SImpl() {
<add> }
<add>
<add> public String toString() {
<add> return "S";
<add> }
<add>
<add> public void invoke() {
<add> m_invokeStep.step(ASPECTS+1);
<add> }
<add> }
<add>
<add> // S Aspect
<add> static class A implements S {
<add> private final String m_name;
<add> private volatile ServiceRegistration m_registration;
<add> private volatile S m_next;
<add> private final int m_rank;
<add>
<add> public A(String name, int rank) {
<add> m_name = name;
<add> m_rank = rank;
<add> }
<add>
<add> public String toString() {
<add> return m_name;
<add> }
<add>
<add> public void invoke() {
<add> int rank = ServiceUtil.getRanking(m_registration.getReference());
<add> m_invokeStep.step(ASPECTS - rank + 1);
<add> m_next.invoke();
<add> }
<add>
<add> public void add(ServiceReference ref, S s) {
<add> System.out.println("+++ A" + m_rank + ".add:" + s + "/" + ServiceUtil.toString(ref));
<add> m_next = s;
<add> }
<add>
<add> public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
<add> System.out.println("+++ A" + m_rank + ".swap: new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
<add> Assert.assertTrue(m_next == oldS);
<add> m_next = newS;
<add> }
<add>
<add> public void change(ServiceReference props, S s) {
<add> System.out.println("+++ A" + m_rank + ".change: s=" + s + ", props=" + ServiceUtil.toString(props));
<add> if (m_changeStep != null) {
<add> int rank = ServiceUtil.getRanking(m_registration.getReference());
<add> m_changeStep.step(rank);
<add> }
<add> }
<add>
<add> public void remove(ServiceReference props, S s) {
<add> System.out.println("+++ A" + m_rank + ".remove: " + s + ", props=" + ServiceUtil.toString(props));
<add> }
<add> }
<add>
<add> // Aspect aware client, depending of "S" service aspects.
<add> static class Client {
<add> private volatile S m_s;
<add> private volatile ServiceReference m_sRef;
<add>
<add> public Client() {
<add> }
<add>
<add> public Dictionary getServiceProperties() {
<add> Dictionary props = new Hashtable();
<add> for (String key : m_sRef.getPropertyKeys()) {
<add> props.put(key, m_sRef.getProperty(key));
<add> }
<add> return props;
<add> }
<add>
<add> public void invoke() {
<add> m_s.invoke();
<add> }
<add>
<add> public String toString() {
<add> return "Client";
<add> }
<add>
<add> public void add(ServiceReference ref, S s) {
<add> System.out.println("+++ Client.add: " + s + "/" + ServiceUtil.toString(ref));
<add> m_s = s;
<add> m_sRef = ref;
<add> }
<add>
<add> public void swap(ServiceReference oldSRef, S oldS, ServiceReference newSRef, S newS) {
<add> System.out.println("+++ Client.swap: new=" + newS + ", props=" + ServiceUtil.toString(newSRef));
<add> Assert.assertTrue(m_s == oldS);
<add> m_s = newS;
<add> m_sRef = newSRef;
<add> }
<add>
<add> public void change(ServiceReference properties, S s) {
<add> System.out.println("+++ Client.change: s=" + s + ", props=" + ServiceUtil.toString(properties));
<add> if (m_changeStep != null) {
<add> m_changeStep.step(ASPECTS+1);
<add> }
<add> }
<add>
<add> public void remove(ServiceReference props, S s) {
<add> System.out.println("+++ Client.remove: " + s + ", props=" + ServiceUtil.toString(props));
<add> }
<add> }
<add>
<add> private int getRandomAspect() {
<add> int index = 0;
<add> do {
<add> index = _rnd.nextInt(ASPECTS);
<add> } while (_randoms.contains(new Integer(index)));
<add> _randoms.add(new Integer(index));
<add> return index;
<add> }
<add>} |
|
JavaScript | mit | f519805e203d25e766e5aa5fc1bd7427b763004d | 0 | atmajs/MaskJS,atmajs/MaskJS,atmajs/MaskJS |
(function() {
var IMPORT = 'import',
IMPORTS = 'imports';
custom_Tags['module'] = class_create({
constructor: function(node, model, ctx, container, ctr) {
var path = path_resolveUrl(node.attr.path, u_resolveLocation(ctx, ctr)),
type = node.attr.type,
endpoint = new Module.Endpoint(path, type);
Module.registerModule(node.nodes, endpoint, ctx, ctr);
},
render: fn_doNothing
});
custom_Tags['import:base'] = function(node, model, ctx, el, ctr){
var base = path_normalize(expression_eval(node.expression, model, ctx, ctr));
if (base != null && base[base.length - 1] !== '/') {
base += '/';
}
Module.cfg('base', base);
};
custom_Tags[IMPORT] = class_create({
meta: {
serializeNodes: true
},
constructor: function(node, model, ctx, el, ctr) {
if (node.alias == null && node.exports == null && Module.isMask(node)) {
// embedding
this.module = Module.createModule(node, ctx, ctr);
}
},
renderStart: function(model, ctx){
if (this.module == null) {
return;
}
var resume = Compo.pause(this, ctx);
var self = this;
this
.module
.loadModule()
.always(function(){
self.scope = self.module.scope;
self.nodes = self.module.exports['__nodes__'];
self.location = self.module.location;
self.getHandler = self.module.getHandler.bind(self.module);
resume();
});
}
});
custom_Tags[IMPORTS] = class_create({
imports_: null,
load_: function(ctx, cb){
var arr = this.imports_,
self = this,
imax = arr.length,
await = imax,
next = cb,
i = -1, x;
function done(error, import_) {
if (error == null) {
if (import_.registerScope) {
import_.registerScope(self);
}
if (ctx._modules != null) {
ctx._modules.add(import_.module);
}
}
if (--await === 0 && next != null) {
next();
}
}
while( ++i < imax ){
x = arr[i];
if (x.async && (--await) === 0) {
next();
next = null;
}
x.loadImport(done);
}
},
start_: function(model, ctx){
var resume = Compo.pause(this, ctx),
nodes = this.nodes,
imax = nodes.length,
i = -1, x
;
var arr = this.imports_ = [];
while( ++i < imax ){
x = nodes[i];
if (x.tagName === IMPORT) {
if (x.path.indexOf('~') !== -1) {
var fn = parser_ensureTemplateFunction(x.path);
if (is_Function(fn)) {
x.path = fn('attr', model, ctx, null, this);
}
}
arr.push(Module.createImport(x, ctx, this));
}
}
this.load_(ctx, resume);
},
// if (NODE)
meta: {
serializeNodes: true
},
serializeNodes: function(){
var arr = [],
i = this.nodes.length, x;
while( --i > -1 ){
x = this.nodes[i];
if (x.tagName === IMPORT) {
arr.push(x);
}
}
return mask_stringify(arr);
},
// endif
renderStart: function(model, ctx){
this.start_(model, ctx);
},
renderStartClient: function(model, ctx){
this.start_(model, ctx);
},
getHandler: function(name){
var arr = this.imports_,
imax = arr.length,
i = -1, import_, x;
while ( ++i < imax ){
import_ = arr[i];
if (import_.type !== 'mask') {
continue;
}
x = import_.getHandler(name);
if (x != null) {
return x;
}
}
return null;
},
getHandlers: function(){
var handlers = {};
var arr = this.imports_,
imax = arr.length,
i = -1, import_, x;
while ( ++i < imax ){
import_ = arr[i];
if (import_ !== 'mask') {
continue;
}
x = import_.getHandlers();
obj_extend(handlers, x);
}
return handlers;
},
});
custom_Tags['await'] = class_create({
progressNodes: null,
completeNodes: null,
errorNodes: null,
namesViaExpr: null,
namesViaAttr: null,
splitNodes_: function(){
var map = {
'@progress': 'progressNodes',
'@fail': 'errorNodes',
'@done': 'completeNodes',
};
coll_each(this.nodes, function(node){
var name = node.tagName,
nodes = node.nodes;
var prop = map[name];
if (prop == null) {
prop = 'completeNodes';
nodes = [ node ];
}
var current = this[prop];
if (current == null) {
this[prop] = nodes;
return;
}
this[prop] = Array
.prototype
.concat
.call(current, nodes);
}, this);
this.nodes = null;
},
getAwaitableNamesViaExpr: function(){
if (this.namesViaExpr != null) {
return this.namesViaExpr;
}
var expr = this.expression;
return this.namesViaExpr = expr == null ? [] : expr
.split(',')
.map(function(x){
return x.trim();
});
},
getAwaitableNamesViaAttr: function(){
if (this.namesViaAttr != null) {
return this.namesViaAttr;
}
var arr = [];
for(var key in this.attr) {
arr.push(key);
}
return this.namesViaAttr = arr;
},
getAwaitableImports: function(){
var namesAttr = this.getAwaitableNamesViaAttr(),
namesExpr = this.getAwaitableNamesViaExpr(),
names = namesAttr.concat(namesExpr);
var imports = Compo.prototype.closest.call(this, 'imports');
if (imports == null) {
this.error_(Error('"imports" not found. "await" should be used within "import" statements.'));
return null;
}
return imports
.imports_
.filter(function(x){
if (x.module.state === 4) {
// loaded
return false;
}
return names.some(function(name){
return x.hasExport(name);
});
});
},
getExports_: function(){
var expr = this.expression;
if (expr != null) {
return expr
.split(',')
.map(function(x){
return x.trim();
});
}
var arr = [];
for(var key in this.attr) {
arr.push(key);
}
return arr;
},
await_: function(ctx, container){
var arr = this.getAwaitableImports();
if (arr == null) {
return;
}
if (arr.length === 0) {
this.complete_();
return;
}
this.progress_(ctx, container);
var resume = Compo.pause(this, ctx),
awaiting = arr.length,
self = this;
coll_each(arr, function(x){
x.module.always(function(){
if (--awaiting === 0) {
self.complete_();
resume();
}
});
});
},
renderStart: function(model, ctx, container){
this.splitNodes_();
this.await_(ctx, container);
},
error_: function(error) {
this.nodes = this.errorNodes || reporter_createErrorNode(error.message);
this.model = error;
},
progress_: function(ctx, container){
var nodes = this.progressNodes;
if (nodes == null) {
return;
}
var hasLiteral = nodes.some(function(x){
return x.type === Dom.TEXTNODE;
});
if (hasLiteral) {
nodes = jmask('div').append(nodes);
}
var node = {
type: Dom.COMPONENT,
nodes: nodes,
controller: new Compo,
attr: {},
};
builder_build(node, null, ctx, container, this);
},
complete_: function(){
var progress = this.components && this.components[0];
if (progress) {
progress.remove();
}
var nodes = this.completeNodes;
var names = this.namesViaAttr;
if (names.length === 1) {
nodes = jmask(names[0]).append(nodes);
}
this.nodes = nodes;
},
});
}());
| src/feature/modules/components.js |
(function() {
var IMPORT = 'import',
IMPORTS = 'imports';
custom_Tags['module'] = class_create({
constructor: function(node, model, ctx, container, ctr) {
var path = path_resolveUrl(node.attr.path, u_resolveLocation(ctx, ctr)),
type = node.attr.type,
endpoint = new Module.Endpoint(path, type);
Module.registerModule(node.nodes, endpoint, ctx, ctr);
},
render: fn_doNothing
});
custom_Tags['import:base'] = function(node, model, ctx, el, ctr){
var base = path_normalize(expression_eval(node.expression, model, ctx, ctr));
if (base != null && base[base.length - 1] !== '/') {
base += '/';
}
Module.cfg('base', base);
};
custom_Tags[IMPORT] = class_create({
meta: {
serializeNodes: true
},
constructor: function(node, model, ctx, el, ctr) {
if (node.alias == null && node.exports == null && Module.isMask(node)) {
// embedding
this.module = Module.createModule(node, ctx, ctr);
}
},
renderStart: function(model, ctx){
if (this.module == null) {
return;
}
var resume = Compo.pause(this, ctx);
var self = this;
this
.module
.loadModule()
.always(function(){
self.scope = self.module.scope;
self.nodes = self.module.source;
self.getHandler = self.module.getHandler.bind(self.module);
resume();
});
}
});
custom_Tags[IMPORTS] = class_create({
imports_: null,
load_: function(ctx, cb){
var arr = this.imports_,
self = this,
imax = arr.length,
await = imax,
next = cb,
i = -1, x;
function done(error, import_) {
if (error == null) {
if (import_.registerScope) {
import_.registerScope(self);
}
if (ctx._modules != null) {
ctx._modules.add(import_.module);
}
}
if (--await === 0 && next != null) {
next();
}
}
while( ++i < imax ){
x = arr[i];
if (x.async && (--await) === 0) {
next();
next = null;
}
x.loadImport(done);
}
},
start_: function(model, ctx){
var resume = Compo.pause(this, ctx),
nodes = this.nodes,
imax = nodes.length,
i = -1, x
;
var arr = this.imports_ = [];
while( ++i < imax ){
x = nodes[i];
if (x.tagName === IMPORT) {
if (x.path.indexOf('~') !== -1) {
var fn = parser_ensureTemplateFunction(x.path);
if (is_Function(fn)) {
x.path = fn('attr', model, ctx, null, this);
}
}
arr.push(Module.createImport(x, ctx, this));
}
}
this.load_(ctx, resume);
},
// if (NODE)
meta: {
serializeNodes: true
},
serializeNodes: function(){
var arr = [],
i = this.nodes.length, x;
while( --i > -1 ){
x = this.nodes[i];
if (x.tagName === IMPORT) {
arr.push(x);
}
}
return mask_stringify(arr);
},
// endif
renderStart: function(model, ctx){
this.start_(model, ctx);
},
renderStartClient: function(model, ctx){
this.start_(model, ctx);
},
getHandler: function(name){
var arr = this.imports_,
imax = arr.length,
i = -1, import_, x;
while ( ++i < imax ){
import_ = arr[i];
if (import_.type !== 'mask') {
continue;
}
x = import_.getHandler(name);
if (x != null) {
return x;
}
}
return null;
},
getHandlers: function(){
var handlers = {};
var arr = this.imports_,
imax = arr.length,
i = -1, import_, x;
while ( ++i < imax ){
import_ = arr[i];
if (import_ !== 'mask') {
continue;
}
x = import_.getHandlers();
obj_extend(handlers, x);
}
return handlers;
},
});
custom_Tags['await'] = class_create({
progressNodes: null,
completeNodes: null,
errorNodes: null,
namesViaExpr: null,
namesViaAttr: null,
splitNodes_: function(){
var map = {
'@progress': 'progressNodes',
'@fail': 'errorNodes',
'@done': 'completeNodes',
};
coll_each(this.nodes, function(node){
var name = node.tagName,
nodes = node.nodes;
var prop = map[name];
if (prop == null) {
prop = 'completeNodes';
nodes = [ node ];
}
var current = this[prop];
if (current == null) {
this[prop] = nodes;
return;
}
this[prop] = Array
.prototype
.concat
.call(current, nodes);
}, this);
this.nodes = null;
},
getAwaitableNamesViaExpr: function(){
if (this.namesViaExpr != null) {
return this.namesViaExpr;
}
var expr = this.expression;
return this.namesViaExpr = expr == null ? [] : expr
.split(',')
.map(function(x){
return x.trim();
});
},
getAwaitableNamesViaAttr: function(){
if (this.namesViaAttr != null) {
return this.namesViaAttr;
}
var arr = [];
for(var key in this.attr) {
arr.push(key);
}
return this.namesViaAttr = arr;
},
getAwaitableImports: function(){
var namesAttr = this.getAwaitableNamesViaAttr(),
namesExpr = this.getAwaitableNamesViaExpr(),
names = namesAttr.concat(namesExpr);
var imports = Compo.prototype.closest.call(this, 'imports');
if (imports == null) {
this.error_(Error('"imports" not found. "await" should be used within "import" statements.'));
return null;
}
return imports
.imports_
.filter(function(x){
if (x.module.state === 4) {
// loaded
return false;
}
return names.some(function(name){
return x.hasExport(name);
});
});
},
getExports_: function(){
var expr = this.expression;
if (expr != null) {
return expr
.split(',')
.map(function(x){
return x.trim();
});
}
var arr = [];
for(var key in this.attr) {
arr.push(key);
}
return arr;
},
await_: function(ctx, container){
var arr = this.getAwaitableImports();
if (arr == null) {
return;
}
if (arr.length === 0) {
this.complete_();
return;
}
this.progress_(ctx, container);
var resume = Compo.pause(this, ctx),
awaiting = arr.length,
self = this;
coll_each(arr, function(x){
x.module.always(function(){
if (--awaiting === 0) {
self.complete_();
resume();
}
});
});
},
renderStart: function(model, ctx, container){
this.splitNodes_();
this.await_(ctx, container);
},
error_: function(error) {
this.nodes = this.errorNodes || reporter_createErrorNode(error.message);
this.model = error;
},
progress_: function(ctx, container){
var nodes = this.progressNodes;
if (nodes == null) {
return;
}
var hasLiteral = nodes.some(function(x){
return x.type === Dom.TEXTNODE;
});
if (hasLiteral) {
nodes = jmask('div').append(nodes);
}
var node = {
type: Dom.COMPONENT,
nodes: nodes,
controller: new Compo,
attr: {},
};
builder_build(node, null, ctx, container, this);
},
complete_: function(){
var progress = this.components && this.components[0];
if (progress) {
progress.remove();
}
var nodes = this.completeNodes;
var names = this.namesViaAttr;
if (names.length === 1) {
nodes = jmask(names[0]).append(nodes);
}
this.nodes = nodes;
},
});
}());
| fix (Modules: Direct Import) Embed only nodes and save module location
| src/feature/modules/components.js | fix (Modules: Direct Import) Embed only nodes and save module location | <ide><path>rc/feature/modules/components.js
<ide> .loadModule()
<ide> .always(function(){
<ide> self.scope = self.module.scope;
<del> self.nodes = self.module.source;
<add> self.nodes = self.module.exports['__nodes__'];
<add> self.location = self.module.location;
<ide> self.getHandler = self.module.getHandler.bind(self.module);
<ide> resume();
<ide> }); |
|
Java | mit | 88a31aaec25668da22b79e5ffad161a9ab967254 | 0 | nousinc/nous-open | package net.nous.open.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import org.json.simple.JSONObject;
/**
* Batched Logback appender for Slack through its webhook api
*/
public class SlackWebhookAppender extends AppenderBase<ILoggingEvent> {
private String webhookUrl;
private URL url;
private String channel;
private String username;
private String iconEmoji;
private Layout<ILoggingEvent> layout;
private int maxLoggingEventLength = 256;
private int maxSlackTextLength = 2048;
private int batchingSecs = 10;
private Queue<ILoggingEvent> eventBuffer = new ConcurrentLinkedQueue<ILoggingEvent>();
private ScheduledExecutorService scheduler;
@Override
public void start() {
if (scheduler == null) {
initializeOrResetScheduler();
}
super.start();
}
private synchronized void initializeOrResetScheduler() {
if (scheduler != null) {
scheduler.shutdownNow();
}
scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new SenderRunnable(), batchingSecs, batchingSecs, TimeUnit.SECONDS);
}
@Override
protected void append(final ILoggingEvent evt) {
addEventToBuffer(evt);
}
private void addEventToBuffer(final ILoggingEvent evt) {
eventBuffer.add(evt);
}
private void sendBufferIfItIsNotEmpty() {
if (eventBuffer.isEmpty())
return;
StringBuffer sbuf = new StringBuffer();
// appending events
ILoggingEvent event = null;
while ((event = eventBuffer.poll()) != null && sbuf.length() <= maxSlackTextLength) {
sbuf.append(extractEventText(event));
}
int remaining = eventBuffer.size();
eventBuffer.clear();
String slackText = trim(sbuf.toString(), maxSlackTextLength, "..\n.. and " + remaining + " more");
sendTextToSlack(slackText);
}
private String trim(String text, int maxLen, String appendingText) {
return text.length() <= maxLen ? text : text.substring(0, maxLen - appendingText.length()) + appendingText;
}
private void sendTextToSlack(String slackText) {
JSONObject obj = null;
try {
obj = new JSONObject();
if (username != null) {
obj.put("username", username);
}
if (iconEmoji != null) {
obj.put("icon_emoji", iconEmoji);
}
if (channel != null) {
obj.put("channel", channel);
}
obj.put("text", slackText);
final byte[] bytes = obj.toJSONString().getBytes("UTF-8");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestProperty("Content-Type", "application/json");
final OutputStream os = conn.getOutputStream();
os.write(bytes);
os.flush();
os.close();
if (conn.getResponseCode() != 200) {
throw new IOException("Bad response code: HTTP/1.0 " + conn.getResponseCode());
}
} catch (Exception ex) {
ex.printStackTrace();
addError("Error to post json object to Slack.com (" + channel + "): " + obj, ex);
}
}
private String extractEventText(ILoggingEvent lastEvent) {
String text = layout.doLayout(lastEvent);
text = trim(text, maxLoggingEventLength, "..");
return text;
}
public String getChannel() {
return channel;
}
public void setChannel(final String channel) {
this.channel = channel;
}
public Layout<ILoggingEvent> getLayout() {
return layout;
}
public void setLayout(final Layout<ILoggingEvent> layout) {
this.layout = layout;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIconEmoji() {
return iconEmoji;
}
public void setIconEmoji(String iconEmoji) {
this.iconEmoji = iconEmoji;
}
public String getWebhookUrl() {
return webhookUrl;
}
/**
* Set your own slack webhock URL here.
* For example: https://mycompany.slack.com/services/hooks/incoming-webhook?token=MY_SLACK_APPENDER_TOKEN
*/
public void setWebhookUrl(String webhookUrl) throws MalformedURLException {
this.webhookUrl = webhookUrl;
this.url = new URL(webhookUrl);
}
private class SenderRunnable implements Runnable {
public void run() {
sendBufferIfItIsNotEmpty();
}
}
public int getMaxLoggingEventLength() {
return maxLoggingEventLength;
}
public void setMaxLoggingEventLength(int maxLoggingEventLength) {
this.maxLoggingEventLength = maxLoggingEventLength;
}
public int getMaxSlackTextLength() {
return maxSlackTextLength;
}
public void setMaxSlackTextLength(int maxSlackTextLength) {
this.maxSlackTextLength = maxSlackTextLength;
}
public int getBatchingSecs() {
return batchingSecs;
}
public void setBatchingSecs(int batchingSecs) {
this.batchingSecs = batchingSecs;
initializeOrResetScheduler();
}
} | src/main/java/net/nous/open/logback/SlackWebhookAppender.java | package net.nous.open.logback;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import org.json.simple.JSONObject;
/**
* Batched Logback appender for Slack through its webhook api
*/
public class SlackWebhookAppender extends AppenderBase<ILoggingEvent> {
private static final int MAX_EVENT_BUFFER_SIZE = 20;
private String webhookUrl;
private URL url;
private String channel;
private String username;
private String iconEmoji;
private Layout<ILoggingEvent> layout;
private int maxLoggingEventLength = 256;
private int maxSlackTextLength = 1024;
private int batchingSecs = 10;
private Queue<ILoggingEvent> eventBuffer = new ConcurrentLinkedQueue<ILoggingEvent>();
private ScheduledExecutorService scheduler;
@Override
public void start() {
if (scheduler == null) {
initializeOrResetScheduler();
}
super.start();
}
private synchronized void initializeOrResetScheduler() {
if (scheduler != null) {
scheduler.shutdownNow();
}
scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new SenderRunnable(), batchingSecs, batchingSecs, TimeUnit.SECONDS);
}
@Override
protected void append(final ILoggingEvent evt) {
addEventToBuffer(evt);
}
private void addEventToBuffer(final ILoggingEvent evt) {
if (eventBuffer.size() < MAX_EVENT_BUFFER_SIZE)
eventBuffer.add(evt);
}
private void sendBufferIfItIsNotEmpty() {
if (eventBuffer.isEmpty())
return;
StringBuffer sbuf = new StringBuffer();
// appending events
while (!eventBuffer.isEmpty()) {
sbuf.append(extractEventText(eventBuffer.poll()));
}
eventBuffer.clear();
String slackText = sbuf.length() <= maxSlackTextLength ? sbuf.toString() : sbuf.substring(0, maxSlackTextLength - 8) + "..\n..\n..";
sendTextToSlack(slackText);
}
private void sendTextToSlack(String slackText) {
JSONObject obj = null;
try {
obj = new JSONObject();
if (username != null) {
obj.put("username", username);
}
if (iconEmoji != null) {
obj.put("icon_emoji", iconEmoji);
}
if (channel != null) {
obj.put("channel", channel);
}
obj.put("text", slackText);
final byte[] bytes = obj.toJSONString().getBytes("UTF-8");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestProperty("Content-Type", "application/json");
final OutputStream os = conn.getOutputStream();
os.write(bytes);
os.flush();
os.close();
if (conn.getResponseCode() != 200) {
throw new IOException("Bad response code: HTTP/1.0 " + conn.getResponseCode());
}
} catch (Exception ex) {
ex.printStackTrace();
addError("Error to post json object to Slack.com (" + channel + "): " + obj, ex);
}
}
private String extractEventText(ILoggingEvent lastEvent) {
String text = layout.doLayout(lastEvent);
text = text.length() <= maxLoggingEventLength ? text : text.substring(0, maxLoggingEventLength-2) + "..";
return text;
}
public String getChannel() {
return channel;
}
public void setChannel(final String channel) {
this.channel = channel;
}
public Layout<ILoggingEvent> getLayout() {
return layout;
}
public void setLayout(final Layout<ILoggingEvent> layout) {
this.layout = layout;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIconEmoji() {
return iconEmoji;
}
public void setIconEmoji(String iconEmoji) {
this.iconEmoji = iconEmoji;
}
public String getWebhookUrl() {
return webhookUrl;
}
/**
* Set your own slack webhock URL here.
* For example: https://mycompany.slack.com/services/hooks/incoming-webhook?token=MY_SLACK_APPENDER_TOKEN
*/
public void setWebhookUrl(String webhookUrl) throws MalformedURLException {
this.webhookUrl = webhookUrl;
this.url = new URL(webhookUrl);
}
private class SenderRunnable implements Runnable {
public void run() {
sendBufferIfItIsNotEmpty();
}
}
public int getMaxLoggingEventLength() {
return maxLoggingEventLength;
}
public void setMaxLoggingEventLength(int maxLoggingEventLength) {
this.maxLoggingEventLength = maxLoggingEventLength;
}
public int getMaxSlackTextLength() {
return maxSlackTextLength;
}
public void setMaxSlackTextLength(int maxSlackTextLength) {
this.maxSlackTextLength = maxSlackTextLength;
}
public int getBatchingSecs() {
return batchingSecs;
}
public void setBatchingSecs(int batchingSecs) {
this.batchingSecs = batchingSecs;
initializeOrResetScheduler();
}
} | better trim messages
| src/main/java/net/nous/open/logback/SlackWebhookAppender.java | better trim messages | <ide><path>rc/main/java/net/nous/open/logback/SlackWebhookAppender.java
<ide> * Batched Logback appender for Slack through its webhook api
<ide> */
<ide> public class SlackWebhookAppender extends AppenderBase<ILoggingEvent> {
<del> private static final int MAX_EVENT_BUFFER_SIZE = 20;
<ide> private String webhookUrl;
<ide> private URL url;
<ide> private String channel;
<ide> private String iconEmoji;
<ide> private Layout<ILoggingEvent> layout;
<ide> private int maxLoggingEventLength = 256;
<del> private int maxSlackTextLength = 1024;
<add> private int maxSlackTextLength = 2048;
<ide> private int batchingSecs = 10;
<ide>
<ide> private Queue<ILoggingEvent> eventBuffer = new ConcurrentLinkedQueue<ILoggingEvent>();
<ide> }
<ide>
<ide> private void addEventToBuffer(final ILoggingEvent evt) {
<del> if (eventBuffer.size() < MAX_EVENT_BUFFER_SIZE)
<del> eventBuffer.add(evt);
<add> eventBuffer.add(evt);
<ide> }
<ide>
<ide> private void sendBufferIfItIsNotEmpty() {
<ide>
<ide> StringBuffer sbuf = new StringBuffer();
<ide> // appending events
<del> while (!eventBuffer.isEmpty()) {
<del> sbuf.append(extractEventText(eventBuffer.poll()));
<add> ILoggingEvent event = null;
<add> while ((event = eventBuffer.poll()) != null && sbuf.length() <= maxSlackTextLength) {
<add> sbuf.append(extractEventText(event));
<ide> }
<del> eventBuffer.clear();
<del> String slackText = sbuf.length() <= maxSlackTextLength ? sbuf.toString() : sbuf.substring(0, maxSlackTextLength - 8) + "..\n..\n..";
<add> int remaining = eventBuffer.size();
<add> eventBuffer.clear();
<add> String slackText = trim(sbuf.toString(), maxSlackTextLength, "..\n.. and " + remaining + " more");
<ide> sendTextToSlack(slackText);
<add> }
<add>
<add> private String trim(String text, int maxLen, String appendingText) {
<add> return text.length() <= maxLen ? text : text.substring(0, maxLen - appendingText.length()) + appendingText;
<ide> }
<ide>
<ide> private void sendTextToSlack(String slackText) {
<ide>
<ide> private String extractEventText(ILoggingEvent lastEvent) {
<ide> String text = layout.doLayout(lastEvent);
<del> text = text.length() <= maxLoggingEventLength ? text : text.substring(0, maxLoggingEventLength-2) + "..";
<add> text = trim(text, maxLoggingEventLength, "..");
<ide> return text;
<ide> }
<ide> |
|
Java | apache-2.0 | 6eac92a1dcdb2ba26b3185551c6161eff3916a39 | 0 | supunucsc/java-sdk,JoshSharpe/java-sdk,watson-developer-cloud/java-sdk,m2fd/java-sdk,m2fd/java-sdk,watson-developer-cloud/java-sdk,watson-developer-cloud/java-sdk,m2fd/java-sdk,watson-developer-cloud/java-sdk,JoshSharpe/java-sdk,supunucsc/java-sdk,supunucsc/java-sdk,JoshSharpe/java-sdk | /**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ibm.watson.developer_cloud.alchemy.v1.model;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage;
/**
* Combined returned by the {@link AlchemyLanguage} service.
*
* @author Nizar Alseddeg ([email protected])
*/
public class CombinedResults extends AlchemyLanguageGenericModel {
/** The author. */
private String author;
/** The concepts. */
private List<Concept> concepts;
/** The entities. */
private List<Entity> entities;
/** The feeds. */
private List<Feed> feeds;
/** The image. */
private String image;
/** The image keywords. */
private List<Keyword> imageKeywords;
/** The keywords. */
private List<Keyword> keywords;
/** The publication date. */
private PublicationDate publicationDate;
/** The relations. */
private SAORelations relations;
/** The doc sentiment. */
@SerializedName("docSentiment")
private Sentiment sentiment;
/** The taxonomy. */
private Taxonomies taxonomy;
/** The title. */
private String title;
/**
* Gets the author.
*
* @return the author
*/
public String getAuthor() {
return author;
}
/**
* Gets the concepts.
*
* @return the concepts
*/
public List<Concept> getConcepts() {
return concepts;
}
/**
* Gets the entities.
*
* @return the entities
*/
public List<Entity> getEntities() {
return entities;
}
/**
* Gets the feeds.
*
* @return the feeds
*/
public List<Feed> getFeeds() {
return feeds;
}
/**
* Gets the image.
*
* @return the image
*/
public String getImage() {
return image;
}
/**
* Gets the image keywords.
*
* @return the imageKeywords
*/
public List<Keyword> getImageKeywords() {
return imageKeywords;
}
/**
* Gets the keywords.
*
* @return the keywords
*/
public List<Keyword> getKeywords() {
return keywords;
}
/**
* Gets the publication date.
*
* @return the publicationDate
*/
public PublicationDate getPublicationDate() {
return publicationDate;
}
/**
* Gets the relations.
*
* @return the relations
*/
public List<SAORelation> getRelations() {
return relations;
}
/**
* Gets the sentiment.
*
* @return the sentiment
*/
public Sentiment getSentiment() {
return sentiment;
}
/**
* Gets the taxonomy.
*
* @return the taxonomy
*/
public List<Taxonomy> getTaxonomy() {
return taxonomy;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() {
return title;
}
/**
* Sets the author.
*
* @param author the author to set
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* Sets the concepts.
*
* @param concepts the concepts to set
*/
public void setConcepts(List<Concept> concepts) {
this.concepts = concepts;
}
/**
* Sets the entities.
*
* @param entities the entities to set
*/
public void setEntities(List<Entity> entities) {
this.entities = entities;
}
/**
* Sets the feeds.
*
* @param feeds the feeds to set
*/
public void setFeeds(List<Feed> feeds) {
this.feeds = feeds;
}
/**
* Sets the image.
*
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
/**
* Sets the image keywords.
*
* @param imageKeywords the imageKeywords to set
*/
public void setImageKeywords(List<Keyword> imageKeywords) {
this.imageKeywords = imageKeywords;
}
/**
* Sets the keywords.
*
* @param keywords the keywords to set
*/
public void setKeywords(List<Keyword> keywords) {
this.keywords = keywords;
}
/**
* Sets the publication date.
*
* @param publicationDate the publicationDate to set
*/
public void setPublicationDate(PublicationDate publicationDate) {
this.publicationDate = publicationDate;
}
/**
* Sets the relations.
*
* @param relations the relations to set
*/
public void setRelations(List<SAORelation> relations) {
this.relations = relations;
}
/**
* Sets the sentiment.
*
* @param sentiment the sentiment to set
*/
public void setSentiment(Sentiment sentiment) {
this.sentiment = sentiment;
}
/**
* Sets the taxonomy.
*
* @param taxonomy the taxonomy to set
*/
public void setTaxonomy(List<Taxonomy> taxonomy) {
this.taxonomy = taxonomy;
}
/**
* Sets the title.
*
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
}
| src/main/java/com/ibm/watson/developer_cloud/alchemy/v1/model/CombinedResults.java | /**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ibm.watson.developer_cloud.alchemy.v1.model;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage;
/**
* Combined returned by the {@link AlchemyLanguage} service.
*
* @author Nizar Alseddeg ([email protected])
*/
public class CombinedResults extends AlchemyLanguageGenericModel {
/** The author. */
private String author;
/** The concepts. */
private List<Concept> concepts;
/** The entities. */
private List<Entity> entities;
/** The feeds. */
private List<Feed> feeds;
/** The image. */
private String image;
/** The image keywords. */
private List<Keyword> imageKeywords;
/** The keywords. */
private List<Keyword> keywords;
/** The publication date. */
private PublicationDate publicationDate;
/** The relations. */
private List<SAORelation> relations;
/** The doc sentiment. */
@SerializedName("docSentiment")
private Sentiment sentiment;
/** The taxonomy. */
private List<Taxonomy> taxonomy;
/** The title. */
private String title;
/**
* Gets the author.
*
* @return the author
*/
public String getAuthor() {
return author;
}
/**
* Gets the concepts.
*
* @return the concepts
*/
public List<Concept> getConcepts() {
return concepts;
}
/**
* Gets the entities.
*
* @return the entities
*/
public List<Entity> getEntities() {
return entities;
}
/**
* Gets the feeds.
*
* @return the feeds
*/
public List<Feed> getFeeds() {
return feeds;
}
/**
* Gets the image.
*
* @return the image
*/
public String getImage() {
return image;
}
/**
* Gets the image keywords.
*
* @return the imageKeywords
*/
public List<Keyword> getImageKeywords() {
return imageKeywords;
}
/**
* Gets the keywords.
*
* @return the keywords
*/
public List<Keyword> getKeywords() {
return keywords;
}
/**
* Gets the publication date.
*
* @return the publicationDate
*/
public PublicationDate getPublicationDate() {
return publicationDate;
}
/**
* Gets the relations.
*
* @return the relations
*/
public List<SAORelation> getRelations() {
return relations;
}
/**
* Gets the sentiment.
*
* @return the sentiment
*/
public Sentiment getSentiment() {
return sentiment;
}
/**
* Gets the taxonomy.
*
* @return the taxonomy
*/
public List<Taxonomy> getTaxonomy() {
return taxonomy;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() {
return title;
}
/**
* Sets the author.
*
* @param author the author to set
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* Sets the concepts.
*
* @param concepts the concepts to set
*/
public void setConcepts(List<Concept> concepts) {
this.concepts = concepts;
}
/**
* Sets the entities.
*
* @param entities the entities to set
*/
public void setEntities(List<Entity> entities) {
this.entities = entities;
}
/**
* Sets the feeds.
*
* @param feeds the feeds to set
*/
public void setFeeds(List<Feed> feeds) {
this.feeds = feeds;
}
/**
* Sets the image.
*
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
/**
* Sets the image keywords.
*
* @param imageKeywords the imageKeywords to set
*/
public void setImageKeywords(List<Keyword> imageKeywords) {
this.imageKeywords = imageKeywords;
}
/**
* Sets the keywords.
*
* @param keywords the keywords to set
*/
public void setKeywords(List<Keyword> keywords) {
this.keywords = keywords;
}
/**
* Sets the publication date.
*
* @param publicationDate the publicationDate to set
*/
public void setPublicationDate(PublicationDate publicationDate) {
this.publicationDate = publicationDate;
}
/**
* Sets the relations.
*
* @param relations the relations to set
*/
public void setRelations(List<SAORelation> relations) {
this.relations = relations;
}
/**
* Sets the sentiment.
*
* @param sentiment the sentiment to set
*/
public void setSentiment(Sentiment sentiment) {
this.sentiment = sentiment;
}
/**
* Sets the taxonomy.
*
* @param taxonomy the taxonomy to set
*/
public void setTaxonomy(List<Taxonomy> taxonomy) {
this.taxonomy = taxonomy;
}
/**
* Sets the title.
*
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
}
| Update CombinedResults.java | src/main/java/com/ibm/watson/developer_cloud/alchemy/v1/model/CombinedResults.java | Update CombinedResults.java | <ide><path>rc/main/java/com/ibm/watson/developer_cloud/alchemy/v1/model/CombinedResults.java
<ide> private PublicationDate publicationDate;
<ide>
<ide> /** The relations. */
<del> private List<SAORelation> relations;
<add> private SAORelations relations;
<ide>
<ide> /** The doc sentiment. */
<ide> @SerializedName("docSentiment")
<ide> private Sentiment sentiment;
<ide>
<ide> /** The taxonomy. */
<del> private List<Taxonomy> taxonomy;
<add> private Taxonomies taxonomy;
<ide>
<ide> /** The title. */
<ide> private String title; |
|
JavaScript | mit | 1e032a2ce14298a112e6724f16b4e7a48bfd48c2 | 0 | qetza/vsts-replacetokens-task,qetza/vsts-replacetokens-task | var gulp = require('gulp');
var debug = require('gulp-debug');
var gutil = require('gulp-util');
var ts = require("gulp-typescript");
var path = require('path');
var shell = require('shelljs');
var minimist = require('minimist');
var semver = require('semver');
var fs = require('fs');
var del = require('del');
var merge = require('merge-stream');
var cp = require('child_process');
var _buildRoot = path.join(__dirname, '_build');
var _packagesRoot = path.join(__dirname, '_packages');
function errorHandler(err) {
process.exit(1);
}
gulp.task('default', ['build']);
gulp.task('build', ['clean', 'compile'], function () {
var extension = gulp.src(['README.md', 'LICENSE.txt', 'images/**/*', '!images/**/*.pdn', 'vss-extension.json'], { base: '.' })
.pipe(debug({title: 'extension:'}))
.pipe(gulp.dest(_buildRoot));
var task = gulp.src(['task/**/*', '!task/**/*.ts'], { base: '.' })
.pipe(debug({title: 'task:'}))
.pipe(gulp.dest(_buildRoot));
getExternalModules();
return merge(extension, task);
});
gulp.task('clean', function() {
return del([_buildRoot]);
});
gulp.task('compile', ['clean'], function() {
var taskPath = path.join(__dirname, 'task', '*.ts');
var tsConfigPath = path.join(__dirname, 'tsconfig.json');
return gulp.src([taskPath], { base: './task' })
.pipe(ts.createProject(tsConfigPath)())
.on('error', errorHandler)
.pipe(gulp.dest(path.join(_buildRoot, 'task')));
});
gulp.task('package', ['build'], function() {
var args = minimist(process.argv.slice(2), {});
var options = {
version: args.ver,
stage: args.stage,
public: args.public,
taskId: args.taskId
}
if (options.version) {
if (options.version === 'auto') {
var ref = new Date(2000, 1, 1);
var now = new Date();
var major = 2
var minor = Math.floor((now - ref) / 86400000);
var patch = Math.floor(Math.floor(now.getSeconds() + (60 * (now.getMinutes() + (60 * now.getHours())))) * 0.5)
options.version = major + '.' + minor + '.' + patch
}
if (!semver.valid(options.version)) {
throw new gutil.PluginError('package', 'Invalid semver version: ' + options.version);
}
}
switch (options.stage) {
case 'dev':
options.taskId = '0664FF86-F509-4392-A33C-B2D9239B9AE5';
options.public = false;
break;
}
updateExtensionManifest(options);
updateTaskManifest(options);
shell.exec('tfx extension create --root "' + _buildRoot + '" --output-path "' + _packagesRoot +'"')
});
getExternalModules = function() {
// copy package.json without dev dependencies
var libPath = path.join(_buildRoot, 'task');
var pkg = require('./package.json');
delete pkg.devDependencies;
fs.writeFileSync(path.join(libPath, 'package.json'), JSON.stringify(pkg, null, 4));
// install modules
var npmPath = shell.which('npm');
shell.pushd(libPath);
{
var cmdline = '"' + npmPath + '" install';
var res = cp.execSync(cmdline);
gutil.log(res.toString());
shell.popd();
}
fs.unlinkSync(path.join(libPath, 'package.json'));
fs.unlinkSync(path.join(libPath, 'package-lock.json'));
}
updateExtensionManifest = function(options) {
var manifestPath = path.join(_buildRoot, 'vss-extension.json')
var manifest = JSON.parse(fs.readFileSync(manifestPath));
if (options.version) {
manifest.version = options.version;
}
if (options.stage) {
manifest.id = manifest.id + '-' + options.stage
manifest.name = manifest.name + ' (' + options.stage + ')'
}
manifest.public = options.public;
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
}
updateTaskManifest = function(options) {
var manifestPath = path.join(_buildRoot, 'task', 'task.json')
var manifest = JSON.parse(fs.readFileSync(manifestPath));
if (options.version) {
manifest.version.Major = semver.major(options.version);
manifest.version.Minor = semver.minor(options.version);
manifest.version.Patch = semver.patch(options.version);
}
manifest.helpMarkDown = 'v' + manifest.version.Major + '.' + manifest.version.Minor + '.' + manifest.version.Patch + ' - ' + manifest.helpMarkDown;
if (options.stage) {
manifest.friendlyName = manifest.friendlyName + ' (' + options.stage
if (options.version) {
manifest.friendlyName = manifest.friendlyName + ' ' + options.version
}
manifest.friendlyName = manifest.friendlyName + ')'
}
if (options.taskId) {
manifest.id = options.taskId
}
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
} | gulpfile.js | var gulp = require('gulp');
var debug = require('gulp-debug');
var gutil = require('gulp-util');
var ts = require("gulp-typescript");
var path = require('path');
var shell = require('shelljs');
var minimist = require('minimist');
var semver = require('semver');
var fs = require('fs');
var del = require('del');
var merge = require('merge-stream');
var cp = require('child_process');
var _buildRoot = path.join(__dirname, '_build');
var _packagesRoot = path.join(__dirname, '_packages');
function errorHandler(err) {
process.exit(1);
}
gulp.task('default', ['build']);
gulp.task('build', ['clean', 'compile'], function () {
var extension = gulp.src(['README.md', 'LICENSE.txt', 'images/**/*', '!images/**/*.pdn', 'vss-extension.json'], { base: '.' })
.pipe(debug({title: 'extension:'}))
.pipe(gulp.dest(_buildRoot));
var task = gulp.src(['task/**/*', '!task/**/*.ts'], { base: '.' })
.pipe(debug({title: 'task:'}))
.pipe(gulp.dest(_buildRoot));
getExternalModules();
return merge(extension, task);
});
gulp.task('clean', function() {
return del([_buildRoot]);
});
gulp.task('compile', ['clean'], function() {
var taskPath = path.join(__dirname, 'task', '*.ts');
var tsConfigPath = path.join(__dirname, 'tsconfig.json');
return gulp.src([taskPath], { base: './task' })
.pipe(ts.createProject(tsConfigPath)())
.on('error', errorHandler)
.pipe(gulp.dest(path.join(_buildRoot, 'task')));
});
gulp.task('package', ['build'], function() {
var args = minimist(process.argv.slice(2), {});
var options = {
version: args.ver,
stage: args.stage,
public: args.public,
taskId: args.taskId
}
if (options.version) {
if (options.version === 'auto') {
var ref = new Date(2000, 1, 1);
var now = new Date();
var major = 2
var minor = Math.floor((now - ref) / 86400000);
var patch = Math.floor(Math.floor(now.getSeconds() + (60 * (now.getMinutes() + (60 * now.getHours())))) * 0.5)
options.version = major + '.' + minor + '.' + patch
}
if (!semver.valid(options.version)) {
throw new gutil.PluginError('package', 'Invalid semver version: ' + options.version);
}
}
switch (options.stage) {
case 'dev':
options.taskId = '0664FF86-F509-4392-A33C-B2D9239B9AE5';
options.public = false;
break;
}
updateExtensionManifest(options);
updateTaskManifest(options);
shell.exec('tfx extension create --root "' + _buildRoot + '" --output-path "' + _packagesRoot +'"')
});
getExternalModules = function() {
// copy package.json without dev dependencies
var libPath = path.join(_buildRoot, 'task');
var pkg = require('./package.json');
delete pkg.devDependencies;
fs.writeFileSync(path.join(libPath, 'package.json'), JSON.stringify(pkg, null, 4));
// install modules
var npmPath = shell.which('npm');
shell.pushd(libPath);
{
var cmdline = '"' + npmPath + '" install';
var res = cp.execSync(cmdline);
gutil.log(res.toString());
shell.popd();
}
fs.unlinkSync(path.join(libPath, 'package.json'));
}
updateExtensionManifest = function(options) {
var manifestPath = path.join(_buildRoot, 'vss-extension.json')
var manifest = JSON.parse(fs.readFileSync(manifestPath));
if (options.version) {
manifest.version = options.version;
}
if (options.stage) {
manifest.id = manifest.id + '-' + options.stage
manifest.name = manifest.name + ' (' + options.stage + ')'
}
manifest.public = options.public;
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
}
updateTaskManifest = function(options) {
var manifestPath = path.join(_buildRoot, 'task', 'task.json')
var manifest = JSON.parse(fs.readFileSync(manifestPath));
if (options.version) {
manifest.version.Major = semver.major(options.version);
manifest.version.Minor = semver.minor(options.version);
manifest.version.Patch = semver.patch(options.version);
}
manifest.helpMarkDown = 'v' + manifest.version.Major + '.' + manifest.version.Minor + '.' + manifest.version.Patch + ' - ' + manifest.helpMarkDown;
if (options.stage) {
manifest.friendlyName = manifest.friendlyName + ' (' + options.stage
if (options.version) {
manifest.friendlyName = manifest.friendlyName + ' ' + options.version
}
manifest.friendlyName = manifest.friendlyName + ')'
}
if (options.taskId) {
manifest.id = options.taskId
}
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 4));
} | Remove unneeded files after build
| gulpfile.js | Remove unneeded files after build | <ide><path>ulpfile.js
<ide> }
<ide>
<ide> fs.unlinkSync(path.join(libPath, 'package.json'));
<add> fs.unlinkSync(path.join(libPath, 'package-lock.json'));
<ide> }
<ide>
<ide> updateExtensionManifest = function(options) { |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.