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
JavaScript
apache-2.0
ba6950d4e02019f02ce8d299453e9729f6b0ef2e
0
indexexchange/Prebid.js,guillaume-sticky/Prebid.js,prebid/Prebid.js,prebid/Prebid.js,atomx/Prebid.js,passit/Prebid.js,SpreeGorilla/Prebid.js,Adikteev/Prebid.js,atomx/Prebid.js,gumgum/Prebid.js,mcallari/Prebid.js,mcallari/Prebid.js,guillaume-sticky/Prebid.js,ImproveDigital/Prebid.js,PWyrembak/Prebid.js,SpreeGorilla/Prebid.js,varashellov/Prebid.js,Somoaudience/Prebid.js,olafbuitelaar/Prebid.js,yieldbot/Prebid.js,nissSK/Prebid.js,yieldbot/Prebid.js,varashellov/Prebid.js,polluxnetwork/Prebid.js,PWyrembak/Prebid.js,tchibirev/Prebid.js,nissSK/Prebid.js,PubWise/Prebid.js,Niksok/Prebid.js,polluxnetwork/Prebid.js,Niksok/Prebid.js,olafbuitelaar/Prebid.js,prebid/Prebid.js,HuddledMasses/Prebid.js,ImproveDigital/Prebid.js,HuddledMasses/Prebid.js,tchibirev/Prebid.js,Adikteev/Prebid.js,ImproveDigital/Prebid.js,gumgum/Prebid.js,indexexchange/Prebid.js,PubWise/Prebid.js,Somoaudience/Prebid.js,PubWise/Prebid.js,PWyrembak/Prebid.js,HuddledMasses/Prebid.js,passit/Prebid.js,gumgum/Prebid.js,Niksok/Prebid.js
import { registerBidder } from 'src/adapters/bidderFactory'; import * as utils from 'src/utils'; const BIDDER_CODE = 'huddledmasses'; const URL = '//huddledmassessupply.com/?c=o&m=multi'; const URL_SYNC = '//huddledmassessupply.com/?c=o&m=cookie'; let sizeObj = { '468x60': 1, '728x90': 2, '300x600': 10, '300x250': 15, '300x100': 19, '320x50': 43, '300x50': 44, '300x300': 48, '300x1050': 54, '970x90': 55, '970x250': 57, '1000x90': 58, '320x80': 59, '640x480': 65, '320x480': 67, '320x320': 72, '320x160': 73, '480x300': 83, '970x310': 94, '970x210': 96, '480x320': 101, '768x1024': 102, '1000x300': 113, '320x100': 117, '800x250': 118, '200x600': 119 }; utils._each(sizeObj, (item, key) => sizeObj[item] = key); export const spec = { code: BIDDER_CODE, /** * Determines whether or not the given bid request is valid. * * @param {object} bid The bid to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: (bid) => { return (!isNaN(bid.params.placement_id) && ((bid.params.sizes !== undefined && bid.params.sizes.length > 0 && bid.params.sizes.some((sizeIndex) => sizeObj[sizeIndex] !== undefined)) || (bid.sizes !== undefined && bid.sizes.length > 0 && bid.sizes.map((size) => `${size[0]}x${size[1]}`).some((size) => sizeObj[size] !== undefined)))); }, /** * Make a server request from the list of BidRequests. * * @param {BidRequest[]} validBidRequests A non-empty list of valid bid requests that should be sent to the Server. * @return ServerRequest Info describing the request to the server. */ buildRequests: (validBidRequests) => { let winTop = window; try { window.top.location.toString(); winTop = window.top; } catch (e) { utils.logMessage(e); }; let location = utils.getTopWindowLocation(); let placements = []; let request = { 'deviceWidth': winTop.screen.width, 'deviceHeight': winTop.screen.height, 'language': (navigator && navigator.language) ? navigator.language : '', 'secure': location.protocol === 'https:' ? 1 : 0, 'host': location.host, 'page': location.pathname, 'placements': placements }; for (let i = 0; i < validBidRequests.length; i++) { let bid = validBidRequests[i]; let placement = {}; placement['placementId'] = bid.params.placement_id; placement['bidId'] = bid.bidId; placement['sizes'] = bid.sizes; placements.push(placement); } return { method: 'POST', url: URL, data: request }; }, /** * Unpack the response from the server into a list of bids. * * @param {*} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: (serverResponse) => { let response = []; try { serverResponse = serverResponse.body; for (let i = 0; i < serverResponse.length; i++) { let resItem = serverResponse[i]; if (resItem.width && !isNaN(resItem.width) && resItem.height && !isNaN(resItem.height) && resItem.requestId && typeof resItem.requestId === 'string' && resItem.cpm && !isNaN(resItem.cpm) && resItem.ad && typeof resItem.ad === 'string' && resItem.ttl && !isNaN(resItem.ttl) && resItem.creativeId && typeof resItem.creativeId === 'string' && resItem.netRevenue && typeof resItem.netRevenue === 'boolean' && resItem.currency && typeof resItem.currency === 'string') { response.push(resItem); } } } catch (e) { utils.logMessage(e); }; return response; }, getUserSyncs: () => { return [{ type: 'image', url: URL_SYNC }]; } }; registerBidder(spec);
modules/huddledmassesBidAdapter.js
import { registerBidder } from 'src/adapters/bidderFactory'; import * as utils from 'src/utils'; const BIDDER_CODE = 'huddledmasses'; const URL = '//huddledmassessupply.com/?c=o&m=multi'; const URL_SYNC = '//huddledmassessupply.com/?c=o&m=cookie'; let sizeObj = { '468x60': 1, '728x90': 2, '300x600': 10, '300x250': 15, '300x100': 19, '320x50': 43, '300x50': 44, '300x300': 48, '300x1050': 54, '970x90': 55, '970x250': 57, '1000x90': 58, '320x80': 59, '640x480': 65, '320x480': 67, '320x320': 72, '320x160': 73, '480x300': 83, '970x310': 94, '970x210': 96, '480x320': 101, '768x1024': 102, '1000x300': 113, '320x100': 117, '800x250': 118, '200x600': 119 }; utils._each(sizeObj, (item, key) => sizeObj[item] = key); export const spec = { code: BIDDER_CODE, /** * Determines whether or not the given bid request is valid. * * @param {object} bid The bid to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: (bid) => { return (!isNaN(bid.params.placement_id) && ((bid.params.sizes !== undefined && bid.params.sizes.length > 0 && bid.params.sizes.some((sizeIndex) => sizeObj[sizeIndex] !== undefined)) || (bid.sizes !== undefined && bid.sizes.length > 0 && bid.sizes.map((size) => `${size[0]}x${size[1]}`).some((size) => sizeObj[size] !== undefined)))); }, /** * Make a server request from the list of BidRequests. * * @param {BidRequest[]} validBidRequests A non-empty list of valid bid requests that should be sent to the Server. * @return ServerRequest Info describing the request to the server. */ buildRequests: (validBidRequests) => { let winTop = window; try { window.top.location.toString(); winTop = window.top; } catch (e) { utils.logMessage(e); }; let location = utils.getTopWindowLocation(); let placements = []; let request = { 'deviceWidth': winTop.screen.width, 'deviceHeight': winTop.screen.height, 'language': navigator ? navigator.language : '', 'secure': location.protocol === 'https:' ? 1 : 0, 'host': location.host, 'page': location.pathname, 'placements': placements }; for (let i = 0; i < validBidRequests.length; i++) { let bid = validBidRequests[i]; let placement = {}; placement['placementId'] = bid.params.placement_id; placement['bidId'] = bid.bidId; placement['sizes'] = bid.sizes; placements.push(placement); } return { method: 'POST', url: URL, data: request }; }, /** * Unpack the response from the server into a list of bids. * * @param {*} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: (serverResponse) => { let response = []; try { serverResponse = serverResponse.body; for (let i = 0; i < serverResponse.length; i++) { let resItem = serverResponse[i]; if (resItem.width && !isNaN(resItem.width) && resItem.height && !isNaN(resItem.height) && resItem.requestId && typeof resItem.requestId === 'string' && resItem.cpm && !isNaN(resItem.cpm) && resItem.ad && typeof resItem.ad === 'string' && resItem.ttl && !isNaN(resItem.ttl) && resItem.creativeId && typeof resItem.creativeId === 'string' && resItem.netRevenue && typeof resItem.netRevenue === 'boolean' && resItem.currency && typeof resItem.currency === 'string') { response.push(resItem); } } } catch (e) { utils.logMessage(e); }; return response; }, getUserSyncs: () => { return [{ type: 'image', url: URL_SYNC }]; } }; registerBidder(spec);
IE bug fix (#1930)
modules/huddledmassesBidAdapter.js
IE bug fix (#1930)
<ide><path>odules/huddledmassesBidAdapter.js <ide> let request = { <ide> 'deviceWidth': winTop.screen.width, <ide> 'deviceHeight': winTop.screen.height, <del> 'language': navigator ? navigator.language : '', <add> 'language': (navigator && navigator.language) ? navigator.language : '', <ide> 'secure': location.protocol === 'https:' ? 1 : 0, <ide> 'host': location.host, <ide> 'page': location.pathname,
Java
apache-2.0
e20cfc8b69344fea56eb186e9b8a474d3f2af4f9
0
jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/scalephant
package de.fernunihagen.dna.jkn.scalephant.storage.entity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fernunihagen.dna.jkn.scalephant.distribution.DistributionGroupName; public class SSTableName { /** * The full name of the table * * Format: dimension_groupname_identifier * * e.g. 3_mydata_mytable2 * */ protected final String fullname; /** * Is the tablename valid? */ protected final boolean valid; /** * The dimension of the table */ protected short dimension; /** * The group of the table */ protected String group; /** * The name of the table */ protected String tablename; /** * The nameprefix */ protected short nameprefix; /** * The value for an invalid dimension */ public final static short INVALID_DIMENSION = -1; /** * The value for an invalid group */ public final static String INVALID_GROUP = null; /** * The value for an invalid table */ public final static String INVALID_TABLENAME = null; /** * The value for an invalid name prefix */ public final static short INVALID_NAMEPEFIX = -1; /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(SSTableName.class); public SSTableName(final String fullname) { super(); this.fullname = fullname; this.valid = splitTablename(); } /** * Split the tablename into the three components * @return */ protected boolean splitTablename() { if(fullname == null) { return false; } final String[] parts = fullname.split("_"); if(parts.length != 3 && parts.length != 4) { logger.warn("Got invalid tablename: "+ fullname); return false; } try { dimension = Short.parseShort(parts[0]); } catch(NumberFormatException e) { logger.warn("Invalid dimension: " + parts[0]); return false; } if(dimension <= 0) { logger.warn("Got invalid dimension: " + dimension); return false; } group = parts[1]; tablename = parts[2]; if(parts.length == 4) { try { nameprefix = Short.parseShort(parts[3]); } catch(NumberFormatException e) { logger.warn("Invalid name prefix: " + parts[3]); return false; } } else { nameprefix = INVALID_NAMEPEFIX; } return true; } /** * Is the tablename valid? * @return */ public boolean isValid() { return valid; } /** * Get the dimension from the tablename * @return */ public short getDimension() { if(! isValid()) { return INVALID_DIMENSION; } return dimension; } /** * Get the group from the tablename * @return */ public String getGroup() { if(! isValid()) { return INVALID_GROUP; } return group; } /** * Get the name of the distribution group * @return */ public String getDistributionGroup() { return dimension + "_" + group; } /** * Get the distribution group as object * @return */ public DistributionGroupName getDistributionGroupObject() { return new DistributionGroupName(getDistributionGroup()); } /** * Get the identifier from the tablename * @return */ public String getTablename() { if(! isValid()) { return INVALID_TABLENAME; } return tablename; } /** * Get the nameprefix of the table * @return */ public short getNameprefix() { return nameprefix; } /** * Is the nameprefix valid? * @return */ public boolean isNameprefixValid() { return nameprefix != INVALID_NAMEPEFIX; } /** * Added getter for the fullname * @return */ public String getFullname() { return fullname; } /** * Get the bytes of the fullname * @return */ public byte[] getFullnameBytes() { return fullname.getBytes(); } @Override public String toString() { return "Tablename [tablename=" + fullname + ", valid=" + valid + ", dimension=" + dimension + ", group=" + group + ", identifier=" + tablename + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + dimension; result = prime * result + ((group == null) ? 0 : group.hashCode()); result = prime * result + ((tablename == null) ? 0 : tablename.hashCode()); result = prime * result + ((fullname == null) ? 0 : fullname.hashCode()); result = prime * result + (valid ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SSTableName other = (SSTableName) obj; if (dimension != other.dimension) return false; if (group == null) { if (other.group != null) return false; } else if (!group.equals(other.group)) return false; if (tablename == null) { if (other.tablename != null) return false; } else if (!tablename.equals(other.tablename)) return false; if (fullname == null) { if (other.fullname != null) return false; } else if (!fullname.equals(other.fullname)) return false; if (valid != other.valid) return false; return true; } }
src/main/java/de/fernunihagen/dna/jkn/scalephant/storage/entity/SSTableName.java
package de.fernunihagen.dna.jkn.scalephant.storage.entity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SSTableName { /** * The full name of the table * * Format: dimension_groupname_identifier * * e.g. 3_mydata_mytable2 * */ protected final String fullname; /** * Is the tablename valid? */ protected final boolean valid; /** * The dimension of the table */ protected short dimension; /** * The group of the table */ protected String group; /** * The name of the table */ protected String tablename; /** * The nameprefix */ protected short nameprefix; /** * The value for an invalid dimension */ public final static short INVALID_DIMENSION = -1; /** * The value for an invalid group */ public final static String INVALID_GROUP = null; /** * The value for an invalid table */ public final static String INVALID_TABLENAME = null; /** * The value for an invalid name prefix */ public final static short INVALID_NAMEPEFIX = -1; /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(SSTableName.class); public SSTableName(final String fullname) { super(); this.fullname = fullname; this.valid = splitTablename(); } /** * Split the tablename into the three components * @return */ protected boolean splitTablename() { if(fullname == null) { return false; } final String[] parts = fullname.split("_"); if(parts.length != 3 && parts.length != 4) { logger.warn("Got invalid tablename: "+ fullname); return false; } try { dimension = Short.parseShort(parts[0]); } catch(NumberFormatException e) { logger.warn("Invalid dimension: " + parts[0]); return false; } if(dimension <= 0) { logger.warn("Got invalid dimension: " + dimension); return false; } group = parts[1]; tablename = parts[2]; if(parts.length == 4) { try { nameprefix = Short.parseShort(parts[3]); } catch(NumberFormatException e) { logger.warn("Invalid name prefix: " + parts[3]); return false; } } else { nameprefix = INVALID_NAMEPEFIX; } return true; } /** * Is the tablename valid? * @return */ public boolean isValid() { return valid; } /** * Get the dimension from the tablename * @return */ public short getDimension() { if(! isValid()) { return INVALID_DIMENSION; } return dimension; } /** * Get the group from the tablename * @return */ public String getGroup() { if(! isValid()) { return INVALID_GROUP; } return group; } /** * Get the name of the distribution group * @return */ public String getDistributionGroup() { return dimension + "_" + group; } /** * Get the identifier from the tablename * @return */ public String getTablename() { if(! isValid()) { return INVALID_TABLENAME; } return tablename; } /** * Get the nameprefix of the table * @return */ public short getNameprefix() { return nameprefix; } /** * Is the nameprefix valid? * @return */ public boolean isNameprefixValid() { return nameprefix != INVALID_NAMEPEFIX; } /** * Added getter for the fullname * @return */ public String getFullname() { return fullname; } /** * Get the bytes of the fullname * @return */ public byte[] getFullnameBytes() { return fullname.getBytes(); } @Override public String toString() { return "Tablename [tablename=" + fullname + ", valid=" + valid + ", dimension=" + dimension + ", group=" + group + ", identifier=" + tablename + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + dimension; result = prime * result + ((group == null) ? 0 : group.hashCode()); result = prime * result + ((tablename == null) ? 0 : tablename.hashCode()); result = prime * result + ((fullname == null) ? 0 : fullname.hashCode()); result = prime * result + (valid ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SSTableName other = (SSTableName) obj; if (dimension != other.dimension) return false; if (group == null) { if (other.group != null) return false; } else if (!group.equals(other.group)) return false; if (tablename == null) { if (other.tablename != null) return false; } else if (!tablename.equals(other.tablename)) return false; if (fullname == null) { if (other.fullname != null) return false; } else if (!fullname.equals(other.fullname)) return false; if (valid != other.valid) return false; return true; } }
Added getDistributionGroupAsObject method
src/main/java/de/fernunihagen/dna/jkn/scalephant/storage/entity/SSTableName.java
Added getDistributionGroupAsObject method
<ide><path>rc/main/java/de/fernunihagen/dna/jkn/scalephant/storage/entity/SSTableName.java <ide> <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <add> <add>import de.fernunihagen.dna.jkn.scalephant.distribution.DistributionGroupName; <ide> <ide> public class SSTableName { <ide> <ide> */ <ide> public String getDistributionGroup() { <ide> return dimension + "_" + group; <add> } <add> <add> /** <add> * Get the distribution group as object <add> * @return <add> */ <add> public DistributionGroupName getDistributionGroupObject() { <add> return new DistributionGroupName(getDistributionGroup()); <ide> } <ide> <ide> /**
JavaScript
mit
b11f69f735552801663f72454a78a648ae9b8283
0
cicadas-2014/EmotionAll,cicadas-2014/EmotionAll
var Map = { dataInput: [], defaultView: function(topic, mapData) { var self = this; $('#map-container').highcharts('Map', { title: { text: topic, style: { color: '#0099CC', font: '24px "HelveticaNeue-Thin", "HelveticaNeue", Arial, sans-serif' } }, mapNavigation: { enabled: true, buttonOptions: { align: 'right', verticalAlign: 'bottom' } }, colorAxis: { type: 'linear', endOnTick: false, startOnTick: false, min: -1, max: 1, stops: [ [0, '#DC381F'], [0.5, '#FFFFFF'], [1, '#32CD32'] ], // minColor: '#FF0000', // maxColor: '#00FF00' }, colors: ['#FFF9E4'], tooltip: { animation: true, pointFormat: '{point.name}: {point.value}', shadow: false }, legend: { align: 'center', itemWidth: 200, reversed: false, }, plotOptions: { series: { joinBy: ['iso-a2', 'code'], }, states: { hover: { enabled: true }, select: { borderColor: 'black', dashStyle: 'shortdot', color: '#FFF9E4' } } }, series: [{ data: self.dataInput, mapData: mapData, name: 'Sentiment Index' }] }) } }; var createMapView = { init: function(trend, tweetData) { var map = Highcharts.maps['custom/world']; var mapData = Highcharts.geojson(map); this.inputData(tweetData); this.layoutMap(trend, mapData); }, inputData: function(data) { Map.dataInput = []; for (var i in data) { Map.dataInput.push(data[i]); } }, layoutMap: function(topic, mapData) { Map.defaultView(topic, mapData); } };
app/assets/javascripts/highChart.js
var Map = { dataInput: [], defaultView: function(topic, mapData) { var self = this; $('#map-container').highcharts('Map', { title: { text: topic, style: { color: '#0099CC', font: '24px "HelveticaNeue-Thin", "HelveticaNeue", Arial, sans-serif' } }, mapNavigation: { enabled: true, buttonOptions: { align: 'right', verticalAlign: 'bottom' } }, colorAxis: { type: 'linear', endOnTick: false, startOnTick: false, min: -1, max: 1, stops: [ [0, '#DC381F'], [0.5, '#FFFFFF'], [1, '#70DB93'] ], // minColor: '#FF0000', // maxColor: '#00FF00' }, colors: ['#FFF9E4'], tooltip: { animation: true, pointFormat: '{point.name}: {point.value}', shadow: false }, legend: { align: 'center', itemWidth: 200, reversed: false, }, plotOptions: { series: { joinBy: ['iso-a2', 'code'], }, states: { hover: { enabled: true }, select: { borderColor: 'black', dashStyle: 'shortdot', color: '#FFF9E4' } } }, series: [{ data: self.dataInput, mapData: mapData, name: 'Sentiment Index' }] }) } }; var createMapView = { init: function(trend, tweetData) { var map = Highcharts.maps['custom/world']; var mapData = Highcharts.geojson(map); this.inputData(tweetData); this.layoutMap(trend, mapData); }, inputData: function(data) { Map.dataInput = []; for (var i in data) { Map.dataInput.push(data[i]); } }, layoutMap: function(topic, mapData) { Map.defaultView(topic, mapData); } };
change min/max map legend
app/assets/javascripts/highChart.js
change min/max map legend
<ide><path>pp/assets/javascripts/highChart.js <ide> stops: [ <ide> [0, '#DC381F'], <ide> [0.5, '#FFFFFF'], <del> [1, '#70DB93'] <add> [1, '#32CD32'] <ide> ], <ide> // minColor: '#FF0000', <ide> // maxColor: '#00FF00'
Java
epl-1.0
517e7ef36699248e8803351f8cf3796d3ecdcfcd
0
Beagle-PSE/Beagle,Beagle-PSE/Beagle,Beagle-PSE/Beagle
package de.uka.ipd.sdq.beagle.analysis; import de.uka.ipd.sdq.beagle.core.Blackboard; import de.uka.ipd.sdq.beagle.core.BlackboardStorer; import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction; import de.uka.ipd.sdq.beagle.core.SEFFBranch; import de.uka.ipd.sdq.beagle.core.SEFFLoop; import de.uka.ipd.sdq.beagle.core.expressions.EvaluableExpression; import de.uka.ipd.sdq.beagle.measurement.BranchDecisionMeasurementResult; import de.uka.ipd.sdq.beagle.measurement.ResourceDemandMeasurementResult; import java.io.Serializable; import java.util.Set; /** * View of the {@link Blackboard} designed to be used by {@link ResultAnalyser}. Reading * information and adding proposed expressions to the {@link Blackboard} is supported. * * @author Christoph Michelbach * * @see Blackboard for information about Blackboard views * */ public class AnalyserBlackboardView { /** * Creates a new {@code AnalyserBlackboardView} for {@code blackboard}. * * @param blackboard The {@link Blackboard} to be accessed through the * {@code AnalyserBlackboardView}. */ public AnalyserBlackboardView(final Blackboard blackboard) { } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllRDIAs()}. * * @return all {@linkplain ResourceDemandingInternalAction resource demanding internal * actions} known to Beagle. Changes to the returned set will not modify the * blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllRDIAs() */ public Set<ResourceDemandingInternalAction> getAllRDIAs() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#writeFor(WRITTEN_TYPE, WRITTEN_TYPE)}. * * @param writer The class the data should be written for. Must not be {@code null}. * @param written The data to write. * @param <WRITTEN_TYPE> {@code written}’s type. * @see de.uka.ipd.sdq.beagle.core.Blackboard#writeFor() */ public <WRITTEN_TYPE extends Serializable> void writeFor( final Class<? extends BlackboardStorer<WRITTEN_TYPE>> writer, final WRITTEN_TYPE written) { } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFLoop)}. * * @param loop A SEFF Loop to get the measurement results of. Must not be {@code null} * . * @return All measurement results reported for {@code loop}. Changes to the returned * set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFLoop) */ public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(final SEFFLoop loop) { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFBranch)}. * * @param branch A SEFF Branch to get the measurement results of. Must not be * {@code null}. * @return All measurement results reported for {@code branch}. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFBranch) */ public Set<BranchDecisionMeasurementResult> getMeasurementResultsFor(final SEFFBranch branch) { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction)} * . * * @param rdia An resource demanding internal action to get the measuremnt results of. * Must not be {@code null}. * @return All measurement results reported for {@code rdia}. Changes to the returned * set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction) */ public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(final ResourceDemandingInternalAction rdia) { return null; } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches()}. * * @return all {@linkplain SEFFBranch SEFF branches} known to Beagle. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches() */ public Set<SEFFBranch> getAllSEFFBranches() { return null; } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFLoops()}. * * @return all {@linkplain SEFFLoop SEFF loops} known to Beagle. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFLoops() */ public Set<SEFFLoop> getAllSEFFLoops() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(ResourceDemandingInternalAction, EvaluableExpression)} * . * * @param rdia A resource demanding internal action. Must not be {@code null}. * @param expression An evaluable expression proposed to describe {@code rdia}’s * measurement results. Must not be {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(ResourceDemandingInternalAction, * EvaluableExpression) */ public void proposeExpressionFor(final ResourceDemandingInternalAction rdia, final EvaluableExpression expression) { } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFLoop, EvaluableExpression)} * . * * @param loop A SEFF Loop. Must not be {@code null}. * @param expression An evaluable expression proposed to describe {@code loop}’s * measurement results. Must not be {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFLoop, * EvaluableExpression) */ public void proposeExpressionFor(final SEFFLoop loop, final EvaluableExpression expression) { } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFBranch, EvaluableExpression)} * . * * @param branch A SEFF Branch. Must not be {@code null}. * @param expression An evaluable expression proposed to describe {@code branch}’s * measurement results. Must not be {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFBranch, * EvaluableExpression) */ public void proposeExpressionFor(final SEFFBranch branch, final EvaluableExpression expression) { } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getRDIAsToBeMeasured()}. * * @return All {@linkplain ResourceDemandingInternalAction resource demanding internal * actions} to be measured. Changes to the returned set will not modify the * blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getRDIAsToBeMeasured() */ public Set<ResourceDemandingInternalAction> getRDIAsToBeMeasured() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFBranchesToBeMeasured()}. * * @return All {@linkplain SEFFBranch SEFF branches} to be measured. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFBranchesToBeMeasured() */ public Set<SEFFBranch> getSEFFBranchesToBeMeasured() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFLoopsToBeMeasured()}. * * @return All {@linkplain SEFFLoop SEFF loops} to be measured. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFLoopsToBeMeasured() */ public Set<SEFFLoop> getSEFFLoopsToBeMeasured() { return null; } }
src/main/java/de/uka/ipd/sdq/beagle/analysis/AnalyserBlackboardView.java
package de.uka.ipd.sdq.beagle.analysis; import de.uka.ipd.sdq.beagle.core.Blackboard; import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction; import de.uka.ipd.sdq.beagle.core.SEFFBranch; import de.uka.ipd.sdq.beagle.core.SEFFLoop; import de.uka.ipd.sdq.beagle.core.expressions.EvaluableExpression; import java.util.Set; /** * View of the {@link Blackboard} designed to be used by {@link ResultAnalyser}. Reading * information and adding proposed expressions to the {@link Blackboard} is supported. * * @author Christoph Michelbach * * @see Blackboard for information about Blackboard views * */ public class AnalyserBlackboardView { /** * Creates a new {@code AnalyserBlackboardView} for {@code blackboard}. * * @param blackboard The {@link Blackboard} to be accessed through the * {@code AnalyserBlackboardView}. */ public AnalyserBlackboardView(final Blackboard blackboard) { } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllRDIAs()}. * * @return all {@linkplain ResourceDemandingInternalAction resource demanding internal * actions} known to Beagle. Changes to the returned set will not modify the * blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllRDIAs() */ public Set<ResourceDemandingInternalAction> getAllRDIAs() { return null; } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches()}. * * @return all {@linkplain SEFFBranch SEFF branches} known to Beagle. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches() */ public Set<SEFFBranch> getAllSEFFBranches() { return null; } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFLoops()}. * * @return all {@linkplain SEFFLoop SEFF loops} known to Beagle. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFLoops() */ public Set<SEFFLoop> getAllSEFFLoops() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(ResourceDemandingInternalAction, EvaluableExpression)} * . * * @param rdia A resource demanding internal action. Must not be {@code null}. * @param expression An evaluable expression proposed to describe {@code rdia}’s * measurement results. Must not be {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(ResourceDemandingInternalAction, * EvaluableExpression) */ public void proposeExpressionFor(final ResourceDemandingInternalAction rdia, final EvaluableExpression expression) { } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFLoop, EvaluableExpression)} * . * * @param loop A SEFF Loop. Must not be {@code null}. * @param expression An evaluable expression proposed to describe {@code loop}’s * measurement results. Must not be {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFLoop, * EvaluableExpression) */ public void proposeExpressionFor(final SEFFLoop loop, final EvaluableExpression expression) { } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFBranch, EvaluableExpression)} * . * * @param branch A SEFF Branch. Must not be {@code null}. * @param expression An evaluable expression proposed to describe {@code branch}’s * measurement results. Must not be {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#proposeExpressionFor(SEFFBranch, * EvaluableExpression) */ public void proposeExpressionFor(final SEFFBranch branch, final EvaluableExpression expression) { } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getRDIAsToBeMeasured()}. * * @return All {@linkplain ResourceDemandingInternalAction resource demanding internal * actions} to be measured. Changes to the returned set will not modify the * blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getRDIAsToBeMeasured() */ public Set<ResourceDemandingInternalAction> getRDIAsToBeMeasured() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFBranchesToBeMeasured()}. * * @return All {@linkplain SEFFBranch SEFF branches} to be measured. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFBranchesToBeMeasured() */ public Set<SEFFBranch> getSEFFBranchesToBeMeasured() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFLoopsToBeMeasured()}. * * @return All {@linkplain SEFFLoop SEFF loops} to be measured. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFLoopsToBeMeasured() */ public Set<SEFFLoop> getSEFFLoopsToBeMeasured() { return null; } }
Added new methods to `AnalyserBlackboardView`.
src/main/java/de/uka/ipd/sdq/beagle/analysis/AnalyserBlackboardView.java
Added new methods to `AnalyserBlackboardView`.
<ide><path>rc/main/java/de/uka/ipd/sdq/beagle/analysis/AnalyserBlackboardView.java <ide> package de.uka.ipd.sdq.beagle.analysis; <ide> <ide> import de.uka.ipd.sdq.beagle.core.Blackboard; <add>import de.uka.ipd.sdq.beagle.core.BlackboardStorer; <ide> import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction; <ide> import de.uka.ipd.sdq.beagle.core.SEFFBranch; <ide> import de.uka.ipd.sdq.beagle.core.SEFFLoop; <ide> import de.uka.ipd.sdq.beagle.core.expressions.EvaluableExpression; <del> <add>import de.uka.ipd.sdq.beagle.measurement.BranchDecisionMeasurementResult; <add>import de.uka.ipd.sdq.beagle.measurement.ResourceDemandMeasurementResult; <add> <add>import java.io.Serializable; <ide> import java.util.Set; <ide> <ide> /** <ide> } <ide> <ide> /** <add> * Delegates to <add> * {@link de.uka.ipd.sdq.beagle.core.Blackboard#writeFor(WRITTEN_TYPE, WRITTEN_TYPE)}. <add> * <add> * @param writer The class the data should be written for. Must not be {@code null}. <add> * @param written The data to write. <add> * @param <WRITTEN_TYPE> {@code written}’s type. <add> * @see de.uka.ipd.sdq.beagle.core.Blackboard#writeFor() <add> */ <add> public <WRITTEN_TYPE extends Serializable> void writeFor( <add> final Class<? extends BlackboardStorer<WRITTEN_TYPE>> writer, final WRITTEN_TYPE written) { <add> } <add> <add> /** <add> * Delegates to <add> * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFLoop)}. <add> * <add> * @param loop A SEFF Loop to get the measurement results of. Must not be {@code null} <add> * . <add> * @return All measurement results reported for {@code loop}. Changes to the returned <add> * set will not modify the blackboard content. Is never {@code null}. <add> * @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFLoop) <add> */ <add> public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(final SEFFLoop loop) { <add> return null; <add> } <add> <add> /** <add> * Delegates to <add> * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFBranch)}. <add> * <add> * @param branch A SEFF Branch to get the measurement results of. Must not be <add> * {@code null}. <add> * @return All measurement results reported for {@code branch}. Changes to the <add> * returned set will not modify the blackboard content. Is never {@code null}. <add> * @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(SEFFBranch) <add> */ <add> public Set<BranchDecisionMeasurementResult> getMeasurementResultsFor(final SEFFBranch branch) { <add> return null; <add> } <add> <add> /** <add> * Delegates to <add> * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction)} <add> * . <add> * <add> * @param rdia An resource demanding internal action to get the measuremnt results of. <add> * Must not be {@code null}. <add> * @return All measurement results reported for {@code rdia}. Changes to the returned <add> * set will not modify the blackboard content. Is never {@code null}. <add> * @see de.uka.ipd.sdq.beagle.core.Blackboard#getMeasurementResultsFor(ResourceDemandingInternalAction) <add> */ <add> public Set<ResourceDemandMeasurementResult> getMeasurementResultsFor(final ResourceDemandingInternalAction rdia) { <add> return null; <add> } <add> <add> /** <ide> * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches()}. <ide> * <ide> * @return all {@linkplain SEFFBranch SEFF branches} known to Beagle. Changes to the
JavaScript
apache-2.0
b86b024207fa6a597330d7557b99f92fd2b0bdc8
0
pivotal-energy-solutions/django-appsearch,pivotal-energy-solutions/django-appsearch,pivotal-energy-solutions/django-appsearch,pivotal-energy-solutions/django-appsearch
// Depends on formset.js (function($){ $.fn.appsearch = function(opts){ var options = $.extend({}, $.fn.appsearch.defaults, opts); var form = this; var _option_template = $("<option />") form.data('options', options); options.modelSelect.on('change.appsearch', function(){ // Model has changed; trigger field list update var select = $(this); var value = select.val(); if (value == '') { form.find('.constraint-form').slideUp('fast', function(){ $(this).find('.delete-row').click(); }) } else { form.trigger('update-field-list'); form.trigger('configure-formset'); } }); form.find('.constraint-field select').on('change.appsearch', function(){ // Field has changed; trigger operator list update for the target constraint var select = $(this); var option = select.find(':selected'); var constraintForm = select.closest('.constraint-form'); form.trigger('update-operator-list', [constraintForm]); // Set the description text var fieldType = option.attr('data-type'); var fieldText = option.text(); var fieldValue = option.val(); var termInputs = constraintForm.find('.term input'); var descriptionBox = constraintForm.find('.description'); form.trigger('field-updated', [termInputs, fieldType, fieldText, fieldValue, constraintForm]); form.trigger('set-field-description', [descriptionBox, fieldType, fieldText, fieldValue, constraintForm]); }); form.find('.constraint-operator select').on('change.appsearch', function(){ var select = $(this); var option = select.find(':selected'); var value = select.val(); var constraintForm = select.closest('.constraint-form') var termInputs = constraintForm.find('.term'); if (options.termlessOperators.indexOf(value) != -1) { // termless operator; hide inputs termInputs.slideUp('fast'); } else { if (options.twoTermOperators.indexOf(value) != -1) { // two-term operator; show both inputs termInputs.slideDown('fast'); } else { // one-term operator; hide second input termInputs.filter('.begin-term').slideDown('fast'); termInputs.filter('.end-term').slideUp('fast'); } } }); form.on('configure-formset.appsearch', function(){ // Re-initialize the formset after stripping out the add/remove links form.find('.add-row,.delete-row').remove(); // formset.js form.find('.constraint-form').formset(options.formsetOptions); // formset.js }); form.on('update-field-list.appsearch', function(e){ // Default handler that tries to call a user-supplied function or else the default one (options.updateFieldList || function(){ var modelSelect = form.find('#model-select-wrapper select') var modelValue = modelSelect.val(); var choices = (options.getFields || $.fn.appsearch._getFields)(form, modelValue); // Remove all constraint forms but the first one. var constraintForms = form.find('.constraint-form'); constraintForms.slice(1).slideUp('fast', function(){ $(this).find('.delete-row').click(); // formset.js }); // 1 or 0 remaining constraint-form divs; make sure 1 exists var constraintForm = constraintForms.eq(0); if (constraintForm.size() == 0) { form.find('.add-row').click(); // formset.js constraintForm = form.find('.constraint-form'); } // Set the field <option> choices var fieldSelect = constraintForm.find('.constraint-field select'); fieldSelect.empty(); for (var i = 0; i < choices.length; i++) { var info = choices[i]; var option = _option_template.clone().val(info[0]).text(info[1]); option.attr('data-type', info[2]); fieldSelect.append(option); } fieldSelect.change(); // Ask for the operator list to update according to the form's field form.trigger('update-operator-list', [constraintForm]); })(e); }); form.on('update-operator-list.appsearch', function(e, constraintForm){ (options.updateOperatorList || function(e, constraintForm){ var fieldSelect = constraintForm.find('.constraint-field select'); var modelValue = options.modelSelect.val(); var fieldValue = fieldSelect.val(); var choices = (options.getOperators || $.fn.appsearch._getOperators)(form, modelValue, fieldValue); var operatorSelect = constraintForm.find('.constraint-operator select').empty(); for (var i = 0; i < choices.length; i++) { operatorSelect.append(_option_template.clone().val(choices[i]).text(choices[i])); } // Propagate change through the operator <select>, updating the term fields operatorSelect.change(); })(e, constraintForm); }); form.on('set-field-description.appsearch', function(e, descriptionBox, type, text, value, constraintForm){ (options.setFieldDescription || function(){ var description; if (type == "text") { description = "Text"; } else if (type == "date") { description = "Date"; } else if (type == "number") { description = "Number"; } else if (type == "boolean") { description = "true or false" // TODO: Change term input to <select> somewhere... } else { console.warn("Unknown field type:", type); } descriptionBox.text(description); })(e, descriptionBox, type, text, value, constraintForm); }); // Make sure preloaded form data is immediately validated. form.trigger('configure-formset'); // Make the form available for chained calls return this; }; $.fn.appsearch._getFields = function(form, modelValue){ var choices = null; $.ajax(form.data('options').constraintFieldDataURL, { data: {'model': modelValue}, async: false, success: function(response){ choices = response.choices; }, error: function(){ choices = []; } }); return choices; }; $.fn.appsearch._getOperators = function(form, modelValue, fieldValue){ var choices = null; $.ajax(form.data('options').constraintOperatorDataURL, { data: {'model': modelValue, 'field': fieldValue}, async: false, success: function(response){ choices = response.choices; }, error: function(){ choices = []; } }); return choices; }; $.fn.appsearch.defaults = { 'constraintFieldDataURL': null, 'constraintOperatorDataURL': null, 'modelSelect': null, 'modelSelectedCallback': null, 'updateFieldList': null, 'updateOperatorList': null, 'constraintFormChanged': null, 'setFieldDescription': null, 'getFields': null, 'getOperators': null, 'termlessOperators': ["exists", "doesn't exist"], 'twoTermOperators': ["between"], 'formsetOptions': null, }; })(jQuery);
appsearch/static/js/jquery.appsearch.js
// Depends on formset.js (function($){ $.fn.appsearch = function(opts){ var options = $.extend({}, $.fn.appsearch.defaults, opts); var form = this; var _option_template = $("<option />") form.data('options', options); options.modelSelect.on('change.appsearch', function(){ // Model has changed; trigger field list update var select = $(this); var value = select.val(); if (value == '') { form.find('.constraint-form').slideUp('fast', function(){ $(this).find('.delete-row').click(); }) } else { form.trigger('update-field-list'); form.trigger('configure-formset'); } }); form.find('.constraint-field select').on('change.appsearch', function(){ // Field has changed; trigger operator list update for the target constraint var select = $(this); var option = select.find(':selected'); var constraintForm = select.closest('.constraint-form'); form.trigger('update-operator-list', [constraintForm]); // Set the description text var fieldType = option.attr('data-type'); var fieldText = option.text(); var fieldValue = option.val(); var termInputs = constraintForm.find('.term input'); var descriptionBox = constraintForm.find('.description'); form.trigger('field-updated', [termInputs, fieldType, fieldText, fieldValue, constraintForm]); form.trigger('set-field-description', [descriptionBox, fieldType, fieldText, fieldValue, constraintForm]); }); form.find('.constraint-operator select').on('change.appsearch', function(){ var select = $(this); var option = select.find(':selected'); var value = select.val(); var constraintForm = select.closest('.constraint-form') var termInputs = constraintForm.find('.term'); if (options.termlessOperators.indexOf(value) != -1) { // termless operator; hide inputs termInputs.slideUp('fast'); } else { if (options.twoTermOperators.indexOf(value) != -1) { // two-term operator; show both inputs termInputs.slideDown('fast'); } else { // one-term operator; hide second input termInputs.filter('.begin-term').slideDown('fast'); termInputs.filter('.end-term').slideUp('fast'); } } }); form.on('configure-formset.appsearch', function(){ // Re-initialize the formset after stripping out the add/remove links form.find('.add-row,.delete-row').remove(); // formset.js form.find('.constraint-form').formset(options.formsetOptions); // formset.js }); form.on('update-field-list.appsearch', function(e){ // Default handler that tries to call a user-supplied function or else the default one (options.updateFieldList || function(){ var modelSelect = form.find('#model-select-wrapper select') var modelValue = modelSelect.val(); var choices = (options.getFields || $.fn.appsearch._getFields)(form, modelValue); // Remove all constraint forms but the first one. var constraintForms = form.find('.constraint-form'); constraintForms.slice(1).slideUp('fast', function(){ $(this).find('.delete-row').click(); // formset.js }); // 1 or 0 remaining constraint-form divs; make sure 1 exists var constraintForm = constraintForms.eq(0); if (constraintForm.size() == 0) { form.find('.add-row').click(); // formset.js constraintForm = form.find('.constraint-form'); } // Set the field <option> choices var fieldSelect = constraintForm.find('.constraint-field select'); fieldSelect.empty(); for (var i = 0; i < choices.length; i++) { var info = choices[i]; var option = _option_template.clone().val(info[0]).text(info[1]); option.attr('data-type', info[2]); fieldSelect.append(option); } fieldSelect.change(); // Ask for the operator list to update according to the form's field form.trigger('update-operator-list', [constraintForm]); })(e); }); form.on('update-operator-list.appsearch', function(e, constraintForm){ (options.updateOperatorList || function(e, constraintForm){ var fieldSelect = constraintForm.find('.constraint-field select'); var modelValue = options.modelSelect.val(); var fieldValue = fieldSelect.val(); var choices = (options.getOperators || $.fn.appsearch._getOperators)(form, modelValue, fieldValue); var operatorSelect = constraintForm.find('.constraint-operator select').empty(); for (var i = 0; i < choices.length; i++) { operatorSelect.append(_option_template.clone().val(choices[i]).text(choices[i])); } // Propagate change through the operator <select>, updating the term fields operatorSelect.change(); })(e, constraintForm); }); form.on('set-field-description.appsearch', function(e, descriptionBox, type, text, value, constraintForm){ (options.setFieldDescription || function(){ var description; if (type == "text") { description = "Text"; } else if (type == "date") { description = "Date format: MM-DD-YYYY"; } else if (type == "number") { description = "Number"; } else if (type == "boolean") { description = "true or false" // TODO: Change term input to <select> somewhere... } else { console.warn("Unknown field type:", type); } descriptionBox.text(description); })(e, descriptionBox, type, text, value, constraintForm); }); // Make sure preloaded form data is immediately validated. form.trigger('configure-formset'); // Make the form available for chained calls return this; }; $.fn.appsearch._getFields = function(form, modelValue){ var choices = null; $.ajax(form.data('options').constraintFieldDataURL, { data: {'model': modelValue}, async: false, success: function(response){ choices = response.choices; }, error: function(){ choices = []; } }); return choices; }; $.fn.appsearch._getOperators = function(form, modelValue, fieldValue){ var choices = null; $.ajax(form.data('options').constraintOperatorDataURL, { data: {'model': modelValue, 'field': fieldValue}, async: false, success: function(response){ choices = response.choices; }, error: function(){ choices = []; } }); return choices; }; $.fn.appsearch.defaults = { 'constraintFieldDataURL': null, 'constraintOperatorDataURL': null, 'modelSelect': null, 'modelSelectedCallback': null, 'updateFieldList': null, 'updateOperatorList': null, 'constraintFormChanged': null, 'setFieldDescription': null, 'getFields': null, 'getOperators': null, 'termlessOperators': ["exists", "doesn't exist"], 'twoTermOperators': ["between"], 'formsetOptions': null, }; })(jQuery);
Make date description generic
appsearch/static/js/jquery.appsearch.js
Make date description generic
<ide><path>ppsearch/static/js/jquery.appsearch.js <ide> if (type == "text") { <ide> description = "Text"; <ide> } else if (type == "date") { <del> description = "Date format: MM-DD-YYYY"; <add> description = "Date"; <ide> } else if (type == "number") { <ide> description = "Number"; <ide> } else if (type == "boolean") {
Java
mit
fc704553fb6975f75450c531a1e1804004e16556
0
hhu-stups/bmoth
package de.bmoth.parser.ast.types; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; public class IntegerOrSetOfPairs extends Observable implements BType, Observer { private BType left; private BType right; public IntegerOrSetOfPairs(BType left, BType right) { setLeftType(left); setRightType(right); } private void setLeftType(BType left) { this.left = left; if (left instanceof Observable) { ((Observable) left).addObserver(this); } } private void setRightType(BType right) { this.right = right; if (right instanceof Observable) { ((Observable) right).addObserver(this); } } @Override public void update(Observable o, Object arg) { o.deleteObserver(this); BType newType = (BType) arg; try { if (newType instanceof IntegerType) { this.setChanged(); this.notifyObservers(newType); if (o == getLeft()) { getRight().unify(IntegerType.getInstance()); } else { getLeft().unify(IntegerType.getInstance()); } } else if (newType instanceof SetType && o == getLeft() && o == getRight()) { this.setChanged(); BType subType = ((SetType) newType).getSubType(); SetType cartesianProductType = new SetType(new CoupleType(subType, subType)); this.notifyObservers(cartesianProductType); } else if (newType instanceof SetType && o == getLeft()) { this.setChanged(); // left is a set if (right instanceof Observable) { ((Observable) right).deleteObserver(this); } SetType r = (SetType) right.unify(new SetType(new UntypedType())); this.notifyObservers(new SetType(new CoupleType(((SetType) newType).getSubType(), r.getSubType()))); } else if (newType instanceof SetType && o != getLeft()) { this.setChanged(); // right is a set if (left instanceof Observable) { ((Observable) left).deleteObserver(this); } SetType l = (SetType) left.unify(new SetType(new UntypedType())); this.notifyObservers(new SetType(new CoupleType(l.getSubType(), ((SetType) newType).getSubType()))); } else if (o == getLeft() && o == getRight()) { setLeftType(newType); setRightType(newType); } else if (o == getLeft()) { setLeftType(newType); } else { setRightType(newType); } } catch (UnificationException e) { // should not happen final Logger logger = Logger.getLogger(getClass().getName()); logger.log(Level.SEVERE, "unification failed in update", e); } } @Override public BType unify(BType otherType) throws UnificationException { if (otherType instanceof SetType) { if (left instanceof Observable) { ((Observable) left).deleteObserver(this); } if (right instanceof Observable) { ((Observable) right).deleteObserver(this); } SetType l = (SetType) left.unify(new SetType(new UntypedType())); SetType r = (SetType) right.unify(new SetType(new UntypedType())); SetType found = new SetType(new CoupleType(l.getSubType(), r.getSubType())); found = (SetType) found.unify(otherType); this.setChanged(); this.notifyObservers(found); return found; } else if (otherType instanceof UntypedType) { ((UntypedType) otherType).replaceBy(this); return this; } else if (otherType instanceof IntegerOrSetOfPairs) { IntegerOrSetOfPairs other = (IntegerOrSetOfPairs) otherType; other.replaceBy(this); this.getLeft().unify(other.getLeft()); this.getRight().unify(other.getRight()); return this; } else if (otherType instanceof SetOrIntegerType) { SetOrIntegerType other = (SetOrIntegerType) otherType; other.replaceBy(this); return this; } else if (otherType instanceof IntegerType) { this.replaceBy(IntegerType.getInstance()); this.left.unify(IntegerType.getInstance()); this.right.unify(IntegerType.getInstance()); return IntegerType.getInstance(); } throw new UnificationException(); } private void replaceBy(BType otherType) { /* * unregister this instance from the sub types, i.e. it will be no * longer updated */ if (getLeft() instanceof Observable) { ((Observable) getLeft()).deleteObserver(this); } if (getRight() instanceof Observable) { ((Observable) getRight()).deleteObserver(this); } // notify all observers of this, they should point now to the otherType this.setChanged(); this.notifyObservers(otherType); } @Override public boolean unifiable(BType otherType) { if (otherType instanceof SetOrIntegerType || otherType instanceof IntegerType || otherType instanceof IntegerOrSetOfPairs || otherType instanceof UntypedType) { return true; } else if (otherType instanceof SetType) { SetType setType = (SetType) otherType; return setType.getSubType() instanceof CoupleType; } else { return false; } } @Override public boolean contains(BType other) { return other == getLeft() || other == getRight(); } @Override public boolean isUntyped() { return true; } public BType getLeft() { return left; } public BType getRight() { return right; } }
src/main/java/de/bmoth/parser/ast/types/IntegerOrSetOfPairs.java
package de.bmoth.parser.ast.types; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; public class IntegerOrSetOfPairs extends Observable implements BType, Observer { private BType left; private BType right; public IntegerOrSetOfPairs(BType left, BType right) { setLeftType(left); setRightType(right); } private void setLeftType(BType left) { this.left = left; if (left instanceof Observable) { ((Observable) left).addObserver(this); } } private void setRightType(BType right) { this.right = right; if (right instanceof Observable) { ((Observable) right).addObserver(this); } } @Override public void update(Observable o, Object arg) { o.deleteObserver(this); BType newType = (BType) arg; try { if (newType instanceof IntegerType) { this.setChanged(); this.notifyObservers(newType); if (o == getLeft()) { getRight().unify(IntegerType.getInstance()); } else { getLeft().unify(IntegerType.getInstance()); } } else if (newType instanceof SetType && o == getLeft() && o == getRight()) { this.setChanged(); BType subType = ((SetType) newType).getSubType(); SetType cartesianProductType = new SetType(new CoupleType(subType, subType)); this.notifyObservers(cartesianProductType); } else if (newType instanceof SetType && o == getLeft()) { this.setChanged(); // left is a set if (right instanceof Observable) { ((Observable) right).deleteObserver(this); } SetType r = (SetType) right.unify(new SetType(new UntypedType())); this.notifyObservers(new SetType(new CoupleType(((SetType) newType).getSubType(), r.getSubType()))); } else if (newType instanceof SetType && o != getLeft()) { this.setChanged(); // right is a set if (left instanceof Observable) { ((Observable) left).deleteObserver(this); } SetType l = (SetType) left.unify(new SetType(new UntypedType())); this.notifyObservers(new SetType(new CoupleType(l.getSubType(), ((SetType) newType).getSubType()))); } else if (o == getLeft() && o == getRight()) { setLeftType(newType); setRightType(newType); } else if (o == getLeft()) { setLeftType(newType); } else { setRightType(newType); } } catch (UnificationException e) { // should not happen final Logger logger = Logger.getLogger(getClass().getName()); logger.log(Level.SEVERE, "unification failed in update", e); } } @Override public BType unify(BType otherType) throws UnificationException { if (otherType instanceof SetType) { if (left instanceof Observable) { ((Observable) left).deleteObserver(this); } if (right instanceof Observable) { ((Observable) right).deleteObserver(this); } SetType l = (SetType) left.unify(new SetType(new UntypedType())); SetType r = (SetType) right.unify(new SetType(new UntypedType())); SetType found = new SetType(new CoupleType(l.getSubType(), r.getSubType())); found = (SetType) found.unify(otherType); this.setChanged(); this.notifyObservers(found); return found; } else if (otherType instanceof UntypedType) { ((UntypedType) otherType).replaceBy(this); return this; } else if (otherType instanceof IntegerOrSetOfPairs) { IntegerOrSetOfPairs other = (IntegerOrSetOfPairs) otherType; other.replaceBy(this); this.getLeft().unify(other.getLeft()); this.getRight().unify(other.getRight()); return this; } else if (otherType instanceof SetOrIntegerType) { SetOrIntegerType other = (SetOrIntegerType) otherType; other.replaceBy(this); return this; } else if (otherType instanceof IntegerType) { this.replaceBy(IntegerType.getInstance()); this.left.unify(IntegerType.getInstance()); this.right.unify(IntegerType.getInstance()); return IntegerType.getInstance(); } throw new UnificationException(); } public void replaceBy(BType otherType) { /* * unregister this instance from the sub types, i.e. it will be no * longer updated */ if (getLeft() instanceof Observable) { ((Observable) getLeft()).deleteObserver(this); } if (getRight() instanceof Observable) { ((Observable) getRight()).deleteObserver(this); } // notify all observers of this, they should point now to the otherType this.setChanged(); this.notifyObservers(otherType); } @Override public boolean unifiable(BType otherType) { if (otherType instanceof SetOrIntegerType || otherType instanceof IntegerType || otherType instanceof IntegerOrSetOfPairs || otherType instanceof UntypedType) { return true; } else if (otherType instanceof SetType) { SetType setType = (SetType) otherType; return setType.getSubType() instanceof CoupleType; } else { return false; } } @Override public boolean contains(BType other) { return other == getLeft() || other == getRight(); } @Override public boolean isUntyped() { return true; } public BType getLeft() { return left; } public BType getRight() { return right; } }
reduce visibility
src/main/java/de/bmoth/parser/ast/types/IntegerOrSetOfPairs.java
reduce visibility
<ide><path>rc/main/java/de/bmoth/parser/ast/types/IntegerOrSetOfPairs.java <ide> throw new UnificationException(); <ide> } <ide> <del> public void replaceBy(BType otherType) { <add> private void replaceBy(BType otherType) { <ide> /* <ide> * unregister this instance from the sub types, i.e. it will be no <ide> * longer updated <ide> @Override <ide> public boolean unifiable(BType otherType) { <ide> if (otherType instanceof SetOrIntegerType || otherType instanceof IntegerType <del> || otherType instanceof IntegerOrSetOfPairs || otherType instanceof UntypedType) { <add> || otherType instanceof IntegerOrSetOfPairs || otherType instanceof UntypedType) { <ide> return true; <ide> } else if (otherType instanceof SetType) { <ide> SetType setType = (SetType) otherType;
JavaScript
mit
281e9f40174206c5ca69733efb6c2d405ffd48eb
0
kentor/notejs-react,kentor/notejs-react,kentor/notejs-react
var browserify = require('browserify'); var buffer = require('vinyl-buffer'); var gulp = require('gulp'); var livereload = require('tiny-lr'); var source = require('vinyl-source-stream'); var sourcemaps = require('gulp-sourcemaps'); var watchify = require('watchify'); gulp.task('express', function() { var express = require('express'); var app = express(); app.use(require('connect-livereload')({ port: 4070 })); app.use(express.static(__dirname + '/public')); app.listen(4069); }); gulp.task('scripts', function() { watchify.args.debug = true; var bundler = watchify(browserify('./public/js/main.js', watchify.args)); bundler.on('update', rebundle); bundler.on('log', console.error); function rebundle() { return bundler .bundle() .pipe(source('app.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./public/js/')); } return rebundle(); }); var tinylr; gulp.task('livereload', function() { tinylr = livereload(); tinylr.listen(4070); }); function notifyLiveReload(event) { var fileName = require('path').relative(__dirname, event.path); tinylr.changed({ body: { files: [fileName] } }); } gulp.task('watch', function() { gulp.watch('public/*.html', notifyLiveReload); gulp.watch('public/js/app.js', notifyLiveReload); }); gulp.task('default', ['express', 'scripts', 'livereload', 'watch'], function() { });
gulpfile.js
var browserify = require('browserify'); var buffer = require('vinyl-buffer'); var gulp = require('gulp'); var source = require('vinyl-source-stream'); var sourcemaps = require('gulp-sourcemaps'); var watchify = require('watchify'); gulp.task('express', function() { var express = require('express'); var app = express(); app.use(require('connect-livereload')({ port: 4070 })); app.use(express.static(__dirname + '/public')); app.listen(4069); }); gulp.task('scripts', function() { watchify.args.debug = true; var bundler = watchify(browserify('./public/js/main.js', watchify.args)); bundler.on('update', rebundle); bundler.on('log', console.error); function rebundle() { return bundler .bundle() .pipe(source('app.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./public/js/')); } return rebundle(); }); var tinylr; gulp.task('livereload', function() { tinylr = require('tiny-lr')(); tinylr.listen(4070); }); function notifyLiveReload(event) { var fileName = require('path').relative(__dirname, event.path); tinylr.changed({ body: { files: [fileName] } }); } gulp.task('watch', function() { gulp.watch('public/*.html', notifyLiveReload); gulp.watch('public/js/app.js', notifyLiveReload); }); gulp.task('default', ['express', 'scripts', 'livereload', 'watch'], function() { });
refactor gulpfile with regards to livereload rename tiny-lr module to livereload since we're using a specific implementation of livereload.
gulpfile.js
refactor gulpfile with regards to livereload
<ide><path>ulpfile.js <ide> var browserify = require('browserify'); <ide> var buffer = require('vinyl-buffer'); <ide> var gulp = require('gulp'); <add>var livereload = require('tiny-lr'); <ide> var source = require('vinyl-source-stream'); <ide> var sourcemaps = require('gulp-sourcemaps'); <ide> var watchify = require('watchify'); <ide> <ide> var tinylr; <ide> gulp.task('livereload', function() { <del> tinylr = require('tiny-lr')(); <add> tinylr = livereload(); <ide> tinylr.listen(4070); <ide> }); <ide>
Java
apache-2.0
cfdef4bb0cf14ab3b8deacaaa95efe8795e49384
0
dslomov/intellij-community,adedayo/intellij-community,kdwink/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,consulo/consulo,lucafavatella/intellij-community,FHannes/intellij-community,jagguli/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,consulo/consulo,wreckJ/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,izonder/intellij-community,kool79/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,holmes/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ryano144/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,kool79/intellij-community,supersven/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,caot/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,fnouama/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,asedunov/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,signed/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,supersven/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,samthor/intellij-community,supersven/intellij-community,ernestp/consulo,Distrotech/intellij-community,amith01994/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,caot/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,adedayo/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,da1z/intellij-community,caot/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,retomerz/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,samthor/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,jagguli/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,amith01994/intellij-community,izonder/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,vladmm/intellij-community,slisson/intellij-community,slisson/intellij-community,vvv1559/intellij-community,da1z/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,signed/intellij-community,amith01994/intellij-community,diorcety/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,consulo/consulo,vladmm/intellij-community,vladmm/intellij-community,da1z/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,FHannes/intellij-community,hurricup/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,blademainer/intellij-community,fitermay/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,semonte/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,kool79/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,semonte/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,allotria/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,kdwink/intellij-community,allotria/intellij-community,adedayo/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,holmes/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,da1z/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,jagguli/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,alphafoobar/intellij-community,ernestp/consulo,orekyuu/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,kdwink/intellij-community,diorcety/intellij-community,FHannes/intellij-community,semonte/intellij-community,joewalnes/idea-community,signed/intellij-community,fnouama/intellij-community,apixandru/intellij-community,supersven/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,allotria/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,slisson/intellij-community,supersven/intellij-community,hurricup/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,semonte/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,supersven/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,kdwink/intellij-community,retomerz/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,supersven/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,fnouama/intellij-community,blademainer/intellij-community,da1z/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,retomerz/intellij-community,consulo/consulo,retomerz/intellij-community,clumsy/intellij-community,xfournet/intellij-community,joewalnes/idea-community,holmes/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,caot/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,robovm/robovm-studio,FHannes/intellij-community,ryano144/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,signed/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,asedunov/intellij-community,samthor/intellij-community,suncycheng/intellij-community,signed/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,izonder/intellij-community,apixandru/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,allotria/intellij-community,da1z/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,holmes/intellij-community,ahb0327/intellij-community,semonte/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,izonder/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,kdwink/intellij-community,holmes/intellij-community,robovm/robovm-studio,adedayo/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,caot/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,hurricup/intellij-community,da1z/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,apixandru/intellij-community,allotria/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ernestp/consulo,petteyg/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ernestp/consulo,robovm/robovm-studio,pwoodworth/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,caot/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,adedayo/intellij-community,da1z/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,caot/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,signed/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,petteyg/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ibinti/intellij-community,diorcety/intellij-community,da1z/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,holmes/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,asedunov/intellij-community,semonte/intellij-community,slisson/intellij-community,ryano144/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,fitermay/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,signed/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,slisson/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,clumsy/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,hurricup/intellij-community,da1z/intellij-community,samthor/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,caot/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,consulo/consulo,fitermay/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,caot/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,signed/intellij-community,slisson/intellij-community,samthor/intellij-community,da1z/intellij-community,adedayo/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,xfournet/intellij-community,caot/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,samthor/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,semonte/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,robovm/robovm-studio,asedunov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,hurricup/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,samthor/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,supersven/intellij-community,slisson/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,allotria/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,joewalnes/idea-community,supersven/intellij-community,joewalnes/idea-community,clumsy/intellij-community,amith01994/intellij-community,ibinti/intellij-community,signed/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,hurricup/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.intelliLang.inject; import com.intellij.lang.injection.MultiHostInjector; import com.intellij.lang.injection.MultiHostRegistrar; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Trinity; import com.intellij.psi.ElementManipulator; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.psi.util.PsiUtilBase; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; /** * @author Gregory.Shrago */ public class TemporaryPlacesInjector implements MultiHostInjector { public static final Logger LOG = Logger.getInstance("org.intellij.plugins.intelliLang.inject.TemporaryPlacesInjector"); @NotNull public List<? extends Class<? extends PsiElement>> elementsToInjectIn() { return Collections.singletonList(PsiLanguageInjectionHost.class); } public void getLanguagesToInject(@NotNull final MultiHostRegistrar registrar, @NotNull final PsiElement context) { final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost)context; final PsiLanguageInjectionHost originalHost = PsiUtilBase.getOriginalElement(host, host.getClass()); final ElementManipulator<PsiLanguageInjectionHost> manipulator = ElementManipulators.getManipulator(host); LOG.assertTrue(manipulator != null, "No manipulator for " + host); final List<TemporaryPlacesRegistry.TemporaryPlace> list = TemporaryPlacesRegistry.getInstance(context.getProject()).getTempInjectionsSafe(originalHost); for (final TemporaryPlacesRegistry.TemporaryPlace place : list) { LOG.assertTrue(place.language != null, "Language should not be NULL"); InjectorUtils.registerInjection( place.language.getLanguage(), Collections.singletonList(Trinity.create(host, place.language, manipulator.getRangeInElement(host))), context.getContainingFile(), registrar); } } }
plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesInjector.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.intelliLang.inject; import com.intellij.lang.injection.MultiHostInjector; import com.intellij.lang.injection.MultiHostRegistrar; import com.intellij.openapi.util.Trinity; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.psi.util.PsiUtilBase; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; /** * @author Gregory.Shrago */ public class TemporaryPlacesInjector implements MultiHostInjector { @NotNull public List<? extends Class<? extends PsiElement>> elementsToInjectIn() { return Collections.singletonList(PsiLanguageInjectionHost.class); } public void getLanguagesToInject(@NotNull final MultiHostRegistrar registrar, @NotNull final PsiElement context) { final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost)context; final PsiLanguageInjectionHost originalHost = PsiUtilBase.getOriginalElement(host, host.getClass()); final List<TemporaryPlacesRegistry.TemporaryPlace> list = TemporaryPlacesRegistry.getInstance(context.getProject()).getTempInjectionsSafe(originalHost); for (final TemporaryPlacesRegistry.TemporaryPlace pair : list) { InjectorUtils.registerInjection(pair.language.getLanguage(), Collections.singletonList( Trinity.create(host, pair.language, ElementManipulators.getManipulator(host).getRangeInElement(host))), context.getContainingFile(), registrar); } } }
19387 - NPE: TemporaryPlacesInjector.getLanguagesToInject (http://ea.jetbrains.com/browser/ea_problems/19387)
plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesInjector.java
19387 - NPE: TemporaryPlacesInjector.getLanguagesToInject (http://ea.jetbrains.com/browser/ea_problems/19387)
<ide><path>lugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/TemporaryPlacesInjector.java <ide> <ide> import com.intellij.lang.injection.MultiHostInjector; <ide> import com.intellij.lang.injection.MultiHostRegistrar; <add>import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.util.Trinity; <add>import com.intellij.psi.ElementManipulator; <ide> import com.intellij.psi.ElementManipulators; <ide> import com.intellij.psi.PsiElement; <ide> import com.intellij.psi.PsiLanguageInjectionHost; <ide> */ <ide> public class TemporaryPlacesInjector implements MultiHostInjector { <ide> <add> public static final Logger LOG = Logger.getInstance("org.intellij.plugins.intelliLang.inject.TemporaryPlacesInjector"); <add> <ide> @NotNull <ide> public List<? extends Class<? extends PsiElement>> elementsToInjectIn() { <ide> return Collections.singletonList(PsiLanguageInjectionHost.class); <ide> public void getLanguagesToInject(@NotNull final MultiHostRegistrar registrar, @NotNull final PsiElement context) { <ide> final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost)context; <ide> final PsiLanguageInjectionHost originalHost = PsiUtilBase.getOriginalElement(host, host.getClass()); <add> final ElementManipulator<PsiLanguageInjectionHost> manipulator = ElementManipulators.getManipulator(host); <add> LOG.assertTrue(manipulator != null, "No manipulator for " + host); <ide> final List<TemporaryPlacesRegistry.TemporaryPlace> list = TemporaryPlacesRegistry.getInstance(context.getProject()).getTempInjectionsSafe(originalHost); <del> for (final TemporaryPlacesRegistry.TemporaryPlace pair : list) { <del> InjectorUtils.registerInjection(pair.language.getLanguage(), Collections.singletonList( <del> Trinity.create(host, pair.language, ElementManipulators.getManipulator(host).getRangeInElement(host))), context.getContainingFile(), <del> registrar); <add> for (final TemporaryPlacesRegistry.TemporaryPlace place : list) { <add> LOG.assertTrue(place.language != null, "Language should not be NULL"); <add> InjectorUtils.registerInjection( <add> place.language.getLanguage(), <add> Collections.singletonList(Trinity.create(host, place.language, manipulator.getRangeInElement(host))), context.getContainingFile(), registrar); <ide> } <ide> } <ide>
Java
apache-2.0
dcb7a07f89f410c277a71563240ff4e7c3a7811d
0
MattGong/robotium,activars/remote-robotium,RobotiumTech/robotium,darker50/robotium,zhic5352/robotium,zhic5352/robotium,lgs3137/robotium,pefilekill/robotiumCode,luohaoyu/robotium,shibenli/robotium,luohaoyu/robotium,hypest/robotium,Eva1123/robotium,SinnerSchraderMobileMirrors/robotium,NetEase/robotium,XRacoon/robotiumEx,lczgywzyy/robotium,acanta2014/robotium,NetEase/robotium,XRacoon/robotiumEx,Eva1123/robotium,MattGong/robotium,hypest/robotium,acanta2014/robotium,pefilekill/robotiumCode,darker50/robotium,lgs3137/robotium,RobotiumTech/robotium,lczgywzyy/robotium,shibenli/robotium
package com.jayway.android.robotium.solo; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import android.app.Activity; import android.app.Instrumentation; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * This class contains view methods. Examples are getViews(), * getCurrentTextViews(), getCurrentImageViews(). * * @author Renas Reda, [email protected] * */ class ViewFetcher { private final Instrumentation inst; private final ActivityUtils activityUtils; private final Sleeper sleeper; /** * Constructs this object. * * @param inst the {@code Instrumentation} instance * @param activityUtils the {@code ActivityUtils} instance * @param sleeper the {@code Sleeper} instance */ public ViewFetcher(Instrumentation inst, ActivityUtils activityUtils, Sleeper sleeper) { this.inst = inst; this.activityUtils = activityUtils; this.sleeper = sleeper; } /** * Returns the absolute top parent {@code View} in for a given {@code View}. * * @param view the {@code View} whose top parent is requested * @return the top parent {@code View} */ public View getTopParent(View view) { if (view.getParent() != null && !view.getParent().getClass().getName().equals("android.view.ViewRoot")) { return getTopParent((View) view.getParent()); } else { return view; } } /** * Returns the list item parent. It is used by clickInList(). * * @param view the view who's parent is requested * @return the parent of the view */ public View getListItemParent(View view) { if (view.getParent() != null && !(view.getParent() instanceof android.widget.ListView)) { return getListItemParent((View) view.getParent()); } else { return view; } } /** * Returns the scroll or list parent view * @param view the view who's parent should be returned * @return the parent scroll view, list view or null */ public View getScrollOrListParent(View view) { if (!(view instanceof android.widget.ListView) && !(view instanceof android.widget.ScrollView)) { try{ return getScrollOrListParent((View) view.getParent()); }catch(Exception e){ return null; } } else { return view; } } /** * Returns views from the shown DecorViews. * * @param onlyFullyVisible if only fully visible views should be returned * @return all the views contained in the DecorViews */ public ArrayList<View> getAllViews(boolean onlyFullyVisible) { Activity activity = activityUtils.getCurrentActivity(false); final View [] views = getWindowDecorViews(); final ArrayList<View> allViews = new ArrayList<View>(); final View [] nonDecorViews = getNonDecorViews(views); if(views !=null && views.length > 0) { if(!activity.hasWindowFocus()){ for(View view : views){ if(!activity.getWindow().getDecorView().equals(view)){ try{ addChildren(allViews,(ViewGroup) view, onlyFullyVisible); } catch (Exception ignored) {} } } } else{ for(View view : nonDecorViews){ try{ addChildren(allViews,(ViewGroup) view, onlyFullyVisible); } catch (Exception ignored) {} } try{ addChildren(allViews,(ViewGroup) getRecentDecorView(views), onlyFullyVisible); } catch (Exception ignored) {} } } return allViews; } /** * Returns the most recent DecorView * * @param views the views to check * @return the most recent DecorView * */ public final View getRecentDecorView(View [] views){ final View [] decorViews = new View[views.length]; int i = 0; for(View view : views){ if(view.getClass().getName().equals("com.android.internal.policy.impl.PhoneWindow$DecorView")) { decorViews[i] = view; i++; } } return getRecentContainer(decorViews); } /** * Returns the most recent view container * * @param views the views to check * @return the most recent view container * */ private final View getRecentContainer(View [] views){ View container = null; long drawingTime = 0; for(View view : views){ if(view !=null && view.isShown() && view.getDrawingTime() > drawingTime){ container = view; drawingTime = view.getDrawingTime(); } } return container; } /** * Returns all views that are non DecorViews * * @param views the views to check * @return the non DecorViews */ private final View[] getNonDecorViews(View [] views){ final View [] decorViews = new View[views.length]; int i = 0; for(View view : views){ if(!(view.getClass().getName().equals("com.android.internal.policy.impl.PhoneWindow$DecorView"))) { decorViews[i] = view; i++; } } return decorViews; } /** * Returns a {@code View} with a given id. * @param id the R.id of the {@code View} to be returned * @return a {@code View} with a given id */ public View getView(int id){ final Activity activity = activityUtils.getCurrentActivity(false); return activity.findViewById(id); } /** * Extracts all {@code View}s located in the currently active {@code Activity}, recursively. * * @param parent the {@code View} whose children should be returned, or {@code null} for all * @param onlyFullyVisible if only fully visible views should be returned * @return all {@code View}s located in the currently active {@code Activity}, never {@code null} */ public ArrayList<View> getViews(View parent, boolean onlyFullyVisible) { final ArrayList<View> views = new ArrayList<View>(); final View parentToUse; if (parent == null){ inst.waitForIdleSync(); return getAllViews(onlyFullyVisible); }else{ parentToUse = parent; views.add(parentToUse); if (parentToUse instanceof ViewGroup) { addChildren(views, (ViewGroup) parentToUse, onlyFullyVisible); } } return views; } /** * Adds all children of {@code viewGroup} (recursively) into {@code views}. * @param views an {@code ArrayList} of {@code View}s * @param viewGroup the {@code ViewGroup} to extract children from */ private void addChildren(ArrayList<View> views, ViewGroup viewGroup, boolean onlyFullyVisible) { for (int i = 0; i < viewGroup.getChildCount(); i++) { final View child = viewGroup.getChildAt(i); if(onlyFullyVisible && isViewFullyShown(child)) views.add(child); else if(!onlyFullyVisible) views.add(child); if (child instanceof ViewGroup) { addChildren(views, (ViewGroup) child, onlyFullyVisible); } } } /** * Returns true if the view is fully shown * @param view the view to check * @return true if the view is fully shown */ public boolean isViewFullyShown(View view){ final int[] xy = new int[2]; final int viewHeight = view.getHeight(); view.getLocationOnScreen(xy); if(xy[1] + viewHeight > getScrollListWindowHeight(view)) return false; return true; } /** * Returns the height of the scroll or list view parent * @param view the view who's parents height should be returned * @return the height of the scroll or list view parent */ public float getScrollListWindowHeight(View view) { final int[] xyParent = new int[2]; final View parent = getScrollOrListParent(view); final float windowHeight; if(parent == null){ windowHeight = activityUtils.getCurrentActivity(false).getWindowManager() .getDefaultDisplay().getHeight(); } else{ parent.getLocationOnScreen(xyParent); windowHeight = xyParent[1] + parent.getHeight(); } return windowHeight; } /** * Returns a {@code View} with a certain index, from the list of current {@code View}s of the specified type. * * @param classToFilterBy which {@code View}s to choose from * @param index choose among all instances of this type, e.g. {@code Button.class} or {@code EditText.class} * @return a {@code View} with a certain index, from the list of current {@code View}s of the specified type */ public <T extends View> T getView(Class<T> classToFilterBy, int index) { sleeper.sleep(); inst.waitForIdleSync(); ArrayList<T> views = getCurrentViews(classToFilterBy); views=RobotiumUtils.removeInvisibleViews(views); T view = null; try{ view = views.get(index); }catch (IndexOutOfBoundsException e){ Assert.assertTrue("No " + classToFilterBy.getSimpleName() + " with index " + index + " is found!", false); } return view; } /** * Returns a {@code View} that shows a given text, from the list of current {@code View}s of the specified type. * * @param classToFilterBy which {@code View}s to choose from * @param text the text that the view shows * @return a {@code View} showing a given text, from the list of current {@code View}s of the specified type */ public <T extends TextView> T getView(Class<T> classToFilterBy, String text) { sleeper.sleep(); inst.waitForIdleSync(); ArrayList<T> views = getCurrentViews(classToFilterBy); T viewToReturn = null; for(T view: views){ if(view.getText().toString().equals(text)) viewToReturn = view; } if(viewToReturn == null) Assert.assertTrue("No " + classToFilterBy.getSimpleName() + " with text " + text + " is found!", false); return viewToReturn; } /** * Returns a view. * * @param classToFilterBy the class to filter by * @param views the list with views * @param index the index of the view * @return the view with a given index */ public final <T extends View> T getView(Class<T> classToFilterBy, ArrayList<T> views, int index){ T viewToReturn = null; long drawingTime = 0; if(views == null){ views = getCurrentViews(classToFilterBy); } if(index < 1){ for(T view : views){ if(view.getDrawingTime() > drawingTime){ drawingTime = view.getDrawingTime(); viewToReturn = view; } } } else{ try{ viewToReturn = views.get(index); }catch (Exception ignored) {} } return viewToReturn; } /** * Returns an {@code ArrayList} of {@code View}s of the specified {@code Class} located in the current * {@code Activity}. * * @param classToFilterBy return all instances of this class, e.g. {@code Button.class} or {@code GridView.class} * @return an {@code ArrayList} of {@code View}s of the specified {@code Class} located in the current {@code Activity} */ public <T extends View> ArrayList<T> getCurrentViews(Class<T> classToFilterBy) { return getCurrentViews(classToFilterBy, null); } /** * Returns an {@code ArrayList} of {@code View}s of the specified {@code Class} located under the specified {@code parent}. * * @param classToFilterBy return all instances of this class, e.g. {@code Button.class} or {@code GridView.class} * @param parent the parent {@code View} for where to start the traversal * @return an {@code ArrayList} of {@code View}s of the specified {@code Class} located under the specified {@code parent} */ public <T extends View> ArrayList<T> getCurrentViews(Class<T> classToFilterBy, View parent) { ArrayList<T> filteredViews = new ArrayList<T>(); List<View> allViews = getViews(parent, true); for(View view : allViews){ if (view != null && classToFilterBy.isAssignableFrom(view.getClass())) { filteredViews.add(classToFilterBy.cast(view)); } } return filteredViews; } private static Class<?> windowManager; static{ try { windowManager = Class.forName("android.view.WindowManagerImpl"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SecurityException e) { e.printStackTrace(); } } /** * Returns the WindorDecorViews shown on the screen * @return the WindorDecorViews shown on the screen * */ public View[] getWindowDecorViews() { Field viewsField; Field instanceField; try { viewsField = windowManager.getDeclaredField("mViews"); instanceField = windowManager.getDeclaredField("mWindowManager"); viewsField.setAccessible(true); instanceField.setAccessible(true); Object instance = instanceField.get(null); return (View[]) viewsField.get(instance); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } }
robotium-solo/src/main/java/com/jayway/android/robotium/solo/ViewFetcher.java
package com.jayway.android.robotium.solo; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import android.app.Activity; import android.app.Instrumentation; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * This class contains view methods. Examples are getViews(), * getCurrentTextViews(), getCurrentImageViews(). * * @author Renas Reda, [email protected] * */ class ViewFetcher { private final Instrumentation inst; private final ActivityUtils activityUtils; private final Sleeper sleeper; /** * Constructs this object. * * @param inst the {@code Instrumentation} instance * @param activityUtils the {@code ActivityUtils} instance * @param sleeper the {@code Sleeper} instance */ public ViewFetcher(Instrumentation inst, ActivityUtils activityUtils, Sleeper sleeper) { this.inst = inst; this.activityUtils = activityUtils; this.sleeper = sleeper; } /** * Returns the absolute top parent {@code View} in for a given {@code View}. * * @param view the {@code View} whose top parent is requested * @return the top parent {@code View} */ public View getTopParent(View view) { if (view.getParent() != null && !view.getParent().getClass().getName().equals("android.view.ViewRoot")) { return getTopParent((View) view.getParent()); } else { return view; } } /** * Returns the list item parent. It is used by clickInList(). * * @param view the view who's parent is requested * @return the parent of the view */ public View getListItemParent(View view) { if (view.getParent() != null && !(view.getParent() instanceof android.widget.ListView)) { return getListItemParent((View) view.getParent()); } else { return view; } } /** * Returns the scroll or list parent view * @param view the view who's parent should be returned * @return the parent scroll view, list view or null */ public View getScrollOrListParent(View view) { if (!(view instanceof android.widget.ListView) && !(view instanceof android.widget.ScrollView)) { try{ return getScrollOrListParent((View) view.getParent()); }catch(Exception e){ return null; } } else { return view; } } /** * Returns views from the shown DecorViews. * * @param onlyFullyVisible if only fully visible views should be returned * @return all the views contained in the DecorViews */ public ArrayList<View> getAllViews(boolean onlyFullyVisible) { Activity activity = activityUtils.getCurrentActivity(false); final View [] views = getWindowDecorViews(); final ArrayList<View> allViews = new ArrayList<View>(); final View [] nonDecorViews = getNonDecorViews(views); if(views !=null && views.length > 0) { if(!activity.hasWindowFocus()){ for(View view : views){ if(!activity.getWindow().getDecorView().equals(view)){ try{ addChildren(allViews,(ViewGroup) view, onlyFullyVisible); } catch (Exception ignored) {} } } } else{ for(View view : nonDecorViews){ try{ addChildren(allViews,(ViewGroup) view, onlyFullyVisible); } catch (Exception ignored) {} } try{ addChildren(allViews,(ViewGroup) getRecentDecorView(views), onlyFullyVisible); } catch (Exception ignored) {} } } return allViews; } /** * Returns the most recent DecorView * * @param views the views to check * @return the most recent DecorView * */ public final View getRecentDecorView(View [] views){ final View [] decorViews = new View[views.length]; int i = 0; for(View view : views){ if(view.getClass().getName().equals("com.android.internal.policy.impl.PhoneWindow$DecorView")) { decorViews[i] = view; i++; } } return getRecentContainer(decorViews); } /** * Returns the most recent view container * * @param views the views to check * @return the most recent view container * */ private final View getRecentContainer(View [] views){ View container = null; long drawingTime = 0; for(View view : views){ if(view !=null && view.isShown() && view.getDrawingTime() > drawingTime){ container = view; drawingTime = view.getDrawingTime(); } } return container; } /** * Returns all views that are non DecorViews * * @param views the views to check * @return the non DecorViews */ private final View[] getNonDecorViews(View [] views){ final View [] decorViews = new View[views.length]; int i = 0; for(View view : views){ if(!(view.getClass().getName().equals("com.android.internal.policy.impl.PhoneWindow$DecorView"))) { decorViews[i] = view; i++; } } return decorViews; } /** * Returns a {@code View} with a given id. * @param id the R.id of the {@code View} to be returned * @return a {@code View} with a given id */ public View getView(int id){ final Activity activity = activityUtils.getCurrentActivity(false); return activity.findViewById(id); } /** * Extracts all {@code View}s located in the currently active {@code Activity}, recursively. * * @param parent the {@code View} whose children should be returned, or {@code null} for all * @param onlyFullyVisible if only fully visible views should be returned * @return all {@code View}s located in the currently active {@code Activity}, never {@code null} */ public ArrayList<View> getViews(View parent, boolean onlyFullyVisible) { final ArrayList<View> views = new ArrayList<View>(); final View parentToUse; if (parent == null){ inst.waitForIdleSync(); return getAllViews(onlyFullyVisible); }else{ parentToUse = parent; views.add(parentToUse); if (parentToUse instanceof ViewGroup) { addChildren(views, (ViewGroup) parentToUse, onlyFullyVisible); } } return views; } /** * Adds all children of {@code viewGroup} (recursively) into {@code views}. * @param views an {@code ArrayList} of {@code View}s * @param viewGroup the {@code ViewGroup} to extract children from */ private void addChildren(ArrayList<View> views, ViewGroup viewGroup, boolean onlyFullyVisible) { for (int i = 0; i < viewGroup.getChildCount(); i++) { final View child = viewGroup.getChildAt(i); if(onlyFullyVisible && isViewFullyShown(child)) views.add(child); if (child instanceof ViewGroup) { addChildren(views, (ViewGroup) child, onlyFullyVisible); } } } /** * Returns true if the view is fully shown * @param view the view to check * @return true if the view is fully shown */ public boolean isViewFullyShown(View view){ final int[] xy = new int[2]; final int viewHeight = view.getHeight(); view.getLocationOnScreen(xy); if(xy[1] + viewHeight > getScrollListWindowHeight(view)) return false; return true; } /** * Returns the height of the scroll or list view parent * @param view the view who's parents height should be returned * @return the height of the scroll or list view parent */ public float getScrollListWindowHeight(View view) { final int[] xyParent = new int[2]; final View parent = getScrollOrListParent(view); final float windowHeight; if(parent == null){ windowHeight = activityUtils.getCurrentActivity(false).getWindowManager() .getDefaultDisplay().getHeight(); } else{ parent.getLocationOnScreen(xyParent); windowHeight = xyParent[1] + parent.getHeight(); } return windowHeight; } /** * Returns a {@code View} with a certain index, from the list of current {@code View}s of the specified type. * * @param classToFilterBy which {@code View}s to choose from * @param index choose among all instances of this type, e.g. {@code Button.class} or {@code EditText.class} * @return a {@code View} with a certain index, from the list of current {@code View}s of the specified type */ public <T extends View> T getView(Class<T> classToFilterBy, int index) { sleeper.sleep(); inst.waitForIdleSync(); ArrayList<T> views = getCurrentViews(classToFilterBy); views=RobotiumUtils.removeInvisibleViews(views); T view = null; try{ view = views.get(index); }catch (IndexOutOfBoundsException e){ Assert.assertTrue("No " + classToFilterBy.getSimpleName() + " with index " + index + " is found!", false); } return view; } /** * Returns a {@code View} that shows a given text, from the list of current {@code View}s of the specified type. * * @param classToFilterBy which {@code View}s to choose from * @param text the text that the view shows * @return a {@code View} showing a given text, from the list of current {@code View}s of the specified type */ public <T extends TextView> T getView(Class<T> classToFilterBy, String text) { sleeper.sleep(); inst.waitForIdleSync(); ArrayList<T> views = getCurrentViews(classToFilterBy); T viewToReturn = null; for(T view: views){ if(view.getText().toString().equals(text)) viewToReturn = view; } if(viewToReturn == null) Assert.assertTrue("No " + classToFilterBy.getSimpleName() + " with text " + text + " is found!", false); return viewToReturn; } /** * Returns a view. * * @param classToFilterBy the class to filter by * @param views the list with views * @param index the index of the view * @return the view with a given index */ public final <T extends View> T getView(Class<T> classToFilterBy, ArrayList<T> views, int index){ T viewToReturn = null; long drawingTime = 0; if(views == null){ views = getCurrentViews(classToFilterBy); } if(index < 1){ for(T view : views){ if(view.getDrawingTime() > drawingTime){ drawingTime = view.getDrawingTime(); viewToReturn = view; } } } else{ try{ viewToReturn = views.get(index); }catch (Exception ignored) {} } return viewToReturn; } /** * Returns an {@code ArrayList} of {@code View}s of the specified {@code Class} located in the current * {@code Activity}. * * @param classToFilterBy return all instances of this class, e.g. {@code Button.class} or {@code GridView.class} * @return an {@code ArrayList} of {@code View}s of the specified {@code Class} located in the current {@code Activity} */ public <T extends View> ArrayList<T> getCurrentViews(Class<T> classToFilterBy) { return getCurrentViews(classToFilterBy, null); } /** * Returns an {@code ArrayList} of {@code View}s of the specified {@code Class} located under the specified {@code parent}. * * @param classToFilterBy return all instances of this class, e.g. {@code Button.class} or {@code GridView.class} * @param parent the parent {@code View} for where to start the traversal * @return an {@code ArrayList} of {@code View}s of the specified {@code Class} located under the specified {@code parent} */ public <T extends View> ArrayList<T> getCurrentViews(Class<T> classToFilterBy, View parent) { ArrayList<T> filteredViews = new ArrayList<T>(); List<View> allViews = getViews(parent, true); for(View view : allViews){ if (view != null && classToFilterBy.isAssignableFrom(view.getClass())) { filteredViews.add(classToFilterBy.cast(view)); } } return filteredViews; } private static Class<?> windowManager; static{ try { windowManager = Class.forName("android.view.WindowManagerImpl"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SecurityException e) { e.printStackTrace(); } } /** * Returns the WindorDecorViews shown on the screen * @return the WindorDecorViews shown on the screen * */ public View[] getWindowDecorViews() { Field viewsField; Field instanceField; try { viewsField = windowManager.getDeclaredField("mViews"); instanceField = windowManager.getDeclaredField("mWindowManager"); viewsField.setAccessible(true); instanceField.setAccessible(true); Object instance = instanceField.get(null); return (View[]) viewsField.get(instance); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } }
Corrected addChildren()
robotium-solo/src/main/java/com/jayway/android/robotium/solo/ViewFetcher.java
Corrected addChildren()
<ide><path>obotium-solo/src/main/java/com/jayway/android/robotium/solo/ViewFetcher.java <ide> final View child = viewGroup.getChildAt(i); <ide> <ide> if(onlyFullyVisible && isViewFullyShown(child)) <add> views.add(child); <add> <add> else if(!onlyFullyVisible) <ide> views.add(child); <ide> <ide> if (child instanceof ViewGroup) {
JavaScript
mit
00d9e467ef51519bd0a82cfa6d5e2e19ebc1be74
0
sir-dunxalot/ember-tooltips,zenefits/ember-tooltips,sir-dunxalot/ember-tooltips,zenefits/ember-tooltips
import Ember from 'ember'; import layout from '../templates/components/tooltip-on-parent'; const { computed, run, get } = Ember; export default Ember.Component.extend({ attributeBindings: ['style'], layout, style: computed(function() { return Ember.String.htmlSafe('display:none;'); }), init(...args) { this._super(args); run.schedule('afterRender', () => { const parentView = this.get('parentView'); const componentNotInDOM = get(parentView, 'tagName') ? false : true; if(componentNotInDOM) { console.warn('The parent component of {{tooltip-on-parent}} has no tagName and therefore no position in the DOM to target'); } else if (parentView.renderTooltip) { parentView.renderTooltip(this); } else { console.warn('No renderTooltip method found on the parent view of the {{tooltip-on-parent}} component'); } this.remove(); }); }, });
addon/components/tooltip-on-parent.js
import Ember from 'ember'; import layout from '../templates/components/tooltip-on-parent'; const { computed, warn, run, get } = Ember; export default Ember.Component.extend({ attributeBindings: ['style'], layout, style: computed(function() { return Ember.String.htmlSafe('display:none;'); }), init(...args) { this._super(args); run.schedule('afterRender', () => { const parentView = this.get('parentView'); const parentHasSelector = get(parentView, 'tagName') ? true : false; const domTarget = get(parentView, 'domTarget'); const target = parentHasSelector ? parentView : domTarget; if (target.renderTooltip) { target.renderTooltip(this); } else { console.warn('No renderTooltip method found on the parent view of the {{tooltip-on-parent}} component'); } this.remove(); }); }, });
tagName warning (no fix available)
addon/components/tooltip-on-parent.js
tagName warning (no fix available)
<ide><path>ddon/components/tooltip-on-parent.js <ide> import Ember from 'ember'; <ide> import layout from '../templates/components/tooltip-on-parent'; <ide> <del>const { computed, warn, run, get } = Ember; <add>const { computed, run, get } = Ember; <ide> <ide> export default Ember.Component.extend({ <ide> attributeBindings: ['style'], <ide> <ide> run.schedule('afterRender', () => { <ide> const parentView = this.get('parentView'); <del> const parentHasSelector = get(parentView, 'tagName') ? true : false; <del> const domTarget = get(parentView, 'domTarget'); <del> const target = parentHasSelector ? parentView : domTarget; <del> <del> if (target.renderTooltip) { <del> target.renderTooltip(this); <add> const componentNotInDOM = get(parentView, 'tagName') ? false : true; <add> if(componentNotInDOM) { <add> console.warn('The parent component of {{tooltip-on-parent}} has no tagName and therefore no position in the DOM to target'); <add> } else if (parentView.renderTooltip) { <add> parentView.renderTooltip(this); <ide> } else { <ide> console.warn('No renderTooltip method found on the parent view of the {{tooltip-on-parent}} component'); <ide> }
Java
apache-2.0
3aa42bf3150fa83c53792c8b2bf6eb4da7b534cb
0
cinchapi/concourse,cinchapi/concourse,dubex/concourse,dubex/concourse,cinchapi/concourse,dubex/concourse,dubex/concourse,cinchapi/concourse,dubex/concourse,cinchapi/concourse,cinchapi/concourse,dubex/concourse
/* * The MIT License (MIT) * * Copyright (c) 2013-2014 Jeff Nelson, Cinchapi Software Collective * * 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 org.cinchapi.concourse.server.storage; import java.io.File; import java.text.MessageFormat; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.concurrent.ThreadSafe; import org.cinchapi.concourse.annotate.Authorized; import org.cinchapi.concourse.annotate.DoNotInvoke; import org.cinchapi.concourse.annotate.Restricted; import org.cinchapi.concourse.server.GlobalState; import org.cinchapi.concourse.server.concurrent.LockService; import org.cinchapi.concourse.server.concurrent.RangeLockService; import org.cinchapi.concourse.server.concurrent.Token; import org.cinchapi.concourse.server.io.FileSystem; import org.cinchapi.concourse.server.jmx.ManagedOperation; import org.cinchapi.concourse.server.storage.db.Database; import org.cinchapi.concourse.server.storage.temp.Buffer; import org.cinchapi.concourse.server.storage.temp.Write; import org.cinchapi.concourse.thrift.Operator; import org.cinchapi.concourse.thrift.TObject; import org.cinchapi.concourse.time.Time; import org.cinchapi.concourse.util.Logger; import com.google.common.collect.Sets; import static com.google.common.base.Preconditions.*; /** * The {@code Engine} schedules concurrent CRUD operations, manages ACID * transactions, versions writes and indexes data. * <p> * The Engine is a {@link BufferedStore}. Writing to the {@link Database} is * expensive because multiple index records must be deserialized, updated and * flushed back to disk for each revision. By using a {@link Buffer}, the Engine * can handle writes in a more efficient manner which minimal impact on Read * performance. The buffering system provides full CD guarantees. * </p> * * @author jnelson */ @ThreadSafe public final class Engine extends BufferedStore implements Transactional, Compoundable { // // NOTES ON LOCKING: // ================= // Even though the individual storage components (Block, Record, etc) // handle their own locking, we must also grab "global" coordinating locks // in the Engine // // 1) to account for the fact that an atomic operation may lock notions of // things to create a virtual fence that ensures the atomicity of its // reads and writes, and // // 2) BufferedStore operations query the buffer and destination separately // and the individual locking protocols of those stores are not sufficient // to prevent dropped data (i.e. while reading from the destination it is // okay to continue writing to the buffer since we'll lock there when its // time BUT, between the time that we unlock in the #destination and the // time when we lock in the #buffer, it is possible for a transport from the // #buffer to the #destination to occur in which case the data would be // dropped since it wasn't read during the #destination query and won't be // read during the #buffer scan). // // It is important to note that we DO NOT need to do any locking for // historical reads because concurrent data writes cannot affect what is // returned. /** * The id used to determine that the Buffer should be dumped. */ public static final String BUFFER_DUMP_ID = "BUFFER"; /** * The number of milliseconds we allow between writes before we pause the * {@link BufferTransportThread}. If there amount of time between writes is * less than this value then we assume we are streaming writes, which means * it is more efficient for the BufferTransportThread to busy-wait than * block. */ protected static final int BUFFER_TRANSPORT_THREAD_ALLOWABLE_INACTIVITY_THRESHOLD_IN_MILLISECONDS = 1000; // visible // for // testing /** * The number of milliseconds we allow the {@link BufferTransportThread} to * sleep without waking up (e.g. being in the TIMED_WAITING) state before we * assume that the thread has hung/stalled and we try to rescue it. */ protected static int BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_THRESOLD_IN_MILLISECONDS = 5000; // visible // for // testing /** * The frequency with which we check to see if the * {@link BufferTransportThread} has hung/stalled. */ protected static int BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_FREQUENCY_IN_MILLISECONDS = 10000; // visible // for // testing /** * The number of milliseconds that the {@link BufferTransportThread} sleeps * after each transport in order to avoid CPU thrashing. */ protected static int BUFFER_TRANSPORT_THREAD_SLEEP_TIME_IN_MILLISECONDS = 5; // visible // for // testing /** * A flag to indicate that the {@link BufferTransportThrread} has appeared * to be hung at some point during the current lifecycle. */ protected final AtomicBoolean bufferTransportThreadHasEverAppearedHung = new AtomicBoolean( false); // visible for testing /** * A flag to indicate that the {@link BufferTransportThread} has ever been * sucessfully restarted after appearing to be hung during the current * lifecycle. */ protected final AtomicBoolean bufferTransportThreadHasEverBeenRestarted = new AtomicBoolean( false); // visible for testing /** * The location where transaction backups are stored. */ protected final String transactionStore; // exposed for Transaction backup /** * The thread that is responsible for transporting buffer content in the * background. */ private final Thread bufferTransportThread; // NOTE: Having a dedicated // thread that sleeps is faster // than using an // ExecutorService. /** * A {@link Timer} that is used to schedule some regular tasks. */ private final Timer scheduler = new Timer(true); /** * The timestamp when the {@link BufferTransportThread} last awoke from * sleep. We use this to help monitor and detect whether the thread has * stalled/hung. */ private final AtomicLong bufferTransportThreadLastWakeUp = new AtomicLong( Time.now()); /** * A flag that indicates that the {@link BufferTransportThread} is currently * paused due to inactivity (e.g. no writes). */ private final AtomicBoolean bufferTransportThreadIsPaused = new AtomicBoolean( false); /** * A flag to indicate if the Engine is running or not. */ private volatile boolean running = false; /** * A lock that prevents the Engine from causing the Buffer to transport * Writes to the Database while a buffered read is occurring. Even though * the Buffer has a transportLock, we must also maintain one at the Engine * level to prevent the appearance of dropped writes where data is * transported from the Buffer to the Database after the Database context is * captured and sent to the Buffer to finish the buffered reading. */ private final ReentrantReadWriteLock transportLock = new ReentrantReadWriteLock(); /** * The environment that is associated with this {@link Engine}. */ private final String environment; /** * A collection of listeners that should be notified of a version change for * a given token. */ @SuppressWarnings("serial") private final Map<Token, Set<VersionChangeListener>> versionChangeListeners = new ConcurrentHashMap<Token, Set<VersionChangeListener>>() { /** * An empty set that is returned on calls to {@link #get(Object)} when * there key does not exist. */ private final Set<VersionChangeListener> emptySet = Collections .unmodifiableSet(Sets.<VersionChangeListener> newHashSet()); @Override public Set<VersionChangeListener> get(Object key) { Set<VersionChangeListener> set = super.get(key); return set != null ? set : emptySet; } }; /** * A flag to indicate that the {@link BufferTransportThread} has gone into * block mode instead of busy waiting at least once. */ protected final AtomicBoolean bufferTransportThreadHasEverPaused = new AtomicBoolean( false); // visible for testing /** * Construct an Engine that is made up of a {@link Buffer} and * {@link Database} in the default locations. * */ public Engine() { this(new Buffer(), new Database(), GlobalState.DEFAULT_ENVIRONMENT); } /** * Construct an Engine that is made up of a {@link Buffer} and * {@link Database} that are both backed by {@code bufferStore} and * {@code dbStore} respectively. * * @param bufferStore * @param dbStore */ public Engine(String bufferStore, String dbStore) { this(bufferStore, dbStore, GlobalState.DEFAULT_ENVIRONMENT); } /** * Construct an Engine that is made up of a {@link Buffer} and * {@link Database} that are both backed by {@code bufferStore} and * {@code dbStore} respectively} and are associated with {@code environment} * . * * @param bufferStore * @param dbStore * @param environment */ public Engine(String bufferStore, String dbStore, String environment) { this(new Buffer(bufferStore), new Database(dbStore), environment); } /** * Construct an Engine that is made up of {@code buffer} and * {@code database}. * * @param buffer * @param database * @param environment */ @Authorized private Engine(Buffer buffer, Database database, String environment) { super(buffer, database, LockService.create(), RangeLockService.create()); this.bufferTransportThread = new BufferTransportThread(); this.transactionStore = buffer.getBackingStore() + File.separator + "txn"; /* (authorized) */ this.environment = environment; } /** * <p> * The Engine is the destination for Transaction commits, which means that * this method will accept Writes from Transactions and create new Writes * within the Engine BufferedStore (e.g. a new Write will be created in the * Buffer and eventually transported to the Database). Creating a new Write * does associate a new timestamp with the transactional data, but this is * the desired behaviour because data from a Transaction should always have * a post commit timestamp. * </p> * <p> * It is also worth calling out the fact that this method does not have any * locks to prevent multiple transactions from concurrently invoking meaning * that two transactions that don't have any overlapping reads/writes * (meaning they don't touch any of the same data) can commit at the same * time and its possible that their writes will be interleaved since calls * to this method don't globally lock. This is <em>okay</em> and does not * violate ACID because the <strong>observed</strong> state of the system * will be the same as if the transactions transported all their Writes * serially. * </p> */ @Override @DoNotInvoke public void accept(Write write) { checkArgument(write.getType() != Action.COMPARE); String key = write.getKey().toString(); TObject value = write.getValue().getTObject(); long record = write.getRecord().longValue(); boolean accepted = write.getType() == Action.ADD ? add(key, value, record) : remove(key, value, record); if(!accepted) { Logger.warn("Write {} was rejected by the Engine " + "because it was previously accepted " + "but not offset. This implies that a " + "premature shutdown occurred and the parent" + "Transaction is attempting to restore " + "itself from backup and finish committing.", write); } else { Logger.debug("'{}' was accepted by the Engine", write); } } @Override public boolean add(String key, TObject value, long record) { lockService.getWriteLock(key, record).lock(); rangeLockService.getWriteLock(key, value).lock(); try { if(super.add(key, value, record)) { notifyVersionChange(Token.wrap(key, record)); notifyVersionChange(Token.wrap(record)); notifyVersionChange(Token.wrap(key)); return true; } return false; } finally { lockService.getWriteLock(key, record).unlock(); rangeLockService.getWriteLock(key, value).unlock(); } } @Override @Restricted public void addVersionChangeListener(Token token, VersionChangeListener listener) { Set<VersionChangeListener> listeners = null; if(!versionChangeListeners.containsKey(token)) { listeners = Sets.newHashSet(); versionChangeListeners.put(token, listeners); } else { listeners = versionChangeListeners.get(token); } listeners.add(listener); } @Override public Map<Long, String> audit(long record) { transportLock.readLock().lock(); lockService.getReadLock(record).lock(); try { return super.audit(record); } finally { lockService.getReadLock(record).unlock(); transportLock.readLock().unlock(); } } @Override public Map<Long, String> audit(String key, long record) { transportLock.readLock().lock(); lockService.getReadLock(key, record).lock(); try { return super.audit(key, record); } finally { lockService.getReadLock(key, record).unlock(); transportLock.readLock().unlock(); } } @Override public Map<String, Set<TObject>> browse(long record) { transportLock.readLock().lock(); lockService.getReadLock(record).lock(); try { return super.browse(record); } finally { lockService.getReadLock(record).unlock(); transportLock.readLock().unlock(); } } @Override public Map<String, Set<TObject>> browse(long record, long timestamp) { transportLock.readLock().lock(); try { return super.browse(record, timestamp); } finally { transportLock.readLock().unlock(); } } @Override public Map<TObject, Set<Long>> browse(String key) { transportLock.readLock().lock(); lockService.getReadLock(key).lock(); try { return super.browse(key); } finally { lockService.getReadLock(key).unlock(); transportLock.readLock().unlock(); } } @Override public Map<TObject, Set<Long>> browse(String key, long timestamp) { transportLock.readLock().lock(); try { return super.browse(key, timestamp); } finally { transportLock.readLock().unlock(); } } /** * Public interface for the {@link Database#dump(String)} method. * * @param id * @return the block dumps */ @ManagedOperation public String dump(String id) { if(id.equalsIgnoreCase(BUFFER_DUMP_ID)) { return ((Buffer) buffer).dump(); } return ((Database) destination).dump(id); } @Override public Set<TObject> fetch(String key, long record) { transportLock.readLock().lock(); lockService.getReadLock(key, record).lock(); try { return super.fetch(key, record); } finally { lockService.getReadLock(key, record).unlock(); transportLock.readLock().unlock(); } } @Override public Set<TObject> fetch(String key, long record, long timestamp) { transportLock.readLock().lock(); try { return super.fetch(key, record, timestamp); } finally { transportLock.readLock().unlock(); } } @Override public Set<Long> doFind(long timestamp, String key, Operator operator, TObject... values) { transportLock.readLock().lock(); try { return super.doFind(timestamp, key, operator, values); } finally { transportLock.readLock().unlock(); } } @Override public Set<Long> doFind(String key, Operator operator, TObject... values) { transportLock.readLock().lock(); rangeLockService.getReadLock(key, operator, values).lock(); try { return super.doFind(key, operator, values); } finally { rangeLockService.getReadLock(key, operator, values).unlock(); transportLock.readLock().unlock(); } } /** * Public interface for the {@link Database#getDumpList()} method. * * @return the dump list */ @ManagedOperation public String getDumpList() { List<String> ids = ((Database) destination).getDumpList(); ids.add("BUFFER"); ListIterator<String> it = ids.listIterator(ids.size()); StringBuilder sb = new StringBuilder(); while (it.hasPrevious()) { sb.append(Math.abs(it.previousIndex() - ids.size())); sb.append(") "); sb.append(it.previous()); sb.append(System.getProperty("line.separator")); } return sb.toString(); } @Override public long getVersion(long record) { return Math.max(buffer.getVersion(record), ((Database) destination).getVersion(record)); } public long getVersion(String key) { return Math.max(buffer.getVersion(key), ((Database) destination).getVersion(key)); } @Override public long getVersion(String key, long record) { return Math.max(buffer.getVersion(key, record), ((Database) destination).getVersion(key, record)); } @Override @Restricted public void notifyVersionChange(Token token) { for (VersionChangeListener listener : versionChangeListeners.get(token)) { listener.onVersionChange(token); } } @Override public boolean remove(String key, TObject value, long record) { lockService.getWriteLock(key, record).lock(); rangeLockService.getWriteLock(key, value).lock(); try { if(super.remove(key, value, record)) { notifyVersionChange(Token.wrap(key, record)); notifyVersionChange(Token.wrap(record)); notifyVersionChange(Token.wrap(key)); return true; } return false; } finally { lockService.getWriteLock(key, record).unlock(); rangeLockService.getWriteLock(key, value).unlock(); } } @Override @Restricted public void removeVersionChangeListener(Token token, VersionChangeListener listener) { versionChangeListeners.get(token).remove(listener); } @Override public Set<Long> search(String key, String query) { // NOTE: Range locking for a search query requires too much overhead, so // we must be willing to live with the fact that a search query may // provide inconsistent results if a match is added while the read is // processing. transportLock.readLock().lock(); try { return super.search(key, query); } finally { transportLock.readLock().unlock(); } } @Override public void start() { if(!running) { Logger.info("Starting the '{}' Engine...", environment); running = true; destination.start(); buffer.start(); doTransactionRecovery(); scheduler.scheduleAtFixedRate( new TimerTask() { @Override public void run() { if(!bufferTransportThreadIsPaused.get() && bufferTransportThreadLastWakeUp.get() != 0 && TimeUnit.MILLISECONDS .convert( Time.now() - bufferTransportThreadLastWakeUp .get(), TimeUnit.MICROSECONDS) > BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_THRESOLD_IN_MILLISECONDS) { bufferTransportThreadHasEverAppearedHung .set(true); bufferTransportThread.interrupt(); } } }, BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_FREQUENCY_IN_MILLISECONDS, BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_FREQUENCY_IN_MILLISECONDS); bufferTransportThread.start(); } } @Override public AtomicOperation startAtomicOperation() { return AtomicOperation.start(this); } @Override public Transaction startTransaction() { return Transaction.start(this); } @Override public void stop() { if(running) { running = false; scheduler.cancel(); buffer.stop(); bufferTransportThread.interrupt(); destination.stop(); } } @Override public boolean verify(String key, TObject value, long record) { transportLock.readLock().lock(); lockService.getReadLock(key, record).lock(); try { return super.verify(key, value, record); } finally { lockService.getReadLock(key, record).unlock(); transportLock.readLock().unlock(); } } @Override public boolean verify(String key, TObject value, long record, long timestamp) { transportLock.readLock().lock(); try { return super.verify(key, value, record, timestamp); } finally { transportLock.readLock().unlock(); } } /** * Restore any transactions that did not finish committing prior to the * previous shutdown. */ private void doTransactionRecovery() { FileSystem.mkdirs(transactionStore); for (File file : new File(transactionStore).listFiles()) { Transaction.recover(this, file.getAbsolutePath()); Logger.info("Restored Transaction from {}", file.getName()); } } /** * Return the number of milliseconds that have elapsed since the last time * the {@link BufferTransportThread} successfully transported data. * * @return the idle time */ private long getBufferTransportThreadIdleTimeInMs() { return TimeUnit.MILLISECONDS.convert( Time.now() - ((Buffer) buffer).getTimeOfLastTransport(), TimeUnit.MICROSECONDS); } /** * A thread that is responsible for transporting content from * {@link #buffer} to {@link #destination}. * * @author jnelson */ private class BufferTransportThread extends Thread { /** * Construct a new instance. */ public BufferTransportThread() { super(MessageFormat.format("BufferTransport [{0}]", environment)); setDaemon(true); } @Override public void run() { while (running) { if(getBufferTransportThreadIdleTimeInMs() > BUFFER_TRANSPORT_THREAD_ALLOWABLE_INACTIVITY_THRESHOLD_IN_MILLISECONDS) { // If there have been no transports within the last second // then make this thread block until the buffer is // transportable so that we do not waste CPU cycles // busy waiting unnecessarily. bufferTransportThreadHasEverPaused.set(true); bufferTransportThreadIsPaused.set(true); Logger.debug( "Paused the background data transport thread because " + "it has been inactive for at least {} milliseconds", BUFFER_TRANSPORT_THREAD_ALLOWABLE_INACTIVITY_THRESHOLD_IN_MILLISECONDS); buffer.waitUntilTransportable(); if(Thread.interrupted()) { // the thread has been // interrupted from the Engine // stopping break; } } doTransport(); try { // NOTE: This thread needs to sleep for a small amount of // time to avoid thrashing Thread.sleep(BUFFER_TRANSPORT_THREAD_SLEEP_TIME_IN_MILLISECONDS); bufferTransportThreadLastWakeUp.set(Time.now()); } catch (InterruptedException e) { Logger.warn( "The data transport thread been sleeping for over " + "{} milliseconds even though there is work to do. " + "An attempt has been made to restart the stalled " + "process.", BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_THRESOLD_IN_MILLISECONDS); bufferTransportThreadHasEverBeenRestarted.set(true); } } } /** * Tell the Buffer to transport data and prevent deadlock in the event * of failure. */ private void doTransport() { if(transportLock.writeLock().tryLock()) { try { bufferTransportThreadIsPaused.compareAndSet(true, false); buffer.transport(destination); } finally { transportLock.writeLock().unlock(); } } } } }
concourse-server/src/main/java/org/cinchapi/concourse/server/storage/Engine.java
/* * The MIT License (MIT) * * Copyright (c) 2013-2014 Jeff Nelson, Cinchapi Software Collective * * 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 org.cinchapi.concourse.server.storage; import java.io.File; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.concurrent.ThreadSafe; import org.cinchapi.concourse.annotate.Authorized; import org.cinchapi.concourse.annotate.DoNotInvoke; import org.cinchapi.concourse.annotate.Restricted; import org.cinchapi.concourse.server.GlobalState; import org.cinchapi.concourse.server.concurrent.LockService; import org.cinchapi.concourse.server.concurrent.RangeLockService; import org.cinchapi.concourse.server.concurrent.Token; import org.cinchapi.concourse.server.io.FileSystem; import org.cinchapi.concourse.server.jmx.ManagedOperation; import org.cinchapi.concourse.server.storage.db.Database; import org.cinchapi.concourse.server.storage.temp.Buffer; import org.cinchapi.concourse.server.storage.temp.Write; import org.cinchapi.concourse.thrift.Operator; import org.cinchapi.concourse.thrift.TObject; import org.cinchapi.concourse.time.Time; import org.cinchapi.concourse.util.Logger; import com.google.common.collect.Sets; import static com.google.common.base.Preconditions.*; /** * The {@code Engine} schedules concurrent CRUD operations, manages ACID * transactions, versions writes and indexes data. * <p> * The Engine is a {@link BufferedStore}. Writing to the {@link Database} is * expensive because multiple index records must be deserialized, updated and * flushed back to disk for each revision. By using a {@link Buffer}, the Engine * can handle writes in a more efficient manner which minimal impact on Read * performance. The buffering system provides full CD guarantees. * </p> * * @author jnelson */ @ThreadSafe public final class Engine extends BufferedStore implements Transactional, Compoundable { // // NOTES ON LOCKING: // ================= // Even though the individual storage components (Block, Record, etc) // handle their own locking, we must also grab "global" coordinating locks // in the Engine // // 1) to account for the fact that an atomic operation may lock notions of // things to create a virtual fence that ensures the atomicity of its // reads and writes, and // // 2) BufferedStore operations query the buffer and destination separately // and the individual locking protocols of those stores are not sufficient // to prevent dropped data (i.e. while reading from the destination it is // okay to continue writing to the buffer since we'll lock there when its // time BUT, between the time that we unlock in the #destination and the // time when we lock in the #buffer, it is possible for a transport from the // #buffer to the #destination to occur in which case the data would be // dropped since it wasn't read during the #destination query and won't be // read during the #buffer scan). // // It is important to note that we DO NOT need to do any locking for // historical reads because concurrent data writes cannot affect what is // returned. /** * The id used to determine that the Buffer should be dumped. */ public static final String BUFFER_DUMP_ID = "BUFFER"; /** * The number of milliseconds we allow between writes before we pause the * {@link BufferTransportThread}. If there amount of time between writes is * less than this value then we assume we are streaming writes, which means * it is more efficient for the BufferTransportThread to busy-wait than * block. */ protected static final int BUFFER_TRANSPORT_THREAD_ALLOWABLE_INACTIVITY_THRESHOLD_IN_MILLISECONDS = 1000; // visible // for // testing /** * The number of milliseconds we allow the {@link BufferTransportThread} to * sleep without waking up (e.g. being in the TIMED_WAITING) state before we * assume that the thread has hung/stalled and we try to rescue it. */ protected static int BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_THRESOLD_IN_MILLISECONDS = 5000; // visible // for // testing /** * The frequency with which we check to see if the * {@link BufferTransportThread} has hung/stalled. */ protected static int BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_FREQUENCY_IN_MILLISECONDS = 10000; // visible // for // testing /** * The number of milliseconds that the {@link BufferTransportThread} sleeps * after each transport in order to avoid CPU thrashing. */ protected static int BUFFER_TRANSPORT_THREAD_SLEEP_TIME_IN_MILLISECONDS = 5; // visible // for // testing /** * A flag to indicate that the {@link BufferTransportThrread} has appeared * to be hung at some point during the current lifecycle. */ protected final AtomicBoolean bufferTransportThreadHasEverAppearedHung = new AtomicBoolean( false); // visible for testing /** * A flag to indicate that the {@link BufferTransportThread} has ever been * sucessfully restarted after appearing to be hung during the current * lifecycle. */ protected final AtomicBoolean bufferTransportThreadHasEverBeenRestarted = new AtomicBoolean( false); // visible for testing /** * The location where transaction backups are stored. */ protected final String transactionStore; // exposed for Transaction backup /** * The thread that is responsible for transporting buffer content in the * background. */ private final Thread bufferTransportThread; // NOTE: Having a dedicated // thread that sleeps is faster // than using an // ExecutorService. /** * A {@link Timer} that is used to schedule some regular tasks. */ private final Timer scheduler = new Timer(true); /** * The timestamp when the {@link BufferTransportThread} last awoke from * sleep. We use this to help monitor and detect whether the thread has * stalled/hung. */ private final AtomicLong bufferTransportThreadLastWakeUp = new AtomicLong( Time.now()); /** * A flag that indicates that the {@link BufferTransportThread} is currently * paused due to inactivity (e.g. no writes). */ private final AtomicBoolean bufferTransportThreadIsPaused = new AtomicBoolean( false); /** * A flag to indicate if the Engine is running or not. */ private volatile boolean running = false; /** * A lock that prevents the Engine from causing the Buffer to transport * Writes to the Database while a buffered read is occurring. Even though * the Buffer has a transportLock, we must also maintain one at the Engine * level to prevent the appearance of dropped writes where data is * transported from the Buffer to the Database after the Database context is * captured and sent to the Buffer to finish the buffered reading. */ private final ReentrantReadWriteLock transportLock = new ReentrantReadWriteLock(); /** * The environment that is associated with this {@link Engine}. */ private final String environment; /** * A collection of listeners that should be notified of a version change for * a given token. */ @SuppressWarnings("serial") private final Map<Token, Set<VersionChangeListener>> versionChangeListeners = new ConcurrentHashMap<Token, Set<VersionChangeListener>>() { /** * An empty set that is returned on calls to {@link #get(Object)} when * there key does not exist. */ private final Set<VersionChangeListener> emptySet = Collections .unmodifiableSet(Sets.<VersionChangeListener> newHashSet()); @Override public Set<VersionChangeListener> get(Object key) { Set<VersionChangeListener> set = super.get(key); return set != null ? set : emptySet; } }; /** * A flag to indicate that the {@link BufferTransportThread} has gone into * block mode instead of busy waiting at least once. */ protected final AtomicBoolean bufferTransportThreadHasEverPaused = new AtomicBoolean( false); // visible for testing /** * Construct an Engine that is made up of a {@link Buffer} and * {@link Database} in the default locations. * */ public Engine() { this(new Buffer(), new Database(), GlobalState.DEFAULT_ENVIRONMENT); } /** * Construct an Engine that is made up of a {@link Buffer} and * {@link Database} that are both backed by {@code bufferStore} and * {@code dbStore} respectively. * * @param bufferStore * @param dbStore */ public Engine(String bufferStore, String dbStore) { this(bufferStore, dbStore, GlobalState.DEFAULT_ENVIRONMENT); } /** * Construct an Engine that is made up of a {@link Buffer} and * {@link Database} that are both backed by {@code bufferStore} and * {@code dbStore} respectively} and are associated with {@code environment} * . * * @param bufferStore * @param dbStore * @param environment */ public Engine(String bufferStore, String dbStore, String environment) { this(new Buffer(bufferStore), new Database(dbStore), environment); } /** * Construct an Engine that is made up of {@code buffer} and * {@code database}. * * @param buffer * @param database * @param environment */ @Authorized private Engine(Buffer buffer, Database database, String environment) { super(buffer, database, LockService.create(), RangeLockService.create()); this.bufferTransportThread = new BufferTransportThread(); this.transactionStore = buffer.getBackingStore() + File.separator + "txn"; /* (authorized) */ this.environment = environment; } /** * <p> * The Engine is the destination for Transaction commits, which means that * this method will accept Writes from Transactions and create new Writes * within the Engine BufferedStore (e.g. a new Write will be created in the * Buffer and eventually transported to the Database). Creating a new Write * does associate a new timestamp with the transactional data, but this is * the desired behaviour because data from a Transaction should always have * a post commit timestamp. * </p> * <p> * It is also worth calling out the fact that this method does not have any * locks to prevent multiple transactions from concurrently invoking meaning * that two transactions that don't have any overlapping reads/writes * (meaning they don't touch any of the same data) can commit at the same * time and its possible that their writes will be interleaved since calls * to this method don't globally lock. This is <em>okay</em> and does not * violate ACID because the <strong>observed</strong> state of the system * will be the same as if the transactions transported all their Writes * serially. * </p> */ @Override @DoNotInvoke public void accept(Write write) { checkArgument(write.getType() != Action.COMPARE); String key = write.getKey().toString(); TObject value = write.getValue().getTObject(); long record = write.getRecord().longValue(); boolean accepted = write.getType() == Action.ADD ? add(key, value, record) : remove(key, value, record); if(!accepted) { Logger.warn("Write {} was rejected by the Engine " + "because it was previously accepted " + "but not offset. This implies that a " + "premature shutdown occurred and the parent" + "Transaction is attempting to restore " + "itself from backup and finish committing.", write); } else { Logger.debug("'{}' was accepted by the Engine", write); } } @Override public boolean add(String key, TObject value, long record) { lockService.getWriteLock(key, record).lock(); rangeLockService.getWriteLock(key, value).lock(); try { if(super.add(key, value, record)) { notifyVersionChange(Token.wrap(key, record)); notifyVersionChange(Token.wrap(record)); notifyVersionChange(Token.wrap(key)); return true; } return false; } finally { lockService.getWriteLock(key, record).unlock(); rangeLockService.getWriteLock(key, value).unlock(); } } @Override @Restricted public void addVersionChangeListener(Token token, VersionChangeListener listener) { Set<VersionChangeListener> listeners = null; if(!versionChangeListeners.containsKey(token)) { listeners = Sets.newHashSet(); versionChangeListeners.put(token, listeners); } else { listeners = versionChangeListeners.get(token); } listeners.add(listener); } @Override public Map<Long, String> audit(long record) { transportLock.readLock().lock(); lockService.getReadLock(record).lock(); try { return super.audit(record); } finally { lockService.getReadLock(record).unlock(); transportLock.readLock().unlock(); } } @Override public Map<Long, String> audit(String key, long record) { transportLock.readLock().lock(); lockService.getReadLock(key, record).lock(); try { return super.audit(key, record); } finally { lockService.getReadLock(key, record).unlock(); transportLock.readLock().unlock(); } } @Override public Map<String, Set<TObject>> browse(long record) { transportLock.readLock().lock(); lockService.getReadLock(record).lock(); try { return super.browse(record); } finally { lockService.getReadLock(record).unlock(); transportLock.readLock().unlock(); } } @Override public Map<String, Set<TObject>> browse(long record, long timestamp) { transportLock.readLock().lock(); try { return super.browse(record, timestamp); } finally { transportLock.readLock().unlock(); } } @Override public Map<TObject, Set<Long>> browse(String key) { transportLock.readLock().lock(); lockService.getReadLock(key).lock(); try { return super.browse(key); } finally { lockService.getReadLock(key).unlock(); transportLock.readLock().unlock(); } } @Override public Map<TObject, Set<Long>> browse(String key, long timestamp) { transportLock.readLock().lock(); try { return super.browse(key, timestamp); } finally { transportLock.readLock().unlock(); } } /** * Public interface for the {@link Database#dump(String)} method. * * @param id * @return the block dumps */ @ManagedOperation public String dump(String id) { if(id.equalsIgnoreCase(BUFFER_DUMP_ID)) { return ((Buffer) buffer).dump(); } return ((Database) destination).dump(id); } @Override public Set<TObject> fetch(String key, long record) { transportLock.readLock().lock(); lockService.getReadLock(key, record).lock(); try { return super.fetch(key, record); } finally { lockService.getReadLock(key, record).unlock(); transportLock.readLock().unlock(); } } @Override public Set<TObject> fetch(String key, long record, long timestamp) { transportLock.readLock().lock(); try { return super.fetch(key, record, timestamp); } finally { transportLock.readLock().unlock(); } } @Override public Set<Long> doFind(long timestamp, String key, Operator operator, TObject... values) { transportLock.readLock().lock(); try { return super.doFind(timestamp, key, operator, values); } finally { transportLock.readLock().unlock(); } } @Override public Set<Long> doFind(String key, Operator operator, TObject... values) { transportLock.readLock().lock(); rangeLockService.getReadLock(key, operator, values).lock(); try { return super.doFind(key, operator, values); } finally { rangeLockService.getReadLock(key, operator, values).unlock(); transportLock.readLock().unlock(); } } /** * Public interface for the {@link Database#getDumpList()} method. * * @return the dump list */ @ManagedOperation public String getDumpList() { List<String> ids = ((Database) destination).getDumpList(); ids.add("BUFFER"); ListIterator<String> it = ids.listIterator(ids.size()); StringBuilder sb = new StringBuilder(); while (it.hasPrevious()) { sb.append(Math.abs(it.previousIndex() - ids.size())); sb.append(") "); sb.append(it.previous()); sb.append(System.getProperty("line.separator")); } return sb.toString(); } @Override public long getVersion(long record) { return Math.max(buffer.getVersion(record), ((Database) destination).getVersion(record)); } public long getVersion(String key) { return Math.max(buffer.getVersion(key), ((Database) destination).getVersion(key)); } @Override public long getVersion(String key, long record) { return Math.max(buffer.getVersion(key, record), ((Database) destination).getVersion(key, record)); } @Override @Restricted public void notifyVersionChange(Token token) { for (VersionChangeListener listener : versionChangeListeners.get(token)) { listener.onVersionChange(token); } } @Override public boolean remove(String key, TObject value, long record) { lockService.getWriteLock(key, record).lock(); rangeLockService.getWriteLock(key, value).lock(); try { if(super.remove(key, value, record)) { notifyVersionChange(Token.wrap(key, record)); notifyVersionChange(Token.wrap(record)); notifyVersionChange(Token.wrap(key)); return true; } return false; } finally { lockService.getWriteLock(key, record).unlock(); rangeLockService.getWriteLock(key, value).unlock(); } } @Override @Restricted public void removeVersionChangeListener(Token token, VersionChangeListener listener) { versionChangeListeners.get(token).remove(listener); } @Override public Set<Long> search(String key, String query) { // NOTE: Range locking for a search query requires too much overhead, so // we must be willing to live with the fact that a search query may // provide inconsistent results if a match is added while the read is // processing. transportLock.readLock().lock(); try { return super.search(key, query); } finally { transportLock.readLock().unlock(); } } @Override public void start() { if(!running) { Logger.info("Starting the '{}' Engine...", environment); running = true; destination.start(); buffer.start(); doTransactionRecovery(); scheduler.scheduleAtFixedRate( new TimerTask() { @Override public void run() { if(!bufferTransportThreadIsPaused.get() && bufferTransportThreadLastWakeUp.get() != 0 && TimeUnit.MILLISECONDS .convert( Time.now() - bufferTransportThreadLastWakeUp .get(), TimeUnit.MICROSECONDS) > BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_THRESOLD_IN_MILLISECONDS) { bufferTransportThreadHasEverAppearedHung .set(true); bufferTransportThread.interrupt(); } } }, BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_FREQUENCY_IN_MILLISECONDS, BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_FREQUENCY_IN_MILLISECONDS); bufferTransportThread.start(); } } @Override public AtomicOperation startAtomicOperation() { return AtomicOperation.start(this); } @Override public Transaction startTransaction() { return Transaction.start(this); } @Override public void stop() { if(running) { running = false; scheduler.cancel(); buffer.stop(); bufferTransportThread.interrupt(); destination.stop(); } } @Override public boolean verify(String key, TObject value, long record) { transportLock.readLock().lock(); lockService.getReadLock(key, record).lock(); try { return super.verify(key, value, record); } finally { lockService.getReadLock(key, record).unlock(); transportLock.readLock().unlock(); } } @Override public boolean verify(String key, TObject value, long record, long timestamp) { transportLock.readLock().lock(); try { return super.verify(key, value, record, timestamp); } finally { transportLock.readLock().unlock(); } } /** * Restore any transactions that did not finish committing prior to the * previous shutdown. */ private void doTransactionRecovery() { FileSystem.mkdirs(transactionStore); for (File file : new File(transactionStore).listFiles()) { Transaction.recover(this, file.getAbsolutePath()); Logger.info("Restored Transaction from {}", file.getName()); } } /** * Return the number of milliseconds that have elapsed since the last time * the {@link BufferTransportThread} successfully transported data. * * @return the idle time */ private long getBufferTransportThreadIdleTimeInMs() { return TimeUnit.MILLISECONDS.convert( Time.now() - ((Buffer) buffer).getTimeOfLastTransport(), TimeUnit.MICROSECONDS); } /** * A thread that is responsible for transporting content from * {@link #buffer} to {@link #destination}. * * @author jnelson */ private class BufferTransportThread extends Thread { /** * Construct a new instance. */ public BufferTransportThread() { super("BufferTransport"); setDaemon(true); } @Override public void run() { while (running) { if(getBufferTransportThreadIdleTimeInMs() > BUFFER_TRANSPORT_THREAD_ALLOWABLE_INACTIVITY_THRESHOLD_IN_MILLISECONDS) { // If there have been no transports within the last second // then make this thread block until the buffer is // transportable so that we do not waste CPU cycles // busy waiting unnecessarily. bufferTransportThreadHasEverPaused.set(true); bufferTransportThreadIsPaused.set(true); Logger.debug( "Paused the background data transport thread because " + "it has been inactive for at least {} milliseconds", BUFFER_TRANSPORT_THREAD_ALLOWABLE_INACTIVITY_THRESHOLD_IN_MILLISECONDS); buffer.waitUntilTransportable(); if(Thread.interrupted()) { // the thread has been // interrupted from the Engine // stopping break; } } doTransport(); try { // NOTE: This thread needs to sleep for a small amount of // time to avoid thrashing Thread.sleep(BUFFER_TRANSPORT_THREAD_SLEEP_TIME_IN_MILLISECONDS); bufferTransportThreadLastWakeUp.set(Time.now()); } catch (InterruptedException e) { Logger.warn( "The data transport thread been sleeping for over " + "{} milliseconds even though there is work to do. " + "An attempt has been made to restart the stalled " + "process.", BUFFER_TRANSPORT_THREAD_HUNG_DETECTION_THRESOLD_IN_MILLISECONDS); bufferTransportThreadHasEverBeenRestarted.set(true); } } } /** * Tell the Buffer to transport data and prevent deadlock in the event * of failure. */ private void doTransport() { if(transportLock.writeLock().tryLock()) { try { bufferTransportThreadIsPaused.compareAndSet(true, false); buffer.transport(destination); } finally { transportLock.writeLock().unlock(); } } } } }
CON-136 use env name for BufferTransport thread
concourse-server/src/main/java/org/cinchapi/concourse/server/storage/Engine.java
CON-136 use env name for BufferTransport thread
<ide><path>oncourse-server/src/main/java/org/cinchapi/concourse/server/storage/Engine.java <ide> package org.cinchapi.concourse.server.storage; <ide> <ide> import java.io.File; <add>import java.text.MessageFormat; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.ListIterator; <ide> * Construct a new instance. <ide> */ <ide> public BufferTransportThread() { <del> super("BufferTransport"); <add> super(MessageFormat.format("BufferTransport [{0}]", environment)); <ide> setDaemon(true); <ide> } <ide>
JavaScript
mit
4d7909878e467ce8230f8a994e8621e713c2c53f
0
Inist-CNRS/ezmaster,Inist-CNRS/ezmaster,Inist-CNRS/ezmaster
'use strict'; // to allow mongodb host and port injection thanks // to the EZMASTER_MONGODB_HOST_PORT environment parameter // (docker uses it) var mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT || 'localhost:27017'; var publicDomain = process.env.EZMASTER_PUBLIC_DOMAIN || '127.0.0.1'; var publicIP = process.env.EZMASTER_PUBLIC_IP || '127.0.0.1'; var baseURL = process.env.EZMASTER_PUBLIC_DOMAIN || 'http://' + publicIP + ':35267'; // socket variable declared here, fed in server.js and used in the 2 heartbeats events. // The 2 heartbeats events are settled in the directory named 'heartbeats'. //var socket = null; module.exports = { connectionURI: 'mongodb://' + mongoHostPort + '/ezmaster', collectionName: 'data', publicDomain: publicDomain, publicIP: publicIP, port: 35267, baseURL: baseURL, // Export of the socket variable. // It is now accessible with core.config.get('socket') or config.get('socket'). //socket: socket, browserifyModules : [ 'vue' , 'vue-resource' , 'components/addInstance' , 'components/table' , 'components/infosMachineTable' , 'vue-validator' , 'heartbeats' ], rootURL : '/', routes: [ 'config.js', 'route.js', 'status.js' ], // THE HEARTBEATS SECTION - HEARTRATE AND EVENTS // The heart will beat every 1 second. 'heartrate': 1000, // Heartbeats events declared here. // We just have to mention the file name to search instead of a complete path because // castor is configured to search events scripts from the project root // in the directory named 'heartbeats'. heartbeats: [ { // Every 1 beat (so here every 1 seconds) // call a script which refreshes the machine information. beat : 1, require: 'eventRefreshInfosMachine' }, /*{ // Every 5 beats (so here every 5 seconds) // call a script which refreshes the instances list. beat : 5, require: 'eventRefreshInstances' }*/ ], middlewares: { // '/' means to catch all the URLs (warning do not use '/*') '/': 'reverseproxy.js' }, filters: ['jbj-parse'] }; module.exports.package = require('./package.json');
castor.config.js
'use strict'; // to allow mongodb host and port injection thanks // to the EZMASTER_MONGODB_HOST_PORT environment parameter // (docker uses it) var mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT || 'localhost:27017'; var publicDomain = process.env.EZMASTER_PUBLIC_DOMAIN || '127.0.0.1'; var publicIP = process.env.EZMASTER_PUBLIC_IP || '127.0.0.1'; var baseURL = process.env.EZMASTER_PUBLIC_DOMAIN || 'http://' + publicIP + ':35267'; // socket variable declared here, fed in server.js and used in the 2 heartbeats events. // The 2 heartbeats events are settled in the directory named 'heartbeats'. //var socket = null; module.exports = { connectionURI: 'mongodb://' + mongoHostPort + '/ezmaster', collectionName: 'data', publicDomain: publicDomain, publicIP: publicIP, port: 35267, baseURL: baseURL, // Export of the socket variable. // It is now accessible with core.config.get('socket') or config.get('socket'). socket: socket, browserifyModules : [ 'vue' , 'vue-resource' , 'components/addInstance' , 'components/table' , 'components/infosMachineTable' , 'vue-validator' , 'heartbeats' ], rootURL : '/', routes: [ 'config.js', 'route.js', 'status.js' ], // THE HEARTBEATS SECTION - HEARTRATE AND EVENTS // The heart will beat every 1 second. 'heartrate': 1000, // Heartbeats events declared here. // We just have to mention the file name to search instead of a complete path because // castor is configured to search events scripts from the project root // in the directory named 'heartbeats'. heartbeats: [ { // Every 1 beat (so here every 1 seconds) // call a script which refreshes the machine information. beat : 1, require: 'eventRefreshInfosMachine' }, /*{ // Every 5 beats (so here every 5 seconds) // call a script which refreshes the instances list. beat : 5, require: 'eventRefreshInstances' }*/ ], middlewares: { // '/' means to catch all the URLs (warning do not use '/*') '/': 'reverseproxy.js' }, filters: ['jbj-parse'] }; module.exports.package = require('./package.json');
Minor changes.
castor.config.js
Minor changes.
<ide><path>astor.config.js <ide> <ide> // Export of the socket variable. <ide> // It is now accessible with core.config.get('socket') or config.get('socket'). <del> socket: socket, <add> //socket: socket, <ide> <ide> browserifyModules : [ <ide> 'vue'
Java
mit
8489b3ef90ffd120500ccc9a2a57dacca03cb84d
0
SomethingKL/SecretLeader,SomethingKL/SecretLeader,SomethingKL/SecretLeader
package entity; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.awt.Color; import java.awt.Color.*; import javax.imageio.ImageIO; import java.util.*; import framework.TCPClient; import ui.SLPanel; public class PolicySelection { /**box around the list*/ private Rectangle box; //the box around the first card private Rectangle card1Box; //the box around the second card private Rectangle card2Box; //the box around the third card private Rectangle card3Box; /**final width of the frame*/ private static final int WIDTH = 100; /**final height of the frame*/ private static final int HEIGHT = 150; //where the image is at private TCPClient client = new TCPClient(); //The first card being displayed private PolicyCard card1; //the second card being displayed private PolicyCard card2; //the third card being displayed private PolicyCard card3; //the first card of the chancellors view private PolicyCard card4; //the second card of the chancellors view private PolicyCard card5; //the username of the player private String playerID; //string for the policies private String cat; //whether the next screen should be chosen private boolean nextState = false; //however many cards we want to create private int cardAmount = 3; //random integer to decide if a card is red or blue private int randInt = 0; public PolicySelection(Point point,String userName) throws IOException{ box = new Rectangle(point.x, point.y,WIDTH*4, HEIGHT); //setting up the file client.openToWrite("data/leaveStarting.txt"); client.writeToFile("#Which screen to be on; 1 for the presidents screen; 2 for the chancellors screen"); client.writeToFile("1"); client.close(); //sets the ID of the player playerID = userName; //need to make these randomized //need to make these randomized Random cardRandomizer = new Random(); card1 = new PolicyCard(new Point(760, 620),"Blue"); card2 = new PolicyCard(new Point(900, 620),"Red"); card3 = new PolicyCard(new Point(1040,620),"Blue"); //////////////how to change the image //card1.getNewImage("Red"); //mapping to assign card values in a loop Map<String,PolicyCard> cardMap = new HashMap<String,PolicyCard>(); (cardMap).put("card1", card1); (cardMap).put("card2", card2); (cardMap).put("card3", card3); //for loop that will assign blue or red to each card in the hash map for(int i = 1; i < cardAmount+1; i++){ randInt = cardRandomizer.nextInt(2); System.out.println(randInt + " random"); String cardName = "card" + i; System.out.println(cardName); PolicyCard card = cardMap.get(cardName); if(randInt == 0){ card.getNewImage("Blue"); System.out.println("card gets blue"); } if(randInt == 1){ card.getNewImage("Red"); System.out.println("card gets red"); } } card1Box = new Rectangle(760,620,WIDTH,HEIGHT); card2Box = new Rectangle(900,620,WIDTH,HEIGHT); card3Box = new Rectangle(1040,620,WIDTH,HEIGHT); } /**{@literal} * @throws IOException * Will only put the cards down if the player is the chancellor or the president */ public void draw(Graphics2D g2d, SLPanel panel) throws IOException{ String[] turnInfo = client.readFile("data/Turn.txt"); String[] setPiece = client.readFile("data/leaveStarting.txt"); client.close(); //the first stage of the game, where the president picks his cards if(setPiece[0].contains(new String("1")) && turnInfo[0].equals(playerID)){ card1.draw(g2d,panel); card2.draw(g2d, panel); card3.draw(g2d, panel); } //the second stage of the game, where the chancellor picks his cards else if(setPiece[0].contains(new String("2")) && turnInfo[1].equals(playerID)){ //pick up the information from the file for each of the card setPiece = client.readFile("data/VotingScreen.txt"); card4 = new PolicyCard(new Point(760, 620),setPiece[0]); card5 = new PolicyCard(new Point(900, 620),setPiece[1]); card4.draw(g2d, panel); card5.draw(g2d, panel); } } /** * @param e, the mouse clicking the button * @return true or false, whether something happened or not */ public void click(MouseEvent e, SLPanel.GameState state) { String[] setPiece = client.readFile("data/leaveStarting.txt"); //this is the border of things that can be clicked //has to be in the right gamestate, right point and in the right part of the game if(box.contains(e.getPoint()) && state == SLPanel.GameState.POLICY && setPiece[0].equals(new String("1"))){ //if each button has been clicked if(card1Box.contains(e.getPoint())){ if(card1.getCardKept()){ card1.flipKept(); //need to figure out how to change the color of a rectangle //need to look like a highlight } else{ card1.flipKept(); } } else if(card2Box.contains(e.getPoint())){ if(card2.getCardKept()){ card2.flipKept(); } else{ card2.flipKept(); } } else if(card3Box.contains(e.getPoint())){ if(card3.getCardKept()){ card3.flipKept(); } else{ card3.flipKept(); } } //resets the board if two are selected if(resetBoard()){ //go to the next screen client.openToWrite("data/leaveStarting.txt"); client.writeToFile("#Which screen to be on; 1 for the presidents screen; 2 for the chancellors screen"); client.writeToFile("2"); client.close(); //to pass the policy cards to the next screen client.openToWrite("data/VotingScreen.txt"); client.writeToFile("#The voting policies to be passed"); client.writeToFile(cat); client.close(); } } else if(box.contains(e.getPoint()) && state == SLPanel.GameState.POLICY && setPiece[0].equals(new String("2"))){ //getting the board information from the file String[] boardInfo = client.readFile("data/Board.txt"); int blue = Integer.parseInt(boardInfo[0]); int red = Integer.parseInt(boardInfo[1]); if(card1Box.contains(e.getPoint())){ //the first card if(card4.getType().equals(new String("Red"))){ System.out.println("card 1 red"); red += 1; } else if (card4.getType().equals(new String("Blue"))){ blue +=1; System.out.println("card 1 blue"); } } //the second card else if(card2Box.contains(e.getPoint())){ //the new card to go on the screen if(card5.getType().equals(new String("Red"))){ System.out.println("card 2 red"); red += 1; } else if (card5.getType().equals(new String("Blue"))){ System.out.println("card 2 blue"); blue +=1; } } else{ assert(false); } //update to the board file! final int newBlue = blue; final int newRed = red; new Thread(() -> doWork(newBlue,newRed)).start(); /* try { Thread.sleep(10000); //1000 milliseconds is one second. } catch(InterruptedException ex) { Thread.currentThread().interrupt(); }*/ //have to get the next screen to come up everytime nextState = true; } } /**Sets the number of blue and red cards in a file * * @param blue, the number of blue cards * @param red, the number of red cards */ private void doWork(int blue, int red) { client.openToWrite("data/Board.txt"); client.writeToFile("#number of Blue victories"); client.writeToFile(String.valueOf(blue)); client.writeToFile("#number of Red victories"); client.writeToFile(String.valueOf(red)); client.close(); return; } /** * @return true or false, whether two cards have been selected or not */ private boolean resetBoard(){ if(card1.getCardKept() && card2.getCardKept()){ cat = card1.getType() + "\n" + card2.getType(); return true; } else if(card1.getCardKept() && card3.getCardKept()){ cat = card1.getType() + "\n" + card3.getType(); return true; } else if(card2.getCardKept() && card3.getCardKept()){ cat = card2.getType() + "\n" + card3.getType(); return true; } else{ return false; } } /** * * @return true or false, whether the next state of the game should happen */ public boolean isNextState(){ return nextState; } }
SecretLeader/src/entity/PolicySelection.java
package entity; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.awt.Color; import java.awt.Color.*; import javax.imageio.ImageIO; import framework.TCPClient; import ui.SLPanel; public class PolicySelection { /**box around the list*/ private Rectangle box; //the box around the first card private Rectangle card1Box; //the box around the second card private Rectangle card2Box; //the box around the third card private Rectangle card3Box; /**final width of the frame*/ private static final int WIDTH = 100; /**final height of the frame*/ private static final int HEIGHT = 150; //where the image is at private TCPClient client = new TCPClient(); //The first card being displayed private PolicyCard card1; //the second card being displayed private PolicyCard card2; //the third card being displayed private PolicyCard card3; //the first card of the chancellors view private PolicyCard card4; //the second card of the chancellors view private PolicyCard card5; //the username of the player private String playerID; //string for the policies private String cat; //whether the next screen should be choosen private boolean nextState = false; public PolicySelection(Point point,String userName) throws IOException{ box = new Rectangle(point.x, point.y,WIDTH*4, HEIGHT); //setting up the file client.openToWrite("data/leaveStarting.txt"); client.writeToFile("#Which screen to be on; 1 for the presidents screen; 2 for the chancellors screen"); client.writeToFile("1"); client.close(); //sets the ID of the player playerID = userName; //need to make these randomized card1 = new PolicyCard(new Point(760, 620),"Blue"); card2 = new PolicyCard(new Point(900, 620),"Red"); card3 = new PolicyCard(new Point(1040,620),"Blue"); //////////////how to change the image card1.getNewImage("Red"); card1Box = new Rectangle(760,620,WIDTH,HEIGHT); card2Box = new Rectangle(900,620,WIDTH,HEIGHT); card3Box = new Rectangle(1040,620,WIDTH,HEIGHT); } /**{@literal} * @throws IOException * Will only put the cards down if the player is the chancellor or the president */ public void draw(Graphics2D g2d, SLPanel panel) throws IOException{ String[] turnInfo = client.readFile("data/Turn.txt"); String[] setPiece = client.readFile("data/leaveStarting.txt"); client.close(); //the first stage of the game, where the president picks his cards if(setPiece[0].contains(new String("1")) && turnInfo[0].equals(playerID)){ card1.draw(g2d,panel); card2.draw(g2d, panel); card3.draw(g2d, panel); } //the second stage of the game, where the chancellor picks his cards else if(setPiece[0].contains(new String("2")) && turnInfo[1].equals(playerID)){ //pick up the information from the file for each of the card setPiece = client.readFile("data/VotingScreen.txt"); card4 = new PolicyCard(new Point(760, 620),setPiece[0]); card5 = new PolicyCard(new Point(900, 620),setPiece[1]); card4.draw(g2d, panel); card5.draw(g2d, panel); } } /** * @param e, the mouse clicking the button * @return true or false, whether something happened or not */ public void click(MouseEvent e, SLPanel.GameState state) { String[] setPiece = client.readFile("data/leaveStarting.txt"); //this is the border of things that can be clicked //has to be in the right gamestate, right point and in the right part of the game if(box.contains(e.getPoint()) && state == SLPanel.GameState.POLICY && setPiece[0].equals(new String("1"))){ //if each button has been clicked if(card1Box.contains(e.getPoint())){ if(card1.getCardKept()){ card1.flipKept(); //need to figure out how to change the color of a rectangle //need to look like a highlight } else{ card1.flipKept(); } } else if(card2Box.contains(e.getPoint())){ if(card2.getCardKept()){ card2.flipKept(); } else{ card2.flipKept(); } } else if(card3Box.contains(e.getPoint())){ if(card3.getCardKept()){ card3.flipKept(); } else{ card3.flipKept(); } } //resets the board if two are selected if(resetBoard()){ //go to the next screen client.openToWrite("data/leaveStarting.txt"); client.writeToFile("#Which screen to be on; 1 for the presidents screen; 2 for the chancellors screen"); client.writeToFile("2"); client.close(); //to pass the policy cards to the next screen client.openToWrite("data/VotingScreen.txt"); client.writeToFile("#The voting policies to be passed"); client.writeToFile(cat); client.close(); } } else if(box.contains(e.getPoint()) && state == SLPanel.GameState.POLICY && setPiece[0].equals(new String("2"))){ //getting the board information from the file String[] boardInfo = client.readFile("data/Board.txt"); int blue = Integer.parseInt(boardInfo[0]); int red = Integer.parseInt(boardInfo[1]); if(card1Box.contains(e.getPoint())){ //the first card if(card4.getType().equals(new String("Red"))){ System.out.println("card 1 red"); red += 1; } else if (card4.getType().equals(new String("Blue"))){ blue +=1; System.out.println("card 1 blue"); } } //the second card else if(card2Box.contains(e.getPoint())){ //the new card to go on the screen if(card5.getType().equals(new String("Red"))){ System.out.println("card 2 red"); red += 1; } else if (card5.getType().equals(new String("Blue"))){ System.out.println("card 2 blue"); blue +=1; } } else{ assert(false); } //update to the board file! final int newBlue = blue; final int newRed = red; new Thread(() -> doWork(newBlue,newRed)).start(); /* try { Thread.sleep(10000); //1000 milliseconds is one second. } catch(InterruptedException ex) { Thread.currentThread().interrupt(); }*/ //have to get the next screen to come up everytime nextState = true; } } /**Sets the number of blue and red cards in a file * * @param blue, the number of blue cards * @param red, the number of red cards */ private void doWork(int blue, int red) { client.openToWrite("data/Board.txt"); client.writeToFile("#number of Blue victories"); client.writeToFile(String.valueOf(blue)); client.writeToFile("#number of Red victories"); client.writeToFile(String.valueOf(red)); client.close(); return; } /** * @return true or false, whether two cards have been selected or not */ private boolean resetBoard(){ if(card1.getCardKept() && card2.getCardKept()){ cat = card1.getType() + "\n" + card2.getType(); return true; } else if(card1.getCardKept() && card3.getCardKept()){ cat = card1.getType() + "\n" + card3.getType(); return true; } else if(card2.getCardKept() && card3.getCardKept()){ cat = card2.getType() + "\n" + card3.getType(); return true; } else{ return false; } } /** * * @return true or false, whether the next state of the game should happen */ public boolean isNextState(){ return nextState; } }
added random - will need tweaking to get working properly
SecretLeader/src/entity/PolicySelection.java
added random - will need tweaking to get working properly
<ide><path>ecretLeader/src/entity/PolicySelection.java <ide> import java.awt.Color; <ide> import java.awt.Color.*; <ide> import javax.imageio.ImageIO; <del> <add>import java.util.*; <ide> import framework.TCPClient; <ide> import ui.SLPanel; <ide> <ide> private String playerID; <ide> //string for the policies <ide> private String cat; <del> //whether the next screen should be choosen <add> //whether the next screen should be chosen <ide> private boolean nextState = false; <add> //however many cards we want to create <add> private int cardAmount = 3; <add> //random integer to decide if a card is red or blue <add> private int randInt = 0; <ide> <ide> public PolicySelection(Point point,String userName) throws IOException{ <ide> box = new Rectangle(point.x, point.y,WIDTH*4, HEIGHT); <ide> //sets the ID of the player <ide> playerID = userName; <ide> //need to make these randomized <add> <add> //need to make these randomized <add> Random cardRandomizer = new Random(); <add> <ide> card1 = new PolicyCard(new Point(760, 620),"Blue"); <ide> card2 = new PolicyCard(new Point(900, 620),"Red"); <ide> card3 = new PolicyCard(new Point(1040,620),"Blue"); <ide> //////////////how to change the image <del> card1.getNewImage("Red"); <add> //card1.getNewImage("Red"); <add> <add> //mapping to assign card values in a loop <add> Map<String,PolicyCard> cardMap = new HashMap<String,PolicyCard>(); <add> (cardMap).put("card1", card1); <add> (cardMap).put("card2", card2); <add> (cardMap).put("card3", card3); <add> //for loop that will assign blue or red to each card in the hash map <add> for(int i = 1; i < cardAmount+1; i++){ <add> randInt = cardRandomizer.nextInt(2); <add> System.out.println(randInt + " random"); <add> String cardName = "card" + i; <add> System.out.println(cardName); <add> PolicyCard card = cardMap.get(cardName); <add> if(randInt == 0){ <add> card.getNewImage("Blue"); <add> System.out.println("card gets blue"); <add> } <add> if(randInt == 1){ <add> card.getNewImage("Red"); <add> System.out.println("card gets red"); <add> } <add> } <ide> <ide> card1Box = new Rectangle(760,620,WIDTH,HEIGHT); <ide> card2Box = new Rectangle(900,620,WIDTH,HEIGHT);
JavaScript
mit
4585cb39eedc33341c1f7f78d215770d1ce60924
0
FNNDSC/ami,FNNDSC/ami,FNNDSC/ami,FNNDSC/vjs,FNNDSC/vjs,FNNDSC/ami,FNNDSC/vjs
/* globals Stats, dat*/ import CamerasOrthographic from 'base/cameras/cameras.orthographic'; import ControlsOrthographic from 'base/controls/controls.trackballortho'; import HelpersLut from 'base/helpers/helpers.lut'; import HelpersStack from 'base/helpers/helpers.stack'; import LoadersVolume from 'base/loaders/loaders.volume'; import ShadersLayerUniform from 'base/shaders/shaders.layer.uniform'; import ShadersLayerVertex from 'base/shaders/shaders.layer.vertex'; import ShadersLayerFragment from 'base/shaders/shaders.layer.fragment'; import ShadersUniform from 'base/shaders/shaders.data.uniform'; import ShadersVertex from 'base/shaders/shaders.data.vertex'; import ShadersFragment from 'base/shaders/shaders.data.fragment'; // standard global letiables let controls; let renderer; let camera; let statsyay; let threeD; // let mouse = { x: 0, y: 0, }; function onMouseMove(event) { // calculate mouse position in normalized device coordinates // (-1 to +1) for both components mouse.x = (event.clientX / threeD.clientWidth) * 2 - 1; mouse.y = -(event.clientY / threeD.clientHeight) * 2 + 1; // push to shaders uniformsLayerMix.uMouse.value = new THREE.Vector2(mouse.x, mouse.y); } // let sceneLayer0TextureTarget; let sceneLayer1TextureTarget; // let sceneLayer0; // let lutLayer0; let sceneLayer1; let meshLayer1; let uniformsLayer1; let materialLayer1; let lutLayer1; let sceneLayerMix; let meshLayerMix; let uniformsLayerMix; let materialLayerMix; let layer1 = { opacity: 1.0, lut: null, interpolation: 1, }; let layerMix = { opacity0: 1.0, opacity1: 1.0, type0: 0, type1: 1, trackMouse: true, }; // FUNCTIONS function init() { // this function is executed on each animation frame function animate() { // render controls.update(); // render first layer offscreen renderer.render(sceneLayer0, camera, sceneLayer0TextureTarget, true); // render second layer offscreen renderer.render(sceneLayer1, camera, sceneLayer1TextureTarget, true); // mix the layers and render it ON screen! renderer.render(sceneLayerMix, camera); statsyay.update(); // request new frame requestAnimationFrame(function() { animate(); }); } // renderer threeD = document.getElementById('r3d'); renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, }); renderer.setSize(threeD.clientWidth, threeD.clientHeight); renderer.setClearColor(0x3F51B5, 1); threeD.appendChild(renderer.domElement); // stats statsyay = new Stats(); threeD.appendChild(statsyay.domElement); // scene sceneLayer0 = new THREE.Scene(); sceneLayer1 = new THREE.Scene(); sceneLayerMix = new THREE.Scene(); // render to texture!!!! sceneLayer0TextureTarget = new THREE.WebGLRenderTarget( threeD.clientWidth, threeD.clientHeight, {minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat, }); sceneLayer1TextureTarget = new THREE.WebGLRenderTarget( threeD.clientWidth, threeD.clientHeight, {minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat, }); // camera camera = new CamerasOrthographic( threeD.clientWidth / -2, threeD.clientWidth / 2, threeD.clientHeight / 2, threeD.clientHeight / -2, 0.1, 10000); // controls controls = new ControlsOrthographic(camera, threeD); controls.staticMoving = true; controls.noRotate = true; camera.controls = controls; animate(); } window.onload = function() { // init threeJS... init(); let data = [ 'patient1/7001_t1_average_BRAINSABC.nii.gz', 'patient2/7002_t1_average_BRAINSABC.nii.gz', ]; let files = data.map(function(v) { return 'https://cdn.rawgit.com/FNNDSC/data/master/nifti/slicer_brain/' + v; }); function buildGUI(stackHelper) { function updateLayer1() { // update layer1 geometry... if (meshLayer1) { meshLayer1.geometry.dispose(); meshLayer1.geometry = stackHelper.slice.geometry; meshLayer1.geometry.verticesNeedUpdate = true; } } function updateLayerMix() { // update layer1 geometry... if (meshLayerMix) { sceneLayerMix.remove(meshLayerMix); meshLayerMix.material.dispose(); // meshLayerMix.material = null; meshLayerMix.geometry.dispose(); // meshLayerMix.geometry = null; // add mesh in this scene with right shaders... meshLayerMix = new THREE.Mesh(stackHelper.slice.geometry, materialLayerMix); // go the LPS space meshLayerMix.applyMatrix(stackHelper.stack._ijk2LPS); sceneLayerMix.add(meshLayerMix); } } let stack = stackHelper._stack; let gui = new dat.GUI({ autoPlace: false, }); let customContainer = document.getElementById('my-gui-container'); customContainer.appendChild(gui.domElement); // // layer 0 folder // let layer0Folder = gui.addFolder('Layer 0 (Base)'); layer0Folder.add( stackHelper.slice, 'windowWidth', 1, stack.minMax[1]).step(1).listen(); layer0Folder.add( stackHelper.slice, 'windowCenter', stack.minMax[0], stack.minMax[1]).step(1).listen(); layer0Folder.add(stackHelper.slice, 'intensityAuto'); layer0Folder.add(stackHelper.slice, 'invert'); let lutUpdate = layer0Folder.add( stackHelper.slice, 'lut', lutLayer0.lutsAvailable()); lutUpdate.onChange(function(value) { lutLayer0.lut = value; stackHelper.slice.lutTexture = lutLayer0.texture; }); let indexUpdate = layer0Folder.add( stackHelper, 'index', 0, stack.dimensionsIJK.z - 1).step(1).listen(); indexUpdate.onChange(function() { updateLayer1(); updateLayerMix(); }); layer0Folder.add(stackHelper.slice, 'interpolation', 0, 1).step(1).listen(); layer0Folder.open(); // // layer 1 folder // let layer1Folder = gui.addFolder('Layer 1'); let interpolationLayer1 = layer1Folder.add(layer1, 'interpolation', 0, 1).step(1).listen(); interpolationLayer1.onChange(function(value) { uniformsLayer1.uInterpolation.value = value; // re-compute shaders let fs = new ShadersFragment(uniformsLayer1); materialLayer1.fragmentShader = fs.compute(); materialLayer1.needsUpdate = true; }); let layer1LutUpdate = layer1Folder.add(layer1, 'lut', lutLayer1.lutsAvailable()); layer1LutUpdate.onChange(function(value) { lutLayer1.lut = value; // propagate to shaders uniformsLayer1.uLut.value = 1; uniformsLayer1.uTextureLUT.value = lutLayer1.texture; }); layer1Folder.open(); // // layer mix folder // let layerMixFolder = gui.addFolder('Layer Mix'); let opacityLayerMix = layerMixFolder.add(layerMix, 'opacity1', 0, 1).step(0.01).listen(); opacityLayerMix.onChange(function(value) { uniformsLayerMix.uOpacity1.value = value; }); let layerMixTrackMouseUpdate = layerMixFolder.add(layerMix, 'trackMouse'); layerMixTrackMouseUpdate.onChange(function(value) { if (value) { uniformsLayerMix.uTrackMouse.value = 1; } else { uniformsLayerMix.uTrackMouse.value = 0; } }); layerMixFolder.open(); // hook up callbacks controls.addEventListener('OnScroll', function(e) { if (e.delta > 0) { if (stackHelper.index >= stack.dimensionsIJK.z - 1) { return false; } stackHelper.index += 1; } else { if (stackHelper.index <= 0) { return false; } stackHelper.index -= 1; } updateLayer1(); updateLayerMix(); }); updateLayer1(); updateLayerMix(); function onWindowResize() { let threeD = document.getElementById('r3d'); camera.canvas = { width: threeD.clientWidth, height: threeD.clientHeight, }; camera.fitBox(2); sceneLayer0TextureTarget.setSize(threeD.clientWidth, threeD.clientHeight); sceneLayer1TextureTarget.setSize(threeD.clientWidth, threeD.clientHeight); renderer.setSize(threeD.clientWidth, threeD.clientHeight); } window.addEventListener('resize', onWindowResize, false); onWindowResize(); // mouse move cb window.addEventListener('mousemove', onMouseMove, false); } let loader = new LoadersVolume(threeD); function handleSeries() { // // first stack of first series let mergedSeries = loader.data[0].mergeSeries(loader.data); loader.free(); loader = null; let stack = null; let stack2 = null; if (mergedSeries[0].seriesInstanceUID !== 'https://cdn.rawgit.com/FNNDSC/data/master/nifti/slicer_brain/patient1/7001_t1_average_BRAINSABC.nii.gz') { stack = mergedSeries[1].stack[0]; stack2 = mergedSeries[0].stack[0]; } else { stack = mergedSeries[0].stack[0]; stack2 = mergedSeries[1].stack[0]; } stack = mergedSeries[0].stack[0]; stack2 = mergedSeries[1].stack[0]; let stackHelper = new HelpersStack(stack); stackHelper.bbox.visible = false; stackHelper.border.visible = false; sceneLayer0.add(stackHelper); // // create layer 1.... // prepare it // * ijk2LPS transforms // * Z spacing // * etc. // stack2.prepare(); // pixels packing for the fragment shaders now happens there stack2.pack(); let textures2 = []; for (let m = 0; m < stack2._rawData.length; m++) { let tex = new THREE.DataTexture( stack2.rawData[m], stack2.textureSize, stack2.textureSize, stack2.textureType, THREE.UnsignedByteType, THREE.UVMapping, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.NearestFilter, THREE.NearestFilter); tex.needsUpdate = true; tex.flipY = true; textures2.push(tex); } // // create material && mesh then add it to sceneLayer1 uniformsLayer1 = ShadersUniform.uniforms(); uniformsLayer1.uTextureSize.value = stack2.textureSize; uniformsLayer1.uTextureContainer.value = textures2; uniformsLayer1.uWorldToData.value = stack2.lps2IJK; uniformsLayer1.uNumberOfChannels.value = stack2.numberOfChannels; uniformsLayer1.uBitsAllocated.value = stack2.bitsAllocated; uniformsLayer1.uPackedPerPixel.value = stack2.packedPerPixel; uniformsLayer1.uWindowCenterWidth.value = [stack2.windowCenter, stack2.windowWidth]; uniformsLayer1.uRescaleSlopeIntercept.value = [stack2.rescaleSlope, stack2.rescaleIntercept]; uniformsLayer1.uDataDimensions.value = [stack2.dimensionsIJK.x, stack2.dimensionsIJK.y, stack2.dimensionsIJK.z]; // generate shaders on-demand! let fs = new ShadersFragment(uniformsLayer1); let vs = new ShadersVertex(); materialLayer1 = new THREE.ShaderMaterial( {side: THREE.DoubleSide, uniforms: uniformsLayer1, vertexShader: vs.compute(), fragmentShader: fs.compute(), }); // add mesh in this scene with right shaders... meshLayer1 = new THREE.Mesh(stackHelper.slice.geometry, materialLayer1); // go the LPS space meshLayer1.applyMatrix(stack._ijk2LPS); sceneLayer1.add(meshLayer1); // // Create the Mix layer uniformsLayerMix = ShadersLayerUniform.uniforms(); uniformsLayerMix.uTextureBackTest0.value = sceneLayer0TextureTarget.texture; uniformsLayerMix.uTextureBackTest1.value = sceneLayer1TextureTarget.texture; uniformsLayerMix.uTrackMouse.value = 1; uniformsLayerMix.uMouse.value = new THREE.Vector2(0, 0); // generate shaders on-demand! let fls = new ShadersLayerFragment(uniformsLayerMix); let vls = new ShadersLayerVertex(); materialLayerMix = new THREE.ShaderMaterial( {side: THREE.DoubleSide, uniforms: uniformsLayerMix, vertexShader: vls.compute(), fragmentShader: fls.compute(), transparent: true, }); // add mesh in this scene with right shaders... meshLayerMix = new THREE.Mesh(stackHelper.slice.geometry, materialLayerMix); // go the LPS space meshLayerMix.applyMatrix(stack._ijk2LPS); sceneLayerMix.add(meshLayerMix); // set camera let worldbb = stack.worldBoundingBox(); let lpsDims = new THREE.Vector3( worldbb[1] - worldbb[0], worldbb[3] - worldbb[2], worldbb[5] - worldbb[4] ); // box: {halfDimensions, center} let box = { center: stack.worldCenter().clone(), halfDimensions: new THREE.Vector3(lpsDims.x + 50, lpsDims.y + 50, lpsDims.z + 50), }; // init and zoom let canvas = { width: threeD.clientWidth, height: threeD.clientHeight, }; camera.directions = [stack.xCosine, stack.yCosine, stack.zCosine]; camera.box = box; camera.canvas = canvas; camera.update(); camera.fitBox(2); // CREATE LUT lutLayer0 = new HelpersLut( 'my-lut-canvases-l0', 'default', 'linear', [[0, 0, 0, 0], [1, 1, 1, 1]], [[0, 1], [1, 1]]); lutLayer0.luts = HelpersLut.presetLuts(); lutLayer1 = new HelpersLut( 'my-lut-canvases-l1', 'default', 'linear', [[0, 0, 0, 0], [1, 1, 1, 1]], [[0, 1], [1, 1]]); lutLayer1.luts = HelpersLut.presetLuts(); layer1.lut = lutLayer1; buildGUI(stackHelper); } // load sequence for each file loader.load(files) .then(function() { handleSeries(); }) .catch(function(error) { window.console.log('oops... something went wrong...'); window.console.log(error); }); };
examples/viewers_compare/viewers_compare.js
/* globals Stats, dat*/ import CamerasOrthographic from 'base/cameras/cameras.orthographic'; import ControlsOrthographic from 'base/controls/controls.trackballortho'; import HelpersLut from 'base/helpers/helpers.lut'; import HelpersStack from 'base/helpers/helpers.stack'; import LoadersVolume from 'base/loaders/loaders.volume'; import ShadersLayerUniform from 'base/shaders/shaders.layer.uniform'; import ShadersLayerVertex from 'base/shaders/shaders.layer.vertex'; import ShadersLayerFragment from 'base/shaders/shaders.layer.fragment'; import ShadersUniform from 'base/shaders/shaders.data.uniform'; import ShadersVertex from 'base/shaders/shaders.data.vertex'; import ShadersFragment from 'base/shaders/shaders.data.fragment'; // standard global letiables let controls; let renderer; let camera; let statsyay; let threeD; // let mouse = { x: 0, y: 0, }; function onMouseMove(event) { // calculate mouse position in normalized device coordinates // (-1 to +1) for both components mouse.x = (event.clientX / threeD.clientWidth) * 2 - 1; mouse.y = -(event.clientY / threeD.clientHeight) * 2 + 1; // push to shaders uniformsLayerMix.uMouse.value = new THREE.Vector2(mouse.x, mouse.y); } // let sceneLayer0TextureTarget; let sceneLayer1TextureTarget; // let sceneLayer0; // let lutLayer0; let sceneLayer1; let meshLayer1; let uniformsLayer1; let materialLayer1; let lutLayer1; let sceneLayerMix; let meshLayerMix; let uniformsLayerMix; let materialLayerMix; let layer1 = { opacity: 1.0, lut: null, interpolation: 1, }; let layerMix = { opacity0: 1.0, opacity1: 1.0, type0: 0, type1: 1, trackMouse: true, }; // FUNCTIONS function init() { // this function is executed on each animation frame function animate() { // render controls.update(); // render first layer offscreen renderer.render(sceneLayer0, camera, sceneLayer0TextureTarget, true); // render second layer offscreen renderer.render(sceneLayer1, camera, sceneLayer1TextureTarget, true); // mix the layers and render it ON screen! renderer.render(sceneLayerMix, camera); statsyay.update(); // request new frame requestAnimationFrame(function() { animate(); }); } // renderer threeD = document.getElementById('r3d'); renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, }); renderer.setSize(threeD.clientWidth, threeD.clientHeight); renderer.setClearColor(0x3F51B5, 1); threeD.appendChild(renderer.domElement); // stats statsyay = new Stats(); threeD.appendChild(statsyay.domElement); // scene sceneLayer0 = new THREE.Scene(); sceneLayer1 = new THREE.Scene(); sceneLayerMix = new THREE.Scene(); // render to texture!!!! sceneLayer0TextureTarget = new THREE.WebGLRenderTarget( threeD.clientWidth, threeD.clientHeight, {minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat, }); sceneLayer1TextureTarget = new THREE.WebGLRenderTarget( threeD.clientWidth, threeD.clientHeight, {minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat, }); // camera camera = new CamerasOrthographic( threeD.clientWidth / -2, threeD.clientWidth / 2, threeD.clientHeight / 2, threeD.clientHeight / -2, 0.1, 10000); // controls controls = new ControlsOrthographic(camera, threeD); controls.staticMoving = true; controls.noRotate = true; camera.controls = controls; animate(); } window.onload = function() { // init threeJS... init(); let data = [ 'patient1/7001_t1_average_BRAINSABC.nii.gz', 'patient2/7002_t1_average_BRAINSABC.nii.gz', ]; let files = data.map(function(v) { return 'https://cdn.rawgit.com/FNNDSC/data/master/nifti/slicer_brain/' + v; }); function buildGUI(stackHelper) { function updateLayer1() { // update layer1 geometry... if (meshLayer1) { meshLayer1.geometry.dispose(); meshLayer1.geometry = stackHelper.slice.geometry; meshLayer1.geometry.verticesNeedUpdate = true; } } function updateLayerMix() { // update layer1 geometry... if (meshLayerMix) { sceneLayerMix.remove(meshLayerMix); meshLayerMix.material.dispose(); // meshLayerMix.material = null; meshLayerMix.geometry.dispose(); // meshLayerMix.geometry = null; // add mesh in this scene with right shaders... meshLayerMix = new THREE.Mesh(stackHelper.slice.geometry, materialLayerMix); // go the LPS space meshLayerMix.applyMatrix(stackHelper.stack._ijk2LPS); sceneLayerMix.add(meshLayerMix); } } let stack = stackHelper._stack; let gui = new dat.GUI({ autoPlace: false, }); let customContainer = document.getElementById('my-gui-container'); customContainer.appendChild(gui.domElement); // // layer 0 folder // let layer0Folder = gui.addFolder('Layer 0 (Base)'); layer0Folder.add( stackHelper.slice, 'windowWidth', 1, stack.minMax[1]).step(1).listen(); layer0Folder.add( stackHelper.slice, 'windowCenter', stack.minMax[0], stack.minMax[1]).step(1).listen(); layer0Folder.add(stackHelper.slice, 'intensityAuto'); layer0Folder.add(stackHelper.slice, 'invert'); let lutUpdate = layer0Folder.add( stackHelper.slice, 'lut', lutLayer0.lutsAvailable()); lutUpdate.onChange(function(value) { lutLayer0.lut = value; stackHelper.slice.lutTexture = lutLayer0.texture; }); let indexUpdate = layer0Folder.add( stackHelper, 'index', 0, stack.dimensionsIJK.z - 1).step(1).listen(); indexUpdate.onChange(function() { updateLayer1(); updateLayerMix(); }); layer0Folder.add(stackHelper.slice, 'interpolation', 0, 1).step(1).listen(); layer0Folder.open(); // // layer 1 folder // let layer1Folder = gui.addFolder('Layer 1'); let interpolationLayer1 = layer1Folder.add(layer1, 'interpolation', 0, 1).step(1).listen(); interpolationLayer1.onChange(function(value) { uniformsLayer1.uInterpolation.value = value; // re-compute shaders let fs = new ShadersFragment(uniformsLayer1); materialLayer1.fragmentShader = fs.compute(); materialLayer1.needsUpdate = true; }); let layer1LutUpdate = layer1Folder.add(layer1, 'lut', lutLayer1.lutsAvailable()); layer1LutUpdate.onChange(function(value) { lutLayer1.lut = value; // propagate to shaders uniformsLayer1.uLut.value = 1; uniformsLayer1.uTextureLUT.value = lutLayer1.texture; }); layer1Folder.open(); // // layer mix folder // let layerMixFolder = gui.addFolder('Layer Mix'); let opacityLayerMix = layerMixFolder.add(layerMix, 'opacity1', 0, 1).step(0.01).listen(); opacityLayerMix.onChange(function(value) { uniformsLayerMix.uOpacity1.value = value; }); let layerMixTrackMouseUpdate = layerMixFolder.add(layerMix, 'trackMouse'); layerMixTrackMouseUpdate.onChange(function(value) { if (value) { uniformsLayerMix.uTrackMouse.value = 1; } else { uniformsLayerMix.uTrackMouse.value = 0; } }); layerMixFolder.open(); // hook up callbacks controls.addEventListener('OnScroll', function(e) { if (e.delta > 0) { if (stackHelper.index >= stack.dimensionsIJK.z - 1) { return false; } stackHelper.index += 1; } else { if (stackHelper.index <= 0) { return false; } stackHelper.index -= 1; } updateLayer1(); updateLayerMix(); }); updateLayer1(); updateLayerMix(); function onWindowResize() { let threeD = document.getElementById('r3d'); camera.canvas = { width: threeD.clientWidth, height: threeD.clientHeight, }; camera.fitBox(2); sceneLayer0TextureTarget.setSize(threeD.clientWidth, threeD.clientHeight); sceneLayer1TextureTarget.setSize(threeD.clientWidth, threeD.clientHeight); renderer.setSize(threeD.clientWidth, threeD.clientHeight); } window.addEventListener('resize', onWindowResize, false); onWindowResize(); // mouse move cb window.addEventListener('mousemove', onMouseMove, false); } let loader = new LoadersVolume(threeD); function handleSeries() { // // first stack of first series let mergedSeries = loader.data[0].mergeSeries(loader.data); loader.free(); loader = null; let stack = null; let stack2 = null; if (mergedSeries[0].seriesInstanceUID !== 'https://cdn.rawgit.com/FNNDSC/data/master/nifti/slicer_brain/patient1/7001_t1_average_BRAINSABC.nii.gz') { stack = mergedSeries[1].stack[0]; stack2 = mergedSeries[0].stack[0]; } else { stack = mergedSeries[0].stack[0]; stack2 = mergedSeries[1].stack[0]; } stack = mergedSeries[0].stack[0]; stack2 = mergedSeries[1].stack[0]; let stackHelper = new HelpersStack(stack); stackHelper.bbox.visible = false; stackHelper.border.visible = false; sceneLayer0.add(stackHelper); // // create layer 1.... // prepare it // * ijk2LPS transforms // * Z spacing // * etc. // stack2.prepare(); // pixels packing for the fragment shaders now happens there stack2.pack(); let textures2 = []; for (let m = 0; m < stack2._rawData.length; m++) { let tex = new THREE.DataTexture( stack2.rawData[m], stack2.textureSize, stack2.textureSize, stack2.textureType, THREE.UnsignedByteType, THREE.UVMapping, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.NearestFilter, THREE.NearestFilter); tex.needsUpdate = true; tex.flipY = true; textures2.push(tex); } // // create material && mesh then add it to sceneLayer1 uniformsLayer1 = ShadersUniform.uniforms(); uniformsLayer1.uTextureSize.value = stack2.textureSize; uniformsLayer1.uTextureContainer.value = textures2; uniformsLayer1.uWorldToData.value = stack2.lps2IJK; uniformsLayer1.uNumberOfChannels.value = stack2.numberOfChannels; uniformsLayer1.uBitsAllocated.value = stack2.bitsAllocated; uniformsLayer1.uPackedPerPixel.value = stack2.packedPerPixel; uniformsLayer1.uWindowCenterWidth.value = [stack2.windowCenter, stack2.windowWidth]; uniformsLayer1.uRescaleSlopeIntercept.value = [stack2.rescaleSlope, stack2.rescaleIntercept]; uniformsLayer1.uDataDimensions.value = [stack2.dimensionsIJK.x, stack2.dimensionsIJK.y, stack2.dimensionsIJK.z]; // generate shaders on-demand! let fs = new ShadersFragment(uniformsLayer1); let vs = new ShadersVertex(); materialLayer1 = new THREE.ShaderMaterial( {side: THREE.DoubleSide, uniforms: uniformsLayer1, vertexShader: vs.compute(), fragmentShader: fs.compute(), }); // add mesh in this scene with right shaders... meshLayer1 = new THREE.Mesh(stackHelper.slice.geometry, materialLayer1); // go the LPS space meshLayer1.applyMatrix(stack2._ijk2LPS); sceneLayer1.add(meshLayer1); // // Create the Mix layer uniformsLayerMix = ShadersLayerUniform.uniforms(); uniformsLayerMix.uTextureBackTest0.value = sceneLayer0TextureTarget.texture; uniformsLayerMix.uTextureBackTest1.value = sceneLayer1TextureTarget.texture; uniformsLayerMix.uTrackMouse.value = 1; uniformsLayerMix.uMouse.value = new THREE.Vector2(0, 0); // generate shaders on-demand! let fls = new ShadersLayerFragment(uniformsLayerMix); let vls = new ShadersLayerVertex(); materialLayerMix = new THREE.ShaderMaterial( {side: THREE.DoubleSide, uniforms: uniformsLayerMix, vertexShader: vls.compute(), fragmentShader: fls.compute(), transparent: true, }); // add mesh in this scene with right shaders... meshLayerMix = new THREE.Mesh(stackHelper.slice.geometry, materialLayerMix); // go the LPS space meshLayerMix.applyMatrix(stack2._ijk2LPS); sceneLayerMix.add(meshLayerMix); // set camera let worldbb = stack.worldBoundingBox(); let lpsDims = new THREE.Vector3( worldbb[1] - worldbb[0], worldbb[3] - worldbb[2], worldbb[5] - worldbb[4] ); // box: {halfDimensions, center} let box = { center: stack.worldCenter().clone(), halfDimensions: new THREE.Vector3(lpsDims.x + 50, lpsDims.y + 50, lpsDims.z + 50), }; // init and zoom let canvas = { width: threeD.clientWidth, height: threeD.clientHeight, }; camera.directions = [stack.xCosine, stack.yCosine, stack.zCosine]; camera.box = box; camera.canvas = canvas; camera.update(); camera.fitBox(2); // CREATE LUT lutLayer0 = new HelpersLut( 'my-lut-canvases-l0', 'default', 'linear', [[0, 0, 0, 0], [1, 1, 1, 1]], [[0, 1], [1, 1]]); lutLayer0.luts = HelpersLut.presetLuts(); lutLayer1 = new HelpersLut( 'my-lut-canvases-l1', 'default', 'linear', [[0, 0, 0, 0], [1, 1, 1, 1]], [[0, 1], [1, 1]]); lutLayer1.luts = HelpersLut.presetLuts(); layer1.lut = lutLayer1; buildGUI(stackHelper); } // load sequence for each file loader.load(files) .then(function() { handleSeries(); }) .catch(function(error) { window.console.log('oops... something went wrong...'); window.console.log(error); }); };
Fix layer1 and layerMix orientation
examples/viewers_compare/viewers_compare.js
Fix layer1 and layerMix orientation
<ide><path>xamples/viewers_compare/viewers_compare.js <ide> // add mesh in this scene with right shaders... <ide> meshLayer1 = new THREE.Mesh(stackHelper.slice.geometry, materialLayer1); <ide> // go the LPS space <del> meshLayer1.applyMatrix(stack2._ijk2LPS); <add> meshLayer1.applyMatrix(stack._ijk2LPS); <ide> sceneLayer1.add(meshLayer1); <ide> <ide> // <ide> // add mesh in this scene with right shaders... <ide> meshLayerMix = new THREE.Mesh(stackHelper.slice.geometry, materialLayerMix); <ide> // go the LPS space <del> meshLayerMix.applyMatrix(stack2._ijk2LPS); <add> meshLayerMix.applyMatrix(stack._ijk2LPS); <ide> sceneLayerMix.add(meshLayerMix); <ide> <ide> // set camera
JavaScript
apache-2.0
c0a925017dc141e90548029ceaaa6a086c6f1506
0
JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder,JimCallahanOrlando/DistrictBuilder
/* * Create an OpenLayers.Layer.WMS type layer. * * @param name The name of the layer (appears in the layer switcher). * @param layer The layer name (or array of names) served by the WMS server * @param extents The extents of the layer -- must be used for GeoWebCache. */ function createLayer( name, layer, srs, extents ) { return new OpenLayers.Layer.WMS( name, 'http://' + MAP_SERVER + '/geoserver/gwc/service/wms', { srs: srs, layers: layer, tiles: 'true', tilesOrigin: extents.left + ',' + extents.bottom, format: 'image/png' }, { displayOutsideMaxExtent: true } ); } /* * Get the value of the "Snap Map to:" dropdown. */ function getSnapLayer() { var orig = $('#snapto').val(); var items = orig.split(';'); return { layer: items[0], level: items[1] }; } /* * Get the value of the "Show Layer by:" dropdown. */ function getShowBy() { return $('#showby').val(); } /* * Get the value of the "Show Boundaries for:" dropdown. */ //function getBoundLayer() { // return $('#boundfor').val(); //} /* * Get the value of the "Show Districts by:" dropdown. This returns * an object with a 'by' and 'modified' property, since the selection * of this dropdown may also be 'None' but for performance and query * reasons, the subject ID may not be empty. */ function getDistrictBy() { var orig = $('#districtby').val(); var mod = new RegExp('^(.*)\.None').test(orig); if (mod) { orig = RegExp.$1; } return { by: orig, modified: mod }; } /** * Get the value of the history cursor. */ function getPlanVersion() { var ver = $('#history_cursor').val(); return ver; } /* * The URLs for updating the calculated geography and demographics. */ var geourl = '/districtmapping/plan/' + PLAN_ID + '/geography'; var demourl = '/districtmapping/plan/' + PLAN_ID + '/demographics'; /** * Get the OpenLayers filters that describe the version and subject * criteria for the district layer. */ function getVersionAndSubjectFilters() { var dby = getDistrictBy(); var ver = getPlanVersion(); return new OpenLayers.Filter.Logical({ type: OpenLayers.Filter.Logical.AND, filters: [ new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'version', value: ver }), new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'subject', value: dby.by }) ] }); } /** * Add proper class names so css may style the PanZoom controls. */ function doMapStyling() { $('#OpenLayers\\.Control\\.PanZoomBar_3_panup').addClass('olControlPan olControlPanUpItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_panright').addClass('olControlPan olControlPanRightItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_pandown').addClass('olControlPan olControlPanDownItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_panleft').addClass('olControlPan olControlPanLeftItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_zoomin').addClass('olControlZoom olControlZoomInInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_zoomout').addClass('olControlZoom olControlZoomOutInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_OpenLayers\\.Map_4').addClass('olControlZoom olControlZoomGrabInactive'); $('#OpenLayers_Control_PanZoomBar_ZoombarOpenLayers\\.Map_4').addClass('olControlZoom olControlZoomBarInactive'); } /* * Resize the map. This is a fix for IE 7, which does not assign a height * to the map div if it is not explicitly set. */ function initializeResizeFix() { var vp = $('.olMapViewport')[0]; if( vp.clientHeight > 0 ) { return; } var resizemap = function() { var mapElem = $('#mapandmenu')[0] if(!window.innerHeight) { mapElem.style.height = (window.document.body.clientHeight - 90) + 'px'; vp.style.height = (window.document.body.clientHeight - 150) + 'px'; } }; resizemap(); window.onresize = resizemap; } /* * Create a div for tooltips on the map itself; this is used * when the info tool is activated. */ function createMapTipDiv() { var tipdiv = document.createElement('div'); var tipelem = document.createElement('h1'); tipelem.appendChild(document.createTextNode('District Name')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.id = 'tipclose'; tipelem.onclick = function(e){ OpenLayers.Event.stop(e); tipdiv.style.display = 'none'; }; tipelem.appendChild(document.createTextNode('[x]')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.appendChild(document.createTextNode('Demographic 1:')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.appendChild(document.createTextNode('Demographic 2:')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.appendChild(document.createTextNode('Demographic 3:')); tipdiv.appendChild(tipelem); tipdiv.style.zIndex = 100000; tipdiv.style.position = 'absolute'; tipdiv.style.opacity = '0.8'; tipdiv.className = 'tooltip'; return tipdiv; } /** * Initialize the map from WMS GetCapabilities. */ function init() { OpenLayers.ProxyHost= "/proxy?url="; $.ajax({ url: OpenLayers.ProxyHost + encodeURIComponent('http://' + MAP_SERVER + '/geoserver/ows?service=wms&version=1.1.1' + '&request=GetCapabilities&namespace=' + NAMESPACE), type: 'GET', success: function(data, textStatus, xhr) { var layer = getSnapLayer().layer; // get the layers in the response var layers = $('Layer > Layer',data); for (var i = 0; i < layers.length; i++) { // get the title of the layer var title = $('> Title',layers[i])[0].firstChild.nodeValue; var name = $('> Name', layers[i])[0].firstChild.nodeValue; // if the title is the displayed snap layer if (title == layer) { // get the SRS and extent, then init the map var bbox = $('> BoundingBox',layers[i]); var srs = bbox.attr('SRS'); var extent = new OpenLayers.Bounds( bbox.attr('minx'), bbox.attr('miny'), bbox.attr('maxx'), bbox.attr('maxy') ); mapinit( srs, extent ); return; } } } }); } /* * Initialize the map with extents and SRS pulled from WMS. */ function mapinit(srs,maxExtent) { // The assignment mode -- the map is initially in navigation mode, // so the assignment mode is null. var assignMode = null; // This projection is web mercator var projection = new OpenLayers.Projection(srs); // Explicitly create the navigation control, since // we'll want to deactivate it in the future. var navigate = new OpenLayers.Control.Navigation({ autoActivate: true, handleRightClicks: true }); // Dynamically compute the resolutions, based on the map extents. // NOTE: Geoserver computes the resolution with the top and the bottom // components of the extent, NOT the left/right. var rez = [(maxExtent.top - maxExtent.bottom) / 256.0]; while (rez.length < 12) { rez.push( rez[rez.length - 1] / 2.0 ); } // Create a slippy map. var olmap = new OpenLayers.Map('map', { // The resolutions here must match the settings in geowebcache. resolutions: rez, maxExtent: maxExtent, projection: projection, units: 'm', controls: [ navigate, new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.KeyboardDefaults() ] }); // These layers are dependent on the layers available in geowebcache // TODO Fetch a list of layers from geowebcache var layers = []; for (layer in MAP_LAYERS) { layers.push(createLayer( MAP_LAYERS[layer], MAP_LAYERS[layer], srs, maxExtent )); } // The strategy for loading the districts. This is effectively // a manual refresh, with no automatic reloading of district // boundaries except when explicitly loaded. var districtStrategy = new OpenLayers.Strategy.Fixed(); // The style for the districts. This serves as the base // style for all rules that apply to the districtLayer var districtStyle = { fill: true, fillOpacity: 0.00, strokeColor: '#ee9900', strokeOpacity: 1, strokeWidth: 2, label: '${name}', fontColor: '#663300', fontSize: '10pt', fontFamily: 'Arial,Helvetica,sans-serif', fontWeight: '800', labelAlign: 'cm' }; // A vector layer that holds all the districts in // the current plan. var districtLayer = new OpenLayers.Layer.Vector( 'Current Plan', { strategies: [ districtStrategy ], protocol: new OpenLayers.Protocol.HTTP({ url: '/districtmapping/plan/' + PLAN_ID + '/district/versioned', format: new OpenLayers.Format.GeoJSON() }), styleMap: new OpenLayers.StyleMap(new OpenLayers.Style(districtStyle)), projection: projection, filter: getVersionAndSubjectFilters() } ); // Create a vector layer to hold the current selection // of features that are to be manipulated/added to a district. var selection = new OpenLayers.Layer.Vector('Selection',{ styleMap: new OpenLayers.StyleMap({ "default": new OpenLayers.Style( OpenLayers.Util.applyDefaults( { fill: true, fillOpacity: 0.0, strokeColor: '#ffff00', strokeWidth: 3 }, OpenLayers.Feature.Vector.style["default"] ) ), "select": new OpenLayers.Style( OpenLayers.Util.applyDefaults( { fill: true, fillColor: '#ee9900', strokeColor: '#ee9900' }, OpenLayers.Feature.Vector.style["select"] ) ), "error": new OpenLayers.Style( OpenLayers.Util.applyDefaults( { fill: false, strokeColor: '#ee0000' }, OpenLayers.Feature.Vector.style["select"] ) ) }) }); // add these layers to the map layers.push(districtLayer); layers.push(selection); olmap.addLayers(layers); // Create a protocol that is used by all editing controls // that selects geography at the specified snap layer. var getProtocol = new OpenLayers.Protocol.WFS({ url: 'http://' + MAP_SERVER + '/geoserver/wfs', featureType: getSnapLayer().layer, featureNS: NS_HREF, featurePrefix: NAMESPACE, srsName: srs, geometryName: 'geom' }); var idProtocol = new OpenLayers.Protocol.WFS({ url: 'http://' + MAP_SERVER + '/geoserver/wfs', featureType: 'identify_geounit', featureNS: NS_HREF, featurePrefix: NAMESPACE, srsName: srs, geometryName: 'geom' }); // Create a simple point and click control for selecting // geounits one at a time. var getControl = new OpenLayers.Control.GetFeature({ autoActivate: false, protocol: getProtocol, multipleKey: 'shiftKey', toggleKey: 'ctrlKey', filterType: OpenLayers.Filter.Spatial.INTERSECTS }); // Create a rectangular drag control for selecting // geounits that intersect a box. var boxControl = new OpenLayers.Control.GetFeature({ autoActivate: false, protocol: getProtocol, click: false, box: true, multipleKey: 'shiftKey', toggleKey: 'ctrlKey', filterType: OpenLayers.Filter.Spatial.INTERSECTS }); // Reload the information tabs and reload the filters var updateInfoDisplay = function() { $('.geography').load(geourl, {demo: getDistrictBy().by, version: getPlanVersion()}, loadTooltips); $('.demographics').load(demourl, {version: getPlanVersion()}, loadTooltips); districtLayer.filter = getVersionAndSubjectFilters(); districtLayer.strategies[0].load(); }; // An assignment function that adds geounits to a district var assignOnSelect = function(feature) { if (selection.features.length == 0) { $('#assign_district').val('-1'); return; } var district_id = feature.data.district_id; var geolevel_id = selection.features[0].attributes.geolevel_id; var geounit_ids = []; for (var i = 0; i < selection.features.length; i++) { geounit_ids.push( selection.features[i].attributes.id ); } geounit_ids = geounit_ids.join('|'); OpenLayers.Element.addClass(olmap.viewPortDiv,'olCursorWait'); $('#working').dialog('open'); $.ajax({ type: 'POST', url: '/districtmapping/plan/' + PLAN_ID + '/district/' + district_id + '/add', data: { geolevel: geolevel_id, geounits: geounit_ids, version: getPlanVersion() }, success: function(data, textStatus, xhr) { var mode = data.success ? 'select' : 'error'; if (data.success) { // update the max version of this plan PLAN_VERSION = data.version; // set the version cursor $('#history_cursor').val(data.version); // update the UI buttons to show that you can // perform an undo now, but not a redo $('#history_redo').addClass('disabled'); $('#history_undo').removeClass('disabled'); updateInfoDisplay(); $('#saveplaninfo').trigger('planSaved', [ data.edited ]); } else { OpenLayers.Element.removeClass(olmap.viewPortDiv, 'olCursorWait'); $('#working').dialog('close'); } for (var i = 0; i < selection.features.length; i++) { selection.drawFeature(selection.features[i], mode); } if (assignMode == null) { $('#assign_district').val('-1'); } else if (assignMode == 'dragdrop') { $('#assign_district').val('-1'); dragdropControl.deactivate(); dragdropControl.resumeTool.activate(); } }, error: function(xhr, textStatus, error) { window.status = 'failed to select'; } }); }; // When the selection is changed, perform the addition or subtraction // to the current geounit selection. Also, if the assignment mode is // either 'anchor' or 'dragdrop', do some more processing. var unitsSelected = function(features, subtract) { if (subtract) { var removeme = []; for (var i = 0; i < selection.features.length; i++) { for (var j = 0; j < features.length; j++) { if (selection.features[i].data.id == features[j].data.id) { removeme.push(selection.features[i]); } } } selection.removeFeatures(removeme); } else { var addme = []; for (var i = 0; i < features.length; i++) { var match = false; for (var j = 0; j < selection.features.length; j++) { if (features[i].data.id == selection.features[j].data.id) { match = true; break; } } if (!match) { addme.push(features[i]) } } selection.addFeatures(addme); // this is necessary because a feature may be selected more // than once, and the js feature object is different, but the // actual feature itself is the same geometry and attributes. for (var i = 0; i < addme.length; i++) { selection.features[addme[i].fid || addme[i].id] = addme[i]; } } if (assignMode == null) { return; } else if (assignMode == 'anchor') { var d_id = $('#assign_district').val(); if (parseInt(d_id,10) > 0) { var feature = { data:{ district_id: d_id } }; assignOnSelect(feature); } } else if (assignMode == 'dragdrop') { var currentTool = olmap.getControlsBy('active',true)[0]; currentTool.deactivate(); dragdropControl.resumeTool = currentTool; dragdropControl.activate(); } }; // Create a polygon select control for free-form selections. var polyControl = new OpenLayers.Control.DrawFeature( selection, OpenLayers.Handler.Polygon, { handlerOptions: { freehand: true, freehandToggle: null }, featureAdded: function(feature){ // WARNING: not a part of the API! var append = this.handler.evt.shiftKey; var subtract = this.handler.evt.ctrlKey && (assignMode == null); var newOpts = getControl.protocol.options; newOpts.featureType = getSnapLayer().layer; getControl.protocol = new OpenLayers.Protocol.WFS( newOpts ); getControl.protocol.read({ filter: new OpenLayers.Filter.Spatial({ type: OpenLayers.Filter.Spatial.INTERSECTS, value: feature.geometry, projection: getProtocol.options.srsName }), callback: function(rsp){ // first, remove the lasso feature var lasso = selection.features[selection.features.length - 1]; selection.removeFeatures([lasso]); if (!(append || subtract)){ // if this is a new lasso, remove all the // old selected features selection.removeFeatures(selection.features); } unitsSelected( rsp.features, subtract ); } }); } } ); // set this timeout function, since jquery is apparently not ready // to select the elements based on this class during regular init. // also, the reference to the polyControl is used in this init method setTimeout(function(){ var jtmp = $('.olHandlerBoxSelectFeature'); var polySelectStyle = { pointRadius: 0, strokeWidth: parseInt(jtmp.css('borderTopWidth').slice(0,1),10), strokeColor: jtmp.css('borderTopColor'), strokeOpacity: parseFloat(jtmp.css('opacity')), fillColor: jtmp.css('background-color'), fillOpacity: parseFloat(jtmp.css('opacity')) }; polyControl.handler.style = polySelectStyle; }, 100); // Create a tooltip inside of the map div var tipdiv = createMapTipDiv(); olmap.div.insertBefore(tipdiv,olmap.div.firstChild); // Create a control that shows the details of the district // underneath the cursor. var idControl = new IdGeounit({ autoActivate: false, protocol: idProtocol }); // Get the feature at the point in the layer. var featureAtPoint = function(pt, lyr) { for (var i = 0; i < lyr.features.length; i++) { if (pt.intersects(lyr.features[i].geometry)) { return lyr.features[i]; } } return null; }; // Test if the provided point lays within the features in the provided // layer. var pointInFeatures = function(pt, lyr) { return featureAtPoint(pt, lyr) != null; }; // Create a control that shows where a drag selection is // traveling. var dragdropControl = new OpenLayers.Control.DragFeature( selection, { documentDrag: true, onStart: function(feature, pixel) { var ll = olmap.getLonLatFromPixel(pixel); dragdropControl.lastPt = new OpenLayers.Geometry.Point(ll.lon, ll.lat); }, onDrag: function(feature, pixel) { var ll = olmap.getLonLatFromPixel(pixel); var pt = new OpenLayers.Geometry.Point(ll.lon, ll.lat); var dist = featureAtPoint(pt, districtLayer); if (dist == null) { dist = { data: { district_id: 1 } }; } $('#assign_district').val(dist.data.district_id); for (var i = 0; i < selection.features.length; i++) { if (selection.features[i].fid != feature.fid) { selection.features[i].geometry.move( pt.x - dragdropControl.lastPt.x, pt.y - dragdropControl.lastPt.y ); selection.drawFeature(selection.features[i]); } } dragdropControl.lastPt = pt; }, onComplete: function(feature, pixel) { var ll = olmap.getLonLatFromPixel(pixel); var pt = new OpenLayers.Geometry.Point(ll.lon, ll.lat); if (pointInFeatures(pt, districtLayer)) { var dfeat = { data:{ district_id: $('#assign_district').val() } }; assignOnSelect(dfeat); } else { selection.removeFeatures(selection.features); $('#assign_district').val('-1'); dragdropControl.deactivate(); dragdropControl.resumeTool.activate(); } } } ); // A callback to create a popup window on the map after a peice // of geography is selected. var idFeature = function(e) { var snapto = getSnapLayer().layer; // get the range of geolevels var maxGeolevel = 0, minGeolevel = 9999; for (var i = 0; i < SNAP_LAYERS.length; i++) { if (snapto == 'simple_' + SNAP_LAYERS[i].level) { maxGeolevel = SNAP_LAYERS[i].geolevel; } minGeolevel = Math.min(minGeolevel, SNAP_LAYERS[i].geolevel); } // get the breadcrumbs to this geounit, starting at the // largest area (lowest geolevel) first, down to the // most specific geolevel var crumbs = {}; var ctics = {}; var tipFeature = e.features[0]; for (var glvl = minGeolevel; glvl <= maxGeolevel; glvl++) { for (var feat = 0; feat < e.features.length; feat++) { if (e.features[feat].data.geolevel_id == glvl) { crumbs[e.features[feat].data.id] = e.features[feat].data.name; } if (e.features[feat].data.geolevel_id == maxGeolevel) { tipFeature = e.features[feat]; for (var demo = 0; demo < DEMOGRAPHICS.length; demo++) { if (e.features[feat].data.subject_id == DEMOGRAPHICS[demo].id) { ctics[DEMOGRAPHICS[demo].text] = parseFloat(e.features[feat].data.number); } } } } } // truncate the breadcrumbs into a single string var place = []; for (var key in crumbs) { place.push(crumbs[key]); } place = place.join(' / '); var centroid = tipFeature.geometry.getCentroid(); var lonlat = new OpenLayers.LonLat( centroid.x, centroid.y ); var pixel = olmap.getPixelFromLonLat(lonlat); tipdiv.style.display = 'block'; tipdiv.childNodes[0].childNodes[0].nodeValue = place; var select = $('#districtby')[0]; var value = parseInt(tipFeature.attributes.number, 10); var node = 2; for (var key in ctics) { tipdiv.childNodes[node].firstChild.nodeValue = key + ': ' + ctics[key].toLocaleString(); node ++; } var halfWidth = tipdiv.clientWidth/2; var halfHeight = tipdiv.clientHeight/2; if (pixel.x < halfWidth) { pixel.x = halfWidth; } else if (pixel.x > olmap.div.clientWidth - halfWidth) { pixel.x = olmap.div.clientWidth - halfWidth; } if (pixel.y < halfHeight) { pixel.y = halfHeight; } else if (pixel.y > (olmap.div.clientHeight-29) - halfHeight) { pixel.y = (olmap.div.clientHeight-29) - halfHeight; } tipdiv.style.left = (pixel.x - halfWidth) + 'px'; tipdiv.style.top = (pixel.y - halfHeight) + 'px'; if (tipdiv.pending) { clearTimeout(tipdiv.timeout); tipdiv.pending = false; } }; // A callback for feature selection in different controls. var featuresSelected = function(e){ var subtract = e.object.modifiers.toggle && (assignMode == null); unitsSelected(e.features, subtract); }; /* * This will return the maps's truly visible bounds; if the info * tabs on the right are up, that's the usual map bounds. If the * info tabs are showing, it's the visible area of the map to the * left of those tabs */ var getVisibleBounds = function() { if ($('.map_menu_content:visible').length > 0) { var offset = $('#map_menu_header').position(); var bounds = olmap.getExtent(); var lonLat = olmap.getLonLatFromPixel(new OpenLayers.Pixel(offset.left, offset.top)); bounds.right = lonLat.lon; return bounds; } return undefined; } /* * This method is useful to determine whether an item is visible * to the user - pass in the bounds from getVisibleBounds if the * info tabs are showing */ var featureOnScreen = function(feature, bounds) { if (bounds && feature.geometry) { return bounds.intersectsBounds(feature.geometry.getBounds()); } else { return feature.onScreen(); } } // Connect the featuresSelected callback above to the featureselected // events in the point and rectangle control. getControl.events.register('featuresselected', getControl, featuresSelected); boxControl.events.register('featuresselected', boxControl, featuresSelected); idControl.events.register('featuresselected', idControl, idFeature); // A callback for deselecting features from different controls. var featureUnselected = function(e){ selection.removeFeatures([e.feature]); }; // Connect the featureUnselected callback above to the featureunselected // events in the point and rectangle control. getControl.events.register('featureunselected', this, featureUnselected); boxControl.events.register('featureunselected', this, featureUnselected); // Connect a method for indicating work when the district layer // is reloaded. districtLayer.events.register('loadstart',districtLayer,function(){ OpenLayers.Element.addClass(olmap.viewPortDiv, 'olCursorWait'); }); // Recompute the rules for the district styling prior to the adding // of the features to the district layer. This is done at this time // to prevent 2 renderings from being triggered on the district layer. districtLayer.events.register('beforefeaturesadded',districtLayer,function(context){ var lowestColor = $('.farunder').css('background-color'); var lowerColor = $('.under').css('background-color'); var upperColor = $('.over').css('background-color'); var highestColor = $('.farover').css('background-color'); var newOptions = OpenLayers.Util.extend({}, districtStyle); var dby = getDistrictBy(); var rules = []; if (!dby.modified) { rules = [ new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO, property: 'number', value: RULES[dby.by].lowest }), symbolizer: { fillColor: lowestColor, fillOpacity: 0.5 } }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN, property: 'number', lowerBoundary: RULES[dby.by].lowest, upperBoundary: RULES[dby.by].lower }), symbolizer: { fillColor: lowerColor, fillOpacity: 0.5 } }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN, property: 'number', lowerBoundary: RULES[dby.by].lower, upperBoundary: RULES[dby.by].upper }) }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN, property: 'number', lowerBoundary: RULES[dby.by].upper, upperBoundary: RULES[dby.by].highest }), symbolizer: { fillColor: upperColor, fillOpacity: 0.5 } }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO, property: 'number', value: RULES[dby.by].highest }), symbolizer: { fillColor: highestColor, fillOpacity: 0.5 } }) ]; } var newStyle = new OpenLayers.Style(newOptions,{ rules:rules }); districtLayer.styleMap = new OpenLayers.StyleMap(newStyle); }); // Connect an event to the district layer that updates the // list of possible districts to assign to. // TODO: this doesn't account for districts with null geometries // which will not come back from the WFS query districtLayer.events.register('loadend',districtLayer,function(){ OpenLayers.Element.removeClass(olmap.viewPortDiv, 'olCursorWait'); selection.removeFeatures(selection.features); var sorted = districtLayer.features.slice(0,districtLayer.features.length); sorted.sort(function(a,b){ return a.attributes.name > b.attributes.name; }); var working = $('#working'); if (working.dialog('isOpen')) { working.dialog('close'); } }); olmap.events.register('movestart',olmap,function(){ tipdiv.style.display = 'none'; }); // When the navigate map tool is clicked, disable all the // controls except the navigation control. $('#navigate_map_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } navigate.activate(); $('#dragdrop_tool').removeClass('toggle'); $('#anchor_tool').removeClass('toggle'); assignMode = null; $('#assign_district').val(-1); tipdiv.style.display = 'none'; }); // When the identify map tool is clicked, disable all the // controls except the identify control. $('#identify_map_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } idControl.activate(); $('#dragdrop_tool').removeClass('toggle'); $('#anchor_tool').removeClass('toggle'); assignMode = null; $('#assign_district').val(-1); }); // When the single pick tool is clicked, disable all the // controls except for the single pick tool. $('#single_drawing_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } getControl.activate(); getControl.features = selection.features; tipdiv.style.display = 'none'; }); // When the rectangle selection tool is clicked, disable all the // controls except for the rectangle selection tool. $('#rectangle_drawing_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } boxControl.activate(); boxControl.features = selection.features; tipdiv.style.display = 'none'; }); // When the polygon selection tool is clicked, disable all the // controls except for the polygon selection tool. $('#polygon_drawing_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } polyControl.activate(); tipdiv.style.display = 'none'; }); // When the assignment tool is clicked, disable all the // controls except for the assignment tool. $('#dragdrop_tool').click(function(evt){ var me = $(this); if (me.hasClass('toggle')) { me.removeClass('toggle'); assignMode = null; dragdropControl.deactivate(); if (dragdropControl.resumeTool) { dragdropControl.resumeTool.activate(); } } else { me.addClass('toggle'); assignMode = 'dragdrop'; if (selection.features.length > 0) { var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } dragdropControl.activate(); dragdropControl.resumeTool = active[0]; } } $('#navigate_map_tool').removeClass('toggle'); navigate.deactivate(); $('#identify_map_tool').removeClass('toggle'); idControl.deactivate(); $('#anchor_tool').removeClass('toggle'); tipdiv.style.display = 'none'; // enable single select tool if no selection tool is enabled if (!(getControl.active || boxControl.active || polyControl.active)) { getControl.activate(); $('#single_drawing_tool').addClass('toggle'); } }); $('#anchor_tool').click(function(evt){ var me = $(this); if (me.hasClass('toggle')) { me.removeClass('toggle'); assignMode = null; $('#assign_district').val(-1); } else { me.addClass('toggle'); assignMode = 'anchor'; } $('#navigate_map_tool').removeClass('toggle'); navigate.deactivate(); $('#identify_map_tool').removeClass('toggle'); idControl.deactivate(); $('#dragdrop_tool').removeClass('toggle'); tipdiv.style.display = 'none'; // enable single select tool if no selection tool is enabled if (!(getControl.active || boxControl.active || polyControl.active)) { getControl.activate(); $('#single_drawing_tool').addClass('toggle'); } }); // Add the created controls to the map olmap.addControls([ getControl, boxControl, polyControl, new GlobalZoom(), idControl, dragdropControl ]); // get a format parser for SLDs and the legend var sldFormat = new OpenLayers.Format.SLD(); // a method that will read the named layer, and return // the default style var getDefaultStyle = function(sld, layerName) { var styles = sld.namedLayers[layerName].userStyles; var style; for(var i=0; i<styles.length; ++i) { style = styles[i]; if(style.isDefault) { break; } } return style; } // // get the styles associated with the current map configuration // var getMapStyles = function() { var snap = getSnapLayer().layer.split('simple_')[1]; var show = getShowBy(); OpenLayers.Request.GET({ url: '/sld/' + snap + '_' + show + '.sld', method: 'GET', callback: function(xhr){ var sld = sldFormat.read(xhr.responseXML || xhr.responseText); var userStyle = getDefaultStyle(sld,getShowBy()); $('#legend_title').empty().append(userStyle.title); var lbody = $('#basemap_legend tbody'); lbody.empty(); var rules = userStyle.rules; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (!('Polygon' in rule.symbolizer)) { continue; } var div = $('<div/>'); div.css('background-color',rule.symbolizer.Polygon.fillColor); div.css('border-width',rule.symbolizer.Polygon.strokeWidth); div.css('border-color',rule.symbolizer.Polygon.strokeColor); div.addClass('swatch'); div.addClass('basemap_swatch'); var swatch = $('<td/>'); swatch.width(32); swatch.append(div); var row = $('<tr/>'); row.append(swatch); var title = $('<td/>'); title.append( rule.title ); row.append(title); lbody.append(row); } } }); }; // Logic for the 'Snap Map to' dropdown, note that this logic // calls the boundsforChange callback $('#snapto').change(function(evt){ var newOpts = getControl.protocol.options; var show = getShowBy(); var snap = getSnapLayer(); var layername = NAMESPACE + ':demo_' + snap.level; if (show != 'none') { layername += '_' + show; } var layers = olmap.getLayersByName(layername); newOpts.featureType = snap.layer; getControl.protocol = boxControl.protocol = new OpenLayers.Protocol.WFS( newOpts ); olmap.setBaseLayer(layers[0]); doMapStyling(); getMapStyles(); }); // Logic for the 'Show Map by' dropdown $('#showby').change(function(evt){ var snap = getSnapLayer(); var show = evt.target.value; var layername = NAMESPACE + ':demo_' + snap.level; if (show != 'none') { layername += '_' + show; } var layers = olmap.getLayersByName(layername); olmap.setBaseLayer(layers[0]); doMapStyling(); getMapStyles(); }); // Logic for the 'Show Districts by' dropdown $('#districtby').change(function(evt){ districtLayer.filter = getVersionAndSubjectFilters(); districtLayer.strategies[0].load(); }); // Logic for the 'Assign District to' dropdown $('#assign_district').change(function(evt){ if (this.value == '-1'){ return true; } else if (this.value == 'new'){ createNewDistrict(); } else if (assignMode == null) { var feature = { data:{ district_id: this.value } }; assignOnSelect(feature); } }); // Logic for the history back button $('#history_undo').click(function(evt){ var cursor = $('#history_cursor'); var ver = cursor.val(); if (ver > 0) { ver--; if (ver == 0) { $(this).addClass('disabled'); } cursor.val(ver); $('#history_redo').removeClass('disabled'); updateInfoDisplay(); } }); // Logic for history redo button $('#history_redo').click(function(evt){ var cursor = $('#history_cursor'); var ver = cursor.val(); if (ver < PLAN_VERSION) { ver++; if (ver == PLAN_VERSION) { $(this).addClass('disabled'); } cursor.val(ver); $('#history_undo').removeClass('disabled'); updateInfoDisplay(); } }); /* * Ask the user for a new district name, then assign the current * selection to the new district upon successful creation of the * district */ var createNewDistrict = function() { if (selection.features.length == 0) { $('#assign_district').val('-1'); return; } if (getPlanVersion() != PLAN_VERSION) { // unsupported at this time is creating a district based // of a previous version of the plan. Inform the user. $('<div id="newdistrictdialog">Districts may only be created from the most current plan at this time.</div>').dialog({ modal: true, autoOpen: true, title: 'Sorry', buttons: { 'OK': function() { $('#newdistrictdialog').remove(); } } }); $('#assign_district').val('-1'); return; } // Once we have the district name, post a request to the // server to create it in the DB var createDistrict = function(district_id) { var geolevel_id = selection.features[0].attributes.geolevel_id; var geounit_ids = []; for (var i = 0; i < selection.features.length; i++) { geounit_ids.push( selection.features[i].attributes.id ); } geounit_ids = geounit_ids.join('|'); OpenLayers.Element.addClass(olmap.viewPortDiv,'olCursorWait'); $('#working').dialog('open'); $.ajax({ type: 'POST', url: '/districtmapping/plan/' + PLAN_ID + '/district/new', data: { district_id: district_id, geolevel: geolevel_id, geounits: geounit_ids, version: getPlanVersion() }, success: function(data, textStatus, xhr) { // update the max version of this plan PLAN_VERSION = data.version; $('#history_cursor').val(data.version); // update the UI buttons to show that you can // perform an undo now, but not a redo $('#history_redo').addClass('disabled'); $('#history_undo').removeClass('disabled'); // add the new district entry to the list $('#assign_district').append('<option value="' + data.district_id + '">' + data.district_name + '</option>'); // detach the list of districts from the DOM var all_options = $('#assign_district option').detach(); // if max # of districts has been reached, remove the // 'New District' option if (all_options.length > (MAX_DISTRICTS + 1)) { // the second to last item will be 'new', the last // item will be the option just added all_options[all_options.length-2] = all_options[all_options.length-1]; } // sort the options all_options.sort(function(a,b){ if (a.value == 'new') { return -1; } else { return parseInt(a.value,10) > parseInt(b.value,10); } }); // attach the options back to the DOM (in order, now) all_options.appendTo('#assign_district'); updateInfoDisplay(); $('#working').dialog('close'); $('#assign_district').val('-1'); OpenLayers.Element.removeClass(olmap.viewPortDiv,'olCursorWait'); } }); }; // create a list of available districts, based on the districts // that are already in the plan var options = $('#assign_district')[0].options; var avail = [] for (var d = 1; d <= MAX_DISTRICTS; d++) { var dtaken = false; for (var o = 0; o < options.length && !dtaken; o++) { dtaken = dtaken || ( options[o].text == 'District ' + d) } if (!dtaken) { avail.push('<option value="'+(d+1)+'">District '+d+'</option>'); } } // Create a dialog to get the new district's name from the user. // On close, destroy the dialog. $('<div id="newdistrictdialog">Please select a district name:<br/><select id="newdistrictname">' + avail.join('') + '</select></div>').dialog({ modal: true, autoOpen: true, title: 'New District', buttons: { 'OK': function() { createDistrict($('#newdistrictname').val()); $(this).dialog("close"); $('#newdistrictdialog').remove(); }, 'Cancel': function() { $(this).dialog("close"); $('#newdistrictdialog').remove(); $('#assign_district').val('-1'); } } }); }; /* * After the map has finished moving, this method updates the jQuery * data attributes of the geography and demographics tables if * different districts are now visible */ olmap.prevVisibleDistricts = ''; var sortByVisibility = function() { var visibleDistricts = ''; var visible, notvisible = ''; for (feature in districtLayer.features) { var feature = districtLayer.features[feature]; var inforow = $('.inforow_' + feature.attributes.district_id); if (featureOnScreen(feature, getVisibleBounds())) { inforow.data('isVisibleOnMap', true); visibleDistricts += feature.id; } else { inforow.data('isVisibleOnMap', false); } } if (visibleDistricts != olmap.prevVisibleDistricts) { var demosorter = viewablesorter({ target: '#demographic_table tbody' }).init(); var geosorter = viewablesorter({ target: '#geography_table tbody' }).init(); demosorter.sortTable(); geosorter.sortTable(); olmap.prevVisibleDistricts = visibleDistricts; } }; districtLayer.events.register("loadend", districtLayer, sortByVisibility); olmap.events.register("moveend", olmap, sortByVisibility); // triggering this event here will configure the map to correspond // with the initial dropdown values (jquery will set them to different // values than the default on a reload). A desirable side effect is // that the map styling and legend info will get loaded, too, so there // is no need to explicitly perform doMapStyling() or getMapStyles() // in this init method. $('#snapto').trigger('change'); // Set the initial map extents to the bounds around the study area. // TODO Make these configurable. olmap.zoomToExtent(maxExtent); OpenLayers.Element.addClass(olmap.viewPortDiv, 'olCursorWait'); // set up sizing for dynamic map size that fills the pg initializeResizeFix(); } IdGeounit = OpenLayers.Class(OpenLayers.Control.GetFeature, { /* * Initialize this control, enabling multiple selects with a single * click. */ initialize: function(options) { options = options || {}; OpenLayers.Util.extend(options, { multiple: true, clickTolerance: 0.5, maxFeatures: 25, filterType: OpenLayers.Filter.Spatial.INTERSECTS }); // concatenate events specific to vector with those from the base this.EVENT_TYPES = OpenLayers.Control.GetFeature.prototype.EVENT_TYPES.concat( OpenLayers.Control.prototype.EVENT_TYPES ); options.handlerOptions = options.handlerOptions || {}; OpenLayers.Control.prototype.initialize.apply(this, [options]); this.features = {}; this.handlers = {}; this.handlers.click = new OpenLayers.Handler.Click(this, {click: this.selectClick}, this.handlerOptions.click || {}); }, selectClick: function(evt) { // Set the cursor to "wait" to tell the user we're working on their click. OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait"); var bounds = this.pixelToBounds(evt.xy); this.setModifiers(evt); this.request(bounds, {single: false}); }, CLASS_NAME: 'IdGeounit' }); GlobalZoom = OpenLayers.Class(OpenLayers.Control, { // DOM Elements /** * Property: controlDiv * {DOMElement} */ controlDiv: null, /* * Constructor: GlobalZoom * * Parameters: * options - {Object} */ initialize: function(options) { OpenLayers.Control.prototype.initialize.apply(this, arguments); }, /** * APIMethod: destroy */ destroy: function() { OpenLayers.Event.stopObservingElement(this.controlDiv); OpenLayers.Control.prototype.destroy.apply(this, arguments); }, /** * Method: setMap * * Properties: * map - {<OpenLayers.Map>} */ setMap: function(map) { OpenLayers.Control.prototype.setMap.apply(this, arguments); }, /** * Method: onZoomToExtent * * Parameters: * e - {Event} */ onZoomToExtent: function(e) { this.map.zoomToMaxExtent(); OpenLayers.Event.stop(e); }, /** * Method: draw * * Returns: * {DOMElement} A reference to the DIV DOMElement containing the * switcher tabs. */ draw: function() { OpenLayers.Control.prototype.draw.apply(this); this.loadContents(); // populate div with current info this.redraw(); return this.div; }, /** * Method: redraw * Goes through and takes the current state of the Map and rebuilds the * control to display that state. Groups base layers into a * radio-button group and lists each data layer with a checkbox. * * Returns: * {DOMElement} A reference to the DIV DOMElement containing the control */ redraw: function() { return this.div; }, /** * Method: loadContents * Set up the labels and divs for the control */ loadContents: function() { //configure main div OpenLayers.Event.observe(this.div, "click", OpenLayers.Function.bindAsEventListener( this.onZoomToExtent, this) ); // layers list div this.controlDiv = document.createElement("div"); this.controlDiv.id = this.id + "_controlDiv"; OpenLayers.Element.addClass(this.controlDiv, "controlDiv"); this.div.appendChild(this.controlDiv); }, CLASS_NAME: "GlobalZoom" });
django/publicmapping/site-media/js/mapping.js
/* * Create an OpenLayers.Layer.WMS type layer. * * @param name The name of the layer (appears in the layer switcher). * @param layer The layer name (or array of names) served by the WMS server * @param extents The extents of the layer -- must be used for GeoWebCache. */ function createLayer( name, layer, srs, extents ) { return new OpenLayers.Layer.WMS( name, 'http://' + MAP_SERVER + '/geoserver/gwc/service/wms', { srs: srs, layers: layer, tiles: 'true', tilesOrigin: extents.left + ',' + extents.bottom, format: 'image/png' }, { displayOutsideMaxExtent: true } ); } /* * Get the value of the "Snap Map to:" dropdown. */ function getSnapLayer() { var orig = $('#snapto').val(); var items = orig.split(';'); return { layer: items[0], level: items[1] }; } /* * Get the value of the "Show Layer by:" dropdown. */ function getShowBy() { return $('#showby').val(); } /* * Get the value of the "Show Boundaries for:" dropdown. */ //function getBoundLayer() { // return $('#boundfor').val(); //} /* * Get the value of the "Show Districts by:" dropdown. This returns * an object with a 'by' and 'modified' property, since the selection * of this dropdown may also be 'None' but for performance and query * reasons, the subject ID may not be empty. */ function getDistrictBy() { var orig = $('#districtby').val(); var mod = new RegExp('^(.*)\.None').test(orig); if (mod) { orig = RegExp.$1; } return { by: orig, modified: mod }; } /** * Get the value of the history cursor. */ function getPlanVersion() { var ver = $('#history_cursor').val(); return ver; } /* * The URLs for updating the calculated geography and demographics. */ var geourl = '/districtmapping/plan/' + PLAN_ID + '/geography'; var demourl = '/districtmapping/plan/' + PLAN_ID + '/demographics'; /** * Get the OpenLayers filters that describe the version and subject * criteria for the district layer. */ function getVersionAndSubjectFilters() { var dby = getDistrictBy(); var ver = getPlanVersion(); return new OpenLayers.Filter.Logical({ type: OpenLayers.Filter.Logical.AND, filters: [ new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'version', value: ver }), new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.EQUAL_TO, property: 'subject', value: dby.by }) ] }); } /** * Add proper class names so css may style the PanZoom controls. */ function doMapStyling() { $('#OpenLayers\\.Control\\.PanZoomBar_3_panup').addClass('olControlPan olControlPanUpItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_panright').addClass('olControlPan olControlPanRightItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_pandown').addClass('olControlPan olControlPanDownItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_panleft').addClass('olControlPan olControlPanLeftItemInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_zoomin').addClass('olControlZoom olControlZoomInInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_zoomout').addClass('olControlZoom olControlZoomOutInactive'); $('#OpenLayers\\.Control\\.PanZoomBar_3_OpenLayers\\.Map_4').addClass('olControlZoom olControlZoomGrabInactive'); $('#OpenLayers_Control_PanZoomBar_ZoombarOpenLayers\\.Map_4').addClass('olControlZoom olControlZoomBarInactive'); } /* * Resize the map. This is a fix for IE 7, which does not assign a height * to the map div if it is not explicitly set. */ function initializeResizeFix() { var vp = $('.olMapViewport')[0]; if( vp.clientHeight > 0 ) { return; } var resizemap = function() { var mapElem = $('#mapandmenu')[0] if(!window.innerHeight) { mapElem.style.height = (window.document.body.clientHeight - 90) + 'px'; vp.style.height = (window.document.body.clientHeight - 150) + 'px'; } }; resizemap(); window.onresize = resizemap; } /* * Create a div for tooltips on the map itself; this is used * when the info tool is activated. */ function createMapTipDiv() { var tipdiv = document.createElement('div'); var tipelem = document.createElement('h1'); tipelem.appendChild(document.createTextNode('District Name')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.id = 'tipclose'; tipelem.onclick = function(e){ OpenLayers.Event.stop(e); tipdiv.style.display = 'none'; }; tipelem.appendChild(document.createTextNode('[x]')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.appendChild(document.createTextNode('Demographic 1:')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.appendChild(document.createTextNode('Demographic 2:')); tipdiv.appendChild(tipelem); tipelem = document.createElement('div'); tipelem.appendChild(document.createTextNode('Demographic 3:')); tipdiv.appendChild(tipelem); tipdiv.style.zIndex = 100000; tipdiv.style.position = 'absolute'; tipdiv.style.opacity = '0.8'; tipdiv.className = 'tooltip'; return tipdiv; } /** * Initialize the map from WMS GetCapabilities. */ function init() { OpenLayers.ProxyHost= "/proxy?url="; $.ajax({ url: OpenLayers.ProxyHost + encodeURIComponent('http://' + MAP_SERVER + '/geoserver/ows?service=wms&version=1.1.1' + '&request=GetCapabilities&namespace=' + NAMESPACE), type: 'GET', success: function(data, textStatus, xhr) { var layer = getSnapLayer().layer; // get the layers in the response var layers = $('Layer > Layer',data); for (var i = 0; i < layers.length; i++) { // get the title of the layer var title = $('> Title',layers[i])[0].firstChild.nodeValue; var name = $('> Name', layers[i])[0].firstChild.nodeValue; // if the title is the displayed snap layer if (title == layer) { // get the SRS and extent, then init the map var bbox = $('> BoundingBox',layers[i]); var srs = bbox.attr('SRS'); var extent = new OpenLayers.Bounds( bbox.attr('minx'), bbox.attr('miny'), bbox.attr('maxx'), bbox.attr('maxy') ); mapinit( srs, extent ); return; } } } }); } /* * Initialize the map with extents and SRS pulled from WMS. */ function mapinit(srs,maxExtent) { // The assignment mode -- the map is initially in navigation mode, // so the assignment mode is null. var assignMode = null; // This projection is web mercator var projection = new OpenLayers.Projection(srs); // Explicitly create the navigation control, since // we'll want to deactivate it in the future. var navigate = new OpenLayers.Control.Navigation({ autoActivate: true, handleRightClicks: true }); // Dynamically compute the resolutions, based on the map extents. var rez = [(maxExtent.right - maxExtent.left) / 256.0]; while (rez.length < 12) { rez.push( rez[rez.length - 1] / 2.0 ); } // Create a slippy map. var olmap = new OpenLayers.Map('map', { // The resolutions here must match the settings in geowebcache. resolutions: rez, maxExtent: maxExtent, projection: projection, units: 'm', controls: [ navigate, new OpenLayers.Control.PanZoomBar(), new OpenLayers.Control.KeyboardDefaults() ] }); // These layers are dependent on the layers available in geowebcache // TODO Fetch a list of layers from geowebcache var layers = []; for (layer in MAP_LAYERS) { layers.push(createLayer( MAP_LAYERS[layer], MAP_LAYERS[layer], srs, maxExtent )); } // The strategy for loading the districts. This is effectively // a manual refresh, with no automatic reloading of district // boundaries except when explicitly loaded. var districtStrategy = new OpenLayers.Strategy.Fixed(); // The style for the districts. This serves as the base // style for all rules that apply to the districtLayer var districtStyle = { fill: true, fillOpacity: 0.00, strokeColor: '#ee9900', strokeOpacity: 1, strokeWidth: 2, label: '${name}', fontColor: '#663300', fontSize: '10pt', fontFamily: 'Arial,Helvetica,sans-serif', fontWeight: '800', labelAlign: 'cm' }; // A vector layer that holds all the districts in // the current plan. var districtLayer = new OpenLayers.Layer.Vector( 'Current Plan', { strategies: [ districtStrategy ], protocol: new OpenLayers.Protocol.HTTP({ url: '/districtmapping/plan/' + PLAN_ID + '/district/versioned', format: new OpenLayers.Format.GeoJSON() }), styleMap: new OpenLayers.StyleMap(new OpenLayers.Style(districtStyle)), projection: projection, filter: getVersionAndSubjectFilters() } ); // Create a vector layer to hold the current selection // of features that are to be manipulated/added to a district. var selection = new OpenLayers.Layer.Vector('Selection',{ styleMap: new OpenLayers.StyleMap({ "default": new OpenLayers.Style( OpenLayers.Util.applyDefaults( { fill: true, fillOpacity: 0.0, strokeColor: '#ffff00', strokeWidth: 3 }, OpenLayers.Feature.Vector.style["default"] ) ), "select": new OpenLayers.Style( OpenLayers.Util.applyDefaults( { fill: true, fillColor: '#ee9900', strokeColor: '#ee9900' }, OpenLayers.Feature.Vector.style["select"] ) ), "error": new OpenLayers.Style( OpenLayers.Util.applyDefaults( { fill: false, strokeColor: '#ee0000' }, OpenLayers.Feature.Vector.style["select"] ) ) }) }); // add these layers to the map layers.push(districtLayer); layers.push(selection); olmap.addLayers(layers); // Create a protocol that is used by all editing controls // that selects geography at the specified snap layer. var getProtocol = new OpenLayers.Protocol.WFS({ url: 'http://' + MAP_SERVER + '/geoserver/wfs', featureType: getSnapLayer().layer, featureNS: NS_HREF, featurePrefix: NAMESPACE, srsName: srs, geometryName: 'geom' }); var idProtocol = new OpenLayers.Protocol.WFS({ url: 'http://' + MAP_SERVER + '/geoserver/wfs', featureType: 'identify_geounit', featureNS: NS_HREF, featurePrefix: NAMESPACE, srsName: srs, geometryName: 'geom' }); // Create a simple point and click control for selecting // geounits one at a time. var getControl = new OpenLayers.Control.GetFeature({ autoActivate: false, protocol: getProtocol, multipleKey: 'shiftKey', toggleKey: 'ctrlKey', filterType: OpenLayers.Filter.Spatial.INTERSECTS }); // Create a rectangular drag control for selecting // geounits that intersect a box. var boxControl = new OpenLayers.Control.GetFeature({ autoActivate: false, protocol: getProtocol, click: false, box: true, multipleKey: 'shiftKey', toggleKey: 'ctrlKey', filterType: OpenLayers.Filter.Spatial.INTERSECTS }); // Reload the information tabs and reload the filters var updateInfoDisplay = function() { $('.geography').load(geourl, {demo: getDistrictBy().by, version: getPlanVersion()}, loadTooltips); $('.demographics').load(demourl, {version: getPlanVersion()}, loadTooltips); districtLayer.filter = getVersionAndSubjectFilters(); districtLayer.strategies[0].load(); }; // An assignment function that adds geounits to a district var assignOnSelect = function(feature) { if (selection.features.length == 0) { $('#assign_district').val('-1'); return; } var district_id = feature.data.district_id; var geolevel_id = selection.features[0].attributes.geolevel_id; var geounit_ids = []; for (var i = 0; i < selection.features.length; i++) { geounit_ids.push( selection.features[i].attributes.id ); } geounit_ids = geounit_ids.join('|'); OpenLayers.Element.addClass(olmap.viewPortDiv,'olCursorWait'); $('#working').dialog('open'); $.ajax({ type: 'POST', url: '/districtmapping/plan/' + PLAN_ID + '/district/' + district_id + '/add', data: { geolevel: geolevel_id, geounits: geounit_ids, version: getPlanVersion() }, success: function(data, textStatus, xhr) { var mode = data.success ? 'select' : 'error'; if (data.success) { // update the max version of this plan PLAN_VERSION = data.version; // set the version cursor $('#history_cursor').val(data.version); // update the UI buttons to show that you can // perform an undo now, but not a redo $('#history_redo').addClass('disabled'); $('#history_undo').removeClass('disabled'); updateInfoDisplay(); $('#saveplaninfo').trigger('planSaved', [ data.edited ]); } else { OpenLayers.Element.removeClass(olmap.viewPortDiv, 'olCursorWait'); $('#working').dialog('close'); } for (var i = 0; i < selection.features.length; i++) { selection.drawFeature(selection.features[i], mode); } if (assignMode == null) { $('#assign_district').val('-1'); } else if (assignMode == 'dragdrop') { $('#assign_district').val('-1'); dragdropControl.deactivate(); dragdropControl.resumeTool.activate(); } }, error: function(xhr, textStatus, error) { window.status = 'failed to select'; } }); }; // When the selection is changed, perform the addition or subtraction // to the current geounit selection. Also, if the assignment mode is // either 'anchor' or 'dragdrop', do some more processing. var unitsSelected = function(features, subtract) { if (subtract) { var removeme = []; for (var i = 0; i < selection.features.length; i++) { for (var j = 0; j < features.length; j++) { if (selection.features[i].data.id == features[j].data.id) { removeme.push(selection.features[i]); } } } selection.removeFeatures(removeme); } else { var addme = []; for (var i = 0; i < features.length; i++) { var match = false; for (var j = 0; j < selection.features.length; j++) { if (features[i].data.id == selection.features[j].data.id) { match = true; break; } } if (!match) { addme.push(features[i]) } } selection.addFeatures(addme); // this is necessary because a feature may be selected more // than once, and the js feature object is different, but the // actual feature itself is the same geometry and attributes. for (var i = 0; i < addme.length; i++) { selection.features[addme[i].fid || addme[i].id] = addme[i]; } } if (assignMode == null) { return; } else if (assignMode == 'anchor') { var d_id = $('#assign_district').val(); if (parseInt(d_id,10) > 0) { var feature = { data:{ district_id: d_id } }; assignOnSelect(feature); } } else if (assignMode == 'dragdrop') { var currentTool = olmap.getControlsBy('active',true)[0]; currentTool.deactivate(); dragdropControl.resumeTool = currentTool; dragdropControl.activate(); } }; // Create a polygon select control for free-form selections. var polyControl = new OpenLayers.Control.DrawFeature( selection, OpenLayers.Handler.Polygon, { handlerOptions: { freehand: true, freehandToggle: null }, featureAdded: function(feature){ // WARNING: not a part of the API! var append = this.handler.evt.shiftKey; var subtract = this.handler.evt.ctrlKey && (assignMode == null); var newOpts = getControl.protocol.options; newOpts.featureType = getSnapLayer().layer; getControl.protocol = new OpenLayers.Protocol.WFS( newOpts ); getControl.protocol.read({ filter: new OpenLayers.Filter.Spatial({ type: OpenLayers.Filter.Spatial.INTERSECTS, value: feature.geometry, projection: getProtocol.options.srsName }), callback: function(rsp){ // first, remove the lasso feature var lasso = selection.features[selection.features.length - 1]; selection.removeFeatures([lasso]); if (!(append || subtract)){ // if this is a new lasso, remove all the // old selected features selection.removeFeatures(selection.features); } unitsSelected( rsp.features, subtract ); } }); } } ); // set this timeout function, since jquery is apparently not ready // to select the elements based on this class during regular init. // also, the reference to the polyControl is used in this init method setTimeout(function(){ var jtmp = $('.olHandlerBoxSelectFeature'); var polySelectStyle = { pointRadius: 0, strokeWidth: parseInt(jtmp.css('borderTopWidth').slice(0,1),10), strokeColor: jtmp.css('borderTopColor'), strokeOpacity: parseFloat(jtmp.css('opacity')), fillColor: jtmp.css('background-color'), fillOpacity: parseFloat(jtmp.css('opacity')) }; polyControl.handler.style = polySelectStyle; }, 100); // Create a tooltip inside of the map div var tipdiv = createMapTipDiv(); olmap.div.insertBefore(tipdiv,olmap.div.firstChild); // Create a control that shows the details of the district // underneath the cursor. var idControl = new IdGeounit({ autoActivate: false, protocol: idProtocol }); // Get the feature at the point in the layer. var featureAtPoint = function(pt, lyr) { for (var i = 0; i < lyr.features.length; i++) { if (pt.intersects(lyr.features[i].geometry)) { return lyr.features[i]; } } return null; }; // Test if the provided point lays within the features in the provided // layer. var pointInFeatures = function(pt, lyr) { return featureAtPoint(pt, lyr) != null; }; // Create a control that shows where a drag selection is // traveling. var dragdropControl = new OpenLayers.Control.DragFeature( selection, { documentDrag: true, onStart: function(feature, pixel) { var ll = olmap.getLonLatFromPixel(pixel); dragdropControl.lastPt = new OpenLayers.Geometry.Point(ll.lon, ll.lat); }, onDrag: function(feature, pixel) { var ll = olmap.getLonLatFromPixel(pixel); var pt = new OpenLayers.Geometry.Point(ll.lon, ll.lat); var dist = featureAtPoint(pt, districtLayer); if (dist == null) { dist = { data: { district_id: 1 } }; } $('#assign_district').val(dist.data.district_id); for (var i = 0; i < selection.features.length; i++) { if (selection.features[i].fid != feature.fid) { selection.features[i].geometry.move( pt.x - dragdropControl.lastPt.x, pt.y - dragdropControl.lastPt.y ); selection.drawFeature(selection.features[i]); } } dragdropControl.lastPt = pt; }, onComplete: function(feature, pixel) { var ll = olmap.getLonLatFromPixel(pixel); var pt = new OpenLayers.Geometry.Point(ll.lon, ll.lat); if (pointInFeatures(pt, districtLayer)) { var dfeat = { data:{ district_id: $('#assign_district').val() } }; assignOnSelect(dfeat); } else { selection.removeFeatures(selection.features); $('#assign_district').val('-1'); dragdropControl.deactivate(); dragdropControl.resumeTool.activate(); } } } ); // A callback to create a popup window on the map after a peice // of geography is selected. var idFeature = function(e) { var snapto = getSnapLayer().layer; // get the range of geolevels var maxGeolevel = 0, minGeolevel = 9999; for (var i = 0; i < SNAP_LAYERS.length; i++) { if (snapto == 'simple_' + SNAP_LAYERS[i].level) { maxGeolevel = SNAP_LAYERS[i].geolevel; } minGeolevel = Math.min(minGeolevel, SNAP_LAYERS[i].geolevel); } // get the breadcrumbs to this geounit, starting at the // largest area (lowest geolevel) first, down to the // most specific geolevel var crumbs = {}; var ctics = {}; var tipFeature = e.features[0]; for (var glvl = minGeolevel; glvl <= maxGeolevel; glvl++) { for (var feat = 0; feat < e.features.length; feat++) { if (e.features[feat].data.geolevel_id == glvl) { crumbs[e.features[feat].data.id] = e.features[feat].data.name; } if (e.features[feat].data.geolevel_id == maxGeolevel) { tipFeature = e.features[feat]; for (var demo = 0; demo < DEMOGRAPHICS.length; demo++) { if (e.features[feat].data.subject_id == DEMOGRAPHICS[demo].id) { ctics[DEMOGRAPHICS[demo].text] = parseFloat(e.features[feat].data.number); } } } } } // truncate the breadcrumbs into a single string var place = []; for (var key in crumbs) { place.push(crumbs[key]); } place = place.join(' / '); var centroid = tipFeature.geometry.getCentroid(); var lonlat = new OpenLayers.LonLat( centroid.x, centroid.y ); var pixel = olmap.getPixelFromLonLat(lonlat); tipdiv.style.display = 'block'; tipdiv.childNodes[0].childNodes[0].nodeValue = place; var select = $('#districtby')[0]; var value = parseInt(tipFeature.attributes.number, 10); var node = 2; for (var key in ctics) { tipdiv.childNodes[node].firstChild.nodeValue = key + ': ' + ctics[key].toLocaleString(); node ++; } var halfWidth = tipdiv.clientWidth/2; var halfHeight = tipdiv.clientHeight/2; if (pixel.x < halfWidth) { pixel.x = halfWidth; } else if (pixel.x > olmap.div.clientWidth - halfWidth) { pixel.x = olmap.div.clientWidth - halfWidth; } if (pixel.y < halfHeight) { pixel.y = halfHeight; } else if (pixel.y > (olmap.div.clientHeight-29) - halfHeight) { pixel.y = (olmap.div.clientHeight-29) - halfHeight; } tipdiv.style.left = (pixel.x - halfWidth) + 'px'; tipdiv.style.top = (pixel.y - halfHeight) + 'px'; if (tipdiv.pending) { clearTimeout(tipdiv.timeout); tipdiv.pending = false; } }; // A callback for feature selection in different controls. var featuresSelected = function(e){ var subtract = e.object.modifiers.toggle && (assignMode == null); unitsSelected(e.features, subtract); }; /* * This will return the maps's truly visible bounds; if the info * tabs on the right are up, that's the usual map bounds. If the * info tabs are showing, it's the visible area of the map to the * left of those tabs */ var getVisibleBounds = function() { if ($('.map_menu_content:visible').length > 0) { var offset = $('#map_menu_header').position(); var bounds = olmap.getExtent(); var lonLat = olmap.getLonLatFromPixel(new OpenLayers.Pixel(offset.left, offset.top)); bounds.right = lonLat.lon; return bounds; } return undefined; } /* * This method is useful to determine whether an item is visible * to the user - pass in the bounds from getVisibleBounds if the * info tabs are showing */ var featureOnScreen = function(feature, bounds) { if (bounds && feature.geometry) { return bounds.intersectsBounds(feature.geometry.getBounds()); } else { return feature.onScreen(); } } // Connect the featuresSelected callback above to the featureselected // events in the point and rectangle control. getControl.events.register('featuresselected', getControl, featuresSelected); boxControl.events.register('featuresselected', boxControl, featuresSelected); idControl.events.register('featuresselected', idControl, idFeature); // A callback for deselecting features from different controls. var featureUnselected = function(e){ selection.removeFeatures([e.feature]); }; // Connect the featureUnselected callback above to the featureunselected // events in the point and rectangle control. getControl.events.register('featureunselected', this, featureUnselected); boxControl.events.register('featureunselected', this, featureUnselected); // Connect a method for indicating work when the district layer // is reloaded. districtLayer.events.register('loadstart',districtLayer,function(){ OpenLayers.Element.addClass(olmap.viewPortDiv, 'olCursorWait'); }); // Recompute the rules for the district styling prior to the adding // of the features to the district layer. This is done at this time // to prevent 2 renderings from being triggered on the district layer. districtLayer.events.register('beforefeaturesadded',districtLayer,function(context){ var lowestColor = $('.farunder').css('background-color'); var lowerColor = $('.under').css('background-color'); var upperColor = $('.over').css('background-color'); var highestColor = $('.farover').css('background-color'); var newOptions = OpenLayers.Util.extend({}, districtStyle); var dby = getDistrictBy(); var rules = []; if (!dby.modified) { rules = [ new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO, property: 'number', value: RULES[dby.by].lowest }), symbolizer: { fillColor: lowestColor, fillOpacity: 0.5 } }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN, property: 'number', lowerBoundary: RULES[dby.by].lowest, upperBoundary: RULES[dby.by].lower }), symbolizer: { fillColor: lowerColor, fillOpacity: 0.5 } }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN, property: 'number', lowerBoundary: RULES[dby.by].lower, upperBoundary: RULES[dby.by].upper }) }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.BETWEEN, property: 'number', lowerBoundary: RULES[dby.by].upper, upperBoundary: RULES[dby.by].highest }), symbolizer: { fillColor: upperColor, fillOpacity: 0.5 } }), new OpenLayers.Rule({ filter: new OpenLayers.Filter.Comparison({ type: OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO, property: 'number', value: RULES[dby.by].highest }), symbolizer: { fillColor: highestColor, fillOpacity: 0.5 } }) ]; } var newStyle = new OpenLayers.Style(newOptions,{ rules:rules }); districtLayer.styleMap = new OpenLayers.StyleMap(newStyle); }); // Connect an event to the district layer that updates the // list of possible districts to assign to. // TODO: this doesn't account for districts with null geometries // which will not come back from the WFS query districtLayer.events.register('loadend',districtLayer,function(){ OpenLayers.Element.removeClass(olmap.viewPortDiv, 'olCursorWait'); selection.removeFeatures(selection.features); var sorted = districtLayer.features.slice(0,districtLayer.features.length); sorted.sort(function(a,b){ return a.attributes.name > b.attributes.name; }); var working = $('#working'); if (working.dialog('isOpen')) { working.dialog('close'); } }); olmap.events.register('movestart',olmap,function(){ tipdiv.style.display = 'none'; }); // When the navigate map tool is clicked, disable all the // controls except the navigation control. $('#navigate_map_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } navigate.activate(); $('#dragdrop_tool').removeClass('toggle'); $('#anchor_tool').removeClass('toggle'); assignMode = null; $('#assign_district').val(-1); tipdiv.style.display = 'none'; }); // When the identify map tool is clicked, disable all the // controls except the identify control. $('#identify_map_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } idControl.activate(); $('#dragdrop_tool').removeClass('toggle'); $('#anchor_tool').removeClass('toggle'); assignMode = null; $('#assign_district').val(-1); }); // When the single pick tool is clicked, disable all the // controls except for the single pick tool. $('#single_drawing_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } getControl.activate(); getControl.features = selection.features; tipdiv.style.display = 'none'; }); // When the rectangle selection tool is clicked, disable all the // controls except for the rectangle selection tool. $('#rectangle_drawing_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } boxControl.activate(); boxControl.features = selection.features; tipdiv.style.display = 'none'; }); // When the polygon selection tool is clicked, disable all the // controls except for the polygon selection tool. $('#polygon_drawing_tool').click(function(evt){ var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } polyControl.activate(); tipdiv.style.display = 'none'; }); // When the assignment tool is clicked, disable all the // controls except for the assignment tool. $('#dragdrop_tool').click(function(evt){ var me = $(this); if (me.hasClass('toggle')) { me.removeClass('toggle'); assignMode = null; dragdropControl.deactivate(); if (dragdropControl.resumeTool) { dragdropControl.resumeTool.activate(); } } else { me.addClass('toggle'); assignMode = 'dragdrop'; if (selection.features.length > 0) { var active = olmap.getControlsBy('active',true); for (var i = 0; i < active.length; i++) { active[i].deactivate(); } dragdropControl.activate(); dragdropControl.resumeTool = active[0]; } } $('#navigate_map_tool').removeClass('toggle'); navigate.deactivate(); $('#identify_map_tool').removeClass('toggle'); idControl.deactivate(); $('#anchor_tool').removeClass('toggle'); tipdiv.style.display = 'none'; // enable single select tool if no selection tool is enabled if (!(getControl.active || boxControl.active || polyControl.active)) { getControl.activate(); $('#single_drawing_tool').addClass('toggle'); } }); $('#anchor_tool').click(function(evt){ var me = $(this); if (me.hasClass('toggle')) { me.removeClass('toggle'); assignMode = null; $('#assign_district').val(-1); } else { me.addClass('toggle'); assignMode = 'anchor'; } $('#navigate_map_tool').removeClass('toggle'); navigate.deactivate(); $('#identify_map_tool').removeClass('toggle'); idControl.deactivate(); $('#dragdrop_tool').removeClass('toggle'); tipdiv.style.display = 'none'; // enable single select tool if no selection tool is enabled if (!(getControl.active || boxControl.active || polyControl.active)) { getControl.activate(); $('#single_drawing_tool').addClass('toggle'); } }); // Add the created controls to the map olmap.addControls([ getControl, boxControl, polyControl, new GlobalZoom(), idControl, dragdropControl ]); // get a format parser for SLDs and the legend var sldFormat = new OpenLayers.Format.SLD(); // a method that will read the named layer, and return // the default style var getDefaultStyle = function(sld, layerName) { var styles = sld.namedLayers[layerName].userStyles; var style; for(var i=0; i<styles.length; ++i) { style = styles[i]; if(style.isDefault) { break; } } return style; } // // get the styles associated with the current map configuration // var getMapStyles = function() { var snap = getSnapLayer().layer.split('simple_')[1]; var show = getShowBy(); OpenLayers.Request.GET({ url: '/sld/' + snap + '_' + show + '.sld', method: 'GET', callback: function(xhr){ var sld = sldFormat.read(xhr.responseXML || xhr.responseText); var userStyle = getDefaultStyle(sld,getShowBy()); $('#legend_title').empty().append(userStyle.title); var lbody = $('#basemap_legend tbody'); lbody.empty(); var rules = userStyle.rules; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (!('Polygon' in rule.symbolizer)) { continue; } var div = $('<div/>'); div.css('background-color',rule.symbolizer.Polygon.fillColor); div.css('border-width',rule.symbolizer.Polygon.strokeWidth); div.css('border-color',rule.symbolizer.Polygon.strokeColor); div.addClass('swatch'); div.addClass('basemap_swatch'); var swatch = $('<td/>'); swatch.width(32); swatch.append(div); var row = $('<tr/>'); row.append(swatch); var title = $('<td/>'); title.append( rule.title ); row.append(title); lbody.append(row); } } }); }; // Logic for the 'Snap Map to' dropdown, note that this logic // calls the boundsforChange callback $('#snapto').change(function(evt){ var newOpts = getControl.protocol.options; var show = getShowBy(); var snap = getSnapLayer(); var layername = NAMESPACE + ':demo_' + snap.level; if (show != 'none') { layername += '_' + show; } var layers = olmap.getLayersByName(layername); newOpts.featureType = snap.layer; getControl.protocol = boxControl.protocol = new OpenLayers.Protocol.WFS( newOpts ); olmap.setBaseLayer(layers[0]); doMapStyling(); getMapStyles(); }); // Logic for the 'Show Map by' dropdown $('#showby').change(function(evt){ var snap = getSnapLayer(); var show = evt.target.value; var layername = NAMESPACE + ':demo_' + snap.level; if (show != 'none') { layername += '_' + show; } var layers = olmap.getLayersByName(layername); olmap.setBaseLayer(layers[0]); doMapStyling(); getMapStyles(); }); // Logic for the 'Show Districts by' dropdown $('#districtby').change(function(evt){ districtLayer.filter = getVersionAndSubjectFilters(); districtLayer.strategies[0].load(); }); // Logic for the 'Assign District to' dropdown $('#assign_district').change(function(evt){ if (this.value == '-1'){ return true; } else if (this.value == 'new'){ createNewDistrict(); } else if (assignMode == null) { var feature = { data:{ district_id: this.value } }; assignOnSelect(feature); } }); // Logic for the history back button $('#history_undo').click(function(evt){ var cursor = $('#history_cursor'); var ver = cursor.val(); if (ver > 0) { ver--; if (ver == 0) { $(this).addClass('disabled'); } cursor.val(ver); $('#history_redo').removeClass('disabled'); updateInfoDisplay(); } }); // Logic for history redo button $('#history_redo').click(function(evt){ var cursor = $('#history_cursor'); var ver = cursor.val(); if (ver < PLAN_VERSION) { ver++; if (ver == PLAN_VERSION) { $(this).addClass('disabled'); } cursor.val(ver); $('#history_undo').removeClass('disabled'); updateInfoDisplay(); } }); /* * Ask the user for a new district name, then assign the current * selection to the new district upon successful creation of the * district */ var createNewDistrict = function() { if (selection.features.length == 0) { $('#assign_district').val('-1'); return; } if (getPlanVersion() != PLAN_VERSION) { // unsupported at this time is creating a district based // of a previous version of the plan. Inform the user. $('<div id="newdistrictdialog">Districts may only be created from the most current plan at this time.</div>').dialog({ modal: true, autoOpen: true, title: 'Sorry', buttons: { 'OK': function() { $('#newdistrictdialog').remove(); } } }); $('#assign_district').val('-1'); return; } // Once we have the district name, post a request to the // server to create it in the DB var createDistrict = function(district_id) { var geolevel_id = selection.features[0].attributes.geolevel_id; var geounit_ids = []; for (var i = 0; i < selection.features.length; i++) { geounit_ids.push( selection.features[i].attributes.id ); } geounit_ids = geounit_ids.join('|'); OpenLayers.Element.addClass(olmap.viewPortDiv,'olCursorWait'); $('#working').dialog('open'); $.ajax({ type: 'POST', url: '/districtmapping/plan/' + PLAN_ID + '/district/new', data: { district_id: district_id, geolevel: geolevel_id, geounits: geounit_ids, version: getPlanVersion() }, success: function(data, textStatus, xhr) { // update the max version of this plan PLAN_VERSION = data.version; $('#history_cursor').val(data.version); // update the UI buttons to show that you can // perform an undo now, but not a redo $('#history_redo').addClass('disabled'); $('#history_undo').removeClass('disabled'); // add the new district entry to the list $('#assign_district').append('<option value="' + data.district_id + '">' + data.district_name + '</option>'); // detach the list of districts from the DOM var all_options = $('#assign_district option').detach(); // if max # of districts has been reached, remove the // 'New District' option if (all_options.length > (MAX_DISTRICTS + 1)) { // the second to last item will be 'new', the last // item will be the option just added all_options[all_options.length-2] = all_options[all_options.length-1]; } // sort the options all_options.sort(function(a,b){ if (a.value == 'new') { return -1; } else { return parseInt(a.value,10) > parseInt(b.value,10); } }); // attach the options back to the DOM (in order, now) all_options.appendTo('#assign_district'); updateInfoDisplay(); $('#working').dialog('close'); $('#assign_district').val('-1'); OpenLayers.Element.removeClass(olmap.viewPortDiv,'olCursorWait'); } }); }; // create a list of available districts, based on the districts // that are already in the plan var options = $('#assign_district')[0].options; var avail = [] for (var d = 1; d <= MAX_DISTRICTS; d++) { var dtaken = false; for (var o = 0; o < options.length && !dtaken; o++) { dtaken = dtaken || ( options[o].text == 'District ' + d) } if (!dtaken) { avail.push('<option value="'+(d+1)+'">District '+d+'</option>'); } } // Create a dialog to get the new district's name from the user. // On close, destroy the dialog. $('<div id="newdistrictdialog">Please select a district name:<br/><select id="newdistrictname">' + avail.join('') + '</select></div>').dialog({ modal: true, autoOpen: true, title: 'New District', buttons: { 'OK': function() { createDistrict($('#newdistrictname').val()); $(this).dialog("close"); $('#newdistrictdialog').remove(); }, 'Cancel': function() { $(this).dialog("close"); $('#newdistrictdialog').remove(); $('#assign_district').val('-1'); } } }); }; /* * After the map has finished moving, this method updates the jQuery * data attributes of the geography and demographics tables if * different districts are now visible */ olmap.prevVisibleDistricts = ''; var sortByVisibility = function() { var visibleDistricts = ''; var visible, notvisible = ''; for (feature in districtLayer.features) { var feature = districtLayer.features[feature]; var inforow = $('.inforow_' + feature.attributes.district_id); if (featureOnScreen(feature, getVisibleBounds())) { inforow.data('isVisibleOnMap', true); visibleDistricts += feature.id; } else { inforow.data('isVisibleOnMap', false); } } if (visibleDistricts != olmap.prevVisibleDistricts) { var demosorter = viewablesorter({ target: '#demographic_table tbody' }).init(); var geosorter = viewablesorter({ target: '#geography_table tbody' }).init(); demosorter.sortTable(); geosorter.sortTable(); olmap.prevVisibleDistricts = visibleDistricts; } }; districtLayer.events.register("loadend", districtLayer, sortByVisibility); olmap.events.register("moveend", olmap, sortByVisibility); // triggering this event here will configure the map to correspond // with the initial dropdown values (jquery will set them to different // values than the default on a reload). A desirable side effect is // that the map styling and legend info will get loaded, too, so there // is no need to explicitly perform doMapStyling() or getMapStyles() // in this init method. $('#snapto').trigger('change'); // Set the initial map extents to the bounds around the study area. // TODO Make these configurable. olmap.zoomToExtent(maxExtent); OpenLayers.Element.addClass(olmap.viewPortDiv, 'olCursorWait'); // set up sizing for dynamic map size that fills the pg initializeResizeFix(); } IdGeounit = OpenLayers.Class(OpenLayers.Control.GetFeature, { /* * Initialize this control, enabling multiple selects with a single * click. */ initialize: function(options) { options = options || {}; OpenLayers.Util.extend(options, { multiple: true, clickTolerance: 0.5, maxFeatures: 25, filterType: OpenLayers.Filter.Spatial.INTERSECTS }); // concatenate events specific to vector with those from the base this.EVENT_TYPES = OpenLayers.Control.GetFeature.prototype.EVENT_TYPES.concat( OpenLayers.Control.prototype.EVENT_TYPES ); options.handlerOptions = options.handlerOptions || {}; OpenLayers.Control.prototype.initialize.apply(this, [options]); this.features = {}; this.handlers = {}; this.handlers.click = new OpenLayers.Handler.Click(this, {click: this.selectClick}, this.handlerOptions.click || {}); }, selectClick: function(evt) { // Set the cursor to "wait" to tell the user we're working on their click. OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait"); var bounds = this.pixelToBounds(evt.xy); this.setModifiers(evt); this.request(bounds, {single: false}); }, CLASS_NAME: 'IdGeounit' }); GlobalZoom = OpenLayers.Class(OpenLayers.Control, { // DOM Elements /** * Property: controlDiv * {DOMElement} */ controlDiv: null, /* * Constructor: GlobalZoom * * Parameters: * options - {Object} */ initialize: function(options) { OpenLayers.Control.prototype.initialize.apply(this, arguments); }, /** * APIMethod: destroy */ destroy: function() { OpenLayers.Event.stopObservingElement(this.controlDiv); OpenLayers.Control.prototype.destroy.apply(this, arguments); }, /** * Method: setMap * * Properties: * map - {<OpenLayers.Map>} */ setMap: function(map) { OpenLayers.Control.prototype.setMap.apply(this, arguments); }, /** * Method: onZoomToExtent * * Parameters: * e - {Event} */ onZoomToExtent: function(e) { this.map.zoomToMaxExtent(); OpenLayers.Event.stop(e); }, /** * Method: draw * * Returns: * {DOMElement} A reference to the DIV DOMElement containing the * switcher tabs. */ draw: function() { OpenLayers.Control.prototype.draw.apply(this); this.loadContents(); // populate div with current info this.redraw(); return this.div; }, /** * Method: redraw * Goes through and takes the current state of the Map and rebuilds the * control to display that state. Groups base layers into a * radio-button group and lists each data layer with a checkbox. * * Returns: * {DOMElement} A reference to the DIV DOMElement containing the control */ redraw: function() { return this.div; }, /** * Method: loadContents * Set up the labels and divs for the control */ loadContents: function() { //configure main div OpenLayers.Event.observe(this.div, "click", OpenLayers.Function.bindAsEventListener( this.onZoomToExtent, this) ); // layers list div this.controlDiv = document.createElement("div"); this.controlDiv.id = this.id + "_controlDiv"; OpenLayers.Element.addClass(this.controlDiv, "controlDiv"); this.div.appendChild(this.controlDiv); }, CLASS_NAME: "GlobalZoom" });
Compute resolutions based on V extent, not H extent.
django/publicmapping/site-media/js/mapping.js
Compute resolutions based on V extent, not H extent.
<ide><path>jango/publicmapping/site-media/js/mapping.js <ide> }); <ide> <ide> // Dynamically compute the resolutions, based on the map extents. <del> var rez = [(maxExtent.right - maxExtent.left) / 256.0]; <add> // NOTE: Geoserver computes the resolution with the top and the bottom <add> // components of the extent, NOT the left/right. <add> var rez = [(maxExtent.top - maxExtent.bottom) / 256.0]; <ide> while (rez.length < 12) { <ide> rez.push( rez[rez.length - 1] / 2.0 ); <ide> }
JavaScript
apache-2.0
6eda07a80f7c9304a0be9caf93bb900ca1d488b3
0
soajs/soajs.dashboard
'use strict'; var fs = require("fs"); var async = require("async"); var deployer = require("soajs.core.drivers"); var utils = require("../../utils/utils.js"); var colls = { git: 'git_accounts', services: 'services', daemons: 'daemons', staticContent: 'staticContent' }; /** * Get activated git record from data store * * @param {Object} soajs * @param {Object} repo * @param {Callback Function} cb */ function getGitRecord(soajs, repo, cb) { var opts = { collection: colls.git, conditions: { 'repos.name': repo }, fields: { provider: 1, domain: 1, token: 1, 'repos.$': 1 } }; BL.model.findEntry(soajs, opts, cb); } function verifyReplicationMode (soajs) { if (soajs.inputmaskData.deployConfig.isKubernetes){ if (soajs.inputmaskData.deployConfig.replication.mode === 'replicated') return "deployment"; else if (soajs.inputmaskData.deployConfig.replication.mode === 'global') return "daemonset"; else return soajs.inputmaskData.deployConfig.replication.mode } return soajs.inputmaskData.deployConfig.replication.mode } /** * Deploy a new SOAJS service of type [ controller || service || daemon ] * * @param {Object} config * @param {Object} soajs * @param {Object} registry * @param {Response Object} res */ function deployServiceOrDaemon(config, soajs, registry, res) { var context = { name: '', origin: '' }; function getEnvInfo(cb) { utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: envRecord.deployer.type === 'manual', code: 618}, function () { context.envRecord = envRecord; return cb(); }); }); }); } function getDashboardConnection(cb) { getDashDbInfo(soajs, function (error, data) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { context.mongoDbs = data.mongoDbs; context.mongoCred = data.mongoCred; context.clusterInfo = data.clusterInfo; context.dbConfig = data.dbConfig; context.origin = context.name = soajs.inputmaskData.name; if (soajs.inputmaskData.type === 'service' && soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.service && soajs.inputmaskData.contentConfig.service.gc) { context.name = soajs.inputmaskData.contentConfig.service.gcName; context.origin = "gcs"; } return cb(); }); }); } function getGitInfo(cb) { getGitRecord(soajs, soajs.inputmaskData.gitSource.owner + '/' + soajs.inputmaskData.gitSource.repo, function (error, accountRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !accountRecord, code: 600}, function () { context.accountRecord = accountRecord; context.accountRecord.providerName = context.accountRecord.provider; if (context.accountRecord.providerName.indexOf('_') !== -1) { context.accountRecord.providerName = context.accountRecord.providerName.split('_')[0]; } return cb(); }); }); } function getServiceDaemonInfo(cb) { var opts = { collection: ((soajs.inputmaskData.type === 'service') ? colls.services : colls.daemons ), conditions: { name: context.name } }; BL.model.findEntry(soajs, opts, function (error, dbRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !dbRecord, code: 600}, function () { registry.loadByEnv({ envCode: soajs.inputmaskData.env.toLowerCase() }, function (error, registry) { utils.checkIfError(soajs, res, {config: config, error: error, code: 446}, function () { context.dbRecord = dbRecord; context.dbRecord.maintenancePort = context.dbRecord.port + registry.serviceConfig.ports.maintenanceInc; return cb(); }); }); }); }); } function constructDeployerParams(cb) { var serviceName = soajs.inputmaskData.env.toLowerCase() + "-" + context.name; var platform = context.envRecord.deployer.selected.split('.')[1]; if (platform === 'docker' && context.name !== 'controller') { serviceName += (soajs.inputmaskData.version) ? "-v" + soajs.inputmaskData.version : ""; } else if (platform === 'kubernetes') { serviceName += (soajs.inputmaskData.version) ? "-v" + soajs.inputmaskData.version : ""; } soajs.inputmaskData.deployConfig.replication.mode = verifyReplicationMode(soajs); var serviceParams = { "env": soajs.inputmaskData.env.toLowerCase(), "id": serviceName.toLowerCase(), // required field to build namespace in kubernetes deployments "name": serviceName.toLowerCase(), "image": soajs.inputmaskData.deployConfig.imagePrefix + "/soajs", "variables": [ "NODE_ENV=production", "SOAJS_ENV=" + soajs.inputmaskData.env.toLowerCase(), "SOAJS_PROFILE=" + context.envRecord.profile, "SOAJS_SRV_AUTOREGISTERHOST=true", "SOAJS_MONGO_NB=" + context.mongoDbs.length, "SOAJS_GIT_OWNER=" + soajs.inputmaskData.gitSource.owner, "SOAJS_GIT_REPO=" + soajs.inputmaskData.gitSource.repo, "SOAJS_GIT_BRANCH=" + soajs.inputmaskData.gitSource.branch, "SOAJS_GIT_COMMIT=" + soajs.inputmaskData.gitSource.commit, "SOAJS_SRV_MEMORY=" + (soajs.inputmaskData.deployConfig.memoryLimit / 1048576) //converting from bytes to mbytes ], "labels": { //very useful when filtering "soajs.content": "true", "soajs.env.code": soajs.inputmaskData.env.toLowerCase(), "soajs.service.name": context.dbRecord.name, "soajs.service.group": ((context.dbRecord.group) ? context.dbRecord.group.toLowerCase().replace(/\s+/g, '-').replace(/_/g, '-') : ''), "soajs.service.type": soajs.inputmaskData.type, "soajs.service.version": "" + soajs.inputmaskData.version, "soajs.service.label": serviceName, "soajs.service.mode": soajs.inputmaskData.deployConfig.replication.mode //replicated || global for swarm, deployment || daemonset for kubernetes }, "cmd": [ 'bash', '-c', './soajsDeployer.sh -T service -X deploy -g ' + context.accountRecord.providerName + ' -G ' + context.accountRecord.domain ], "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit, "replication": { "mode": soajs.inputmaskData.deployConfig.replication.mode }, "version": soajs.inputmaskData.version || "", "containerDir": config.imagesDir, "restartPolicy": { "condition": "any", //TODO: make dynamic "maxAttempts": 5 //TODO: make dynamic }, "network": config.network, "ports": [ { "name": "service", "isPublished": false, "target": context.dbRecord.port }, { "name": "maintenance", "isPublished": false, "target": context.dbRecord.maintenancePort } ] }; if (soajs.inputmaskData.deployConfig.readinessProbe) { serviceParams.readinessProbe = { "initialDelaySeconds": soajs.inputmaskData.deployConfig.readinessProbe.initialDelaySeconds, "timeoutSeconds": soajs.inputmaskData.deployConfig.readinessProbe.timeoutSeconds, "periodSeconds": soajs.inputmaskData.deployConfig.readinessProbe.periodSeconds, "successThreshold": soajs.inputmaskData.deployConfig.readinessProbe.successThreshold, "failureThreshold": soajs.inputmaskData.deployConfig.readinessProbe.failureThreshold }; } if(soajs.inputmaskData.deployConfig.replication.replicas) { serviceParams.replication.replicas = soajs.inputmaskData.deployConfig.replication.replicas; } if (soajs.inputmaskData.deployConfig.useLocalSOAJS) { serviceParams.cmd[2] = serviceParams.cmd[2] + ' -L'; } if (soajs.inputmaskData.type === 'daemon' && soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.daemon) { //TODO: check to verify that grpConfName is present serviceParams.variables.push("SOAJS_DAEMON_GRP_CONF=" + soajs.inputmaskData.contentConfig.daemon.grpConfName); } if (context.dbRecord.src && context.dbRecord.src.cmd) { if (Array.isArray(context.dbRecord.src.cmd) && context.dbRecord.src.cmd.length > 0) { var commands = context.dbRecord.src.cmd.join("; "); serviceParams.cmd[2] = commands + "; " + serviceParams.cmd[2]; } } if (context.dbRecord.src && context.dbRecord.src.main) { serviceParams.cmd[2] = serviceParams.cmd[2] + ' -M ' + context.dbRecord.src.main; } //adding info about database servers for (var i = 0; i < context.mongoDbs.length; i++) { serviceParams.variables.push("SOAJS_MONGO_IP_" + (i + 1) + "=" + context.mongoDbs[i].host); serviceParams.variables.push("SOAJS_MONGO_PORT_" + (i + 1) + "=" + context.mongoDbs[i].port); } //if database prefix exists, add it to env variables if (context.dbConfig && context.dbConfig.prefix) { serviceParams.variables.push("SOAJS_MONGO_PREFIX=" + context.dbConfig.prefix); } //if mongo credentials exist, add them to env variables if (context.mongoCred && context.mongoCred.username && context.mongoCred.password) { serviceParams.variables.push("SOAJS_MONGO_USERNAME=" + context.mongoCred.username); serviceParams.variables.push("SOAJS_MONGO_PASSWORD=" + context.mongoCred.password); } //if replica set is used, add name to env variables if (context.clusterInfo.URLParam && context.clusterInfo.URLParam.replicaSet && context.clusterInfo.URLParam.replicaSet) { serviceParams.variables.push("SOAJS_MONGO_RSNAME=" + context.clusterInfo.URLParam.replicaSet); } //if authSource is set, add it to env variables if (context.clusterInfo.URLParam && context.clusterInfo.URLParam.authSource) { serviceParams.variables.push("SOAJS_MONGO_AUTH_DB=" + context.clusterInfo.URLParam.authSource); } //if ssl is set, add it to env variables if (context.clusterInfo.URLParam && context.clusterInfo.URLParam.ssl) { serviceParams.variables.push("SOAJS_MONGO_SSL=true"); } //if private repo, add token to env variables if (context.accountRecord.token) { if (context.accountRecord.provider === 'bitbucket_enterprise') { context.accountRecord.token = new Buffer(context.accountRecord.token, 'base64').toString(); } serviceParams.variables.push("SOAJS_GIT_TOKEN=" + context.accountRecord.token); } //if gc, add gc info to env variables if (soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.service && soajs.inputmaskData.contentConfig.service.gc) { serviceParams.variables.push("SOAJS_GC_NAME=" + soajs.inputmaskData.contentConfig.service.gcName); serviceParams.variables.push("SOAJS_GC_VERSION=" + soajs.inputmaskData.contentConfig.service.gcVersion); } //Add additional variables if any if (soajs.inputmaskData.variables && soajs.inputmaskData.variables.length > 0) { serviceParams.variables = serviceParams.variables.concat(soajs.inputmaskData.variables); } context.serviceParams = serviceParams; return cb(); } function createHAService(cb) { var options = utils.buildDeployerOptions(context.envRecord, soajs, BL); options.params = context.serviceParams; soajs.log.debug("Creating HA service with deployer: " + JSON.stringify(options.params)); deployer.deployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, cb); }); } function checkPort(cb){ if(soajs.inputmaskData.deployConfig.isKubernetes && soajs.inputmaskData.deployConfig.exposedPort){ var nginxInputPort = soajs.inputmaskData.deployConfig.exposedPort; if(nginxInputPort < config.kubeNginx.minPort || nginxInputPort > config.kubeNginx.maxPort){ var errMsg = config.errors[824]; errMsg = errMsg.replace("%PORTNUMBER%", nginxInputPort); errMsg = errMsg.replace("%MINNGINXPORT%", config.kubeNginx.minPort); errMsg = errMsg.replace("%MAXNGINXPORT%", config.kubeNginx.maxPort); return res.jsonp(soajs.buildResponse({"code": 824, "msg": errMsg})); } else{ return cb(); } } else{ return cb(); } } function checkMemoryRequirement (cb) { if (context.dbRecord && context.dbRecord.prerequisites && context.dbRecord.prerequisites.memory) { utils.checkIfError(soajs, res, { config: config, error: (context.dbRecord.prerequisites.memory > soajs.inputmaskData.deployConfig.memoryLimit), code: 910 }, cb); } else { return cb(); } } getEnvInfo(function () { checkPort(function(){ getDashboardConnection(function () { getGitInfo(function () { getServiceDaemonInfo(function () { checkMemoryRequirement(function () { constructDeployerParams(function () { createHAService(function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); }); }); }); } /** * Get environment record and extract cluster information from it * * @param {Object} soajs * @param {Callback Function} cb */ function getDashDbInfo(soajs, cb) { utils.getEnvironment(soajs, BL.model, 'DASHBOARD', function (error, envRecord) { if (error) { return cb(error); } var clusterName = envRecord.dbs.config.session.cluster; var data = { mongoDbs: envRecord.dbs.clusters[clusterName].servers, mongoCred: envRecord.dbs.clusters[clusterName].credentials, clusterInfo: envRecord.dbs.clusters[clusterName], dbConfig: envRecord.dbs.config }; return cb(null, data); }); } var BL = { model: null, /** * Deploy a new SOAJS service of type [ nginx || controller || service || daemon ], routes to specific function * * @param {Object} options * @param {Response Object} res */ "deployService": function (config, soajs, registry, res) { if (soajs.inputmaskData.type === 'nginx') { BL.deployNginx(config, soajs, res); } else if (['service', 'daemon'].indexOf(soajs.inputmaskData.type) !== -1) { deployServiceOrDaemon(config, soajs, registry, res); } }, /** * Deploy a new custom service * * @param {Object} options * @param {Response Object} res */ "deployCustomService": function (config, soajs, res) { soajs.inputmaskData.deployConfig.replication.mode = verifyReplicationMode(soajs); var serviceParams = { "env": soajs.inputmaskData.env.toLowerCase(), "id": soajs.inputmaskData.name.toLowerCase(), "name": soajs.inputmaskData.name.toLowerCase(), "image": soajs.inputmaskData.deployConfig.image, "variables": soajs.inputmaskData.variables || [], "labels": soajs.inputmaskData.labels, "cmd": soajs.inputmaskData.command.cmd.concat(soajs.inputmaskData.command.args), "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit, "replication": { "mode": soajs.inputmaskData.deployConfig.replication.mode }, "containerDir": soajs.inputmaskData.deployConfig.workDir, "restartPolicy": { "condition": soajs.inputmaskData.deployConfig.restartPolicy.condition, "maxAttempts": soajs.inputmaskData.deployConfig.restartPolicy.maxAttempts }, "network": soajs.inputmaskData.deployConfig.network, "ports": soajs.inputmaskData.deployConfig.ports || [] }; if(soajs.inputmaskData.deployConfig.replication.replicas) { serviceParams.replication.replicas = soajs.inputmaskData.deployConfig.replication.replicas; } if (soajs.inputmaskData.deployConfig.volume && Object.keys(soajs.inputmaskData.deployConfig.volume).length > 0) { serviceParams.volume = { //NOTE: onyl one volume is supported for now "name": soajs.inputmaskData.name + '-volume', "type": soajs.inputmaskData.deployConfig.volume.type, "readOnly": soajs.inputmaskData.deployConfig.volume.readOnly || false, "source": soajs.inputmaskData.deployConfig.volume.source, "target": soajs.inputmaskData.deployConfig.volume.target }; } if (soajs.inputmaskData.deployConfig.readinessProbe) { serviceParams.readinessProbe = { //NOTE: only httpGet readiness probe is supported for now "path": soajs.inputmaskData.deployConfig.readinessProbe.path, "port": soajs.inputmaskData.deployConfig.readinessProbe.port, "initialDelaySeconds": soajs.inputmaskData.deployConfig.readinessProbe.initialDelaySeconds, "timeoutSeconds": soajs.inputmaskData.deployConfig.readinessProbe.timeoutSeconds, "periodSeconds": soajs.inputmaskData.deployConfig.readinessProbe.periodSeconds, "successThreshold": soajs.inputmaskData.deployConfig.readinessProbe.successThreshold, "failureThreshold": soajs.inputmaskData.deployConfig.readinessProbe.failureThreshold }; } utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !envRecord, code: 446}, function () { var options = utils.buildDeployerOptions(envRecord, soajs, BL); options.params = serviceParams; deployer.deployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); }, /** * Deploy a new nginx service * * @param {Object} options * @param {Response Object} res */ "deployNginx": function (config, soajs, res) { /* 1- get environment information 2- get ui information 3- initialize deployer 3.1- construct deployer params 3.2- deploy nginx container */ var context = {}, options = {}; function getEnvInfo(cb) { //from envCode, load env, get port and domain utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 600}, function () { utils.checkIfError(soajs, res, { config: config, error: !envRecord.deployer.type || !envRecord.deployer.selected, code: 743 }, function () { context.envRecord = envRecord; return cb(); }); }); }); } function getCustomUIConfig(cb) { if (!soajs.inputmaskData.contentConfig || !soajs.inputmaskData.contentConfig.nginx || !soajs.inputmaskData.contentConfig.nginx.ui) return cb(); var id = soajs.inputmaskData.contentConfig.nginx.ui.id; BL.model.validateCustomId(soajs, id, function (error, id) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { var opts = { collection: colls.staticContent, conditions: { '_id': id } }; BL.model.findEntry(soajs, opts, function (error, srcRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { if (!srcRecord) return cb(); getGitRecord(soajs, srcRecord.src.owner + '/' + srcRecord.src.repo, function (error, tokenRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !tokenRecord, code: 600}, function () { if (tokenRecord.token) { if (tokenRecord.provider === 'bitbucket_enterprise') { tokenRecord.token = new Buffer(tokenRecord.token, 'base64').toString(); } srcRecord.token = tokenRecord.token; } context.ui = srcRecord; return cb(); }); }); }); }); }); }); }); } function getControllerDomain(cb) { options.params = { env: soajs.inputmaskData.env.toLowerCase(), serviceName: 'controller', version: '1' }; deployer.getServiceHost(options, function (error, controllerDomainName) { utils.checkIfError(soajs, res, {config: config, error: error}, function () { context.controller = { domain: controllerDomainName }; return cb(); }); }); } function constructDeployerParams() { soajs.inputmaskData.deployConfig.replication.mode = verifyReplicationMode(soajs); var nginxParams = { "env": context.envRecord.code.toLowerCase(), "id": soajs.inputmaskData.env.toLowerCase() + "-nginx", "name": soajs.inputmaskData.env.toLowerCase() + "-nginx", "image": soajs.inputmaskData.deployConfig.imagePrefix + "/nginx", "variables": [ "SOAJS_NX_CONTROLLER_NB=1", "SOAJS_NX_CONTROLLER_IP_1=" + context.controller.domain, "SOAJS_NX_DOMAIN=" + context.envRecord.domain, "SOAJS_NX_SITE_DOMAIN=" + context.envRecord.sitePrefix + "." + context.envRecord.domain, "SOAJS_NX_API_DOMAIN=" + context.envRecord.apiPrefix + "." + context.envRecord.domain ], "labels": { "soajs.content": "true", "soajs.env.code": soajs.inputmaskData.env.toLowerCase(), "soajs.service.name": "nginx", "soajs.service.group": "nginx", "soajs.service.type": "nginx", "soajs.service.label": soajs.inputmaskData.env.toLowerCase() + "-nginx", "soajs.service.mode": soajs.inputmaskData.deployConfig.replication.mode //replicated || global for swarm, deployment || daemonset for kubernetes }, "cmd": [ './soajsDeployer.sh', '-T', 'nginx', '-X', 'deploy' ], "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit, "containerDir": config.imagesDir, "replication": { "mode": soajs.inputmaskData.deployConfig.replication.mode }, "restartPolicy": { "condition": "any", //TODO: make dynamic "maxAttempts": 5 //TODO: make dynamic }, "network": config.network, "ports": [ //NOTE: an https port is automatically exposed with a random port //NOTE: only one http exposed port is permitted for now for nginx deployment { "name": "http", "isPublished": true, "target": 80, "published": ((soajs.inputmaskData.deployConfig.ports && soajs.inputmaskData.deployConfig.ports[0]) ? soajs.inputmaskData.deployConfig.ports[0].published : null) }, { "name": "https", "isPublished": true, "target": 443 } ] }; if(soajs.inputmaskData.deployConfig.replication.replicas) { nginxParams.replication.replicas = soajs.inputmaskData.deployConfig.replication.replicas; } if (soajs.inputmaskData.deployConfig.readinessProbe) { nginxParams.readinessProbe = { "initialDelaySeconds": soajs.inputmaskData.deployConfig.readinessProbe.initialDelaySeconds, "timeoutSeconds": soajs.inputmaskData.deployConfig.readinessProbe.timeoutSeconds, "periodSeconds": soajs.inputmaskData.deployConfig.readinessProbe.periodSeconds, "successThreshold": soajs.inputmaskData.deployConfig.readinessProbe.successThreshold, "failureThreshold": soajs.inputmaskData.deployConfig.readinessProbe.failureThreshold }; } if (soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.nginx && soajs.inputmaskData.contentConfig.nginx.supportSSL) { nginxParams.cmd.push('-s'); nginxParams.ssl = { "enabled": true } if(soajs.inputmaskData.contentConfig.nginx.kubeSecret){ nginxParams.variables.push("SOAJS_NX_CUSTOM_SSL=1"); nginxParams.variables.push("SOAJS_NX_SSL_CERTS_LOCATION=/etc/soajs/ssl"); nginxParams.ssl.secret = soajs.inputmaskData.contentConfig.nginx.kubeSecret } nginxParams.variables.push("SOAJS_NX_API_HTTPS=1"); nginxParams.variables.push("SOAJS_NX_API_HTTP_REDIRECT=1"); nginxParams.variables.push("SOAJS_NX_SITE_HTTPS=1"); nginxParams.variables.push("SOAJS_NX_SITE_HTTP_REDIRECT=1"); } if (context.ui) { nginxParams.variables.push("SOAJS_GIT_REPO=" + context.ui.src.repo); nginxParams.variables.push("SOAJS_GIT_OWNER=" + context.ui.src.owner); nginxParams.variables.push("SOAJS_GIT_BRANCH=" + soajs.inputmaskData.contentConfig.nginx.ui.branch); nginxParams.variables.push("SOAJS_GIT_COMMIT=" + soajs.inputmaskData.contentConfig.nginx.ui.commit); if (context.ui.token) { nginxParams.variables.push("SOAJS_GIT_TOKEN=" + context.ui.token); } } return nginxParams; } function createHAService(cb) { options.params = context.nginxParams; soajs.log.debug("Creating HA service with deployer: " + JSON.stringify(options.params)); deployer.deployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, cb); }); } function checkPort(cb){ //TODO: check if exposed port is set before proceeding in case of type === nginx var nginxInputPort = soajs.inputmaskData.deployConfig.ports[0].published; var deployType = context.envRecord.deployer.selected.split('.')[1]; if(deployType === "kubernetes" && (nginxInputPort < config.kubeNginx.minPort || nginxInputPort > config.kubeNginx.maxPort)){ var errMsg = config.errors[824]; errMsg = errMsg.replace("%PORTNUMBER%", nginxInputPort); errMsg = errMsg.replace("%MINNGINXPORT%", config.kubeNginx.minPort); errMsg = errMsg.replace("%MAXNGINXPORT%", config.kubeNginx.maxPort); return res.jsonp(soajs.buildResponse({"code": 824, "msg": errMsg})); } else{ if(deployType === "kubernetes") { soajs.inputmaskData.deployConfig.ports[0].published += 30000; } return cb(); } } getEnvInfo(function () { options = utils.buildDeployerOptions(context.envRecord, soajs, BL); checkPort(function() { getCustomUIConfig(function () { getControllerDomain(function () { context.nginxParams = constructDeployerParams(); createHAService(function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); }, /** * Redeploy a service (does not update config, only simulates a deployment restart) * * @param {Object} options * @param {Response Object} res */ "redeployService": function (config, soajs, res) { utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 402}, function () { var options = utils.buildDeployerOptions(envRecord, soajs, BL); options.params = { id: soajs.inputmaskData.serviceId, mode: soajs.inputmaskData.mode //NOTE: only required for kubernetes driver }; if (soajs.inputmaskData.ssl && soajs.inputmaskData.ssl.supportSSL) { options.params.ssl = { "enabled": true }; if (soajs.inputmaskData.ssl.kubeSecret) { options.params.ssl.kubeSecret = soajs.inputmaskData.ssl.kubeSecret; } } getUIConfig(function (error, config) { //error is already catered for in function if (config.available) { options.params.ui = config.values; } deployer.redeployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); function getUIConfig (cb) { if (!soajs.inputmaskData.ui) { return cb(null, { available: false }); } BL.model.validateCustomId(soajs, soajs.inputmaskData.ui.id, function (error, id) { utils.checkIfError(soajs, res, {config: config, error: error, code: 701}, function () { var opts = { collection: colls.staticContent, condition: { _id: id } }; BL.model.findEntry(soajs, opts, function (error, record) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !record, code: 905}, function () { getGitRecord(soajs, record.src.owner + '/' + record.src.repo, function (error, gitRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !gitRecord, code: 757}, function () { var result = { available: true, values: { owner: record.src.owner, repo: record.src.repo, branch: soajs.inputmaskData.ui.branch, commit: soajs.inputmaskData.ui.commit, provider: gitRecord.provider, domain: gitRecord.domain } }; if (gitRecord.access === 'private' && gitRecord.token) { if (gitRecord.provider === 'bitbucket_enterprise') { gitRecord.token = new Buffer(gitRecord.token, 'base64').toString(); } result.values.token = gitRecord.token; } return cb(null, result); }); }); }); }); }); }); }); }); } } }; module.exports = { "init": function (modelName, cb) { var modelPath; if (!modelName) { return cb(new Error("No Model Requested!")); } modelPath = __dirname + "/../../models/" + modelName + ".js"; return requireModel(modelPath, cb); /** * checks if model file exists, requires it and returns it. * @param filePath * @param cb */ function requireModel(filePath, cb) { //check if file exist. if not return error fs.exists(filePath, function (exists) { if (!exists) { return cb(new Error("Requested Model Not Found!")); } BL.model = require(filePath); return cb(null, BL); }); } } };
lib/cloud/deploy.js
'use strict'; var fs = require("fs"); var async = require("async"); var deployer = require("soajs.core.drivers"); var utils = require("../../utils/utils.js"); var colls = { git: 'git_accounts', services: 'services', daemons: 'daemons', staticContent: 'staticContent' }; /** * Get activated git record from data store * * @param {Object} soajs * @param {Object} repo * @param {Callback Function} cb */ function getGitRecord(soajs, repo, cb) { var opts = { collection: colls.git, conditions: { 'repos.name': repo }, fields: { provider: 1, domain: 1, token: 1, 'repos.$': 1 } }; BL.model.findEntry(soajs, opts, cb); } function verifyReplicationMode (soajs) { if (soajs.inputmaskData.deployConfig.isKubernetes){ if (soajs.inputmaskData.deployConfig.replication.mode === 'replicated') return "deployment"; else if (soajs.inputmaskData.deployConfig.replication.mode === 'global') return "daemonset"; else return soajs.inputmaskData.deployConfig.replication.mode } return soajs.inputmaskData.deployConfig.replication.mode } /** * Deploy a new SOAJS service of type [ controller || service || daemon ] * * @param {Object} config * @param {Object} soajs * @param {Object} registry * @param {Response Object} res */ function deployServiceOrDaemon(config, soajs, registry, res) { var context = { name: '', origin: '' }; function getEnvInfo(cb) { utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: envRecord.deployer.type === 'manual', code: 618}, function () { context.envRecord = envRecord; return cb(); }); }); }); } function getDashboardConnection(cb) { getDashDbInfo(soajs, function (error, data) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { context.mongoDbs = data.mongoDbs; context.mongoCred = data.mongoCred; context.clusterInfo = data.clusterInfo; context.dbConfig = data.dbConfig; context.origin = context.name = soajs.inputmaskData.name; if (soajs.inputmaskData.type === 'service' && soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.service && soajs.inputmaskData.contentConfig.service.gc) { context.name = soajs.inputmaskData.contentConfig.service.gcName; context.origin = "gcs"; } return cb(); }); }); } function getGitInfo(cb) { getGitRecord(soajs, soajs.inputmaskData.gitSource.owner + '/' + soajs.inputmaskData.gitSource.repo, function (error, accountRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !accountRecord, code: 600}, function () { context.accountRecord = accountRecord; context.accountRecord.providerName = context.accountRecord.provider; if (context.accountRecord.providerName.indexOf('_') !== -1) { context.accountRecord.providerName = context.accountRecord.providerName.split('_')[0]; } return cb(); }); }); } function getServiceDaemonInfo(cb) { var opts = { collection: ((soajs.inputmaskData.type === 'service') ? colls.services : colls.daemons ), conditions: { name: context.name } }; BL.model.findEntry(soajs, opts, function (error, dbRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !dbRecord, code: 600}, function () { registry.loadByEnv({ envCode: soajs.inputmaskData.env.toLowerCase() }, function (error, registry) { utils.checkIfError(soajs, res, {config: config, error: error, code: 446}, function () { context.dbRecord = dbRecord; context.dbRecord.maintenancePort = context.dbRecord.port + registry.serviceConfig.ports.maintenanceInc; return cb(); }); }); }); }); } function constructDeployerParams(cb) { var serviceName = soajs.inputmaskData.env.toLowerCase() + "-" + context.name; var platform = context.envRecord.deployer.selected.split('.')[1]; if (platform === 'docker' && context.name !== 'controller') { serviceName += (soajs.inputmaskData.version) ? "-v" + soajs.inputmaskData.version : ""; } else if (platform === 'kubernetes') { serviceName += (soajs.inputmaskData.version) ? "-v" + soajs.inputmaskData.version : ""; } soajs.inputmaskData.deployConfig.replication.mode = verifyReplicationMode(soajs); var serviceParams = { "env": soajs.inputmaskData.env.toLowerCase(), "id": serviceName.toLowerCase(), // required field to build namespace in kubernetes deployments "name": serviceName.toLowerCase(), "image": soajs.inputmaskData.deployConfig.imagePrefix + "/soajs", "variables": [ "NODE_ENV=production", "SOAJS_ENV=" + soajs.inputmaskData.env.toLowerCase(), "SOAJS_PROFILE=" + context.envRecord.profile, "SOAJS_SRV_AUTOREGISTERHOST=true", "SOAJS_MONGO_NB=" + context.mongoDbs.length, "SOAJS_GIT_OWNER=" + soajs.inputmaskData.gitSource.owner, "SOAJS_GIT_REPO=" + soajs.inputmaskData.gitSource.repo, "SOAJS_GIT_BRANCH=" + soajs.inputmaskData.gitSource.branch, "SOAJS_GIT_COMMIT=" + soajs.inputmaskData.gitSource.commit, "SOAJS_SRV_MEMORY=" + (soajs.inputmaskData.deployConfig.memoryLimit / 1048576) //converting from bytes to mbytes ], "labels": { //very useful when filtering "soajs.content": "true", "soajs.env.code": soajs.inputmaskData.env.toLowerCase(), "soajs.service.name": context.dbRecord.name, "soajs.service.group": ((context.dbRecord.group) ? context.dbRecord.group.toLowerCase().replace(/\s+/g, '-').replace(/_/g, '-') : ''), "soajs.service.type": soajs.inputmaskData.type, "soajs.service.version": "" + soajs.inputmaskData.version, "soajs.service.label": serviceName, "soajs.service.mode": soajs.inputmaskData.deployConfig.replication.mode //replicated || global for swarm, deployment || daemonset for kubernetes }, "cmd": [ 'bash', '-c', './soajsDeployer.sh -T service -X deploy -g ' + context.accountRecord.providerName + ' -G ' + context.accountRecord.domain ], "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit, "replication": { "mode": soajs.inputmaskData.deployConfig.replication.mode }, "version": soajs.inputmaskData.version || "", "containerDir": config.imagesDir, "restartPolicy": { "condition": "any", //TODO: make dynamic "maxAttempts": 5 //TODO: make dynamic }, "network": config.network, "ports": [ { "name": "service", "isPublished": false, "target": context.dbRecord.port }, { "name": "maintenance", "isPublished": false, "target": context.dbRecord.maintenancePort } ] }; if (soajs.inputmaskData.deployConfig.readinessProbe) { serviceParams.readinessProbe = { "initialDelaySeconds": soajs.inputmaskData.deployConfig.readinessProbe.initialDelaySeconds, "timeoutSeconds": soajs.inputmaskData.deployConfig.readinessProbe.timeoutSeconds, "periodSeconds": soajs.inputmaskData.deployConfig.readinessProbe.periodSeconds, "successThreshold": soajs.inputmaskData.deployConfig.readinessProbe.successThreshold, "failureThreshold": soajs.inputmaskData.deployConfig.readinessProbe.failureThreshold }; } if(soajs.inputmaskData.deployConfig.replication.replicas) { serviceParams.replication.replicas = soajs.inputmaskData.deployConfig.replication.replicas; } if (soajs.inputmaskData.deployConfig.useLocalSOAJS) { serviceParams.cmd[2] = serviceParams.cmd[2] + ' -L'; } if (soajs.inputmaskData.type === 'daemon' && soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.daemon) { //TODO: check to verify that grpConfName is present serviceParams.variables.push("SOAJS_DAEMON_GRP_CONF=" + soajs.inputmaskData.contentConfig.daemon.grpConfName); } if (context.dbRecord.src && context.dbRecord.src.cmd) { if (Array.isArray(context.dbRecord.src.cmd) && context.dbRecord.src.cmd.length > 0) { var commands = context.dbRecord.src.cmd.join("; "); serviceParams.cmd[2] = commands + "; " + serviceParams.cmd[2]; } } if (context.dbRecord.src && context.dbRecord.src.main) { serviceParams.cmd[2] = serviceParams.cmd[2] + ' -M ' + context.dbRecord.src.main; } //adding info about database servers for (var i = 0; i < context.mongoDbs.length; i++) { serviceParams.variables.push("SOAJS_MONGO_IP_" + (i + 1) + "=" + context.mongoDbs[i].host); serviceParams.variables.push("SOAJS_MONGO_PORT_" + (i + 1) + "=" + context.mongoDbs[i].port); } //if database prefix exists, add it to env variables if (context.dbConfig && context.dbConfig.prefix) { serviceParams.variables.push("SOAJS_MONGO_PREFIX=" + context.dbConfig.prefix); } //if mongo credentials exist, add them to env variables if (context.mongoCred && context.mongoCred.username && context.mongoCred.password) { serviceParams.variables.push("SOAJS_MONGO_USERNAME=" + context.mongoCred.username); serviceParams.variables.push("SOAJS_MONGO_PASSWORD=" + context.mongoCred.password); } //if replica set is used, add name to env variables if (context.clusterInfo.URLParam && context.clusterInfo.URLParam.replicaSet && context.clusterInfo.URLParam.replicaSet) { serviceParams.variables.push("SOAJS_MONGO_RSNAME=" + context.clusterInfo.URLParam.replicaSet); } //if authSource is set, add it to env variables if (context.clusterInfo.URLParam && context.clusterInfo.URLParam.authSource) { serviceParams.variables.push("SOAJS_MONGO_AUTH_DB=" + context.clusterInfo.URLParam.authSource); } //if ssl is set, add it to env variables if (context.clusterInfo.URLParam && context.clusterInfo.URLParam.ssl) { serviceParams.variables.push("SOAJS_MONGO_SSL=true"); } //if private repo, add token to env variables if (context.accountRecord.token) { if (context.accountRecord.provider === 'bitbucket_enterprise') { context.accountRecord.token = new Buffer(context.accountRecord.token, 'base64').toString(); } serviceParams.variables.push("SOAJS_GIT_TOKEN=" + context.accountRecord.token); } //if gc, add gc info to env variables if (soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.service && soajs.inputmaskData.contentConfig.service.gc) { serviceParams.variables.push("SOAJS_GC_NAME=" + soajs.inputmaskData.contentConfig.service.gcName); serviceParams.variables.push("SOAJS_GC_VERSION=" + soajs.inputmaskData.contentConfig.service.gcVersion); } //Add additional variables if any if (soajs.inputmaskData.variables && soajs.inputmaskData.variables.length > 0) { serviceParams.variables = serviceParams.variables.concat(soajs.inputmaskData.variables); } context.serviceParams = serviceParams; return cb(); } function createHAService(cb) { var options = utils.buildDeployerOptions(context.envRecord, soajs, BL); options.params = context.serviceParams; soajs.log.debug("Creating HA service with deployer: " + JSON.stringify(options.params)); deployer.deployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, cb); }); } function checkPort(cb){ if(soajs.inputmaskData.deployConfig.isKubernetes && soajs.inputmaskData.deployConfig.exposedPort){ var nginxInputPort = soajs.inputmaskData.deployConfig.exposedPort; if(nginxInputPort < config.kubeNginx.minPort || nginxInputPort > config.kubeNginx.maxPort){ var errMsg = config.errors[824]; errMsg = errMsg.replace("%PORTNUMBER%", nginxInputPort); errMsg = errMsg.replace("%MINNGINXPORT%", config.kubeNginx.minPort); errMsg = errMsg.replace("%MAXNGINXPORT%", config.kubeNginx.maxPort); return res.jsonp(soajs.buildResponse({"code": 824, "msg": errMsg})); } else{ return cb(); } } else{ return cb(); } } function checkMemoryRequirement (cb) { if (context.dbRecord && context.dbRecord.prerequisites && context.dbRecord.prerequisites.memory) { utils.checkIfError(soajs, res, { config: config, error: (context.dbRecord.prerequisites.memory > soajs.inputmaskData.deployConfig.memoryLimit), code: 910 }, cb); } else { return cb(); } } getEnvInfo(function () { checkPort(function(){ getDashboardConnection(function () { getGitInfo(function () { getServiceDaemonInfo(function () { checkMemoryRequirement(function () { constructDeployerParams(function () { createHAService(function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); }); }); }); } /** * Get environment record and extract cluster information from it * * @param {Object} soajs * @param {Callback Function} cb */ function getDashDbInfo(soajs, cb) { utils.getEnvironment(soajs, BL.model, 'DASHBOARD', function (error, envRecord) { if (error) { return cb(error); } var clusterName = envRecord.dbs.config.session.cluster; var data = { mongoDbs: envRecord.dbs.clusters[clusterName].servers, mongoCred: envRecord.dbs.clusters[clusterName].credentials, clusterInfo: envRecord.dbs.clusters[clusterName], dbConfig: envRecord.dbs.config }; return cb(null, data); }); } var BL = { model: null, /** * Deploy a new SOAJS service of type [ nginx || controller || service || daemon ], routes to specific function * * @param {Object} options * @param {Response Object} res */ "deployService": function (config, soajs, registry, res) { if (soajs.inputmaskData.type === 'nginx') { BL.deployNginx(config, soajs, res); } else if (['service', 'daemon'].indexOf(soajs.inputmaskData.type) !== -1) { deployServiceOrDaemon(config, soajs, registry, res); } }, /** * Deploy a new custom service * * @param {Object} options * @param {Response Object} res */ "deployCustomService": function (config, soajs, res) { soajs.inputmaskData.deployConfig.replication.mode = verifyReplicationMode(soajs); var serviceParams = { "env": soajs.inputmaskData.env.toLowerCase(), "id": soajs.inputmaskData.name.toLowerCase(), "name": soajs.inputmaskData.name.toLowerCase(), "image": soajs.inputmaskData.deployConfig.image, "variables": soajs.inputmaskData.variables || [], "labels": soajs.inputmaskData.labels, "cmd": soajs.inputmaskData.command.cmd.concat(soajs.inputmaskData.command.args), "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit, "replication": { "mode": soajs.inputmaskData.deployConfig.replication.mode }, "containerDir": soajs.inputmaskData.deployConfig.workDir, "restartPolicy": { "condition": soajs.inputmaskData.deployConfig.restartPolicy.condition, "maxAttempts": soajs.inputmaskData.deployConfig.restartPolicy.maxAttempts }, "network": soajs.inputmaskData.deployConfig.network, "ports": soajs.inputmaskData.deployConfig.ports || [] }; if(soajs.inputmaskData.deployConfig.replication.replicas) { serviceParams.replication.replicas = soajs.inputmaskData.deployConfig.replication.replicas; } if (soajs.inputmaskData.deployConfig.volume && Object.keys(soajs.inputmaskData.deployConfig.volume).length > 0) { serviceParams.volume = { //NOTE: onyl one volume is supported for now "name": soajs.inputmaskData.name + '-volume', "type": soajs.inputmaskData.deployConfig.volume.type, "readOnly": soajs.inputmaskData.deployConfig.volume.readOnly || false, "source": soajs.inputmaskData.deployConfig.volume.source, "target": soajs.inputmaskData.deployConfig.volume.target }; } if (soajs.inputmaskData.deployConfig.readinessProbe) { serviceParams.readinessProbe = { //NOTE: only httpGet readiness probe is supported for now "path": soajs.inputmaskData.deployConfig.readinessProbe.path, "port": soajs.inputmaskData.deployConfig.readinessProbe.port, "initialDelaySeconds": soajs.inputmaskData.deployConfig.readinessProbe.initialDelaySeconds, "timeoutSeconds": soajs.inputmaskData.deployConfig.readinessProbe.timeoutSeconds, "periodSeconds": soajs.inputmaskData.deployConfig.readinessProbe.periodSeconds, "successThreshold": soajs.inputmaskData.deployConfig.readinessProbe.successThreshold, "failureThreshold": soajs.inputmaskData.deployConfig.readinessProbe.failureThreshold }; } utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !envRecord, code: 446}, function () { var options = utils.buildDeployerOptions(envRecord, soajs, BL); options.params = serviceParams; deployer.deployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); }, /** * Deploy a new nginx service * * @param {Object} options * @param {Response Object} res */ "deployNginx": function (config, soajs, res) { /* 1- get environment information 2- get ui information 3- initialize deployer 3.1- construct deployer params 3.2- deploy nginx container */ var context = {}, options = {}; function getEnvInfo(cb) { //from envCode, load env, get port and domain utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 600}, function () { utils.checkIfError(soajs, res, { config: config, error: !envRecord.deployer.type || !envRecord.deployer.selected, code: 743 }, function () { context.envRecord = envRecord; return cb(); }); }); }); } function getCustomUIConfig(cb) { if (!soajs.inputmaskData.contentConfig || !soajs.inputmaskData.contentConfig.nginx || !soajs.inputmaskData.contentConfig.nginx.ui) return cb(); var id = soajs.inputmaskData.contentConfig.nginx.ui.id; BL.model.validateCustomId(soajs, id, function (error, id) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { var opts = { collection: colls.staticContent, conditions: { '_id': id } }; BL.model.findEntry(soajs, opts, function (error, srcRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { if (!srcRecord) return cb(); getGitRecord(soajs, srcRecord.src.owner + '/' + srcRecord.src.repo, function (error, tokenRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !tokenRecord, code: 600}, function () { if (tokenRecord.token) { if (tokenRecord.provider === 'bitbucket_enterprise') { tokenRecord.token = new Buffer(tokenRecord.token, 'base64').toString(); } srcRecord.token = tokenRecord.token; } context.ui = srcRecord; return cb(); }); }); }); }); }); }); }); } function getControllerDomain(cb) { options.params = { env: soajs.inputmaskData.env.toLowerCase(), serviceName: 'controller', version: '1' }; deployer.getServiceHost(options, function (error, controllerDomainName) { utils.checkIfError(soajs, res, {config: config, error: error}, function () { context.controller = { domain: controllerDomainName }; return cb(); }); }); } function constructDeployerParams() { soajs.inputmaskData.deployConfig.replication.mode = verifyReplicationMode(soajs); var nginxParams = { "env": context.envRecord.code.toLowerCase(), "id": soajs.inputmaskData.env.toLowerCase() + "-nginx", "name": soajs.inputmaskData.env.toLowerCase() + "-nginx", "image": soajs.inputmaskData.deployConfig.imagePrefix + "/nginx", "variables": [ "SOAJS_NX_CONTROLLER_NB=1", "SOAJS_NX_CONTROLLER_IP_1=" + context.controller.domain, "SOAJS_NX_DOMAIN=" + context.envRecord.domain, "SOAJS_NX_SITE_DOMAIN=" + context.envRecord.sitePrefix + "." + context.envRecord.domain, "SOAJS_NX_API_DOMAIN=" + context.envRecord.apiPrefix + "." + context.envRecord.domain ], "labels": { "soajs.content": "true", "soajs.env.code": soajs.inputmaskData.env.toLowerCase(), "soajs.service.name": "nginx", "soajs.service.group": "nginx", "soajs.service.type": "nginx", "soajs.service.label": soajs.inputmaskData.env.toLowerCase() + "-nginx", "soajs.service.mode": soajs.inputmaskData.deployConfig.replication.mode //replicated || global for swarm, deployment || daemonset for kubernetes }, "cmd": [ './soajsDeployer.sh', '-T', 'nginx', '-X', 'deploy' ], "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit, "containerDir": config.imagesDir, "replication": { "mode": soajs.inputmaskData.deployConfig.replication.mode }, "restartPolicy": { "condition": "any", //TODO: make dynamic "maxAttempts": 5 //TODO: make dynamic }, "network": config.network, "ports": [ //NOTE: an https port is automatically exposed with a random port //NOTE: only one http exposed port is permitted for now for nginx deployment { "name": "http", "isPublished": true, "target": 80, "published": ((soajs.inputmaskData.deployConfig.ports && soajs.inputmaskData.deployConfig.ports[0]) ? soajs.inputmaskData.deployConfig.ports[0].published : null) }, { "name": "https", "isPublished": true, "target": 443 } ] }; if(soajs.inputmaskData.deployConfig.replication.replicas) { nginxParams.replication.replicas = soajs.inputmaskData.deployConfig.replication.replicas; } if (soajs.inputmaskData.deployConfig.readinessProbe) { nginxParams.readinessProbe = { "initialDelaySeconds": soajs.inputmaskData.deployConfig.readinessProbe.initialDelaySeconds, "timeoutSeconds": soajs.inputmaskData.deployConfig.readinessProbe.timeoutSeconds, "periodSeconds": soajs.inputmaskData.deployConfig.readinessProbe.periodSeconds, "successThreshold": soajs.inputmaskData.deployConfig.readinessProbe.successThreshold, "failureThreshold": soajs.inputmaskData.deployConfig.readinessProbe.failureThreshold }; } if (soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.nginx && soajs.inputmaskData.contentConfig.nginx.supportSSL) { nginxParams.cmd.push('-s'); nginxParams.ssl = { "enabled": true } if(soajs.inputmaskData.contentConfig.nginx.kubeSecret){ nginxParams.variables.push("SOAJS_NX_CUSTOM_SSL=1"); nginxParams.variables.push("SOAJS_NX_SSL_CERTS_LOCATION=/etc/ssl"); nginxParams.ssl.secret = soajs.inputmaskData.contentConfig.nginx.kubeSecret } nginxParams.variables.push("SOAJS_NX_API_HTTPS=1"); nginxParams.variables.push("SOAJS_NX_API_HTTP_REDIRECT=1"); nginxParams.variables.push("SOAJS_NX_SITE_HTTPS=1"); nginxParams.variables.push("SOAJS_NX_SITE_HTTP_REDIRECT=1"); } if (context.ui) { nginxParams.variables.push("SOAJS_GIT_REPO=" + context.ui.src.repo); nginxParams.variables.push("SOAJS_GIT_OWNER=" + context.ui.src.owner); nginxParams.variables.push("SOAJS_GIT_BRANCH=" + soajs.inputmaskData.contentConfig.nginx.ui.branch); nginxParams.variables.push("SOAJS_GIT_COMMIT=" + soajs.inputmaskData.contentConfig.nginx.ui.commit); if (context.ui.token) { nginxParams.variables.push("SOAJS_GIT_TOKEN=" + context.ui.token); } } return nginxParams; } function createHAService(cb) { options.params = context.nginxParams; soajs.log.debug("Creating HA service with deployer: " + JSON.stringify(options.params)); deployer.deployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, cb); }); } function checkPort(cb){ //TODO: check if exposed port is set before proceeding in case of type === nginx var nginxInputPort = soajs.inputmaskData.deployConfig.ports[0].published; var deployType = context.envRecord.deployer.selected.split('.')[1]; if(deployType === "kubernetes" && (nginxInputPort < config.kubeNginx.minPort || nginxInputPort > config.kubeNginx.maxPort)){ var errMsg = config.errors[824]; errMsg = errMsg.replace("%PORTNUMBER%", nginxInputPort); errMsg = errMsg.replace("%MINNGINXPORT%", config.kubeNginx.minPort); errMsg = errMsg.replace("%MAXNGINXPORT%", config.kubeNginx.maxPort); return res.jsonp(soajs.buildResponse({"code": 824, "msg": errMsg})); } else{ if(deployType === "kubernetes") { soajs.inputmaskData.deployConfig.ports[0].published += 30000; } return cb(); } } getEnvInfo(function () { options = utils.buildDeployerOptions(context.envRecord, soajs, BL); checkPort(function() { getCustomUIConfig(function () { getControllerDomain(function () { context.nginxParams = constructDeployerParams(); createHAService(function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); }, /** * Redeploy a service (does not update config, only simulates a deployment restart) * * @param {Object} options * @param {Response Object} res */ "redeployService": function (config, soajs, res) { utils.getEnvironment(soajs, BL.model, soajs.inputmaskData.env, function (error, envRecord) { utils.checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 402}, function () { var options = utils.buildDeployerOptions(envRecord, soajs, BL); options.params = { id: soajs.inputmaskData.serviceId, mode: soajs.inputmaskData.mode //NOTE: only required for kubernetes driver }; if (soajs.inputmaskData.ssl && soajs.inputmaskData.ssl.supportSSL) { options.params.ssl = { "enabled": true }; if (soajs.inputmaskData.ssl.kubeSecret) { options.params.ssl.kubeSecret = soajs.inputmaskData.ssl.kubeSecret; } } getUIConfig(function (error, config) { //error is already catered for in function if (config.available) { options.params.ui = config.values; } deployer.redeployService(options, function (error) { utils.checkIfError(soajs, res, {config: config, error: error}, function () { return res.jsonp(soajs.buildResponse(null, true)); }); }); }); }); }); function getUIConfig (cb) { if (!soajs.inputmaskData.ui) { return cb(null, { available: false }); } BL.model.validateCustomId(soajs, soajs.inputmaskData.ui.id, function (error, id) { utils.checkIfError(soajs, res, {config: config, error: error, code: 701}, function () { var opts = { collection: colls.staticContent, condition: { _id: id } }; BL.model.findEntry(soajs, opts, function (error, record) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !record, code: 905}, function () { getGitRecord(soajs, record.src.owner + '/' + record.src.repo, function (error, gitRecord) { utils.checkIfError(soajs, res, {config: config, error: error, code: 600}, function () { utils.checkIfError(soajs, res, {config: config, error: !gitRecord, code: 757}, function () { var result = { available: true, values: { owner: record.src.owner, repo: record.src.repo, branch: soajs.inputmaskData.ui.branch, commit: soajs.inputmaskData.ui.commit, provider: gitRecord.provider, domain: gitRecord.domain } }; if (gitRecord.access === 'private' && gitRecord.token) { if (gitRecord.provider === 'bitbucket_enterprise') { gitRecord.token = new Buffer(gitRecord.token, 'base64').toString(); } result.values.token = gitRecord.token; } return cb(null, result); }); }); }); }); }); }); }); }); } } }; module.exports = { "init": function (modelName, cb) { var modelPath; if (!modelName) { return cb(new Error("No Model Requested!")); } modelPath = __dirname + "/../../models/" + modelName + ".js"; return requireModel(modelPath, cb); /** * checks if model file exists, requires it and returns it. * @param filePath * @param cb */ function requireModel(filePath, cb) { //check if file exist. if not return error fs.exists(filePath, function (exists) { if (!exists) { return cb(new Error("Requested Model Not Found!")); } BL.model = require(filePath); return cb(null, BL); }); } } };
Updated environment variable set for nginx deployment
lib/cloud/deploy.js
Updated environment variable set for nginx deployment
<ide><path>ib/cloud/deploy.js <ide> <ide> if(soajs.inputmaskData.contentConfig.nginx.kubeSecret){ <ide> nginxParams.variables.push("SOAJS_NX_CUSTOM_SSL=1"); <del> nginxParams.variables.push("SOAJS_NX_SSL_CERTS_LOCATION=/etc/ssl"); <add> nginxParams.variables.push("SOAJS_NX_SSL_CERTS_LOCATION=/etc/soajs/ssl"); <ide> <ide> nginxParams.ssl.secret = soajs.inputmaskData.contentConfig.nginx.kubeSecret <ide> }
Java
lgpl-2.1
91576fcfd30027e48068ebc063ab325e26523d35
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2005 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // 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 com.threerings.jme.sprite; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.samskivert.util.ObserverList; /** * Represents a visual entity that one controls as a single unit. Sprites * can be made to follow paths which is one of their primary reasons for * existence. */ public class Sprite extends Node { /** * Walks down the hierarchy provided setting the animation speed on * any controllers found along the way. */ public static void setAnimationSpeed (Spatial spatial, float speed) { for (int ii = 0; ii < spatial.getControllers().size(); ii++) { spatial.getController(ii).setSpeed(speed); } if (spatial instanceof Node) { Node node = (Node)spatial; for (int ii = 0; ii < node.getQuantity(); ii++) { setAnimationSpeed(node.getChild(ii), speed); } } } /** * Walks down the hierarchy provided turning on or off any controllers * found along the way. */ public static void setAnimationActive (Spatial spatial, boolean active) { for (int ii = 0; ii < spatial.getControllers().size(); ii++) { spatial.getController(ii).setActive(active); } if (spatial instanceof Node) { Node node = (Node)spatial; for (int ii = 0; ii < node.getQuantity(); ii++) { setAnimationActive(node.getChild(ii), active); } } } public Sprite () { super(""); setName("sprite:" + hashCode()); } /** * Adds an observer to this sprite. Observers are notified when path * related events take place. */ public void addObserver (SpriteObserver obs) { if (_observers == null) { _observers = new ObserverList(ObserverList.SAFE_IN_ORDER_NOTIFY); } _observers.add(obs); } /** * Removes the specified observer from this sprite. */ public void removeObserver (SpriteObserver obs) { if (_observers != null) { _observers.remove(obs); } } /** * Returns true if this sprite is moving along a path, false if not. */ public boolean isMoving () { return _path != null; } /** * Instructs this sprite to move along the specified path. Any * currently executing path will be cancelled. */ public void move (Path path) { // if there's a previous path, let it know that it's going away cancelMove(); // save off this path _path = path; addController(_path); } /** * Cancels any currently executing path. Any registered observers will * be notified of the cancellation. */ public void cancelMove () { if (_path != null) { Path oldpath = _path; _path = null; oldpath.wasRemoved(); if (_observers != null) { _observers.apply(new CancelledOp(this, oldpath)); } } } /** * Called by the active path when it has completed. <em>Note:</em> * don't call this method unless you are implementing a {@link Path}. */ public void pathCompleted () { Path oldpath = _path; _path = null; removeController(oldpath); oldpath.wasRemoved(); if (_observers != null) { _observers.apply(new CompletedOp(this, oldpath)); } } /** * Configures the speed of all controllers in our model hierarchy. */ public void setAnimationSpeed (float speed) { setAnimationSpeed(this, speed); } /** * Configures the speed of all controllers in our model hierarchy. */ public void setAnimationActive (boolean active) { setAnimationActive(this, active); } /** Used to dispatch {@link PathObserver#pathCancelled}. */ protected static class CancelledOp implements ObserverList.ObserverOp { public CancelledOp (Sprite sprite, Path path) { _sprite = sprite; _path = path; } public boolean apply (Object observer) { if (observer instanceof PathObserver) { ((PathObserver)observer).pathCancelled(_sprite, _path); } return true; } protected Sprite _sprite; protected Path _path; } /** Used to dispatch {@link PathObserver#pathCompleted}. */ protected static class CompletedOp implements ObserverList.ObserverOp { public CompletedOp (Sprite sprite, Path path) { _sprite = sprite; _path = path; } public boolean apply (Object observer) { if (observer instanceof PathObserver) { ((PathObserver)observer).pathCompleted(_sprite, _path); } return true; } protected Sprite _sprite; protected Path _path; } protected ObserverList _observers; protected Path _path; }
src/java/com/threerings/jme/sprite/Sprite.java
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2005 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // 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 com.threerings.jme.sprite; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.samskivert.util.ObserverList; /** * Represents a visual entity that one controls as a single unit. Sprites * can be made to follow paths which is one of their primary reasons for * existence. */ public class Sprite extends Node { /** * Walks down the hierarchy provided setting the animation speed on * any controllers found along the way. */ public static void setAnimationSpeed (Spatial spatial, float speed) { for (int ii = 0; ii < spatial.getControllers().size(); ii++) { spatial.getController(ii).setSpeed(speed); } if (spatial instanceof Node) { Node node = (Node)spatial; for (int ii = 0; ii < node.getQuantity(); ii++) { setAnimationSpeed(node.getChild(ii), speed); } } } /** * Walks down the hierarchy provided turning on or off any controllers * found along the way. */ public static void setAnimationActive (Spatial spatial, boolean active) { for (int ii = 0; ii < spatial.getControllers().size(); ii++) { spatial.getController(ii).setActive(active); } if (spatial instanceof Node) { Node node = (Node)spatial; for (int ii = 0; ii < node.getQuantity(); ii++) { setAnimationActive(node.getChild(ii), active); } } } public Sprite () { super(""); setName("sprite:" + hashCode()); } /** * Adds an observer to this sprite. Observers are notified when path * related events take place. */ public void addObserver (SpriteObserver obs) { if (_observers == null) { _observers = new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY); } _observers.add(obs); } /** * Removes the specified observer from this sprite. */ public void removeObserver (SpriteObserver obs) { if (_observers != null) { _observers.remove(obs); } } /** * Returns true if this sprite is moving along a path, false if not. */ public boolean isMoving () { return _path != null; } /** * Instructs this sprite to move along the specified path. Any * currently executing path will be cancelled. */ public void move (Path path) { // if there's a previous path, let it know that it's going away cancelMove(); // save off this path _path = path; addController(_path); } /** * Cancels any currently executing path. Any registered observers will * be notified of the cancellation. */ public void cancelMove () { if (_path != null) { Path oldpath = _path; _path = null; oldpath.wasRemoved(); if (_observers != null) { _observers.apply(new CancelledOp(this, oldpath)); } } } /** * Called by the active path when it has completed. <em>Note:</em> * don't call this method unless you are implementing a {@link Path}. */ public void pathCompleted () { Path oldpath = _path; _path = null; removeController(oldpath); oldpath.wasRemoved(); if (_observers != null) { _observers.apply(new CompletedOp(this, oldpath)); } } /** * Configures the speed of all controllers in our model hierarchy. */ public void setAnimationSpeed (float speed) { setAnimationSpeed(this, speed); } /** * Configures the speed of all controllers in our model hierarchy. */ public void setAnimationActive (boolean active) { setAnimationActive(this, active); } /** Used to dispatch {@link PathObserver#pathCancelled}. */ protected static class CancelledOp implements ObserverList.ObserverOp { public CancelledOp (Sprite sprite, Path path) { _sprite = sprite; _path = path; } public boolean apply (Object observer) { if (observer instanceof PathObserver) { ((PathObserver)observer).pathCancelled(_sprite, _path); } return true; } protected Sprite _sprite; protected Path _path; } /** Used to dispatch {@link PathObserver#pathCompleted}. */ protected static class CompletedOp implements ObserverList.ObserverOp { public CompletedOp (Sprite sprite, Path path) { _sprite = sprite; _path = path; } public boolean apply (Object observer) { if (observer instanceof PathObserver) { ((PathObserver)observer).pathCompleted(_sprite, _path); } return true; } protected Sprite _sprite; protected Path _path; } protected ObserverList _observers; protected Path _path; }
Life is a lot easier if our observers are notified in the order they are registered rather than in reverse. I'd like to make this change to media.AbstractMedia as well but no doubt zillions of things depend on the current notification ordering for that package. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@3691 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/jme/sprite/Sprite.java
Life is a lot easier if our observers are notified in the order they are registered rather than in reverse. I'd like to make this change to media.AbstractMedia as well but no doubt zillions of things depend on the current notification ordering for that package.
<ide><path>rc/java/com/threerings/jme/sprite/Sprite.java <ide> public void addObserver (SpriteObserver obs) <ide> { <ide> if (_observers == null) { <del> _observers = new ObserverList(ObserverList.FAST_UNSAFE_NOTIFY); <add> _observers = new ObserverList(ObserverList.SAFE_IN_ORDER_NOTIFY); <ide> } <ide> _observers.add(obs); <ide> }
JavaScript
mit
33f60fccd70fa51e808afd4f74026e4e57738e56
0
nadavspi/UnwiseConnect,nadavspi/UnwiseConnect,nadavspi/UnwiseConnect
import React from 'react'; import { fetchScheduleEntryById, fetchTicketScheduleEntryIds } from '../../../helpers/cw'; const ScheduleEntries = ({ ticketNumber }) => { const [entries, setEntries] = React.useState([]); const [isLoading, setIsLoading] = React.useState(false); const displayEntries = () => { setIsLoading(true); fetchTicketScheduleEntryIds(ticketNumber).then(results => { return Promise.all(results.map(result => { return fetchScheduleEntryById(result); })); }).then(entries => { setEntries(entries); setIsLoading(false); }); }; React.useEffect(() => { displayEntries(); }, []); const entryCard = entry => { let startDate = entry.dateStart; let endDate = entry.dateEnd; if (startDate) { const startDateObj = new Date(startDate); startDate = startDateObj.toLocaleDateString() + ' ' + startDateObj.toLocaleTimeString(); } if (endDate) { const endDateObj = new Date(endDate); endDate = endDateObj.toLocaleDateString() + ' ' + endDateObj.toLocaleTimeString(); } return( <React.Fragment> <td>{entry.member.name}</td> <td>{startDate}</td> <td>{endDate}</td> <td>{entry.hours}</td> <td>{(entry.doneFlag) ? <div className="glyphicon glyphicon-ok" aria-hidden="true" /> : ''}</td> </React.Fragment> ); }; return ( <div> <h4>Schedule Entries</h4> {isLoading && (<p style={{textAlign: 'center'}}>Loading &hellip;</p>)} <table className="table table-striped table-bordered"> <thead> <tr> <th>Member Name</th> <th>Start Date</th> <th>End Date</th> <th>Hours</th> <th>Done</th> </tr> </thead> <tbody> {entries.map(entry => <tr key={entry.id}> {entryCard(entry)} </tr> )} </tbody> </table> </div> ); }; export default ScheduleEntries;
src/components/Tickets/DetailsModal/ScheduleEntries.js
import React from 'react'; import { fetchScheduleEntryById, fetchTicketScheduleEntryIds } from '../../../helpers/cw'; const ScheduleEntries = ({ ticketNumber }) => { const [entries, setEntries] = React.useState([]); const [isLoading, setIsLoading] = React.useState(false); React.useEffect(() => { displayEntries(); }, []); const displayEntries = () => { setIsLoading(true); fetchTicketScheduleEntryIds(ticketNumber).then(results => { return Promise.all(results.map(result => { return fetchScheduleEntryById(result); })); }).then(entries => { setEntries(entries); setIsLoading(false); }); } const entryCard = entry => { let startDate = entry.dateStart; let endDate = entry.dateEnd; if (startDate) { const startDateObj = new Date(startDate); startDate = startDateObj.toLocaleDateString() + ' ' + startDateObj.toLocaleTimeString(); } if (endDate) { const endDateObj = new Date(endDate); endDate = endDateObj.toLocaleDateString() + ' ' + endDateObj.toLocaleTimeString(); } return( <React.Fragment> <td>{entry.member.name}</td> <td>{startDate}</td> <td>{endDate}</td> <td>{entry.hours}</td> <td>{(entry.doneFlag) ? <div className="glyphicon glyphicon-ok" aria-hidden="true" /> : ''}</td> </React.Fragment> ); } return ( <div> <h4>Schedule Entries</h4> {isLoading && (<p style={{textAlign: 'center'}}>Loading &hellip;</p>)} <table className="table table-striped table-bordered"> <thead> <tr> <th>Member Name</th> <th>Start Date</th> <th>End Date</th> <th>Hours</th> <th>Done</th> </tr> </thead> <tbody> {entries.map(entry => <tr key={entry.id}> {entryCard(entry)} </tr> )} </tbody> </table> </div> ); } export default ScheduleEntries;
Switch method calls, adds semicolons to prevent ASI Switches order of the useEffect hook and the method it calls. While both achieve the same result, this order looks better.
src/components/Tickets/DetailsModal/ScheduleEntries.js
Switch method calls, adds semicolons to prevent ASI
<ide><path>rc/components/Tickets/DetailsModal/ScheduleEntries.js <ide> <ide> const [entries, setEntries] = React.useState([]); <ide> const [isLoading, setIsLoading] = React.useState(false); <del> <del> React.useEffect(() => { <del> displayEntries(); <del> }, []); <ide> <ide> const displayEntries = () => { <ide> setIsLoading(true); <ide> setEntries(entries); <ide> setIsLoading(false); <ide> }); <del> } <add> }; <add> <add> React.useEffect(() => { <add> displayEntries(); <add> }, []); <ide> <ide> const entryCard = entry => { <ide> let startDate = entry.dateStart; <ide> <td>{(entry.doneFlag) ? <div className="glyphicon glyphicon-ok" aria-hidden="true" /> : ''}</td> <ide> </React.Fragment> <ide> ); <del> } <add> }; <ide> <ide> return ( <ide> <div> <ide> </table> <ide> </div> <ide> ); <del>} <add>}; <ide> <ide> export default ScheduleEntries;
Java
apache-2.0
f51b22d71656cc5fc9d841ed1864cbf62edce248
0
graceland/graceland-core,graceland/graceland-core,graceland/graceland-core,graceland/graceland-core
package io.graceland; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import org.junit.Before; import org.junit.Test; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import com.google.common.collect.ImmutableList; import io.dropwizard.Bundle; import io.dropwizard.cli.Command; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.Managed; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.servlets.tasks.Task; import io.dropwizard.setup.AdminEnvironment; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.graceland.application.Application; import io.graceland.application.SimpleApplication; import io.graceland.dropwizard.Configurator; import io.graceland.dropwizard.Initializer; import io.graceland.filter.FilterPattern; import io.graceland.plugin.AbstractPlugin; import io.graceland.plugin.Plugin; import io.graceland.testing.TestBundle; import io.graceland.testing.TestCommand; import io.graceland.testing.TestConfigurator; import io.graceland.testing.TestFilter; import io.graceland.testing.TestHealthCheck; import io.graceland.testing.TestInitializer; import io.graceland.testing.TestManaged; import io.graceland.testing.TestResource; import io.graceland.testing.TestTask; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PlatformTest { private PlatformConfiguration configuration = mock(PlatformConfiguration.class); private Bootstrap<PlatformConfiguration> bootstrap = mock(Bootstrap.class); private Environment environment = mock(Environment.class); private LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); private JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); private HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); private AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); private ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); @Before public void before() { when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); } protected Platform newPlatform(Application application) { return new Platform(application); } @Test(expected = NullPointerException.class) public void start_must_be_called_with_args() throws Exception { Application application = mock(Application.class); Platform platform = newPlatform(application); platform.start(null); } @Test public void can_build_with_application() { Application application = mock(Application.class); when(application.getPlugins()).thenReturn(ImmutableList.<Plugin>of()); Platform.forApplication(application); } @Test(expected = NullPointerException.class) public void cannot_build_with_null_application() { Platform.forApplication(null); } @Test(expected = NullPointerException.class) public void constructed_with_valid_application() { new Platform(null); } @Test public void start_with_no_args() throws Exception { Application application = mock(Application.class); when(application.getPlugins()).thenReturn(ImmutableList.<Plugin>of()); String[] args = new String[]{}; new Platform(application).start(args); } @Test public void run_adds_jersey_components() throws Exception { final Object jerseyComponent = new Object(); final Class<TestResource> jerseyComponentClass = TestResource.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindJerseyComponent(jerseyComponent); bindJerseyComponent(jerseyComponentClass); } } ); new Platform(application).run(configuration, environment); verify(jerseyEnvironment).register(eq(jerseyComponent)); verify(jerseyEnvironment).register(isA(TestResource.class)); } @Test public void run_adds_managed() throws Exception { final Managed managed = mock(Managed.class); final Class<TestManaged> managedClass = TestManaged.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindManaged(managed); bindManaged(managedClass); } } ); new Platform(application).run(configuration, environment); verify(lifecycleEnvironment).manage(eq(managed)); verify(lifecycleEnvironment).manage(isA(TestManaged.class)); } @Test public void run_adds_healthchecks() throws Exception { final HealthCheck healthCheck = mock(HealthCheck.class); final Class<TestHealthCheck> healthCheckClass = TestHealthCheck.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindHealthCheck(healthCheck); bindHealthCheck(healthCheckClass); } } ); new Platform(application).run(configuration, environment); verify(healthCheckRegistry).register(anyString(), eq(healthCheck)); verify(healthCheckRegistry).register(anyString(), isA(TestHealthCheck.class)); } @Test public void run_adds_tasks() throws Exception { final Task task = mock(Task.class); final Class<TestTask> taskClass = TestTask.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindTask(task); bindTask(taskClass); } } ); new Platform(application).run(configuration, environment); verify(adminEnvironment).addTask(eq(task)); verify(adminEnvironment).addTask(isA(TestTask.class)); } @Test public void run_adds_configurators() throws Exception { final Configurator configurator = mock(Configurator.class); final Class<TestConfigurator> configuratorClass = TestConfigurator.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindConfigurator(configurator); bindConfigurator(configuratorClass); } } ); new Platform(application).run(configuration, environment); verify(configurator).configure(configuration, environment); // TODO: Figure out how to check for the class generated configurator } @Test public void run_adds_filters() throws Exception { final String filterName = "my-filter-name"; final Filter filter = mock(Filter.class); final Class<TestFilter> filterClass = TestFilter.class; EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class); ImmutableList<String> urlPatterns = ImmutableList.of("/*", "/test"); final FilterPattern filterPattern = FilterPattern.newInstance(dispatcherTypes, true, urlPatterns); FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); when(servletEnvironment.addFilter(anyString(), any(TestFilter.class))).thenReturn(filterDynamic); Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { buildFilter(filter) .withName(filterName) .withPriority(999) .withPattern(filterPattern) .bind(); buildFilter(filterClass).withPriority(0).bind(); } } ); new Platform(application).run(configuration, environment); verify(servletEnvironment).addFilter(eq(filterClass.getSimpleName()), isA(filterClass)); verify(servletEnvironment).addFilter(eq(filterName), eq(filter)); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypes), eq(true), eq("/*")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypes), eq(true), eq("/test")); } @Test public void run_adds_filter_and_joins_FilterPatterns_correctly() throws Exception { final Filter filter = mock(Filter.class); final EnumSet<DispatcherType> dispatcherTypesA = EnumSet.allOf(DispatcherType.class); final EnumSet<DispatcherType> dispatcherTypesB = EnumSet.of(DispatcherType.ASYNC); FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); when(servletEnvironment.addFilter(anyString(), any(TestFilter.class))).thenReturn(filterDynamic); Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { buildFilter(filter) .withPattern(FilterPattern.newInstance(dispatcherTypesA, true, "/a", "/b")) .withPattern(FilterPattern.newInstance(dispatcherTypesA, true, "/c", "/d")) .withPattern(FilterPattern.newInstance(dispatcherTypesB, true, "/e", "/f")) .withPattern(FilterPattern.newInstance(dispatcherTypesB, false, "/g", "/h")) .bind(); } } ); new Platform(application).run(configuration, environment); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/a")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/b")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/c")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/d")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(true), eq("/e")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(true), eq("/f")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(false), eq("/g")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(false), eq("/h")); } @Test public void initialize_adds_bundles() { final Bundle bundle = mock(Bundle.class); final Class<TestBundle> bundleClass = TestBundle.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindBundle(bundle); bindBundle(bundleClass); } } ); new Platform(application).initialize(bootstrap); verify(bootstrap).addBundle(eq(bundle)); verify(bootstrap).addBundle(isA(TestBundle.class)); } @Test public void initialize_adds_commands() { final Command command = mock(Command.class); final Class<TestCommand> commandClass = TestCommand.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindCommand(command); bindCommand(commandClass); } } ); new Platform(application).initialize(bootstrap); verify(bootstrap).addCommand(eq(command)); verify(bootstrap).addCommand(isA(TestCommand.class)); } @Test public void initialize_adds_initializers() { final Initializer initializer = mock(Initializer.class); final Class<TestInitializer> initializerClass = TestInitializer.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindInitializer(initializer); bindInitializer(initializerClass); } } ); new Platform(application).initialize(bootstrap); // TODO: Add a verification for the class-generated Initializer verify(initializer).initialize(eq(bootstrap)); } private Application buildApplication(final Plugin plugin) { return new SimpleApplication() { @Override protected void configure() { loadPlugin(plugin); } }; } }
graceland-platform/src/test/java/io/graceland/PlatformTest.java
package io.graceland; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import org.junit.Before; import org.junit.Test; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.HealthCheckRegistry; import com.google.common.collect.ImmutableList; import io.dropwizard.Bundle; import io.dropwizard.cli.Command; import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.jetty.setup.ServletEnvironment; import io.dropwizard.lifecycle.Managed; import io.dropwizard.lifecycle.setup.LifecycleEnvironment; import io.dropwizard.servlets.tasks.Task; import io.dropwizard.setup.AdminEnvironment; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.graceland.application.Application; import io.graceland.application.SimpleApplication; import io.graceland.dropwizard.Configurator; import io.graceland.dropwizard.Initializer; import io.graceland.filter.FilterPattern; import io.graceland.plugin.AbstractPlugin; import io.graceland.plugin.Plugin; import io.graceland.testing.TestBundle; import io.graceland.testing.TestCommand; import io.graceland.testing.TestConfigurator; import io.graceland.testing.TestFilter; import io.graceland.testing.TestHealthCheck; import io.graceland.testing.TestInitializer; import io.graceland.testing.TestManaged; import io.graceland.testing.TestResource; import io.graceland.testing.TestTask; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PlatformTest { private PlatformConfiguration configuration = mock(PlatformConfiguration.class); private Bootstrap<PlatformConfiguration> bootstrap = mock(Bootstrap.class); private Environment environment = mock(Environment.class); private LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); private JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); private HealthCheckRegistry healthCheckRegistry = mock(HealthCheckRegistry.class); private AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); private ServletEnvironment servletEnvironment = mock(ServletEnvironment.class); @Before public void before() { when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthCheckRegistry); when(environment.admin()).thenReturn(adminEnvironment); when(environment.servlets()).thenReturn(servletEnvironment); } protected Platform newPlatform(Application application) { return new Platform(application); } @Test(expected = NullPointerException.class) public void start_must_be_called_with_args() throws Exception { Application application = mock(Application.class); Platform platform = newPlatform(application); platform.start(null); } @Test public void can_build_with_application() { Application application = mock(Application.class); when(application.getPlugins()).thenReturn(ImmutableList.<Plugin>of()); Platform.forApplication(application); } @Test(expected = NullPointerException.class) public void cannot_build_with_null_application() { Platform.forApplication(null); } @Test(expected = NullPointerException.class) public void constructed_with_valid_application() { new Platform(null); } @Test public void start_with_no_args() throws Exception { Application application = mock(Application.class); when(application.getPlugins()).thenReturn(ImmutableList.<Plugin>of()); String[] args = new String[]{}; new Platform(application).start(args); } @Test public void run_adds_jersey_components() throws Exception { final Object jerseyComponent = new Object(); final Class<TestResource> jerseyComponentClass = TestResource.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindJerseyComponent(jerseyComponent); bindJerseyComponent(jerseyComponentClass); } } ); new Platform(application).run(configuration, environment); verify(jerseyEnvironment).register(eq(jerseyComponent)); verify(jerseyEnvironment).register(isA(TestResource.class)); } @Test public void run_adds_managed() throws Exception { final Managed managed = mock(Managed.class); final Class<TestManaged> managedClass = TestManaged.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindManaged(managed); bindManaged(managedClass); } } ); new Platform(application).run(configuration, environment); verify(lifecycleEnvironment).manage(eq(managed)); verify(lifecycleEnvironment).manage(isA(TestManaged.class)); } @Test public void run_adds_healthchecks() throws Exception { final HealthCheck healthCheck = mock(HealthCheck.class); final Class<TestHealthCheck> healthCheckClass = TestHealthCheck.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindHealthCheck(healthCheck); bindHealthCheck(healthCheckClass); } } ); new Platform(application).run(configuration, environment); verify(healthCheckRegistry).register(anyString(), eq(healthCheck)); verify(healthCheckRegistry).register(anyString(), isA(TestHealthCheck.class)); } @Test public void run_adds_tasks() throws Exception { final Task task = mock(Task.class); final Class<TestTask> taskClass = TestTask.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindTask(task); bindTask(taskClass); } } ); new Platform(application).run(configuration, environment); verify(adminEnvironment).addTask(eq(task)); verify(adminEnvironment).addTask(isA(TestTask.class)); } @Test public void run_adds_configurators() throws Exception { final Configurator configurator = mock(Configurator.class); final Class<TestConfigurator> configuratorClass = TestConfigurator.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindConfigurator(configurator); bindConfigurator(configuratorClass); } } ); new Platform(application).run(configuration, environment); verify(configurator).configure(configuration, environment); // TODO: Figure out how to check for the class generated configurator } @Test public void run_adds_filters() throws Exception { final String filterName = "my-filter-name"; final Filter filter = mock(Filter.class); final Class<TestFilter> filterClass = TestFilter.class; final TestFilter patternedFilter = new TestFilter(); EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class); ImmutableList<String> urlPatterns = ImmutableList.of("/*", "/test"); final FilterPattern filterPattern = FilterPattern.newInstance(dispatcherTypes, true, urlPatterns); FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); when(servletEnvironment.addFilter(anyString(), any(TestFilter.class))).thenReturn(filterDynamic); Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { buildFilter(filter) .withName(filterName) .withPriority(999) .withPattern(filterPattern) .bind(); buildFilter(filterClass).withPriority(0).bind(); } } ); new Platform(application).run(configuration, environment); verify(servletEnvironment).addFilter(eq(filterClass.getSimpleName()), isA(filterClass)); verify(servletEnvironment).addFilter(eq(filterName), eq(filter)); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypes), eq(true), eq("/*")); verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypes), eq(true), eq("/test")); } @Test public void initialize_adds_bundles() { final Bundle bundle = mock(Bundle.class); final Class<TestBundle> bundleClass = TestBundle.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindBundle(bundle); bindBundle(bundleClass); } } ); new Platform(application).initialize(bootstrap); verify(bootstrap).addBundle(eq(bundle)); verify(bootstrap).addBundle(isA(TestBundle.class)); } @Test public void initialize_adds_commands() { final Command command = mock(Command.class); final Class<TestCommand> commandClass = TestCommand.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindCommand(command); bindCommand(commandClass); } } ); new Platform(application).initialize(bootstrap); verify(bootstrap).addCommand(eq(command)); verify(bootstrap).addCommand(isA(TestCommand.class)); } @Test public void initialize_adds_initializers() { final Initializer initializer = mock(Initializer.class); final Class<TestInitializer> initializerClass = TestInitializer.class; Application application = buildApplication( new AbstractPlugin() { @Override protected void configure() { bindInitializer(initializer); bindInitializer(initializerClass); } } ); new Platform(application).initialize(bootstrap); // TODO: Add a verification for the class-generated Initializer verify(initializer).initialize(eq(bootstrap)); } private Application buildApplication(final Plugin plugin) { return new SimpleApplication() { @Override protected void configure() { loadPlugin(plugin); } }; } }
added a complex test for binding a filter with many patterns.
graceland-platform/src/test/java/io/graceland/PlatformTest.java
added a complex test for binding a filter with many patterns.
<ide><path>raceland-platform/src/test/java/io/graceland/PlatformTest.java <ide> final String filterName = "my-filter-name"; <ide> final Filter filter = mock(Filter.class); <ide> final Class<TestFilter> filterClass = TestFilter.class; <del> final TestFilter patternedFilter = new TestFilter(); <ide> <ide> EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class); <ide> ImmutableList<String> urlPatterns = ImmutableList.of("/*", "/test"); <ide> <ide> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypes), eq(true), eq("/*")); <ide> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypes), eq(true), eq("/test")); <add> } <add> <add> @Test <add> public void run_adds_filter_and_joins_FilterPatterns_correctly() throws Exception { <add> final Filter filter = mock(Filter.class); <add> final EnumSet<DispatcherType> dispatcherTypesA = EnumSet.allOf(DispatcherType.class); <add> final EnumSet<DispatcherType> dispatcherTypesB = EnumSet.of(DispatcherType.ASYNC); <add> <add> FilterRegistration.Dynamic filterDynamic = mock(FilterRegistration.Dynamic.class); <add> when(servletEnvironment.addFilter(anyString(), any(TestFilter.class))).thenReturn(filterDynamic); <add> <add> Application application = buildApplication( <add> new AbstractPlugin() { <add> @Override <add> protected void configure() { <add> buildFilter(filter) <add> .withPattern(FilterPattern.newInstance(dispatcherTypesA, true, "/a", "/b")) <add> .withPattern(FilterPattern.newInstance(dispatcherTypesA, true, "/c", "/d")) <add> .withPattern(FilterPattern.newInstance(dispatcherTypesB, true, "/e", "/f")) <add> .withPattern(FilterPattern.newInstance(dispatcherTypesB, false, "/g", "/h")) <add> .bind(); <add> } <add> } <add> ); <add> <add> new Platform(application).run(configuration, environment); <add> <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/a")); <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/b")); <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/c")); <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesA), eq(true), eq("/d")); <add> <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(true), eq("/e")); <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(true), eq("/f")); <add> <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(false), eq("/g")); <add> verify(filterDynamic).addMappingForUrlPatterns(eq(dispatcherTypesB), eq(false), eq("/h")); <ide> } <ide> <ide> @Test
Java
apache-2.0
053d1a949d9e5ebca7347c4089ffe3d77cbabc7a
0
jagguli/intellij-community,petteyg/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,kool79/intellij-community,fnouama/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,signed/intellij-community,ibinti/intellij-community,joewalnes/idea-community,hurricup/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ernestp/consulo,alphafoobar/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,semonte/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,signed/intellij-community,da1z/intellij-community,ryano144/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,izonder/intellij-community,semonte/intellij-community,kool79/intellij-community,apixandru/intellij-community,jagguli/intellij-community,petteyg/intellij-community,clumsy/intellij-community,caot/intellij-community,ernestp/consulo,blademainer/intellij-community,supersven/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,petteyg/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,semonte/intellij-community,retomerz/intellij-community,FHannes/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,da1z/intellij-community,holmes/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,supersven/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,izonder/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,slisson/intellij-community,izonder/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,clumsy/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,holmes/intellij-community,tmpgit/intellij-community,supersven/intellij-community,izonder/intellij-community,consulo/consulo,holmes/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,adedayo/intellij-community,diorcety/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,izonder/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,adedayo/intellij-community,allotria/intellij-community,samthor/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,samthor/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,kdwink/intellij-community,asedunov/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,slisson/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,consulo/consulo,robovm/robovm-studio,salguarnieri/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,diorcety/intellij-community,dslomov/intellij-community,FHannes/intellij-community,allotria/intellij-community,ahb0327/intellij-community,supersven/intellij-community,robovm/robovm-studio,blademainer/intellij-community,caot/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,ryano144/intellij-community,apixandru/intellij-community,izonder/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ernestp/consulo,nicolargo/intellij-community,clumsy/intellij-community,signed/intellij-community,dslomov/intellij-community,caot/intellij-community,kool79/intellij-community,blademainer/intellij-community,ernestp/consulo,orekyuu/intellij-community,semonte/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,kdwink/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,izonder/intellij-community,consulo/consulo,allotria/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,consulo/consulo,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,apixandru/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,signed/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,semonte/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,asedunov/intellij-community,allotria/intellij-community,ibinti/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,jagguli/intellij-community,FHannes/intellij-community,samthor/intellij-community,samthor/intellij-community,akosyakov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,retomerz/intellij-community,ibinti/intellij-community,hurricup/intellij-community,semonte/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,signed/intellij-community,slisson/intellij-community,adedayo/intellij-community,adedayo/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,asedunov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,supersven/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,allotria/intellij-community,dslomov/intellij-community,asedunov/intellij-community,asedunov/intellij-community,robovm/robovm-studio,hurricup/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,ryano144/intellij-community,hurricup/intellij-community,samthor/intellij-community,kool79/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,jagguli/intellij-community,Lekanich/intellij-community,kool79/intellij-community,FHannes/intellij-community,da1z/intellij-community,vladmm/intellij-community,hurricup/intellij-community,allotria/intellij-community,samthor/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,joewalnes/idea-community,dslomov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,fnouama/intellij-community,adedayo/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,holmes/intellij-community,apixandru/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,caot/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,fitermay/intellij-community,samthor/intellij-community,apixandru/intellij-community,ibinti/intellij-community,xfournet/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,dslomov/intellij-community,signed/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,kdwink/intellij-community,signed/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,retomerz/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,caot/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,allotria/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,petteyg/intellij-community,retomerz/intellij-community,petteyg/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,petteyg/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,blademainer/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,ibinti/intellij-community,supersven/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,consulo/consulo,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,da1z/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,retomerz/intellij-community,slisson/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,caot/intellij-community,vladmm/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,semonte/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,signed/intellij-community,joewalnes/idea-community,dslomov/intellij-community,fnouama/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,xfournet/intellij-community,samthor/intellij-community,kool79/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,allotria/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,fnouama/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,da1z/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,asedunov/intellij-community,allotria/intellij-community,FHannes/intellij-community,slisson/intellij-community,FHannes/intellij-community,slisson/intellij-community,ryano144/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,caot/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ernestp/consulo,suncycheng/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ryano144/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,consulo/consulo,Distrotech/intellij-community,hurricup/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,izonder/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,semonte/intellij-community,retomerz/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ernestp/consulo,adedayo/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.tasks; import com.intellij.execution.BeforeRunTaskProvider; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.concurrency.Semaphore; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.execution.MavenRunner; import org.jetbrains.idea.maven.execution.MavenRunnerParameters; import org.jetbrains.idea.maven.navigator.SelectMavenGoalDialog; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenLog; import java.util.Collections; public class MavenBeforeRunTasksProvider extends BeforeRunTaskProvider<MavenBeforeRunTask> { public static final Key<MavenBeforeRunTask> TASK_ID = Key.create("Maven.BeforeRunTask"); private final Project myProject; public MavenBeforeRunTasksProvider(Project project) { myProject = project; } public Key<MavenBeforeRunTask> getId() { return TASK_ID; } public String getDescription(RunConfiguration runConfiguration, MavenBeforeRunTask task) { String desc = null; if (task.isEnabled()) { Pair<MavenProject, String> projectAndGoal = getProjectAndGoalChecked(task); if (projectAndGoal != null) desc = projectAndGoal.first.getDisplayName() + ":" + projectAndGoal.second; } return desc == null ? TasksBundle.message("maven.tasks.before.run.empty") : TasksBundle.message("maven.tasks.before.run", desc); } private Pair<MavenProject, String> getProjectAndGoalChecked(MavenBeforeRunTask task) { String path = task.getProjectPath(); String goal = task.getGoal(); if (path == null || goal == null) return null; VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); if (file == null) return null; MavenProject project = MavenProjectsManager.getInstance(myProject).findProject(file); if (project == null) return null; return Pair.create(project, goal); } public boolean hasConfigurationButton() { return true; } public MavenBeforeRunTask createTask(RunConfiguration runConfiguration) { return new MavenBeforeRunTask(); } public boolean configureTask(RunConfiguration runConfiguration, MavenBeforeRunTask task) { SelectMavenGoalDialog dialog = new SelectMavenGoalDialog(myProject, task.getProjectPath(), task.getGoal(), TasksBundle.message("maven.tasks.select.goal.title")); dialog.show(); if (!dialog.isOK()) return false; task.setProjectPath(dialog.getSelectedProjectPath()); task.setGoal(dialog.getSelectedGoal()); return true; } public boolean executeTask(final DataContext context, RunConfiguration configuration, final MavenBeforeRunTask task) { final Semaphore targetDone = new Semaphore(); final boolean[] result = new boolean[1]; try { ApplicationManager.getApplication().invokeAndWait(new Runnable() { public void run() { final Project project = PlatformDataKeys.PROJECT.getData(context); final Pair<MavenProject, String> projectAndGoal = getProjectAndGoalChecked(task); if (project == null || project.isDisposed() || projectAndGoal == null) return; FileDocumentManager.getInstance().saveAllDocuments(); targetDone.down(); new Task.Backgroundable(project, TasksBundle.message("maven.tasks.executing"), true) { public void run(@NotNull ProgressIndicator indicator) { try { MavenRunnerParameters params = new MavenRunnerParameters( true, projectAndGoal.first.getDirectory(), Collections.singletonList(projectAndGoal.second), MavenProjectsManager.getInstance(project).getExplicitProfiles()); result[0] = MavenRunner.getInstance(project).runBatch(Collections.singletonList(params), null, null, TasksBundle.message("maven.tasks.executing"), indicator); } finally { targetDone.up(); } } @Override public boolean shouldStartInBackground() { return MavenRunner.getInstance(project).getSettings().isRunMavenInBackground(); } @Override public void processSentToBackground() { MavenRunner.getInstance(project).getSettings().setRunMavenInBackground(true); } }.queue(); } }, ModalityState.NON_MODAL); } catch (Exception e) { MavenLog.LOG.error(e); return false; } targetDone.waitFor(); return result[0]; } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.tasks; import com.intellij.execution.BeforeRunTaskProvider; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.concurrency.Semaphore; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.execution.MavenRunner; import org.jetbrains.idea.maven.execution.MavenRunnerParameters; import org.jetbrains.idea.maven.navigator.SelectMavenGoalDialog; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.utils.MavenLog; import java.util.Collections; public class MavenBeforeRunTasksProvider extends BeforeRunTaskProvider<MavenBeforeRunTask> { public static final Key<MavenBeforeRunTask> TASK_ID = Key.create("Maven.BeforeRunTask"); private final Project myProject; public MavenBeforeRunTasksProvider(Project project) { myProject = project; } public Key<MavenBeforeRunTask> getId() { return TASK_ID; } public String getDescription(RunConfiguration runConfiguration, MavenBeforeRunTask task) { String desc = null; if (task.isEnabled()) { Pair<MavenProject, String> projectAndGoal = getProjectAndGoalChecked(task); if (projectAndGoal != null) desc = projectAndGoal.first.getDisplayName() + ":" + projectAndGoal.second; } return desc == null ? TasksBundle.message("maven.tasks.before.run.empty") : TasksBundle.message("maven.tasks.before.run", desc); } private Pair<MavenProject, String> getProjectAndGoalChecked(MavenBeforeRunTask task) { String path = task.getProjectPath(); String goal = task.getGoal(); if (path == null || goal == null) return null; VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); if (file == null) return null; MavenProject project = MavenProjectsManager.getInstance(myProject).findProject(file); if (project == null) return null; return Pair.create(project, goal); } public boolean hasConfigurationButton() { return true; } public MavenBeforeRunTask createTask(RunConfiguration runConfiguration) { return new MavenBeforeRunTask(); } public boolean configureTask(RunConfiguration runConfiguration, MavenBeforeRunTask task) { SelectMavenGoalDialog dialog = new SelectMavenGoalDialog(myProject, task.getProjectPath(), task.getGoal(), TasksBundle.message("maven.tasks.select.goal.title")); dialog.show(); if (!dialog.isOK()) return false; task.setProjectPath(dialog.getSelectedProjectPath()); task.setGoal(dialog.getSelectedGoal()); return true; } public boolean executeTask(final DataContext context, RunConfiguration configuration, final MavenBeforeRunTask task) { final Semaphore targetDone = new Semaphore(); final boolean[] result = new boolean[1]; try { ApplicationManager.getApplication().invokeAndWait(new Runnable() { public void run() { final Project project = PlatformDataKeys.PROJECT.getData(context); final Pair<MavenProject, String> projectAndGoal = getProjectAndGoalChecked(task); if (project == null || project.isDisposed() || projectAndGoal == null) return; targetDone.down(); new Task.Backgroundable(project, TasksBundle.message("maven.tasks.executing"), true) { public void run(@NotNull ProgressIndicator indicator) { try { MavenRunnerParameters params = new MavenRunnerParameters( true, projectAndGoal.first.getDirectory(), Collections.singletonList(projectAndGoal.second), MavenProjectsManager.getInstance(project).getExplicitProfiles()); result[0] = MavenRunner.getInstance(project).runBatch(Collections.singletonList(params), null, null, TasksBundle.message("maven.tasks.executing"), indicator); } finally { targetDone.up(); } } @Override public boolean shouldStartInBackground() { return MavenRunner.getInstance(project).getSettings().isRunMavenInBackground(); } @Override public void processSentToBackground() { MavenRunner.getInstance(project).getSettings().setRunMavenInBackground(true); } }.queue(); } }, ModalityState.NON_MODAL); } catch (Exception e) { MavenLog.LOG.error(e); return false; } targetDone.waitFor(); return result[0]; } }
maven: saving documents prior to 'before run' tasks
plugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java
maven: saving documents prior to 'before run' tasks
<ide><path>lugins/maven/src/main/java/org/jetbrains/idea/maven/tasks/MavenBeforeRunTasksProvider.java <ide> import com.intellij.openapi.actionSystem.PlatformDataKeys; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.application.ModalityState; <add>import com.intellij.openapi.fileEditor.FileDocumentManager; <ide> import com.intellij.openapi.progress.ProgressIndicator; <ide> import com.intellij.openapi.progress.Task; <ide> import com.intellij.openapi.project.Project; <ide> <ide> if (project == null || project.isDisposed() || projectAndGoal == null) return; <ide> <add> FileDocumentManager.getInstance().saveAllDocuments(); <add> <ide> targetDone.down(); <ide> new Task.Backgroundable(project, TasksBundle.message("maven.tasks.executing"), true) { <ide> public void run(@NotNull ProgressIndicator indicator) {
JavaScript
mit
e74519ea60cf5e4934c7347815344e9e4b5cd626
0
mmig/mmir-lib
/* * Copyright (C) 2012-2013 DFKI GmbH * Deutsches Forschungszentrum fuer Kuenstliche Intelligenz * German Research Center for Artificial Intelligence * http://www.dfki.de * * 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. */ define(['mmirf/constants', 'mmirf/configurationManager', 'mmirf/commonUtils', 'mmirf/semanticInterpreter', 'mmirf/util/deferred', 'mmirf/util/loadFile', 'mmirf/logger', 'module'], /** * A class for managing the language of the application. <br> * It's purpose is to load the controllers and their views / partials and provide functions to find controllers or * perform actions or helper-actions. * * This "class" is structured as a singleton - so that only one instance is in use.<br> * * @name LanguageManager * @memberOf mmir * @class * * * @requires mmir.Constants * @requires mmir.CommonUtils * @requires mmir.SemanticInterpreter * */ function( constants, configurationManager, commonUtils, semanticInterpreter, deferred, loadFile, Logger, module ){ //the next comment enables JSDoc2 to map all functions etc. to the correct class description /** @scope mmir.LanguageManager.prototype */ /** * Object containing the instance of the class * {@link LanguageManager} * * @type Object * @private * * @memberOf LanguageManager# */ var instance = null; /** * @private * @type Logger * @memberOf LanguageManager# */ var logger = Logger.create(module); /** * @private * @type LanguageManagerModuleConfig * @memberOf LanguageManager# */ var _conf = module.config(module); /** * JSON object containing the contents of a dictionary file - which are * found in 'config/languages/&lt;language&gt;/dictionary.json'. * * @type JSON * @private * * @memberOf LanguageManager# */ var dictionary = null; /** * A String holding the currently loaded language, e.g. "en". * * @type String * @private * * @memberOf LanguageManager# */ var currentLanguage = null; /** * A JSON-Object holding the speech-configuration for the currently loaded language. * * @type JSON-Object * @private * * @memberOf LanguageManager# */ var currentSpeechConfig = null; /** * An array of all available languages. * * @type Array * @private * * @memberOf LanguageManager# */ var languages = null; /** * A keyword which can be used in views (ehtml) to display the current * language.<br> * If this keyword is used inside a view or partial, it is replaced by the * current language string. * * @type String * @private * @example @localize('current_language') * * @memberOf LanguageManager# */ var keyword_current_language = 'current_language'; /** * Function to set a new language, but only, if the new language is * different from the current language. * * @function * @param {String} * lang The language of the dictionary which should be loaded. * @returns {String} The (new) current language * @private * * @memberOf LanguageManager# */ function setLanguage(lang) { if ((lang) && (currentLanguage != lang)) { loadDictionary(lang); loadSpeechConfig(lang); requestGrammar(lang); } return currentLanguage; } /** * @function * @private * @param {String} lang * Language String, i.e.: en, de * @param {"source"|"bin"} [grammarType] OPTIONAL * only check grammar specifications ("source", i.e. JSON grammar), * or executable grammar ("bin", i.e. compiled grammar) existence * @returns {Boolean|"source"|"bin"} TRUE if a grammar exists for given language * (and if grammarType was given, when the * existing grammar matches the grammar type) * @memberOf LanguageManager# */ function doCheckExistsGrammar(lang, grammarType) { var langFiles = null; var retValue = false; if (lang) { //check for existence of JSON grammar if(!grammarType || grammarType === 'source'){ langFiles = commonUtils.listDir(constants.getLanguagePath() + lang); if (langFiles) { if (langFiles.indexOf(constants.getGrammarFileUrl()) > -1) { retValue = true; } } } //check for existence of compiled grammar if(!langFiles || !retValue && (!grammarType || grammarType === 'bin')){ langFiles = commonUtils.listDir(constants.getGeneratedGrammarsPath().replace(/\/$/, '')); if(langFiles){ var re = new RegExp( typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD? '^mmirf/grammar/'+lang+'.js$' : '^'+lang+'_'+constants.getGrammarFileUrl().replace(/\.json/i, '.js')+'$', 'i' ); for(var i=langFiles.length - 1; i >= 0; --i){ if(re.test(langFiles[i])){ retValue = true; break; } } } } } return retValue; } /** * Request grammar for the provided language. * * If there is no grammar available for the requested language, no new * grammar is set. * * A grammar is available, if at least one of the following is true for the * requested language * <ul> * <li>there exists a JSON grammar file (with correct name and at the * correct location)</li> * <li>there exists a compiled JavaScript grammar file (with correct name * and at the correct location)</li> * </ul> * * TODO document location for JSON and JavaScript grammar files * * @function * @param {String} * lang The language of the grammar which should be loaded. * @returns {String} The current grammar language * @async * @private * * @memberOf LanguageManager# */ function requestGrammar(lang, doSetNextBestAlternative) { if (semanticInterpreter.hasGrammar(lang) || doCheckExistsGrammar(lang)) { semanticInterpreter.setCurrentGrammar(lang); return lang; } else if (doSetNextBestAlternative) { // try to find a language, for which a grammar is available var grammarLang = null; if (languages.length > 0) { // first: try to find a language with COMPILED grammar for ( var i = 0, size = languages.length; i < size; ++i) { grammarLang = languages[i]; if (semanticInterpreter.hasGrammar(grammarLang)) { break; } else { grammarLang = null; } } // ... otherwise: try to find a language with JSON grammar: if (!grammarLang) { for ( var i = 0, size = languages.length; i < size; ++i) { grammarLang = languages[i]; if (doCheckExistsGrammar(grammarLang)) { break; } else { grammarLang = null; } } } } if (grammarLang) { logger.warn('Could not find grammar for selected language ' + lang + ', using grammar for language ' + grammarLang + ' instead.'); semanticInterpreter.setCurrentGrammar(grammarLang); } else { logger.info('Could not find any grammar for one of [' + languages.join(', ') + '], disabling SemanticInterpret.'); semanticInterpreter.setEnabled(false); } } return semanticInterpreter.getCurrentGrammar(); } /** * * @param {"dictionary" | "speechConfig" | "grammar"} type the type of the resource * @param {String} lang the language code / ID * @return {String} the resource ID for loading */ function getResourceUri(type, lang){ if(typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD){ // webpack ID: 'mmirf/settings/(dictionary|speechConfig|grammar)/<lang>' var id = 'mmirf/settings/'+type.replace(/Config$/, '')+'/'+lang; if(__webpack_modules__[id]){ return __webpack_require__(id); } } var funcName = 'get' + type[0].toUpperCase() + type.substring(1) + 'FileUrl'; return constants[funcName](lang); } /** * Loads the speech-configuration for the provided language and updates the current * language. * * @function * @param {String} lang * The language of the speech-configuration which should be loaded. * @returns {String} The (new) current language * @async * @private * * @memberOf LanguageManager# */ function loadSpeechConfig(lang) { if (lang && currentLanguage != lang) { currentLanguage = lang; } if(_conf && _conf.speech && _conf.speech[lang]){ if(logger.isVerbose()) logger.verbose("loadSpeechConfig(): loaded configuration from module.config().speech["+lang+"] -> ", _conf.speech[lang]); currentSpeechConfig = _conf.speech[lang]; return;/////////// EARLY EXIT /////////////// } var path = getResourceUri('speechConfig', lang); loadFile({ async : false, dataType : "json", url : path, success : function(data) { if(logger.isVerbose()) logger.v("loadSpeechConfig("+lang+"): success -> ", data); currentSpeechConfig = data; }, error : function(xhr, statusStr, error) { logger.error("loadSpeechConfig("+lang+"): Error loading speech configuration from \""+path+"\": " + error? error.stack? error.stack : error : ''); // error } }); return currentLanguage; } /** * Loads the dictionary for the provided language and updates the current * language. * * @function * @param {String} * lang The language of the dictionary which should be loaded. * @returns {String} The (new) current language * @async * @private * * @memberOf LanguageManager# */ function loadDictionary(lang) { if (lang && currentLanguage != lang) { currentLanguage = lang; } if(_conf && _conf.dictionary && _conf.dictionary[lang]){ if(logger.isVerbose()) logger.verbose("loadDictionary(): loaded configuration from module.config().dictionary["+lang+"] -> ", _conf.dictionary[lang]); dictionary = _conf.dictionary[lang]; return;/////////// EARLY EXIT /////////////// } var path = getResourceUri('dictionary', lang); loadFile({ async : false, dataType : "json", url : path, success : function(data) { if(logger.isVerbose()) logger.v("loadDictionary("+lang+"): success -> ", data); dictionary = data; }, error : function(xhr, statusStr, error) { logger.error("loadDictionary("+lang+"): Error loading language dictionary from \""+path+"\": " + error? error.stack? error.stack : error : ''); // error } }); return currentLanguage; } /** * Translates a keyword using the current dictionary and returns the * translation. * * @function * @param {String} * textVarName The keyword which should be looked up * @returns {String} the translation of the keyword * @private * * @memberOf LanguageManager# */ function internalGetText(textVarName) { var translated = ""; if (dictionary[textVarName] && dictionary[textVarName].length > 0) { translated = dictionary[textVarName]; } else if (textVarName === keyword_current_language){ translated = currentLanguage; } else { translated = "undefined"; logger.warn("[Dictionary] '" + textVarName + "' not found in " + JSON.stringify(dictionary)); } return translated; } /** * Constructor-Method of Singleton mmir.LanguageManager.<br> * * @constructs LanguageManager * @memberOf LanguageManager# * @private * @ignore * */ function constructor() { var _isInitialized = false; /** @lends mmir.LanguageManager.prototype */ return { /** * @param {String} [lang] OPTIONAL * a language code for setting the current language and * selecting the corresponding language resources * * @returns {Promise} * a deferred promise that gets resolved when the language manager is initialized * * @memberOf mmir.LanguageManager.prototype */ init: function(lang){ if (!lang && !currentLanguage) { //try to retrieve language from configuration: var appLang = configurationManager.get("language"); if (appLang) { lang = appLang; logger.info("init(): No language argument specified: using language from configuration '" + appLang + "'."); } else { appLang = constants.getLanguage(); if (appLang) { lang = appLang; logger.info("init(): No language argument specified: using language from mmir.constants '" + appLang + "'."); } else { if (languages.length > 0) { appLang = this.determineLanguage(lang); if(appLang){ lang = appLang; logger.info("init() No language argument specified: used determinLanguage() for selecting language '" + appLang + "'."); } } }//END: else(consts::lang) }//END: else(config::lang) if(!lang){ logger.warn("init(): No language specified. And no language could be read from directory '" + constants.getLanguagePath() + "'."); } }//END: if(!lang && !currentLanguage) // get all the languages/dictionaries by name languages = commonUtils.listDir(constants.getLanguagePath()) || []; if (logger.isDebug()) logger.debug("init() Found dictionaries for: " + JSON.stringify(languages)); var defer = deferred(); if(this.existsDictionary(lang)){ loadDictionary(lang); } else if(logger.isDebug()){ logger.debug("init(): no dictionary for language " + lang); } if(this.existsSpeechConfig(lang)){ loadSpeechConfig(lang); } else if(logger.isDebug()){//TODO set/generate default speech-config? logger.debug("init(): no speech-config (asr/tts) for language " + lang); } requestGrammar(lang, true);//2nd argument TRUE: if no grammar is available for lang, try to find/set any available grammar _isInitialized = true; defer.resolve(this); return defer; }, /** * Returns the dictionary of the currently used language. * * @function * @returns {Object} The JSON object for the dictionary of the * currently used language * @public * * @memberOf mmir.LanguageManager.prototype */ getDictionary : function() { return dictionary; }, /** * If a dictionary exists for the given language, 'true' is * returned. Else the method returns 'false'. * * @function * @returns {Boolean} True if a dictionary exists for given * language. * @param {String} * Language String, i.e.: en, de * @public * * @memberOf mmir.LanguageManager.prototype */ existsDictionary : function(lang) { var langFiles = null; var retValue = false; if (lang != null) { langFiles = commonUtils.listDir(constants.getLanguagePath() + lang); if (langFiles != null) { if (langFiles.indexOf(constants.getDictionaryFileUrl()) > -1) { retValue = true; } } } return retValue; }, /** * If a speech-configuration (file) exists for the given language. * * @function * @returns {Boolean} * <code>true</code>if a speech-configuration exists for given language. * Otherwise <code>false</code>. * * @param {String} lang * the language for which existence of the configuration should be checked, e.g. en, de * * @public * * @memberOf mmir.LanguageManager.prototype */ existsSpeechConfig : function(lang) { var langFiles = null; var retValue = false; if (lang != null) { langFiles = commonUtils.listDir(constants.getLanguagePath() + lang); if (langFiles != null) { if (langFiles.indexOf(constants.getSpeechConfigFileUrl()) > -1) { retValue = true; } } } return retValue; }, /** * If a JSON grammar file exists for the given language, 'true' is * returned. Else the method returns 'false'. * * @function * @param {String} lang * Language String, i.e.: en, de * @param {"source"|"bin"} [grammarType] OPTIONAL * only check grammar specifications ("source", i.e. JSON grammar), * or executable grammar ("bin", i.e. compiled grammar) existence * @returns {Boolean|"source"|"bin"} TRUE if a grammar exists for given language * (and if grammarType was given, when the * existing grammar matches the grammar type) * @public * * @memberOf mmir.LanguageManager.prototype */ existsGrammar : doCheckExistsGrammar, /** * Chooses a language for the application. * * <p> * The language selection is done as follows: * <ol> * <li>check if a default language exists<br> * if it does and if both (!) grammar and dictionary exist for this * language, return this language </li> * <li>walk through all languages alphabetically * <ol> * <li>if for a language both (!) grammar and dictionary exist, * return this language memorize the first language with a grammar * (do not care, if a dictionary exists) </li> * </ol> * <li>test if a grammar exists for the default language - do not * care about dictionaries - if it does, return the default language * </li> * <li>If a language was found (in Step 2.1) return this language * </li> * <li>If still no language is returned take the default language * if it has a dictionary </li> * <li>If a language exists, take it (the first one) </li> * <li>Take the default language - no matter what </li> * </ol> * * @function * @returns {String} The determined language * @public * * @memberOf mmir.LanguageManager.prototype */ determineLanguage : function(lang) { var tempLanguage = lang; var firstLanguageWithGrammar = null; // first check, if language - given in parameter - exists if (tempLanguage != null) { // check if both grammar and dictionary exist for given // language if (instance.existsGrammar(tempLanguage) && instance.existsDictionary(tempLanguage)) { return tempLanguage; } } tempLanguage = constants.getLanguage(); // then check, if default language exists if (tempLanguage != null) { // check if both grammar and dictionary exist for default // language if (instance.existsGrammar(tempLanguage) && instance.existsDictionary(tempLanguage)) { return tempLanguage; } } // walk through the languages alphabetically for ( var i = 0; i < languages.length; i++) { tempLanguage = languages[i]; // check if a grammar and dictionary exists for every // language if (instance.existsGrammar(tempLanguage)) { // memorize the first language with a grammar (for // later) if (firstLanguageWithGrammar == null) { firstLanguageWithGrammar = tempLanguage; } if (instance.existsDictionary(tempLanguage)) { return tempLanguage; } } } // still no language found - take the default language and test // if a grammar exists tempLanguage = constants.getLanguage(); if (tempLanguage != null) { // check if both grammar and dictionary exist for default // language if (instance.existsGrammar(tempLanguage)) { return tempLanguage; } else if (firstLanguageWithGrammar != null) { return firstLanguageWithGrammar; } else if (instance.existsDictionary(tempLanguage)) { return tempLanguage; } } // still no language - take the first one tempLanguage = languages[0]; if (tempLanguage != null) { return tempLanguage; } return constants.getLanguage(); }, /** * Sets a new language, but only, if the new language is different * from the current language. * * @function * @returns {String} The (new) current language * @public * * @memberOf mmir.LanguageManager.prototype */ setLanguage : function(lang) { return setLanguage(lang); }, /** * Gets the language currently used for the translation. * * @function * @returns {String} The current language * @public * * @memberOf mmir.LanguageManager.prototype */ getLanguage : function() { return currentLanguage; }, /** * Gets the default language. * * @function * @returns {String} The default language * @public * * @memberOf mmir.LanguageManager.prototype */ getDefaultLanguage : function() { return constants.getLanguage(); }, /** * Gets an array of all for the translation available languages.<br> * * @function * @returns {String} An array of all for the translation available * languages * @public * * @memberOf mmir.LanguageManager.prototype */ getLanguages : function() { return languages; }, /** * Looks up a keyword in the current dictionary and returns the * translation. * * @function * @param {String} * textVarName The keyword which is to be translated * @returns {String} The translation of the keyword * @public * * @memberOf mmir.LanguageManager.prototype */ getText : function(textVarName) { return internalGetText(textVarName); }, /** * Get the language code setting for a specific plugin. * * Returns the default setting, if no specific setting for the specified plugin was defined. * * @public * @param {String} pluginId * @param {String|Array<String>} [feature] OPTIONAL * dot-separate path String or "path Array" * This parameter may be omitted, if no <code>separator</code> parameter * is used. * DEFAULT: "language" (the language feature) * @param {String} [separator] OPTIONAL * the speparator-string that should be used for separating * the country-part and the language-part of the code * @returns {String} the language-setting/-code * * @memberOf mmir.LanguageManager.prototype */ getLanguageConfig : function(pluginId, feature, separator) { if(!currentSpeechConfig){ logger.warn('no speech configuration ('+constants.getSpeechConfigFileUrl()+') available for '+currentLanguage); if(!feature || feature === 'language'){ return currentLanguage; } return void(0); } //if nothing is specfied: // return default language-setting if(typeof pluginId === 'undefined'){ return currentSpeechConfig.language; /////////// EARLY EXIT /////////////// } //ASSERT pluginId is defined //default feature is language if(typeof feature === 'undefined'){ feature = 'language'; } var value; if(currentSpeechConfig.plugins && currentSpeechConfig.plugins[pluginId] && typeof currentSpeechConfig.plugins[pluginId][feature] !== 'undefined'){ //if there is a plugin-specific setting for this feature value = currentSpeechConfig.plugins[pluginId][feature]; } else if(feature !== 'plugins' && typeof currentSpeechConfig[feature] !== 'undefined'){ //otherwise take the default setting (NOTE: the name "plugins" is not allowed for features!) value = currentSpeechConfig[feature]; } //if there is a separator specified: replace default separator '-' with this one if(value && typeof separator !== 'undefined'){ value = value.replace(/-/, separator); } return value; }, /** * HELPER for dealing with specific language / country code quirks of speech services: * Get the language code for a specific ASR or TTS service, that is if the service requires some * specific codes/transformations, then the transformed code is retruned by this function * (otherwise the unchanged langCode is returned). * * @public * @param {String} providerName * corrections for: "nuance" | "mary" * @param {String} langCode * the original language / country code * @returns {String} the (possibly "fixed") language-setting/-code * * @memberOf mmir.LanguageManager.prototype */ fixLang : function(providerName, langCode) { if(providerName === 'nuance'){ //QUIRK nuanceasr short-language code for the UK is UK instead of GB: // replace en-GB with en-UK if necessary (preserving separator char) langCode = langCode.replace(/en(.)GB/i, 'en$1UK'); } else if(providerName === 'mary'){ //QUIRK marytts does not accept language+country code for German: // must only be language code if(/de.DE/i.test(langCode)){ langCode = 'de'; } } return langCode; } };//END: return{} }//END: construcor = function(){... //FIXME as of now, the LanguageManager needs to be initialized, // by calling init() // -> should this be done explicitly (async-loading for dictionary and grammar? with returned Deferred?) instance = new constructor(); return instance; });
manager/settings/languageManager.js
/* * Copyright (C) 2012-2013 DFKI GmbH * Deutsches Forschungszentrum fuer Kuenstliche Intelligenz * German Research Center for Artificial Intelligence * http://www.dfki.de * * 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. */ define(['mmirf/constants', 'mmirf/configurationManager', 'mmirf/commonUtils', 'mmirf/semanticInterpreter', 'mmirf/util/deferred', 'mmirf/util/loadFile', 'mmirf/logger', 'module'], /** * A class for managing the language of the application. <br> * It's purpose is to load the controllers and their views / partials and provide functions to find controllers or * perform actions or helper-actions. * * This "class" is structured as a singleton - so that only one instance is in use.<br> * * @name LanguageManager * @memberOf mmir * @class * * * @requires mmir.Constants * @requires mmir.CommonUtils * @requires mmir.SemanticInterpreter * */ function( constants, configurationManager, commonUtils, semanticInterpreter, deferred, loadFile, Logger, module ){ //the next comment enables JSDoc2 to map all functions etc. to the correct class description /** @scope mmir.LanguageManager.prototype */ /** * Object containing the instance of the class * {@link LanguageManager} * * @type Object * @private * * @memberOf LanguageManager# */ var instance = null; /** * @private * @type Logger * @memberOf LanguageManager# */ var logger = Logger.create(module); /** * @private * @type LanguageManagerModuleConfig * @memberOf LanguageManager# */ var _conf = module.config(module); /** * JSON object containing the contents of a dictionary file - which are * found in 'config/languages/&lt;language&gt;/dictionary.json'. * * @type JSON * @private * * @memberOf LanguageManager# */ var dictionary = null; /** * A String holding the currently loaded language, e.g. "en". * * @type String * @private * * @memberOf LanguageManager# */ var currentLanguage = null; /** * A JSON-Object holding the speech-configuration for the currently loaded language. * * @type JSON-Object * @private * * @memberOf LanguageManager# */ var currentSpeechConfig = null; /** * An array of all available languages. * * @type Array * @private * * @memberOf LanguageManager# */ var languages = null; /** * A keyword which can be used in views (ehtml) to display the current * language.<br> * If this keyword is used inside a view or partial, it is replaced by the * current language string. * * @type String * @private * @example @localize('current_language') * * @memberOf LanguageManager# */ var keyword_current_language = 'current_language'; /** * Function to set a new language, but only, if the new language is * different from the current language. * * @function * @param {String} * lang The language of the dictionary which should be loaded. * @returns {String} The (new) current language * @private * * @memberOf LanguageManager# */ function setLanguage(lang) { if ((lang) && (currentLanguage != lang)) { loadDictionary(lang); loadSpeechConfig(lang); requestGrammar(lang); } return currentLanguage; } /** * @function * @private * @param {String} lang * Language String, i.e.: en, de * @param {"source"|"bin"} [grammarType] OPTIONAL * only check grammar specifications ("source", i.e. JSON grammar), * or executable grammar ("bin", i.e. compiled grammar) existence * @returns {Boolean|"source"|"bin"} TRUE if a grammar exists for given language * (and if grammarType was given, when the * existing grammar matches the grammar type) * @memberOf LanguageManager# */ function doCheckExistsGrammar(lang, grammarType) { var langFiles = null; var retValue = false; if (lang) { //check for existence of JSON grammar if(!grammarType || grammarType === 'source'){ langFiles = commonUtils.listDir(constants.getLanguagePath() + lang); if (langFiles) { if (langFiles.indexOf(constants.getGrammarFileUrl()) > -1) { retValue = true; } } } //check for existence of compiled grammar if(!langFiles || !retValue && (!grammarType || grammarType === 'bin')){ langFiles = commonUtils.listDir(constants.getGeneratedGrammarsPath().replace(/\/$/, '')); if(langFiles){ var re = new RegExp( typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD? '^mmirf/grammar/'+lang+'.js$' : '^'+lang+'_'+constants.getGrammarFileUrl().replace(/\.json/i, '.js')+'$', 'i' ); for(var i=langFiles.length - 1; i >= 0; --i){ if(re.test(langFiles[i])){ retValue = true; break; } } } } } return retValue; } /** * Request grammar for the provided language. * * If there is no grammar available for the requested language, no new * grammar is set. * * A grammar is available, if at least one of the following is true for the * requested language * <ul> * <li>there exists a JSON grammar file (with correct name and at the * correct location)</li> * <li>there exists a compiled JavaScript grammar file (with correct name * and at the correct location)</li> * </ul> * * TODO document location for JSON and JavaScript grammar files * * @function * @param {String} * lang The language of the grammar which should be loaded. * @returns {String} The current grammar language * @async * @private * * @memberOf LanguageManager# */ function requestGrammar(lang, doSetNextBestAlternative) { if (semanticInterpreter.hasGrammar(lang) || doCheckExistsGrammar(lang)) { semanticInterpreter.setCurrentGrammar(lang); return lang; } else if (doSetNextBestAlternative) { // try to find a language, for which a grammar is available var grammarLang = null; if (languages.length > 0) { // first: try to find a language with COMPILED grammar for ( var i = 0, size = languages.length; i < size; ++i) { grammarLang = languages[i]; if (semanticInterpreter.hasGrammar(grammarLang)) { break; } else { grammarLang = null; } } // ... otherwise: try to find a language with JSON grammar: if (!grammarLang) { for ( var i = 0, size = languages.length; i < size; ++i) { grammarLang = languages[i]; if (doCheckExistsGrammar(grammarLang)) { break; } else { grammarLang = null; } } } } if (grammarLang) { logger.warn('Could not find grammar for selected language ' + lang + ', using grammar for language ' + grammarLang + ' instead.'); semanticInterpreter.setCurrentGrammar(grammarLang); } else { logger.info('Could not find any grammar for one of [' + languages.join(', ') + '], disabling SemanticInterpret.'); semanticInterpreter.setEnabled(false); } } return semanticInterpreter.getCurrentGrammar(); } /** * * @param {"dictionary" | "speechConfig" | "grammar"} type the type of the resource * @param {String} lang the language code / ID * @return {String} the resource ID for loading */ function getResourceUri(type, lang){ if(typeof WEBPACK_BUILD !== 'undefined' && WEBPACK_BUILD){ // webpack ID: 'mmirf/settings/(dictionary|speechConfig|grammar)/<lang>' var id = 'mmirf/settings/'+type.replace(/Config$/, '')+'/'+lang; if(__webpack_modules__[id]){ return __webpack_require__(id); } } var funcName = 'get' + type[0].toUpperCase() + type.substring(1) + 'FileUrl'; return constants[funcName](lang); } /** * Loads the speech-configuration for the provided language and updates the current * language. * * @function * @param {String} lang * The language of the speech-configuration which should be loaded. * @returns {String} The (new) current language * @async * @private * * @memberOf LanguageManager# */ function loadSpeechConfig(lang) { if (lang && currentLanguage != lang) { currentLanguage = lang; } if(_conf && _conf.speech && _conf.speech[lang]){ if(logger.isVerbose()) logger.verbose("loadSpeechConfig(): loaded configuration from module.config().speech["+lang+"] -> ", _conf.speech[lang]); currentSpeechConfig = _conf.speech[lang]; return;/////////// EARLY EXIT /////////////// } var path = getResourceUri('speechConfig', lang); loadFile({ async : false, dataType : "json", url : path, success : function(data) { if(logger.isVerbose()) logger.v("loadSpeechConfig("+lang+"): success -> ", data); currentSpeechConfig = data; }, error : function(xhr, statusStr, error) { logger.error("loadSpeechConfig("+lang+"): Error loading speech configuration from \""+path+"\": " + error? error.stack? error.stack : error : ''); // error } }); return currentLanguage; } /** * Loads the dictionary for the provided language and updates the current * language. * * @function * @param {String} * lang The language of the dictionary which should be loaded. * @returns {String} The (new) current language * @async * @private * * @memberOf LanguageManager# */ function loadDictionary(lang) { if (lang && currentLanguage != lang) { currentLanguage = lang; } if(_conf && _conf.dictionary && _conf.dictionary[lang]){ if(logger.isVerbose()) logger.verbose("loadDictionary(): loaded configuration from module.config().dictionary["+lang+"] -> ", _conf.dictionary[lang]); dictionary = _conf.dictionary[lang]; return;/////////// EARLY EXIT /////////////// } var path = getResourceUri('dictionary', lang); loadFile({ async : false, dataType : "json", url : path, success : function(data) { if(logger.isVerbose()) logger.v("loadDictionary("+lang+"): success -> ", data); dictionary = data; }, error : function(xhr, statusStr, error) { logger.error("loadDictionary("+lang+"): Error loading language dictionary from \""+path+"\": " + error? error.stack? error.stack : error : ''); // error } }); return currentLanguage; } /** * Translates a keyword using the current dictionary and returns the * translation. * * @function * @param {String} * textVarName The keyword which should be looked up * @returns {String} the translation of the keyword * @private * * @memberOf LanguageManager# */ function internalGetText(textVarName) { var translated = ""; if (dictionary[textVarName] && dictionary[textVarName].length > 0) { translated = dictionary[textVarName]; } else if (textVarName === keyword_current_language){ translated = currentLanguage; } else { translated = "undefined"; logger.warn("[Dictionary] '" + textVarName + "' not found in " + JSON.stringify(dictionary)); } return translated; } /** * Constructor-Method of Singleton mmir.LanguageManager.<br> * * @constructs LanguageManager * @memberOf LanguageManager# * @private * @ignore * */ function constructor() { var _isInitialized = false; /** @lends mmir.LanguageManager.prototype */ return { /** * @param {String} [lang] OPTIONAL * a language code for setting the current language and * selecting the corresponding language resources * * @returns {Promise} * a deferred promise that gets resolved when the language manager is initialized * * @memberOf mmir.LanguageManager.prototype */ init: function(lang){ if (!lang && !currentLanguage) { //try to retrieve language from configuration: var appLang = configurationManager.get("language"); if (appLang) { lang = appLang; logger.info("init(): No language argument specified: using language from configuration '" + appLang + "'."); } else { appLang = constants.getLanguage(); if (appLang) { lang = appLang; logger.info("init(): No language argument specified: using language from mmir.constants '" + appLang + "'."); } else { if (languages.length > 0) { appLang = this.determineLanguage(lang); if(appLang){ lang = appLang; logger.info("init() No language argument specified: used determinLanguage() for selecting language '" + appLang + "'."); } } }//END: else(consts::lang) }//END: else(config::lang) if(!lang){ logger.warn("init(): No language specified. And no language could be read from directory '" + constants.getLanguagePath() + "'."); } }//END: if(!lang && !currentLanguage) // get all the languages/dictionaries by name languages = commonUtils.listDir(constants.getLanguagePath()); if (logger.isDebug()) logger.debug("init() Found dictionaries for: " + JSON.stringify(languages)); var defer = deferred(); if(this.existsDictionary(lang)){ loadDictionary(lang); } else if(logger.isDebug()){ logger.debug("init(): no dictionary for language " + lang); } if(this.existsSpeechConfig(lang)){ loadSpeechConfig(lang); } else if(logger.isDebug()){//TODO set/generate default speech-config? logger.debug("init(): no speech-config (asr/tts) for language " + lang); } requestGrammar(lang, true);//2nd argument TRUE: if no grammar is available for lang, try to find/set any available grammar _isInitialized = true; defer.resolve(this); return defer; }, /** * Returns the dictionary of the currently used language. * * @function * @returns {Object} The JSON object for the dictionary of the * currently used language * @public * * @memberOf mmir.LanguageManager.prototype */ getDictionary : function() { return dictionary; }, /** * If a dictionary exists for the given language, 'true' is * returned. Else the method returns 'false'. * * @function * @returns {Boolean} True if a dictionary exists for given * language. * @param {String} * Language String, i.e.: en, de * @public * * @memberOf mmir.LanguageManager.prototype */ existsDictionary : function(lang) { var langFiles = null; var retValue = false; if (lang != null) { langFiles = commonUtils.listDir(constants.getLanguagePath() + lang); if (langFiles != null) { if (langFiles.indexOf(constants.getDictionaryFileUrl()) > -1) { retValue = true; } } } return retValue; }, /** * If a speech-configuration (file) exists for the given language. * * @function * @returns {Boolean} * <code>true</code>if a speech-configuration exists for given language. * Otherwise <code>false</code>. * * @param {String} lang * the language for which existence of the configuration should be checked, e.g. en, de * * @public * * @memberOf mmir.LanguageManager.prototype */ existsSpeechConfig : function(lang) { var langFiles = null; var retValue = false; if (lang != null) { langFiles = commonUtils.listDir(constants.getLanguagePath() + lang); if (langFiles != null) { if (langFiles.indexOf(constants.getSpeechConfigFileUrl()) > -1) { retValue = true; } } } return retValue; }, /** * If a JSON grammar file exists for the given language, 'true' is * returned. Else the method returns 'false'. * * @function * @param {String} lang * Language String, i.e.: en, de * @param {"source"|"bin"} [grammarType] OPTIONAL * only check grammar specifications ("source", i.e. JSON grammar), * or executable grammar ("bin", i.e. compiled grammar) existence * @returns {Boolean|"source"|"bin"} TRUE if a grammar exists for given language * (and if grammarType was given, when the * existing grammar matches the grammar type) * @public * * @memberOf mmir.LanguageManager.prototype */ existsGrammar : doCheckExistsGrammar, /** * Chooses a language for the application. * * <p> * The language selection is done as follows: * <ol> * <li>check if a default language exists<br> * if it does and if both (!) grammar and dictionary exist for this * language, return this language </li> * <li>walk through all languages alphabetically * <ol> * <li>if for a language both (!) grammar and dictionary exist, * return this language memorize the first language with a grammar * (do not care, if a dictionary exists) </li> * </ol> * <li>test if a grammar exists for the default language - do not * care about dictionaries - if it does, return the default language * </li> * <li>If a language was found (in Step 2.1) return this language * </li> * <li>If still no language is returned take the default language * if it has a dictionary </li> * <li>If a language exists, take it (the first one) </li> * <li>Take the default language - no matter what </li> * </ol> * * @function * @returns {String} The determined language * @public * * @memberOf mmir.LanguageManager.prototype */ determineLanguage : function(lang) { var tempLanguage = lang; var firstLanguageWithGrammar = null; // first check, if language - given in parameter - exists if (tempLanguage != null) { // check if both grammar and dictionary exist for given // language if (instance.existsGrammar(tempLanguage) && instance.existsDictionary(tempLanguage)) { return tempLanguage; } } tempLanguage = constants.getLanguage(); // then check, if default language exists if (tempLanguage != null) { // check if both grammar and dictionary exist for default // language if (instance.existsGrammar(tempLanguage) && instance.existsDictionary(tempLanguage)) { return tempLanguage; } } // walk through the languages alphabetically for ( var i = 0; i < languages.length; i++) { tempLanguage = languages[i]; // check if a grammar and dictionary exists for every // language if (instance.existsGrammar(tempLanguage)) { // memorize the first language with a grammar (for // later) if (firstLanguageWithGrammar == null) { firstLanguageWithGrammar = tempLanguage; } if (instance.existsDictionary(tempLanguage)) { return tempLanguage; } } } // still no language found - take the default language and test // if a grammar exists tempLanguage = constants.getLanguage(); if (tempLanguage != null) { // check if both grammar and dictionary exist for default // language if (instance.existsGrammar(tempLanguage)) { return tempLanguage; } else if (firstLanguageWithGrammar != null) { return firstLanguageWithGrammar; } else if (instance.existsDictionary(tempLanguage)) { return tempLanguage; } } // still no language - take the first one tempLanguage = languages[0]; if (tempLanguage != null) { return tempLanguage; } return constants.getLanguage(); }, /** * Sets a new language, but only, if the new language is different * from the current language. * * @function * @returns {String} The (new) current language * @public * * @memberOf mmir.LanguageManager.prototype */ setLanguage : function(lang) { return setLanguage(lang); }, /** * Gets the language currently used for the translation. * * @function * @returns {String} The current language * @public * * @memberOf mmir.LanguageManager.prototype */ getLanguage : function() { return currentLanguage; }, /** * Gets the default language. * * @function * @returns {String} The default language * @public * * @memberOf mmir.LanguageManager.prototype */ getDefaultLanguage : function() { return constants.getLanguage(); }, /** * Gets an array of all for the translation available languages.<br> * * @function * @returns {String} An array of all for the translation available * languages * @public * * @memberOf mmir.LanguageManager.prototype */ getLanguages : function() { return languages; }, /** * Looks up a keyword in the current dictionary and returns the * translation. * * @function * @param {String} * textVarName The keyword which is to be translated * @returns {String} The translation of the keyword * @public * * @memberOf mmir.LanguageManager.prototype */ getText : function(textVarName) { return internalGetText(textVarName); }, /** * Get the language code setting for a specific plugin. * * Returns the default setting, if no specific setting for the specified plugin was defined. * * @public * @param {String} pluginId * @param {String|Array<String>} [feature] OPTIONAL * dot-separate path String or "path Array" * This parameter may be omitted, if no <code>separator</code> parameter * is used. * DEFAULT: "language" (the language feature) * @param {String} [separator] OPTIONAL * the speparator-string that should be used for separating * the country-part and the language-part of the code * @returns {String} the language-setting/-code * * @memberOf mmir.LanguageManager.prototype */ getLanguageConfig : function(pluginId, feature, separator) { if(!currentSpeechConfig){ logger.warn('no speech configuration ('+constants.getSpeechConfigFileUrl()+') available for '+currentLanguage); if(!feature || feature === 'language'){ return currentLanguage; } return void(0); } //if nothing is specfied: // return default language-setting if(typeof pluginId === 'undefined'){ return currentSpeechConfig.language; /////////// EARLY EXIT /////////////// } //ASSERT pluginId is defined //default feature is language if(typeof feature === 'undefined'){ feature = 'language'; } var value; if(currentSpeechConfig.plugins && currentSpeechConfig.plugins[pluginId] && typeof currentSpeechConfig.plugins[pluginId][feature] !== 'undefined'){ //if there is a plugin-specific setting for this feature value = currentSpeechConfig.plugins[pluginId][feature]; } else if(feature !== 'plugins' && typeof currentSpeechConfig[feature] !== 'undefined'){ //otherwise take the default setting (NOTE: the name "plugins" is not allowed for features!) value = currentSpeechConfig[feature]; } //if there is a separator specified: replace default separator '-' with this one if(value && typeof separator !== 'undefined'){ value = value.replace(/-/, separator); } return value; }, /** * HELPER for dealing with specific language / country code quirks of speech services: * Get the language code for a specific ASR or TTS service, that is if the service requires some * specific codes/transformations, then the transformed code is retruned by this function * (otherwise the unchanged langCode is returned). * * @public * @param {String} providerName * corrections for: "nuance" | "mary" * @param {String} langCode * the original language / country code * @returns {String} the (possibly "fixed") language-setting/-code * * @memberOf mmir.LanguageManager.prototype */ fixLang : function(providerName, langCode) { if(providerName === 'nuance'){ //QUIRK nuanceasr short-language code for the UK is UK instead of GB: // replace en-GB with en-UK if necessary (preserving separator char) langCode = langCode.replace(/en(.)GB/i, 'en$1UK'); } else if(providerName === 'mary'){ //QUIRK marytts does not accept language+country code for German: // must only be language code if(/de.DE/i.test(langCode)){ langCode = 'de'; } } return langCode; } };//END: return{} }//END: construcor = function(){... //FIXME as of now, the LanguageManager needs to be initialized, // by calling init() // -> should this be done explicitly (async-loading for dictionary and grammar? with returned Deferred?) instance = new constructor(); return instance; });
FIX handle missing languages-directory setting graceful
manager/settings/languageManager.js
FIX handle missing languages-directory setting graceful
<ide><path>anager/settings/languageManager.js <ide> <ide> <ide> // get all the languages/dictionaries by name <del> languages = commonUtils.listDir(constants.getLanguagePath()); <add> languages = commonUtils.listDir(constants.getLanguagePath()) || []; <ide> <ide> if (logger.isDebug()) logger.debug("init() Found dictionaries for: " + JSON.stringify(languages)); <ide>
Java
apache-2.0
75efdf6587585a54218bad56a1f4effe606ab526
0
alex-charos/ttlfc
src/test/java/com/spectral/ttlfc/test/controller/TestDev.java
package com.spectral.ttlfc.test.controller; import com.spectral.ttlfc.model.Player; public class TestDev { public static void change(Player p) { p.setEmail("changed"); p = new Player(); } public static void main(String[] args) { Player p = new Player(); p.setEmail("main"); change(p); System.out.println(p.getEmail()); } }
removing pointless file
src/test/java/com/spectral/ttlfc/test/controller/TestDev.java
removing pointless file
<ide><path>rc/test/java/com/spectral/ttlfc/test/controller/TestDev.java <del>package com.spectral.ttlfc.test.controller; <del> <del>import com.spectral.ttlfc.model.Player; <del> <del>public class TestDev { <del> <del> public static void change(Player p) { <del> <del> p.setEmail("changed"); <del> p = new Player(); <del> <del> } <del> public static void main(String[] args) { <del> Player p = new Player(); <del> p.setEmail("main"); <del> change(p); <del> System.out.println(p.getEmail()); <del> <del> } <del>}
Java
epl-1.0
eef95cc159bf95197ee3b696764cb0b37f85f814
0
sbrannen/junit-lambda,junit-team/junit-lambda
/* * Copyright 2015-2017 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.commons.util; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedMethods; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; import static org.junit.platform.commons.util.AnnotationUtils.findPublicAnnotatedFields; import static org.junit.platform.commons.util.AnnotationUtils.findRepeatableAnnotations; import static org.junit.platform.commons.util.AnnotationUtils.getDefaultValue; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP; import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.TOP_DOWN; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; /** * Unit tests for {@link AnnotationUtils}. * * @since 1.0 */ class AnnotationUtilsTests { @Test void getDefaultValueForNullAnnotation() { assertThrows(PreconditionViolationException.class, () -> getDefaultValue(null, "foo", String.class)); } @Test void getDefaultValueForNullAttributeName() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, null, String.class)); } @Test void getDefaultValueForNullAttributeType() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, "foo", null)); } @Test void getDefaultValueForNonMatchingAttributeType() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, "value", Integer.class)); assertThat(exception.getMessage()).contains("Attribute 'value' in annotation", AnnotationWithDefaultValue.class.getName(), "is of type java.lang.String, not java.lang.Integer"); } @Test void getDefaultValueForEmptyAttributeName() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, " \t ", String.class)); } @Test void getDefaultValueForAttributeWithDefault() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; Optional<String> defaultValue = getDefaultValue(annotation, "value", String.class); assertThat(defaultValue).contains("default"); } @Test void findAnnotationForNullOptional() { assertThat(findAnnotation((Optional<AnnotatedElement>) null, Annotation1.class)).isEmpty(); } @Test void findAnnotationForEmptyOptional() { assertThat(findAnnotation(Optional.empty(), Annotation1.class)).isEmpty(); } @Test void findAnnotationForNullAnnotatedElement() { assertThat(findAnnotation((AnnotatedElement) null, Annotation1.class)).isEmpty(); } @Test void findAnnotationOnClassWithoutAnnotation() { assertThat(findAnnotation(Annotation1Class.class, Annotation2.class)).isNotPresent(); } @Test void findAnnotationIndirectlyPresentOnOptionalClass() { Optional<Class<?>> optional = Optional.of(SubInheritedAnnotationClass.class); assertThat(findAnnotation(optional, InheritedAnnotation.class)).isPresent(); } @Test void findAnnotationIndirectlyPresentOnClass() { assertThat(findAnnotation(SubInheritedAnnotationClass.class, InheritedAnnotation.class)).isPresent(); } @Test void findAnnotationDirectlyPresentOnClass() { assertThat(findAnnotation(Annotation1Class.class, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnClass() { assertThat(findAnnotation(ComposedAnnotationClass.class, Annotation1.class)).isPresent(); } /** * <b>Note:</b> there is no findAnnotationIndirectlyMetaPresentOnMethod counterpart because {@link Inherited} * annotation has no effect if the annotated type is used to annotate anything other than a class. * * @see Inherited */ @Test void findAnnotationIndirectlyMetaPresentOnClass() { assertThat(findAnnotation(InheritedComposedAnnotationSubClass.class, Annotation1.class)).isPresent(); } @Test void findAnnotationDirectlyPresentOnImplementedInterface() { assertThat(findAnnotation(TestingTraitClass.class, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnImplementedInterface() { assertThat(findAnnotation(ComposedTestingTraitClass.class, Annotation1.class)).isPresent(); } @Test void findAnnotationDirectlyPresentOnMethod() throws Exception { Method method = Annotation2Class.class.getDeclaredMethod("method"); assertThat(findAnnotation(method, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnMethod() throws Exception { Method method = ComposedAnnotationClass.class.getDeclaredMethod("method"); assertThat(findAnnotation(method, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnOptionalMethod() throws Exception { Method method = ComposedAnnotationClass.class.getDeclaredMethod("method"); assertThat(findAnnotation(Optional.of(method), Annotation1.class)).isPresent(); } @Test void isAnnotatedForClassWithoutAnnotation() { assertFalse(isAnnotated(Annotation1Class.class, Annotation2.class)); } @Test void isAnnotatedWhenIndirectlyPresentOnClass() { assertTrue(isAnnotated(SubInheritedAnnotationClass.class, InheritedAnnotation.class)); } @Test void isAnnotatedWhenDirectlyPresentOnClass() { assertTrue(isAnnotated(Annotation1Class.class, Annotation1.class)); } @Test void isAnnotatedWhenMetaPresentOnClass() { assertTrue(isAnnotated(ComposedAnnotationClass.class, Annotation1.class)); } @Test void isAnnotatedWhenDirectlyPresentOnMethod() throws Exception { assertTrue(isAnnotated(Annotation2Class.class.getDeclaredMethod("method"), Annotation1.class)); } @Test void isAnnotatedWhenMetaPresentOnMethod() throws Exception { assertTrue(isAnnotated(ComposedAnnotationClass.class.getDeclaredMethod("method"), Annotation1.class)); } @Test void findRepeatableAnnotationsForNullAnnotatedElement() { assertThat(findRepeatableAnnotations(null, Tag.class)).isEmpty(); } @Test void findRepeatableAnnotationsWithSingleTag() throws Exception { assertTagsFound(SingleTaggedClass.class, "a"); } @Test void findRepeatableAnnotationsWithSingleComposedTag() throws Exception { assertTagsFound(SingleComposedTaggedClass.class, "fast"); } @Test void findRepeatableAnnotationsWithSingleComposedTagOnImplementedInterface() throws Exception { assertTagsFound(TaggedInterfaceClass.class, "fast"); } @Test void findRepeatableAnnotationsWithLocalComposedTagAndComposedTagOnImplementedInterface() throws Exception { assertTagsFound(LocalTagOnTaggedInterfaceClass.class, "fast", "smoke"); } @Test void findRepeatableAnnotationsWithMultipleTags() throws Exception { assertTagsFound(MultiTaggedClass.class, "a", "b", "c"); } @Test void findRepeatableAnnotationsWithMultipleComposedTags() throws Exception { assertTagsFound(MultiComposedTaggedClass.class, "fast", "smoke"); assertTagsFound(FastAndSmokyTaggedClass.class, "fast", "smoke"); } @Test void findRepeatableAnnotationsWithContainer() throws Exception { assertTagsFound(ContainerTaggedClass.class, "a", "b", "c", "d"); } @Test void findRepeatableAnnotationsWithComposedTagBeforeContainer() throws Exception { assertTagsFound(ContainerAfterComposedTaggedClass.class, "fast", "a", "b", "c"); } private void assertTagsFound(Class<?> clazz, String... tags) throws Exception { assertEquals(asList(tags), findRepeatableAnnotations(clazz, Tag.class).stream().map(Tag::value).collect(toList()), () -> "Tags found for class " + clazz.getName()); } @Test void findInheritedRepeatableAnnotationsWithSingleAnnotationOnSuperclass() throws Exception { assertExtensionsFound(SingleExtensionClass.class, "a"); assertExtensionsFound(SubSingleExtensionClass.class, "a"); } @Test void findInheritedRepeatableAnnotationsWithMultipleAnnotationsOnSuperclass() throws Exception { assertExtensionsFound(MultiExtensionClass.class, "a", "b", "c"); assertExtensionsFound(SubMultiExtensionClass.class, "a", "b", "c", "x", "y", "z"); } @Test void findInheritedRepeatableAnnotationsWithContainerAnnotationOnSuperclass() throws Exception { assertExtensionsFound(ContainerExtensionClass.class, "a", "b", "c"); assertExtensionsFound(SubContainerExtensionClass.class, "a", "b", "c", "x"); } @Test void findInheritedRepeatableAnnotationsWithSingleComposedAnnotation() throws Exception { assertExtensionsFound(SingleComposedExtensionClass.class, "foo"); } @Test void findInheritedRepeatableAnnotationsWithSingleComposedAnnotationOnSuperclass() throws Exception { assertExtensionsFound(SubSingleComposedExtensionClass.class, "foo"); } @Test void findInheritedRepeatableAnnotationsWithMultipleComposedAnnotations() throws Exception { assertExtensionsFound(MultiComposedExtensionClass.class, "foo", "bar"); } @Test void findInheritedRepeatableAnnotationsWithMultipleComposedAnnotationsOnSuperclass() throws Exception { assertExtensionsFound(SubMultiComposedExtensionClass.class, "foo", "bar"); } @Test void findInheritedRepeatableAnnotationsWithMultipleComposedAnnotationsOnSuperclassAndLocalContainerAndComposed() throws Exception { assertExtensionsFound(ContainerPlusSubMultiComposedExtensionClass.class, "foo", "bar", "x", "y", "z"); } private void assertExtensionsFound(Class<?> clazz, String... tags) throws Exception { assertEquals(asList(tags), findRepeatableAnnotations(clazz, ExtendWith.class).stream().map(ExtendWith::value).collect(toList()), () -> "Extensions found for class " + clazz.getName()); } @Test void findAnnotatedMethodsForNullClass() { assertThrows(PreconditionViolationException.class, () -> findAnnotatedMethods(null, Annotation1.class, TOP_DOWN)); } @Test void findAnnotatedMethodsForNullAnnotationType() { assertThrows(PreconditionViolationException.class, () -> findAnnotatedMethods(ClassWithAnnotatedMethods.class, null, TOP_DOWN)); } @Test void findAnnotatedMethodsForAnnotationThatIsNotPresent() { assertThat(findAnnotatedMethods(ClassWithAnnotatedMethods.class, Fast.class, TOP_DOWN)).isEmpty(); } @Test void findAnnotatedMethodsForAnnotationOnMethodsInClassUsingHierarchyDownMode() throws Exception { Method method2 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method2"); Method method3 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method3"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation2.class, TOP_DOWN); assertThat(methods).containsOnly(method2, method3); } @Test void findAnnotatedMethodsForAnnotationOnMethodsInClassHierarchyUsingHierarchyUpMode() throws Exception { Method method1 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method1"); Method method3 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method3"); Method superMethod = SuperClassWithAnnotatedMethod.class.getDeclaredMethod("superMethod"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation1.class, BOTTOM_UP); assertEquals(3, methods.size()); assertThat(methods.subList(0, 2)).containsOnly(method1, method3); assertEquals(superMethod, methods.get(2)); } @Test void findAnnotatedMethodsForAnnotationUsedInClassAndSuperClassHierarchyDown() throws Exception { Method method1 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method1"); Method method3 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method3"); Method superMethod = SuperClassWithAnnotatedMethod.class.getDeclaredMethod("superMethod"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation1.class, TOP_DOWN); assertEquals(3, methods.size()); assertEquals(superMethod, methods.get(0)); assertThat(methods.subList(1, 3)).containsOnly(method1, method3); } @Test void findAnnotatedMethodsForAnnotationUsedInInterface() throws Exception { Method interfaceMethod = InterfaceWithAnnotatedDefaultMethod.class.getDeclaredMethod("interfaceMethod"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation3.class, BOTTOM_UP); assertThat(methods).containsExactly(interfaceMethod); } @Test void findPublicAnnotatedFieldsForNullClass() { assertThrows(PreconditionViolationException.class, () -> findPublicAnnotatedFields(null, String.class, Annotation1.class)); } @Test void findPublicAnnotatedFieldsForNullFieldType() { assertThrows(PreconditionViolationException.class, () -> findPublicAnnotatedFields(getClass(), null, Annotation1.class)); } @Test void findPublicAnnotatedFieldsForNullAnnotationType() { assertThrows(PreconditionViolationException.class, () -> findPublicAnnotatedFields(getClass(), String.class, null)); } @Test void findPublicAnnotatedFieldsForPrivateField() { List<Field> fields = findPublicAnnotatedFields(getClass(), Boolean.class, Annotation1.class); assertNotNull(fields); assertEquals(0, fields.size()); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedFieldOfWrongFieldType() { List<Field> fields = findPublicAnnotatedFields(getClass(), BigDecimal.class, Annotation1.class); assertNotNull(fields); assertEquals(0, fields.size()); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedField() { List<Field> fields = findPublicAnnotatedFields(getClass(), String.class, Annotation1.class); assertNotNull(fields); assertIterableEquals(asList("directlyAnnotatedField"), asNames(fields)); } @Test void findPublicAnnotatedFieldsForMetaAnnotatedField() { List<Field> fields = findPublicAnnotatedFields(getClass(), Number.class, Annotation1.class); assertNotNull(fields); assertEquals(1, fields.size()); assertIterableEquals(asList("metaAnnotatedField"), asNames(fields)); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedFieldInInterface() { List<Field> fields = findPublicAnnotatedFields(InterfaceWithAnnotatedFields.class, String.class, Annotation1.class); assertNotNull(fields); assertIterableEquals(asList("foo"), asNames(fields)); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedFieldsInClassAndInterface() { List<Field> fields = findPublicAnnotatedFields(ClassWithAnnotatedFieldsFromInterface.class, String.class, Annotation1.class); assertNotNull(fields); assertThat(asNames(fields)).containsExactlyInAnyOrder("foo", "bar"); } private List<String> asNames(List<Field> fields) { return fields.stream().map(Field::getName).collect(toList()); } // ------------------------------------------------------------------------- @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface AnnotationWithDefaultValue { String value() default "default"; } @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @interface Annotation1 { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Annotation2 { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Annotation3 { } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @interface InheritedAnnotation { } @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Annotation1 @interface ComposedAnnotation { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Annotation1 @Inherited @interface InheritedComposedAnnotation { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Tags { Tag[] value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Repeatable(Tags.class) @interface Tag { String value(); } @Retention(RetentionPolicy.RUNTIME) @Tag("fast") @interface Fast { } @Retention(RetentionPolicy.RUNTIME) @Tag("smoke") @interface Smoke { } @Retention(RetentionPolicy.RUNTIME) @Fast @Smoke @interface FastAndSmoky { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @interface Extensions { ExtendWith[] value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Repeatable(Extensions.class) @interface ExtendWith { String value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @ExtendWith("foo") @interface ExtendWithFoo { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) // Intentionally NOT @Inherited in order to ensure that the algorithm for // findRepeatableAnnotations() in fact lives up to the claims in the // JavaDoc regarding searching for repeatable annotations with implicit // "inheritance" if the repeatable annotation is @Inherited but the // custom composed annotation is not @Inherited. // @Inherited @ExtendWith("bar") @interface ExtendWithBar { } @AnnotationWithDefaultValue static class AnnotationWithDefaultValueClass { } @Annotation1 static class Annotation1Class { } @Annotation2 static class Annotation2Class { @Annotation1 void method() { } } @InheritedAnnotation static class InheritedAnnotationClass { } static class SubInheritedAnnotationClass extends InheritedAnnotationClass { } @ComposedAnnotation static class ComposedAnnotationClass { @ComposedAnnotation void method() { } } @InheritedComposedAnnotation static class InheritedComposedAnnotationClass { @InheritedComposedAnnotation void method() { } } static class InheritedComposedAnnotationSubClass extends InheritedComposedAnnotationClass { } @Annotation1 interface TestingTrait { } static class TestingTraitClass implements TestingTrait { } @ComposedAnnotation interface ComposedTestingTrait { } static class ComposedTestingTraitClass implements ComposedTestingTrait { } @Tag("a") static class SingleTaggedClass { } @Fast static class SingleComposedTaggedClass { } @Tag("a") @Tag("b") @Tag("c") static class MultiTaggedClass { } @Fast @Smoke static class MultiComposedTaggedClass { } @FastAndSmoky static class FastAndSmokyTaggedClass { } @Fast interface TaggedInterface { } static class TaggedInterfaceClass implements TaggedInterface { } @Smoke static class LocalTagOnTaggedInterfaceClass implements TaggedInterface { } @Tags({ @Tag("a"), @Tag("b"), @Tag("c") }) @Tag("d") static class ContainerTaggedClass { } @Fast @Tags({ @Tag("a"), @Tag("b"), @Tag("c") }) static class ContainerAfterComposedTaggedClass { } @ExtendWith("a") static class SingleExtensionClass { } static class SubSingleExtensionClass extends SingleExtensionClass { } @ExtendWith("a") @ExtendWith("b") @ExtendWith("c") static class MultiExtensionClass { } @ExtendWith("x") @ExtendWith("y") @ExtendWith("b") // duplicates parent @ExtendWith("z") @ExtendWith("a") // duplicates parent static class SubMultiExtensionClass extends MultiExtensionClass { } @Extensions({ @ExtendWith("a"), @ExtendWith("b"), @ExtendWith("c"), @ExtendWith("a") }) static class ContainerExtensionClass { } @ExtendWith("x") static class SubContainerExtensionClass extends ContainerExtensionClass { } @ExtendWithFoo static class SingleComposedExtensionClass { } static class SubSingleComposedExtensionClass extends SingleComposedExtensionClass { } @ExtendWithFoo @ExtendWithBar static class MultiComposedExtensionClass { } static class SubMultiComposedExtensionClass extends MultiComposedExtensionClass { } @ExtendWith("x") @Extensions({ @ExtendWith("y"), @ExtendWith("z") }) @ExtendWithBar static class ContainerPlusSubMultiComposedExtensionClass extends MultiComposedExtensionClass { } interface InterfaceWithAnnotatedDefaultMethod { @Annotation3 default void interfaceMethod() { } } static class SuperClassWithAnnotatedMethod { @Annotation1 void superMethod() { } } static class ClassWithAnnotatedMethods extends SuperClassWithAnnotatedMethod implements InterfaceWithAnnotatedDefaultMethod { @Annotation1 void method1() { } @Annotation2 void method2() { } @Annotation1 @Annotation2 void method3() { } } @Annotation1 private Boolean privateDirectlyAnnotatedField; @Annotation1 public String directlyAnnotatedField; @ComposedAnnotation public Integer metaAnnotatedField; interface InterfaceWithAnnotatedFields { @Annotation1 String foo = "bar"; @Annotation1 boolean wrongType = false; } class ClassWithAnnotatedFieldsFromInterface implements InterfaceWithAnnotatedFields { @Annotation1 public String bar = "baz"; @Annotation1 public boolean notAString = true; } }
platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java
/* * Copyright 2015-2017 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.commons.util; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotatedMethods; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; import static org.junit.platform.commons.util.AnnotationUtils.findPublicAnnotatedFields; import static org.junit.platform.commons.util.AnnotationUtils.findRepeatableAnnotations; import static org.junit.platform.commons.util.AnnotationUtils.getDefaultValue; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP; import static org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode.TOP_DOWN; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; /** * Unit tests for {@link AnnotationUtils}. * * @since 1.0 */ class AnnotationUtilsTests { @Test void getDefaultValueForNullAnnotation() { assertThrows(PreconditionViolationException.class, () -> getDefaultValue(null, "foo", String.class)); } @Test void getDefaultValueForNullAttributeName() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, null, String.class)); } @Test void getDefaultValueForNullAttributeType() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, "foo", null)); } @Test void getDefaultValueForNonMatchingAttributeType() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, "value", Integer.class)); assertThat(exception.getMessage()).contains("Attribute 'value' in annotation", AnnotationWithDefaultValue.class.getName(), "is of type java.lang.String, not java.lang.Integer"); } @Test void getDefaultValueForEmptyAttributeName() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; assertThrows(PreconditionViolationException.class, () -> getDefaultValue(annotation, " \t ", String.class)); } @Test void getDefaultValueForAttributeWithDefault() { Annotation annotation = AnnotationWithDefaultValueClass.class.getAnnotations()[0]; Optional<String> defaultValue = getDefaultValue(annotation, "value", String.class); assertThat(defaultValue).contains("default"); } @Test void findAnnotationForNullOptional() { assertThat(findAnnotation((Optional<AnnotatedElement>) null, Annotation1.class)).isEmpty(); } @Test void findAnnotationForEmptyOptional() { assertThat(findAnnotation(Optional.empty(), Annotation1.class)).isEmpty(); } @Test void findAnnotationForNullAnnotatedElement() { assertThat(findAnnotation((AnnotatedElement) null, Annotation1.class)).isEmpty(); } @Test void findAnnotationOnClassWithoutAnnotation() { assertThat(findAnnotation(Annotation1Class.class, Annotation2.class)).isNotPresent(); } @Test void findAnnotationIndirectlyPresentOnOptionalClass() { Optional<Class<?>> optional = Optional.of(SubInheritedAnnotationClass.class); assertThat(findAnnotation(optional, InheritedAnnotation.class)).isPresent(); } @Test void findAnnotationIndirectlyPresentOnClass() { assertThat(findAnnotation(SubInheritedAnnotationClass.class, InheritedAnnotation.class)).isPresent(); } @Test void findAnnotationDirectlyPresentOnClass() { assertThat(findAnnotation(Annotation1Class.class, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnClass() { assertThat(findAnnotation(ComposedAnnotationClass.class, Annotation1.class)).isPresent(); } /** * <b>Note:</b> there is no findAnnotationIndirectlyMetaPresentOnMethod counterpart because {@link Inherited} * annotation has no effect if the annotated type is used to annotate anything other than a class. * * @see Inherited */ @Test void findAnnotationIndirectlyMetaPresentOnClass() { assertThat(findAnnotation(InheritedComposedAnnotationSubClass.class, Annotation1.class)).isPresent(); } @Test void findAnnotationDirectlyPresentOnImplementedInterface() { assertThat(findAnnotation(TestingTraitClass.class, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnImplementedInterface() { assertThat(findAnnotation(ComposedTestingTraitClass.class, Annotation1.class)).isPresent(); } @Test void findAnnotationDirectlyPresentOnMethod() throws Exception { Method method = Annotation2Class.class.getDeclaredMethod("method"); assertThat(findAnnotation(method, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnMethod() throws Exception { Method method = ComposedAnnotationClass.class.getDeclaredMethod("method"); assertThat(findAnnotation(method, Annotation1.class)).isPresent(); } @Test void findAnnotationMetaPresentOnOptionalMethod() throws Exception { Method method = ComposedAnnotationClass.class.getDeclaredMethod("method"); assertThat(findAnnotation(Optional.of(method), Annotation1.class)).isPresent(); } @Test void isAnnotatedForClassWithoutAnnotation() { assertFalse(isAnnotated(Annotation1Class.class, Annotation2.class)); } @Test void isAnnotatedWhenIndirectlyPresentOnClass() { assertTrue(isAnnotated(SubInheritedAnnotationClass.class, InheritedAnnotation.class)); } @Test void isAnnotatedWhenDirectlyPresentOnClass() { assertTrue(isAnnotated(Annotation1Class.class, Annotation1.class)); } @Test void isAnnotatedWhenMetaPresentOnClass() { assertTrue(isAnnotated(ComposedAnnotationClass.class, Annotation1.class)); } @Test void isAnnotatedWhenDirectlyPresentOnMethod() throws Exception { assertTrue(isAnnotated(Annotation2Class.class.getDeclaredMethod("method"), Annotation1.class)); } @Test void isAnnotatedWhenMetaPresentOnMethod() throws Exception { assertTrue(isAnnotated(ComposedAnnotationClass.class.getDeclaredMethod("method"), Annotation1.class)); } @Test void findRepeatableAnnotationsForNullAnnotatedElement() { assertThat(findRepeatableAnnotations(null, Tag.class)).isEmpty(); } @Test void findRepeatableAnnotationsWithSingleTag() throws Exception { assertTagsFound(SingleTaggedClass.class, "a"); } @Test void findRepeatableAnnotationsWithSingleComposedTag() throws Exception { assertTagsFound(SingleComposedTaggedClass.class, "fast"); } @Test void findRepeatableAnnotationsWithSingleComposedTagOnImplementedInterface() throws Exception { assertTagsFound(TaggedInterfaceClass.class, "fast"); } @Test void findRepeatableAnnotationsWithLocalComposedTagAndComposedTagOnImplementedInterface() throws Exception { assertTagsFound(LocalTagOnTaggedInterfaceClass.class, "fast", "smoke"); } @Test void findRepeatableAnnotationsWithMultipleTags() throws Exception { assertTagsFound(MultiTaggedClass.class, "a", "b", "c"); } @Test void findRepeatableAnnotationsWithMultipleComposedTags() throws Exception { assertTagsFound(MultiComposedTaggedClass.class, "fast", "smoke"); assertTagsFound(FastAndSmokyTaggedClass.class, "fast", "smoke"); } @Test void findRepeatableAnnotationsWithContainer() throws Exception { assertTagsFound(ContainerTaggedClass.class, "a", "b", "c", "d"); } @Test void findRepeatableAnnotationsWithComposedTagBeforeContainer() throws Exception { assertTagsFound(ContainerAfterComposedTaggedClass.class, "fast", "a", "b", "c"); } private void assertTagsFound(Class<?> clazz, String... tags) throws Exception { assertEquals(asList(tags), findRepeatableAnnotations(clazz, Tag.class).stream().map(Tag::value).collect(toList()), () -> "Tags found for class " + clazz.getName()); } @Test void findInheritedRepeatableAnnotationsWithSingleAnnotationOnSuperclass() throws Exception { assertExtensionsFound(SingleExtensionClass.class, "a"); assertExtensionsFound(SubSingleExtensionClass.class, "a"); } @Test void findInheritedRepeatableAnnotationsWithMultipleAnnotationsOnSuperclass() throws Exception { assertExtensionsFound(MultiExtensionClass.class, "a", "b", "c"); assertExtensionsFound(SubMultiExtensionClass.class, "a", "b", "c", "x", "y", "z"); } @Test void findInheritedRepeatableAnnotationsWithContainerAnnotationOnSuperclass() throws Exception { assertExtensionsFound(ContainerExtensionClass.class, "a", "b", "c"); assertExtensionsFound(SubContainerExtensionClass.class, "a", "b", "c", "x"); } @Test void findInheritedRepeatableAnnotationsWithSingleComposedAnnotation() throws Exception { assertExtensionsFound(SingleComposedExtensionClass.class, "foo"); } @Test void findInheritedRepeatableAnnotationsWithSingleComposedAnnotationOnSuperclass() throws Exception { assertExtensionsFound(SubSingleComposedExtensionClass.class, "foo"); } @Test void findInheritedRepeatableAnnotationsWithMultipleComposedAnnotations() throws Exception { assertExtensionsFound(MultiComposedExtensionClass.class, "foo", "bar"); } @Test void findInheritedRepeatableAnnotationsWithMultipleComposedAnnotationsOnSuperclass() throws Exception { assertExtensionsFound(SubMultiComposedExtensionClass.class, "foo", "bar"); } @Test void findInheritedRepeatableAnnotationsWithMultipleComposedAnnotationsOnSuperclassAndLocalContainerAndComposed() throws Exception { assertExtensionsFound(ContainerPlusSubMultiComposedExtensionClass.class, "foo", "bar", "x", "y", "z"); } private void assertExtensionsFound(Class<?> clazz, String... tags) throws Exception { assertEquals(asList(tags), findRepeatableAnnotations(clazz, ExtendWith.class).stream().map(ExtendWith::value).collect(toList()), () -> "Extensions found for class " + clazz.getName()); } @Test void findAnnotatedMethodsForNullClass() { assertThrows(PreconditionViolationException.class, () -> findAnnotatedMethods(null, Annotation1.class, TOP_DOWN)); } @Test void findAnnotatedMethodsForNullAnnotationType() { assertThrows(PreconditionViolationException.class, () -> findAnnotatedMethods(ClassWithAnnotatedMethods.class, null, TOP_DOWN)); } @Test void findAnnotatedMethodsForAnnotationThatIsNotPresent() { assertThat(findAnnotatedMethods(ClassWithAnnotatedMethods.class, Fast.class, TOP_DOWN)).isEmpty(); } @Test void findAnnotatedMethodsForAnnotationOnMethodsInClassUsingHierarchyDownMode() throws Exception { Method method2 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method2"); Method method3 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method3"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation2.class, TOP_DOWN); assertThat(methods).containsOnly(method2, method3); } @Test void findAnnotatedMethodsForAnnotationOnMethodsInClassHierarchyUsingHierarchyUpMode() throws Exception { Method method1 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method1"); Method method3 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method3"); Method superMethod = SuperClassWithAnnotatedMethod.class.getDeclaredMethod("superMethod"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation1.class, BOTTOM_UP); assertEquals(3, methods.size()); assertThat(methods.subList(0, 2)).containsOnly(method1, method3); assertEquals(superMethod, methods.get(2)); } @Test void findAnnotatedMethodsForAnnotationUsedInClassAndSuperClassHierarchyDown() throws Exception { Method method1 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method1"); Method method3 = ClassWithAnnotatedMethods.class.getDeclaredMethod("method3"); Method superMethod = SuperClassWithAnnotatedMethod.class.getDeclaredMethod("superMethod"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation1.class, TOP_DOWN); assertEquals(3, methods.size()); assertEquals(superMethod, methods.get(0)); assertThat(methods.subList(1, 3)).containsOnly(method1, method3); } @Test void findAnnotatedMethodsForAnnotationUsedInInterface() throws Exception { Method interfaceMethod = InterfaceWithAnnotatedDefaultMethod.class.getDeclaredMethod("interfaceMethod"); List<Method> methods = findAnnotatedMethods(ClassWithAnnotatedMethods.class, Annotation3.class, BOTTOM_UP); assertThat(methods).containsExactly(interfaceMethod); } @Test void findPublicAnnotatedFieldsForNullClass() { assertThrows(PreconditionViolationException.class, () -> findPublicAnnotatedFields(null, String.class, Annotation1.class)); } @Test void findPublicAnnotatedFieldsForNullFieldType() { assertThrows(PreconditionViolationException.class, () -> findPublicAnnotatedFields(getClass(), null, Annotation1.class)); } @Test void findPublicAnnotatedFieldsForNullAnnotationType() { assertThrows(PreconditionViolationException.class, () -> findPublicAnnotatedFields(getClass(), String.class, null)); } @Test void findPublicAnnotatedFieldsForPrivateField() { List<Field> fields = findPublicAnnotatedFields(getClass(), Boolean.class, Annotation1.class); assertNotNull(fields); assertEquals(0, fields.size()); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedFieldOfWrongFieldType() { List<Field> fields = findPublicAnnotatedFields(getClass(), BigDecimal.class, Annotation1.class); assertNotNull(fields); assertEquals(0, fields.size()); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedField() { List<Field> fields = findPublicAnnotatedFields(getClass(), String.class, Annotation1.class); assertNotNull(fields); assertIterableEquals(asList("directlyAnnotatedField"), asNames(fields)); } @Test void findPublicAnnotatedFieldsForMetaAnnotatedField() { List<Field> fields = findPublicAnnotatedFields(getClass(), Number.class, Annotation1.class); assertNotNull(fields); assertEquals(1, fields.size()); assertIterableEquals(asList("metaAnnotatedField"), asNames(fields)); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedFieldInInterface() { List<Field> fields = findPublicAnnotatedFields(InterfaceWithAnnotatedFields.class, String.class, Annotation1.class); assertNotNull(fields); assertIterableEquals(asList("foo"), asNames(fields)); } @Test void findPublicAnnotatedFieldsForDirectlyAnnotatedFieldsInClassAndInterface() { List<Field> fields = findPublicAnnotatedFields(ClassWithAnnotatedFieldsFromInterface.class, String.class, Annotation1.class); assertNotNull(fields); assertThat(asNames(fields)).containsExactlyInAnyOrder("foo", "bar"); } private List<String> asNames(List<Field> fields) { return fields.stream().map(Field::getName).collect(toList()); } // ------------------------------------------------------------------------- @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface AnnotationWithDefaultValue { String value() default "default"; } @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @interface Annotation1 { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Annotation2 { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Annotation3 { } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @interface InheritedAnnotation { } @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Annotation1 @interface ComposedAnnotation { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Annotation1 @Inherited @interface InheritedComposedAnnotation { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @interface Tags { Tag[] value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Repeatable(Tags.class) @interface Tag { String value(); } @Retention(RetentionPolicy.RUNTIME) @Tag("fast") @interface Fast { } @Retention(RetentionPolicy.RUNTIME) @Tag("smoke") @interface Smoke { } @Retention(RetentionPolicy.RUNTIME) @Fast @Smoke @interface FastAndSmoky { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @interface Extensions { ExtendWith[] value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Repeatable(Extensions.class) @interface ExtendWith { String value(); } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Inherited @ExtendWith("foo") @interface ExtendWithFoo { } @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) // Intentionally NOT @Inherited in order to ensure that the algorithm for // findRepeatableAnnotations() in fact lives up to the claims in the // JavaDoc regarding searching for repeatable annotations with implicit // "inheritance" if the repeatable annotation is @Inherited but the // custom composed annotation is not @Inherited. // @Inherited @ExtendWith("bar") @interface ExtendWithBar { } @AnnotationWithDefaultValue static class AnnotationWithDefaultValueClass { } @Annotation1 static class Annotation1Class { } @Annotation2 static class Annotation2Class { @Annotation1 void method() { } } @InheritedAnnotation static class InheritedAnnotationClass { } static class SubInheritedAnnotationClass extends InheritedAnnotationClass { } @ComposedAnnotation static class ComposedAnnotationClass { @ComposedAnnotation void method() { } } @InheritedComposedAnnotation static class InheritedComposedAnnotationClass { @InheritedComposedAnnotation void method() { } } static class InheritedComposedAnnotationSubClass extends InheritedComposedAnnotationClass { } @Annotation1 interface TestingTrait { } static class TestingTraitClass implements TestingTrait { } @ComposedAnnotation interface ComposedTestingTrait { } static class ComposedTestingTraitClass implements ComposedTestingTrait { } @Tag("a") static class SingleTaggedClass { } @Fast static class SingleComposedTaggedClass { } @Tag("a") @Tag("b") @Tag("c") static class MultiTaggedClass { } @Fast @Smoke static class MultiComposedTaggedClass { } @FastAndSmoky static class FastAndSmokyTaggedClass { } @Fast interface TaggedInterface { } static class TaggedInterfaceClass implements TaggedInterface { } @Smoke static class LocalTagOnTaggedInterfaceClass implements TaggedInterface { } @Tags({ @Tag("a"), @Tag("b"), @Tag("c") }) @Tag("d") static class ContainerTaggedClass { } @Fast @Tags({ @Tag("a"), @Tag("b"), @Tag("c") }) static class ContainerAfterComposedTaggedClass { } @ExtendWith("a") static class SingleExtensionClass { } static class SubSingleExtensionClass extends SingleExtensionClass { } @ExtendWith("a") @ExtendWith("b") @ExtendWith("c") static class MultiExtensionClass { } @ExtendWith("x") @ExtendWith("y") @ExtendWith("b") // duplicates parent @ExtendWith("z") @ExtendWith("a") // duplicates parent static class SubMultiExtensionClass extends MultiExtensionClass { } @Extensions({ @ExtendWith("a"), @ExtendWith("b"), @ExtendWith("c"), @ExtendWith("a") }) static class ContainerExtensionClass { } @ExtendWith("x") static class SubContainerExtensionClass extends ContainerExtensionClass { } @ExtendWithFoo static class SingleComposedExtensionClass { } static class SubSingleComposedExtensionClass extends SingleComposedExtensionClass { } @ExtendWithFoo @ExtendWithBar static class MultiComposedExtensionClass { } static class SubMultiComposedExtensionClass extends MultiComposedExtensionClass { } @ExtendWith("x") @Extensions({ @ExtendWith("y"), @ExtendWith("z") }) @ExtendWithBar static class ContainerPlusSubMultiComposedExtensionClass extends MultiComposedExtensionClass { } interface InterfaceWithAnnotatedDefaultMethod { @Annotation3 default void interfaceMethod() { } } static class SuperClassWithAnnotatedMethod { @Annotation1 void superMethod() { } } static class ClassWithAnnotatedMethods extends SuperClassWithAnnotatedMethod implements InterfaceWithAnnotatedDefaultMethod { @Annotation1 void method1() { } @Annotation2 void method2() { } @Annotation1 @Annotation2 void method3() { } } @Annotation1 private Boolean privateDirectlyAnnotatedField; @Annotation1 public String directlyAnnotatedField; @ComposedAnnotation public Integer metaAnnotatedField; interface InterfaceWithAnnotatedFields { @Annotation1 String foo = "bar"; @Annotation1 boolean wrongType = false; } class ClassWithAnnotatedFieldsFromInterface implements InterfaceWithAnnotatedFields { @Annotation1 public String bar = "baz"; @Annotation1 public boolean notAString = true; } }
Spot On!
platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java
Spot On!
<ide><path>latform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java <ide> @Target({ ElementType.TYPE, ElementType.METHOD }) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> // Intentionally NOT @Inherited in order to ensure that the algorithm for <del> // findRepeatableAnnotations() in fact lives up to the claims in the <add> // findRepeatableAnnotations() in fact lives up to the claims in the <ide> // JavaDoc regarding searching for repeatable annotations with implicit <ide> // "inheritance" if the repeatable annotation is @Inherited but the <ide> // custom composed annotation is not @Inherited.
Java
apache-2.0
6362bca90f952c6fff9d6ec199899c0582731152
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package graph.core.gui; import java.io.*; import java.awt.*; import java.awt.event.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.batik.dom.*; import org.apache.batik.svggen.*; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.event.*; import org.jfree.chart.plot.*; import org.jfree.chart.renderer.xy.*; import org.jfree.data.xy.*; import org.jibble.epsgraphics.EpsGraphics2D; import org.w3c.dom.*; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.*; import biomodelsim.core.gui.*; import buttons.core.gui.*; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { /** * */ private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private String savedPics; // directory for saved pictures private BioSim biomodelsim; // tstubd gui private JButton save; private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private JCheckBox resize; private boolean displayed; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(String printer_track_quantity, String label, String printer_id, String outDir, int readIn, XYSeriesCollection dataset, String time, BioSim biomodelsim, String open, Log log, String graphName) { // initializes member variables this.log = log; if (graphName != null) { this.graphName = graphName; } else { this.graphName = outDir.split(File.separator)[outDir.split(File.separator).length - 1] + ".grf"; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data; if (dataset == null) { data = new XYSeriesCollection(); } else { data = dataset; } displayed = false; // graph the output data setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, readIn, data, time); if (open != null) { open(open); } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, int readIn, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Click here to create graph"); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); save = new JButton("Save"); exportJPeg = new JButton("Export As JPEG"); exportPng = new JButton("Export As PNG"); exportPdf = new JButton("Export As PDF"); exportEps = new JButton("Export As EPS"); exportSvg = new JButton("Export As SVG"); save.addActionListener(this); exportJPeg.addActionListener(this); exportPng.addActionListener(this); exportPdf.addActionListener(this); exportEps.addActionListener(this); exportSvg.addActionListener(this); ButtonHolder.add(save); ButtonHolder.add(exportJPeg); ButtonHolder.add(exportPng); ButtonHolder.add(exportPdf); ButtonHolder.add(exportEps); ButtonHolder.add(exportSvg); // puts all the components of the graph gui into a display panel JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null); splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file, Component component) { InputStream input; component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { input = new BufferedInputStream(new ProgressMonitorInputStream(component, "Reading Reb2sac Output Data From " + new File(file).getName(), new FileInputStream(new File(file)))); graphSpecies = new ArrayList<String>(); boolean reading = true; char cha; int readCount = 0; while (reading) { String word = ""; boolean readWord = true; while (readWord) { int read = input.read(); readCount++; if (read == -1) { reading = false; readWord = false; } cha = (char) read; if (Character.isWhitespace(cha)) { input.mark(3); char next = (char) input.read(); char after = (char) input.read(); String check = "" + next + after; if (word.equals("") || word.equals("0") || check.equals("0,")) { readWord = false; } else { word += cha; } input.reset(); } else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?' || cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '=' || cha == '#') { readWord = false; } else if (read != -1) { word += cha; } } int getNum; try { getNum = Integer.parseInt(word); if (getNum == 0) { int read = 0; while (read != -1) { read = input.read(); } } } catch (Exception e1) { if (word.equals("")) { } else { graphSpecies.add(word); } } } } catch (Exception e) { JOptionPane.showMessageDialog(component, "Error Reading Data!" + "\nThere was an error reading the simulation output data.", "Error Reading Data", JOptionPane.ERROR_MESSAGE); } component.setCursor(null); } /** * This private helper method parses the output file of ODE, monte carlo, * and markov abstractions. */ private ArrayList<ArrayList<Double>> readData(String file, Component component, String printer_track_quantity, String label, String directory) { String[] s = file.split(File.separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if (label.contains("variance")) { return calculateAverageVarianceDeviation(file, stem, 1, directory); } else if (label.contains("deviation")) { return calculateAverageVarianceDeviation(file, stem, 2, directory); } else if (label.contains("average")) { return calculateAverageVarianceDeviation(file, stem, 0, directory); } else { ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); InputStream input; component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { input = new BufferedInputStream(new ProgressMonitorInputStream(component, "Reading Reb2sac Output Data From " + new File(file).getName(), new FileInputStream(new File(file)))); boolean reading = true; char cha; int readCount = 0; while (reading) { String word = ""; boolean readWord = true; while (readWord) { int read = input.read(); readCount++; if (read == -1) { reading = false; readWord = false; } cha = (char) read; if (Character.isWhitespace(cha)) { input.mark(3); char next = (char) input.read(); char after = (char) input.read(); String check = "" + next + after; if (word.equals("") || word.equals("0") || check.equals("0,")) { readWord = false; } else { word += cha; } input.reset(); } else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?' || cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '=' || cha == '#') { readWord = false; } else if (read != -1) { word += cha; } } int getNum; try { getNum = Integer.parseInt(word); if (getNum == 0) { for (int i = 0; i < graphSpecies.size(); i++) { data.add(new ArrayList<Double>()); } (data.get(0)).add(0.0); int counter = 1; reading = true; while (reading) { word = ""; readWord = true; int read; while (readWord) { read = input.read(); cha = (char) read; while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';' && cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '(' && cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']' && cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '=' && read != -1) { word += cha; read = input.read(); cha = (char) read; } if (read == -1) { reading = false; } readWord = false; } int insert; if (!word.equals("")) { if (counter < graphSpecies.size()) { insert = counter; } else { insert = counter % graphSpecies.size(); } (data.get(insert)).add(Double.parseDouble(word)); counter++; } } } } catch (Exception e1) { } } } catch (Exception e) { JOptionPane.showMessageDialog(component, "Error Reading Data!" + "\nThere was an error reading the simulation output data.", "Error Reading Data", JOptionPane.ERROR_MESSAGE); } component.setCursor(null); return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == save) { save(); } // if the export as jpeg button is clicked else if (e.getSource() == exportJPeg) { export(0); } // if the export as png button is clicked else if (e.getSource() == exportPng) { export(1); } // if the export as pdf button is clicked else if (e.getSource() == exportPdf) { export(2); } // if the export as eps button is clicked else if (e.getSource() == exportEps) { export(3); } // if the export as svg button is clicked else if (e.getSource() == exportSvg) { export(4); } } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(series.getY(k).doubleValue(), maxY); minY = Math.min(series.getY(k).doubleValue(), minY); maxX = Math.max(series.getX(k).doubleValue(), maxX); minX = Math.min(series.getX(k).doubleValue(), minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } else if ((maxY - minY) < .001) { axis.setRange(minY - 1, maxY + 1); } else { axis.setRange(Double.parseDouble(num.format(minY - (Math.abs(minY) * .1))), Double .parseDouble(num.format(maxY + (Math.abs(maxY) * .1)))); } axis.setAutoTickUnitSelection(true); axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } else if ((maxX - minX) < .001) { axis.setRange(minX - 1, maxX + 1); } else { axis.setRange(Double.parseDouble(num.format(minX)), Double .parseDouble(num.format(maxX))); } axis.setAutoTickUnitSelection(true); } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { editGraph(); } /** * This method currently does nothing. */ public void mousePressed(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseReleased(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); colors.put("Red ", draw.getNextPaint()); colors.put("Blue ", draw.getNextPaint()); colors.put("Green ", draw.getNextPaint()); colors.put("Yellow ", draw.getNextPaint()); colors.put("Magenta ", draw.getNextPaint()); colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray (Light)", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } private void editGraph() { if (!displayed) { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } JPanel titlePanel = new JPanel(new GridLayout(4, 6)); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } titlePanel.add(titleLabel); titlePanel.add(title); titlePanel.add(xMin); titlePanel.add(XMin); titlePanel.add(yMin); titlePanel.add(YMin); titlePanel.add(xLabel); titlePanel.add(x); titlePanel.add(xMax); titlePanel.add(XMax); titlePanel.add(yMax); titlePanel.add(YMax); titlePanel.add(yLabel); titlePanel.add(y); titlePanel.add(xScale); titlePanel.add(XScale); titlePanel.add(yScale); titlePanel.add(YScale); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(resize); String simDirString = outDir.split(File.separator)[outDir.split(File.separator).length - 1]; final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString); String[] files = new File(outDir).list(); for (int i = 1; i < files.length; i++) { String index = files[i]; int j = i; while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { files[j] = files[j - 1]; j = j - 1; } files[j] = index; } boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { if (file.contains("run-")) { add = true; } else { simDir .add(new DefaultMutableTreeNode(file .substring(0, file.length() - 4))); } } else if (new File(outDir + File.separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + File.separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } } if (addIt) { directories.add(file); DefaultMutableTreeNode d = new DefaultMutableTreeNode(file); boolean add2 = false; for (String f : new File(outDir + File.separator + file).list()) { if (f.contains(printer_id.substring(0, printer_id.length() - 8))) { if (f.contains("run-")) { add2 = true; } else { d .add(new DefaultMutableTreeNode(f.substring(0, f .length() - 4))); } } } if (add2) { d.add(new DefaultMutableTreeNode("Average")); d.add(new DefaultMutableTreeNode("Variance")); d.add(new DefaultMutableTreeNode("Standard Deviation")); } int run = 1; for (String s : new File(outDir + File.separator + file).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s .length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + File.separator + file + File.separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { d.add(new DefaultMutableTreeNode("run-" + (i + 1))); } } simDir.add(d); } } } if (add) { simDir.add(new DefaultMutableTreeNode("Average")); simDir.add(new DefaultMutableTreeNode("Variance")); simDir.add(new DefaultMutableTreeNode("Standard Deviation")); } int run = 1; for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + File.separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { simDir.add(new DefaultMutableTreeNode("run-" + (i + 1))); } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph." + "\nPerform some simutations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { final JTree tree = new JTree(simDir); for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); final JPanel specPanel = new JPanel(); final JFrame f = new JFrame("Edit Graph"); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath() .getLastPathComponent(); if (!directories.contains(node.toString())) { selected = node.toString(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else { try { select = Integer.parseInt(selected.substring(4)) + 2; } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (directories.contains(node.getParent().toString())) { specPanel.add(fixGraphCoices(node.getParent().toString())); } else { specPanel.add(fixGraphCoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (directories.contains(node.getParent().toString())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( node.getParent().toString())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected( g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected( g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = e.getPath().getLastPathComponent().toString(); if (directories.contains(node.getParent().toString())) { if (s.equals("Average")) { s = "(" + node.getParent().toString() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + node.getParent().toString() + ", " + (char) 948 + ")"; } else { if (s.contains("-run")) { s = s.substring(0, s.length() - 4); } else if (s.contains("run-")) { s = s.substring(4); } s = "(" + node.getParent().toString() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.contains("-run")) { s = s.substring(0, s.length() - 4); } else if (s.contains("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } series.get(i).setText(text); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); boolean stop = false; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; break; } } if (!stop) { tree.setSelectionRow(1); } JScrollPane scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(titlePanel, "North"); editPanel.add(specPanel, "Center"); editPanel.add(scrollpane, "West"); scroll.setViewportView(editPanel); JButton ok = new JButton("Ok"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); minY = Double.parseDouble(num.format(minY)); maxY = Double.parseDouble(num.format(maxY)); scaleY = Double.parseDouble(num.format(scaleY)); minX = Double.parseDouble(num.format(minX)); maxX = Double.parseDouble(num.format(maxX)); scaleX = Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot() .getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } readGraphSpecies(outDir + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber().toLowerCase(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber(), g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + File.separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + File.separator + g.getDirectory() + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber().toLowerCase(), g .getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } displayed = false; f.dispose(); } }); final JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } displayed = false; f.dispose(); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(ok); buttonPanel.add(cancel); JPanel all = new JPanel(new BorderLayout()); all.add(scroll, "Center"); all.add(buttonPanel, "South"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { cancel.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; f.addWindowListener(w); f.setContentPane(all); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int xx = screenSize.width / 2 - frameSize.width / 2; int yy = screenSize.height / 2 - frameSize.height / 2; f.setLocation(xx, yy); f.setVisible(true); displayed = true; } } } private JPanel fixGraphCoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { int nextOne = 1; while (!new File(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); } else { readGraphSpecies(outDir + File.separator + selected + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { int nextOne = 1; while (!new File(outDir + File.separator + directory + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + directory + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); } else { readGraphSpecies(outDir + File.separator + directory + File.separator + selected + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Species"); JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connected"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Filled"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[34]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Gray (Dark)")) { cols[7]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Red (Dark)")) { cols[8]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Dark)")) { cols[9]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Dark)")) { cols[10]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Dark)")) { cols[13]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) { cols[15]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) { cols[16]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) { cols[17]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) { cols[18]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) { cols[19]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) { cols[20]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Gray (Light)")) { cols[21]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Light)")) { cols[28]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Light)")) { cols[29]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Light)")) { cols[33]++; } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red ")) { cols[15]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue ")) { cols[16]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green ")) { cols[17]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow ")) { cols[18]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta ")) { cols[19]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan ")) { cols[20]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Gray (Light)")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Light)")) { cols[33]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if (cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } Paint paint = draw.getNextPaint(); Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i) .getSelectedItem()), colory.get(colorsCombo.get(i) .getSelectedItem()), filled.get(i).isSelected(), visible.get(i) .isSelected(), connected.get(i).isSelected(), selected, series.get( i).getText().trim(), i, directory)); } else { use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); Object[] col = this.colors.keySet().toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorsCombo.get(i)); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { chart = ChartFactory.createXYLineChart(title, x, y, dataset, PlotOrientation.VERTICAL, true, true, false); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Click here to create graph"); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); save = new JButton("Save"); exportJPeg = new JButton("Export As JPEG"); exportPng = new JButton("Export As PNG"); exportPdf = new JButton("Export As PDF"); exportEps = new JButton("Export As EPS"); exportSvg = new JButton("Export As SVG"); save.addActionListener(this); exportJPeg.addActionListener(this); exportPng.addActionListener(this); exportPdf.addActionListener(this); exportEps.addActionListener(this); exportSvg.addActionListener(this); ButtonHolder.add(save); ButtonHolder.add(exportJPeg); ButtonHolder.add(exportPng); ButtonHolder.add(exportPdf); ButtonHolder.add(exportEps); ButtonHolder.add(exportSvg); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null); splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export(int output) { try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } File file; if (savedPics != null) { file = new File(savedPics); } else { file = null; } String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY, "Save"); if (!filename.equals("")) { if (output == 0) { if (filename.length() < 4) { filename += ".jpg"; } else if (filename.length() < 5 && !filename.substring((filename.length() - 4), filename.length()) .equals(".jpg")) { filename += ".jpg"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".jpg") || filename.substring((filename.length() - 5), filename.length()) .equals(".jpeg")) { } else { filename += ".jpg"; } } } else if (output == 1) { if (filename.length() < 4) { filename += ".png"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".png")) { } else { filename += ".png"; } } } else if (output == 2) { if (filename.length() < 4) { filename += ".pdf"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".pdf")) { } else { filename += ".pdf"; } } } else if (output == 3) { if (filename.length() < 4) { filename += ".eps"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".eps")) { } else { filename += ".eps"; } } } else if (output == 4) { if (filename.length() < 4) { filename += ".svg"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".svg")) { } else { filename += ".svg"; } } } file = new File(filename); if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation .getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator.setSVGCanvasSize(new Dimension(width, height)); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); } savedPics = filename; } } else { if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream( file)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); } savedPics = filename; } } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile, String fileStem, int choice, String directory) { InputStream input; ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); try { input = new BufferedInputStream(new ProgressMonitorInputStream(biomodelsim.frame(), "Reading Reb2sac Output Data From " + new File(startFile).getName(), new FileInputStream(new File(startFile)))); boolean reading = true; char cha; int readCount = 0; while (reading) { String word = ""; boolean readWord = true; while (readWord) { int read = input.read(); readCount++; if (read == -1) { reading = false; readWord = false; } cha = (char) read; if (Character.isWhitespace(cha)) { input.mark(3); char next = (char) input.read(); char after = (char) input.read(); String check = "" + next + after; if (word.equals("") || word.equals("0") || check.equals("0,")) { readWord = false; } else { word += cha; } input.reset(); } else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?' || cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '=' || cha == '#') { readWord = false; } else if (read != -1) { word += cha; } } int getNum; try { getNum = Integer.parseInt(word); if (getNum == 0) { boolean first = true; int runsToMake = 1; String[] findNum = startFile.split(File.separator); String search = findNum[findNum.length - 1]; int firstOne = Integer.parseInt(search.substring(4, search.length() - 4)); if (directory == null) { for (String f : new File(outDir).list()) { if (f.contains(fileStem)) { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f .length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } } } else { for (String f : new File(outDir + File.separator + directory).list()) { if (f.contains(fileStem)) { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f .length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } } } for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } (average.get(0)).add(0.0); (variance.get(0)).add(0.0); int count = 0; int skip = firstOne; for (int j = 0; j < runsToMake; j++) { int counter = 1; if (!first) { if (firstOne != 1) { j--; firstOne = 1; } boolean loop = true; while (loop && j < runsToMake && (j + 1) != skip) { if (directory == null) { if (new File(outDir + File.separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { input = new BufferedInputStream( new ProgressMonitorInputStream( biomodelsim.frame(), "Reading Reb2sac Output Data From " + new File( outDir + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8)) .getName(), new FileInputStream( new File( outDir + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))))); for (int i = 0; i < readCount; i++) { input.read(); } loop = false; count++; } else { j++; } } else { if (new File(outDir + File.separator + directory + File.separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { input = new BufferedInputStream( new ProgressMonitorInputStream( biomodelsim.frame(), "Reading Reb2sac Output Data From " + new File( outDir + File.separator + directory + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8)) .getName(), new FileInputStream( new File( outDir + File.separator + directory + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))))); for (int i = 0; i < readCount; i++) { input.read(); } loop = false; count++; } else { j++; } } } } reading = true; while (reading) { word = ""; readWord = true; int read; while (readWord) { read = input.read(); cha = (char) read; while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';' && cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '(' && cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']' && cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '=' && read != -1) { word += cha; read = input.read(); cha = (char) read; } if (read == -1) { reading = false; first = false; } readWord = false; } int insert; if (!word.equals("")) { if (first) { if (counter < graphSpecies.size()) { insert = counter; (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)) .add(Double.parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } else { insert = counter % graphSpecies.size(); (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)) .add(Double.parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } } else { if (counter < graphSpecies.size()) { insert = counter; try { double old = (average.get(insert)).get(insert / graphSpecies.size()); (average.get(insert)) .set( insert / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); double newMean = (average.get(insert)).get(insert / graphSpecies.size()); if (insert == 0) { (variance.get(insert)) .set( insert / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); } else { double vary = (((count - 1) * (variance .get(insert)).get(insert / graphSpecies.size())) + (Double .parseDouble(word) - newMean) * (Double.parseDouble(word) - old)) / count; (variance.get(insert)).set(insert / graphSpecies.size(), vary); } } catch (Exception e2) { (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)).add(Double .parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } } else { insert = counter % graphSpecies.size(); try { double old = (average.get(insert)).get(counter / graphSpecies.size()); (average.get(insert)) .set( counter / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); double newMean = (average.get(insert)).get(counter / graphSpecies.size()); if (insert == 0) { (variance.get(insert)) .set( counter / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); } else { double vary = (((count - 1) * (variance .get(insert)).get(counter / graphSpecies.size())) + (Double .parseDouble(word) - newMean) * (Double.parseDouble(word) - old)) / count; (variance.get(insert)).set(counter / graphSpecies.size(), vary); } } catch (Exception e2) { (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)).add(Double .parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } } } counter++; } } } } } catch (Exception e1) { } } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } } catch (Exception e) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Error Reading Data!" + "\nThere was an error reading the simulation output data.", "Error Reading Data", JOptionPane.ERROR_MESSAGE); } if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } public void save() { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { graph.store(new FileOutputStream(new File(outDir + File.separator + graphName)), "Graph Data"); log.addText("Creating graph file:\n" + outDir + File.separator + graphName + "\n"); } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } private void open(String filename) { Properties graph = new Properties(); try { graph.load(new FileInputStream(new File(filename))); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } graphed.add(new GraphSpecies( shapes.get(graph.getProperty("species.shape." + next)), colors.get(graph .getProperty("species.paint." + next)), filled, visible, connected, graph.getProperty("species.run.number." + next), graph .getProperty("species.name." + next), Integer.parseInt(graph .getProperty("species.number." + next)), graph .getProperty("species.directory." + next))); next++; } refresh(); } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } public void refresh() { double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); minY = Double.parseDouble(num.format(minY)); maxY = Double.parseDouble(num.format(maxY)); scaleY = Double.parseDouble(num.format(scaleY)); minX = Double.parseDouble(num.format(minX)); maxX = Double.parseDouble(num.format(maxX)); scaleX = Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (ableToGraph) { int nextOne = 1; while (!new File(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber().toLowerCase(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber(), g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + File.separator + g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (ableToGraph) { int nextOne = 1; while (!new File(outDir + File.separator + g.getDirectory() + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber().toLowerCase(), g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart .getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, Paint p) { shape = s; paint = p; } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Unknown Color"; } public void setPaint(String paint) { this.paint = colors.get(paint); } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory; private int number; private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected, String runNumber, String species, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.number = number; this.directory = directory; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } }
gui/src/graph/Graph.java
package graph.core.gui; import java.io.*; import java.awt.*; import java.awt.event.*; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.batik.dom.*; import org.apache.batik.svggen.*; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.event.*; import org.jfree.chart.plot.*; import org.jfree.chart.renderer.xy.*; import org.jfree.data.xy.*; import org.jibble.epsgraphics.EpsGraphics2D; import org.w3c.dom.*; import com.lowagie.text.Document; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.*; import biomodelsim.core.gui.*; import buttons.core.gui.*; /** * This is the Graph class. It takes in data and draws a graph of that data. The * Graph class implements the ActionListener class, the ChartProgressListener * class, and the MouseListener class. This allows the Graph class to perform * actions when buttons are pressed, when the chart is drawn, or when the chart * is clicked. * * @author Curtis Madsen */ public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener { /** * */ private static final long serialVersionUID = 4350596002373546900L; private JFreeChart chart; // Graph of the output data private String outDir; // output directory private String printer_id; // printer id /* * Text fields used to change the graph window */ private JTextField XMin, XMax, XScale, YMin, YMax, YScale; private ArrayList<String> graphSpecies; // names of species in the graph private String savedPics; // directory for saved pictures private BioSim biomodelsim; // tstubd gui private JButton save; private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg; // buttons private HashMap<String, Paint> colors; private HashMap<String, Shape> shapes; private String selected, lastSelected; private LinkedList<GraphSpecies> graphed; private JCheckBox resize; private boolean displayed; private Log log; private ArrayList<JCheckBox> boxes; private ArrayList<JTextField> series; private ArrayList<JComboBox> colorsCombo; private ArrayList<JComboBox> shapesCombo; private ArrayList<JCheckBox> connected; private ArrayList<JCheckBox> visible; private ArrayList<JCheckBox> filled; private JCheckBox use; private JCheckBox connectedLabel; private JCheckBox visibleLabel; private JCheckBox filledLabel; private String graphName; /** * Creates a Graph Object from the data given and calls the private graph * helper method. */ public Graph(String printer_track_quantity, String label, String printer_id, String outDir, int readIn, XYSeriesCollection dataset, String time, BioSim biomodelsim, String open, Log log, String graphName) { // initializes member variables this.log = log; if (graphName != null) { this.graphName = graphName; } else { this.graphName = outDir.split(File.separator)[outDir.split(File.separator).length - 1] + ".grf"; } this.outDir = outDir; this.printer_id = printer_id; this.biomodelsim = biomodelsim; XYSeriesCollection data; if (dataset == null) { data = new XYSeriesCollection(); } else { data = dataset; } displayed = false; // graph the output data setUpShapesAndColors(); graphed = new LinkedList<GraphSpecies>(); selected = ""; lastSelected = ""; graph(printer_track_quantity, label, readIn, data, time); if (open != null) { open(open); } } /** * This private helper method calls the private readData method, sets up a * graph frame, and graphs the data. * * @param dataset * @param time */ private void graph(String printer_track_quantity, String label, int readIn, XYSeriesCollection dataset, String time) { chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset, PlotOrientation.VERTICAL, true, true, false); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Click here to create graph"); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); graph.addMouseListener(this); // creates text fields for changing the graph's dimensions resize = new JCheckBox("Auto Resize"); resize.setSelected(true); XMin = new JTextField(); XMax = new JTextField(); XScale = new JTextField(); YMin = new JTextField(); YMax = new JTextField(); YScale = new JTextField(); // creates the buttons for the graph frame JPanel ButtonHolder = new JPanel(); save = new JButton("Save"); exportJPeg = new JButton("Export As JPEG"); exportPng = new JButton("Export As PNG"); exportPdf = new JButton("Export As PDF"); exportEps = new JButton("Export As EPS"); exportSvg = new JButton("Export As SVG"); save.addActionListener(this); exportJPeg.addActionListener(this); exportPng.addActionListener(this); exportPdf.addActionListener(this); exportEps.addActionListener(this); exportSvg.addActionListener(this); ButtonHolder.add(save); ButtonHolder.add(exportJPeg); ButtonHolder.add(exportPng); ButtonHolder.add(exportPdf); ButtonHolder.add(exportEps); ButtonHolder.add(exportSvg); // puts all the components of the graph gui into a display panel JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null); splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); this.add(splitPane, "South"); // determines maximum and minimum values and resizes resize(dataset); this.revalidate(); } private void readGraphSpecies(String file, Component component) { InputStream input; component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { input = new BufferedInputStream(new ProgressMonitorInputStream(component, "Reading Reb2sac Output Data From " + new File(file).getName(), new FileInputStream(new File(file)))); graphSpecies = new ArrayList<String>(); boolean reading = true; char cha; int readCount = 0; while (reading) { String word = ""; boolean readWord = true; while (readWord) { int read = input.read(); readCount++; if (read == -1) { reading = false; readWord = false; } cha = (char) read; if (Character.isWhitespace(cha)) { input.mark(3); char next = (char) input.read(); char after = (char) input.read(); String check = "" + next + after; if (word.equals("") || word.equals("0") || check.equals("0,")) { readWord = false; } else { word += cha; } input.reset(); } else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?' || cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '=' || cha == '#') { readWord = false; } else if (read != -1) { word += cha; } } int getNum; try { getNum = Integer.parseInt(word); if (getNum == 0) { int read = 0; while (read != -1) { read = input.read(); } } } catch (Exception e1) { if (word.equals("")) { } else { graphSpecies.add(word); } } } } catch (Exception e) { JOptionPane.showMessageDialog(component, "Error Reading Data!" + "\nThere was an error reading the simulation output data.", "Error Reading Data", JOptionPane.ERROR_MESSAGE); } component.setCursor(null); } /** * This private helper method parses the output file of ODE, monte carlo, * and markov abstractions. */ private ArrayList<ArrayList<Double>> readData(String file, Component component, String printer_track_quantity, String label, String directory) { String[] s = file.split(File.separator); String getLast = s[s.length - 1]; String stem = ""; int t = 0; try { while (!Character.isDigit(getLast.charAt(t))) { stem += getLast.charAt(t); t++; } } catch (Exception e) { } if (label.contains("variance")) { return calculateAverageVarianceDeviation(file, stem, 1, directory); } else if (label.contains("deviation")) { return calculateAverageVarianceDeviation(file, stem, 2, directory); } else if (label.contains("average")) { return calculateAverageVarianceDeviation(file, stem, 0, directory); } else { ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); InputStream input; component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { input = new BufferedInputStream(new ProgressMonitorInputStream(component, "Reading Reb2sac Output Data From " + new File(file).getName(), new FileInputStream(new File(file)))); boolean reading = true; char cha; int readCount = 0; while (reading) { String word = ""; boolean readWord = true; while (readWord) { int read = input.read(); readCount++; if (read == -1) { reading = false; readWord = false; } cha = (char) read; if (Character.isWhitespace(cha)) { input.mark(3); char next = (char) input.read(); char after = (char) input.read(); String check = "" + next + after; if (word.equals("") || word.equals("0") || check.equals("0,")) { readWord = false; } else { word += cha; } input.reset(); } else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?' || cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '=' || cha == '#') { readWord = false; } else if (read != -1) { word += cha; } } int getNum; try { getNum = Integer.parseInt(word); if (getNum == 0) { for (int i = 0; i < graphSpecies.size(); i++) { data.add(new ArrayList<Double>()); } (data.get(0)).add(0.0); int counter = 1; reading = true; while (reading) { word = ""; readWord = true; int read; while (readWord) { read = input.read(); cha = (char) read; while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';' && cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '(' && cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']' && cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '=' && read != -1) { word += cha; read = input.read(); cha = (char) read; } if (read == -1) { reading = false; } readWord = false; } int insert; if (!word.equals("")) { if (counter < graphSpecies.size()) { insert = counter; } else { insert = counter % graphSpecies.size(); } (data.get(insert)).add(Double.parseDouble(word)); counter++; } } } } catch (Exception e1) { } } } catch (Exception e) { JOptionPane.showMessageDialog(component, "Error Reading Data!" + "\nThere was an error reading the simulation output data.", "Error Reading Data", JOptionPane.ERROR_MESSAGE); } component.setCursor(null); return data; } } /** * This method adds and removes plots from the graph depending on what check * boxes are selected. */ public void actionPerformed(ActionEvent e) { // if the save button is clicked if (e.getSource() == save) { save(); } // if the export as jpeg button is clicked else if (e.getSource() == exportJPeg) { export(0); } // if the export as png button is clicked else if (e.getSource() == exportPng) { export(1); } // if the export as pdf button is clicked else if (e.getSource() == exportPdf) { export(2); } // if the export as eps button is clicked else if (e.getSource() == exportEps) { export(3); } // if the export as svg button is clicked else if (e.getSource() == exportSvg) { export(4); } } /** * Private method used to auto resize the graph. */ private void resize(XYSeriesCollection dataset) { NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); XYPlot plot = chart.getXYPlot(); XYItemRenderer rend = plot.getRenderer(); double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries series = dataset.getSeries(j); Boolean visible = rend.getSeriesVisible(j); if (visible == null || visible.equals(true)) { for (int k = 0; k < series.getItemCount(); k++) { maxY = Math.max(series.getY(k).doubleValue(), maxY); minY = Math.min(series.getY(k).doubleValue(), minY); maxX = Math.max(series.getX(k).doubleValue(), maxX); minX = Math.min(series.getX(k).doubleValue(), minX); } } } NumberAxis axis = (NumberAxis) plot.getRangeAxis(); if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) { axis.setRange(-1, 1); } else if ((maxY - minY) < .001) { axis.setRange(minY - 1, maxY + 1); } else { axis.setRange(Double.parseDouble(num.format(minY - (Math.abs(minY) * .1))), Double .parseDouble(num.format(maxY + (Math.abs(maxY) * .1)))); } axis.setAutoTickUnitSelection(true); axis = (NumberAxis) plot.getDomainAxis(); if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) { axis.setRange(-1, 1); } else if ((maxX - minX) < .001) { axis.setRange(minX - 1, maxX + 1); } else { axis.setRange(Double.parseDouble(num.format(minX)), Double .parseDouble(num.format(maxX))); } axis.setAutoTickUnitSelection(true); } /** * After the chart is redrawn, this method calculates the x and y scale and * updates those text fields. */ public void chartProgress(ChartProgressEvent e) { // if the chart drawing is started if (e.getType() == ChartProgressEvent.DRAWING_STARTED) { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } // if the chart drawing is finished else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) { this.setCursor(null); JFreeChart chart = e.getChart(); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); YMin.setText("" + axis.getLowerBound()); YMax.setText("" + axis.getUpperBound()); YScale.setText("" + axis.getTickUnit().getSize()); axis = (NumberAxis) plot.getDomainAxis(); XMin.setText("" + axis.getLowerBound()); XMax.setText("" + axis.getUpperBound()); XScale.setText("" + axis.getTickUnit().getSize()); } } /** * Invoked when the mouse is clicked on the chart. Allows the user to edit * the title and labels of the chart. */ public void mouseClicked(MouseEvent e) { editGraph(); } /** * This method currently does nothing. */ public void mousePressed(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseReleased(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseEntered(MouseEvent e) { } /** * This method currently does nothing. */ public void mouseExited(MouseEvent e) { } private void setUpShapesAndColors() { DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); colors = new HashMap<String, Paint>(); shapes = new HashMap<String, Shape>(); colors.put("Red", draw.getNextPaint()); colors.put("Blue", draw.getNextPaint()); colors.put("Green", draw.getNextPaint()); colors.put("Yellow", draw.getNextPaint()); colors.put("Magenta", draw.getNextPaint()); colors.put("Cyan", draw.getNextPaint()); colors.put("Tan", draw.getNextPaint()); colors.put("Gray (Dark)", draw.getNextPaint()); colors.put("Red (Dark)", draw.getNextPaint()); colors.put("Blue (Dark)", draw.getNextPaint()); colors.put("Green (Dark)", draw.getNextPaint()); colors.put("Yellow (Dark)", draw.getNextPaint()); colors.put("Magenta (Dark)", draw.getNextPaint()); colors.put("Cyan (Dark)", draw.getNextPaint()); colors.put("Black", draw.getNextPaint()); colors.put("Red ", draw.getNextPaint()); colors.put("Blue ", draw.getNextPaint()); colors.put("Green ", draw.getNextPaint()); colors.put("Yellow ", draw.getNextPaint()); colors.put("Magenta ", draw.getNextPaint()); colors.put("Cyan ", draw.getNextPaint()); colors.put("Gray (Light)", draw.getNextPaint()); colors.put("Red (Extra Dark)", draw.getNextPaint()); colors.put("Blue (Extra Dark)", draw.getNextPaint()); colors.put("Green (Extra Dark)", draw.getNextPaint()); colors.put("Yellow (Extra Dark)", draw.getNextPaint()); colors.put("Magenta (Extra Dark)", draw.getNextPaint()); colors.put("Cyan (Extra Dark)", draw.getNextPaint()); colors.put("Red (Light)", draw.getNextPaint()); colors.put("Blue (Light)", draw.getNextPaint()); colors.put("Green (Light)", draw.getNextPaint()); colors.put("Yellow (Light)", draw.getNextPaint()); colors.put("Magenta (Light)", draw.getNextPaint()); colors.put("Cyan (Light)", draw.getNextPaint()); shapes.put("Square", draw.getNextShape()); shapes.put("Circle", draw.getNextShape()); shapes.put("Triangle", draw.getNextShape()); shapes.put("Diamond", draw.getNextShape()); shapes.put("Rectangle (Horizontal)", draw.getNextShape()); shapes.put("Triangle (Upside Down)", draw.getNextShape()); shapes.put("Circle (Half)", draw.getNextShape()); shapes.put("Arrow", draw.getNextShape()); shapes.put("Rectangle (Vertical)", draw.getNextShape()); shapes.put("Arrow (Backwards)", draw.getNextShape()); } private void editGraph() { if (!displayed) { final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { old.add(g); } JPanel titlePanel = new JPanel(new GridLayout(4, 6)); JLabel titleLabel = new JLabel("Title:"); JLabel xLabel = new JLabel("X-Axis Label:"); JLabel yLabel = new JLabel("Y-Axis Label:"); final JTextField title = new JTextField(chart.getTitle().getText(), 5); final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5); final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5); final JLabel xMin = new JLabel("X-Min:"); final JLabel xMax = new JLabel("X-Max:"); final JLabel xScale = new JLabel("X-Step:"); final JLabel yMin = new JLabel("Y-Min:"); final JLabel yMax = new JLabel("Y-Max:"); final JLabel yScale = new JLabel("Y-Step:"); resize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } } }); if (resize.isSelected()) { xMin.setEnabled(false); XMin.setEnabled(false); xMax.setEnabled(false); XMax.setEnabled(false); xScale.setEnabled(false); XScale.setEnabled(false); yMin.setEnabled(false); YMin.setEnabled(false); yMax.setEnabled(false); YMax.setEnabled(false); yScale.setEnabled(false); YScale.setEnabled(false); } else { xMin.setEnabled(true); XMin.setEnabled(true); xMax.setEnabled(true); XMax.setEnabled(true); xScale.setEnabled(true); XScale.setEnabled(true); yMin.setEnabled(true); YMin.setEnabled(true); yMax.setEnabled(true); YMax.setEnabled(true); yScale.setEnabled(true); YScale.setEnabled(true); } titlePanel.add(titleLabel); titlePanel.add(title); titlePanel.add(xMin); titlePanel.add(XMin); titlePanel.add(yMin); titlePanel.add(YMin); titlePanel.add(xLabel); titlePanel.add(x); titlePanel.add(xMax); titlePanel.add(XMax); titlePanel.add(yMax); titlePanel.add(YMax); titlePanel.add(yLabel); titlePanel.add(y); titlePanel.add(xScale); titlePanel.add(XScale); titlePanel.add(yScale); titlePanel.add(YScale); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(new JPanel()); titlePanel.add(resize); String simDirString = outDir.split(File.separator)[outDir.split(File.separator).length - 1]; final DefaultMutableTreeNode simDir = new DefaultMutableTreeNode(simDirString); String[] files = new File(outDir).list(); for (int i = 1; i < files.length; i++) { String index = files[i]; int j = i; while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) { files[j] = files[j - 1]; j = j - 1; } files[j] = index; } boolean add = false; final ArrayList<String> directories = new ArrayList<String>(); for (String file : files) { if (file.length() > 3 && file.substring(file.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { if (file.contains("run-")) { add = true; } else { simDir .add(new DefaultMutableTreeNode(file .substring(0, file.length() - 4))); } } else if (new File(outDir + File.separator + file).isDirectory()) { boolean addIt = false; for (String getFile : new File(outDir + File.separator + file).list()) { if (getFile.length() > 3 && getFile.substring(getFile.length() - 4).equals( "." + printer_id.substring(0, printer_id.length() - 8))) { addIt = true; } } if (addIt) { directories.add(file); DefaultMutableTreeNode d = new DefaultMutableTreeNode(file); boolean add2 = false; for (String f : new File(outDir + File.separator + file).list()) { if (f.contains(printer_id.substring(0, printer_id.length() - 8))) { if (f.contains("run-")) { add2 = true; } else { d .add(new DefaultMutableTreeNode(f.substring(0, f .length() - 4))); } } } if (add2) { d.add(new DefaultMutableTreeNode("Average")); d.add(new DefaultMutableTreeNode("Variance")); d.add(new DefaultMutableTreeNode("Standard Deviation")); } int run = 1; for (String s : new File(outDir + File.separator + file).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s .length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + File.separator + file + File.separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { d.add(new DefaultMutableTreeNode("run-" + (i + 1))); } } simDir.add(d); } } } if (add) { simDir.add(new DefaultMutableTreeNode("Average")); simDir.add(new DefaultMutableTreeNode("Variance")); simDir.add(new DefaultMutableTreeNode("Standard Deviation")); } int run = 1; for (String s : new File(outDir).list()) { if (s.length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = s.charAt(s.length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (s.contains("run-")) { run = Math.max(run, Integer.parseInt(s.substring(4, s.length() - end.length()))); } } } } for (int i = 0; i < run; i++) { if (new File(outDir + File.separator + "run-" + (i + 1) + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { simDir.add(new DefaultMutableTreeNode("run-" + (i + 1))); } } if (simDir.getChildCount() == 0) { JOptionPane.showMessageDialog(biomodelsim.frame(), "No data to graph." + "\nPerform some simutations to create some data first.", "No Data", JOptionPane.PLAIN_MESSAGE); } else { final JTree tree = new JTree(simDir); for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(tree); final JPanel specPanel = new JPanel(); final JFrame f = new JFrame("Edit Graph"); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath() .getLastPathComponent(); if (!directories.contains(node.toString())) { selected = node.toString(); int select; if (selected.equals("Average")) { select = 0; } else if (selected.equals("Variance")) { select = 1; } else if (selected.equals("Standard Deviation")) { select = 2; } else if (selected.contains("-run")) { select = 0; } else { try { select = Integer.parseInt(selected.substring(4)) + 2; } catch (Exception e1) { select = -1; } } if (select != -1) { specPanel.removeAll(); if (directories.contains(node.getParent().toString())) { specPanel.add(fixGraphCoices(node.getParent().toString())); } else { specPanel.add(fixGraphCoices("")); } specPanel.revalidate(); specPanel.repaint(); for (int i = 0; i < series.size(); i++) { series.get(i).setText(graphSpecies.get(i + 1)); } for (int i = 0; i < boxes.size(); i++) { boxes.get(i).setSelected(false); } if (directories.contains(node.getParent().toString())) { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals( node.getParent().toString())) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected( g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } else { for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getDirectory().equals("")) { boxes.get(g.getNumber()).setSelected(true); series.get(g.getNumber()).setText(g.getSpecies()); colorsCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getPaintName()); shapesCombo.get(g.getNumber()).setSelectedItem( g.getShapeAndPaint().getShapeName()); connected.get(g.getNumber()).setSelected( g.getConnected()); visible.get(g.getNumber()).setSelected(g.getVisible()); filled.get(g.getNumber()).setSelected(g.getFilled()); } } } boolean allChecked = true; boolean allCheckedVisible = true; boolean allCheckedFilled = true; boolean allCheckedConnected = true; for (int i = 0; i < boxes.size(); i++) { if (!boxes.get(i).isSelected()) { allChecked = false; String s = ""; s = e.getPath().getLastPathComponent().toString(); if (directories.contains(node.getParent().toString())) { if (s.equals("Average")) { s = "(" + node.getParent().toString() + ", " + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + node.getParent().toString() + ", " + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + node.getParent().toString() + ", " + (char) 948 + ")"; } else { if (s.contains("-run")) { s = s.substring(0, s.length() - 4); } else if (s.contains("run-")) { s = s.substring(4); } s = "(" + node.getParent().toString() + ", " + s + ")"; } } else { if (s.equals("Average")) { s = "(" + (char) 967 + ")"; } else if (s.equals("Variance")) { s = "(" + (char) 948 + (char) 178 + ")"; } else if (s.equals("Standard Deviation")) { s = "(" + (char) 948 + ")"; } else { if (s.contains("-run")) { s = s.substring(0, s.length() - 4); } else if (s.contains("run-")) { s = s.substring(4); } s = "(" + s + ")"; } } String text = series.get(i).getText(); String end = ""; if (text.length() >= s.length()) { for (int j = 0; j < s.length(); j++) { end = text.charAt(text.length() - 1 - j) + end; } if (!s.equals(end)) { text += " " + s; } } else { text += " " + s; } series.get(i).setText(text); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); } if (!visible.get(i).isSelected()) { allCheckedVisible = false; } if (!connected.get(i).isSelected()) { allCheckedConnected = false; } if (!filled.get(i).isSelected()) { allCheckedFilled = false; } } if (allChecked) { use.setSelected(true); } else { use.setSelected(false); } if (allCheckedVisible) { visibleLabel.setSelected(true); } else { visibleLabel.setSelected(false); } if (allCheckedFilled) { filledLabel.setSelected(true); } else { filledLabel.setSelected(false); } if (allCheckedConnected) { connectedLabel.setSelected(true); } else { connectedLabel.setSelected(false); } } } else { specPanel.removeAll(); specPanel.revalidate(); specPanel.repaint(); } } }); boolean stop = false; for (int i = 1; i < tree.getRowCount(); i++) { tree.setSelectionRow(i); if (selected.equals(lastSelected)) { stop = true; break; } } if (!stop) { tree.setSelectionRow(1); } JScrollPane scroll = new JScrollPane(); scroll.setPreferredSize(new Dimension(1050, 500)); JPanel editPanel = new JPanel(new BorderLayout()); editPanel.add(titlePanel, "North"); editPanel.add(specPanel, "Center"); editPanel.add(scrollpane, "West"); scroll.setViewportView(editPanel); JButton ok = new JButton("Ok"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { double minY; double maxY; double scaleY; double minX; double maxX; double scaleX; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); minY = Double.parseDouble(num.format(minY)); maxY = Double.parseDouble(num.format(maxY)); scaleY = Double.parseDouble(num.format(scaleY)); minX = Double.parseDouble(num.format(minX)); maxX = Double.parseDouble(num.format(maxX)); scaleX = Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Must enter doubles into the inputs " + "to change the graph's dimensions!", "Error", JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected; selected = ""; ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot() .getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase( index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } readGraphSpecies(outDir + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber().toLowerCase(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber(), g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + File.separator + g.getDirectory()).list()) { if (s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e1) { ableToGraph = false; } if (ableToGraph) { int next = 1; while (!new File(outDir + File.separator + g.getDirectory() + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { next++; } readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + "run-" + next + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), y.getText().trim(), g .getRunNumber().toLowerCase(), g .getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase( index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add( (data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } displayed = false; f.dispose(); } }); final JButton cancel = new JButton("Cancel"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selected = ""; int size = graphed.size(); for (int i = 0; i < size; i++) { graphed.remove(); } for (GraphSpecies g : old) { graphed.add(g); } displayed = false; f.dispose(); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(ok); buttonPanel.add(cancel); JPanel all = new JPanel(new BorderLayout()); all.add(scroll, "Center"); all.add(buttonPanel, "South"); WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { cancel.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; f.addWindowListener(w); f.setContentPane(all); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int xx = screenSize.width / 2 - frameSize.width / 2; int yy = screenSize.height / 2 - frameSize.height / 2; f.setLocation(xx, yy); f.setVisible(true); displayed = true; } } } private JPanel fixGraphCoices(final String directory) { if (directory.equals("")) { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { int nextOne = 1; while (!new File(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); } else { readGraphSpecies(outDir + File.separator + selected + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); } } else { if (selected.equals("Average") || selected.equals("Variance") || selected.equals("Standard Deviation")) { int nextOne = 1; while (!new File(outDir + File.separator + directory + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + directory + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame()); } else { readGraphSpecies(outDir + File.separator + directory + File.separator + selected + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); } } for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); } JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1)); JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3)); JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3)); use = new JCheckBox("Use"); JLabel specs = new JLabel("Species"); JLabel color = new JLabel("Color"); JLabel shape = new JLabel("Shape"); connectedLabel = new JCheckBox("Connected"); visibleLabel = new JCheckBox("Visible"); filledLabel = new JCheckBox("Filled"); connectedLabel.setSelected(true); visibleLabel.setSelected(true); filledLabel.setSelected(true); boxes = new ArrayList<JCheckBox>(); series = new ArrayList<JTextField>(); colorsCombo = new ArrayList<JComboBox>(); shapesCombo = new ArrayList<JComboBox>(); connected = new ArrayList<JCheckBox>(); visible = new ArrayList<JCheckBox>(); filled = new ArrayList<JCheckBox>(); use.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (use.isSelected()) { for (JCheckBox box : boxes) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : boxes) { if (box.isSelected()) { box.doClick(); } } } } }); connectedLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (connectedLabel.isSelected()) { for (JCheckBox box : connected) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : connected) { if (box.isSelected()) { box.doClick(); } } } } }); visibleLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (visibleLabel.isSelected()) { for (JCheckBox box : visible) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : visible) { if (box.isSelected()) { box.doClick(); } } } } }); filledLabel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (filledLabel.isSelected()) { for (JCheckBox box : filled) { if (!box.isSelected()) { box.doClick(); } } } else { for (JCheckBox box : filled) { if (box.isSelected()) { box.doClick(); } } } } }); speciesPanel1.add(use); speciesPanel2.add(specs); speciesPanel2.add(color); speciesPanel2.add(shape); speciesPanel3.add(connectedLabel); speciesPanel3.add(visibleLabel); speciesPanel3.add(filledLabel); final HashMap<String, Shape> shapey = this.shapes; final HashMap<String, Paint> colory = this.colors; for (int i = 0; i < graphSpecies.size() - 1; i++) { JCheckBox temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { String s = series.get(i).getText(); ((JCheckBox) e.getSource()).setSelected(false); int[] cols = new int[34]; int[] shaps = new int[10]; for (int k = 0; k < boxes.size(); k++) { if (boxes.get(k).isSelected()) { if (colorsCombo.get(k).getSelectedItem().equals("Red")) { cols[0]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) { cols[1]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green")) { cols[2]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) { cols[3]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) { cols[4]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) { cols[5]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) { cols[6]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Gray (Dark)")) { cols[7]++; } else if (colorsCombo.get(k).getSelectedItem() .equals("Red (Dark)")) { cols[8]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Dark)")) { cols[9]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Dark)")) { cols[10]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Dark)")) { cols[11]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Dark)")) { cols[12]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Dark)")) { cols[13]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Black")) { cols[14]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Red ")) { cols[15]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Blue ")) { cols[16]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Green ")) { cols[17]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Yellow ")) { cols[18]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Magenta ")) { cols[19]++; } else if (colorsCombo.get(k).getSelectedItem().equals("Cyan ")) { cols[20]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Gray (Light)")) { cols[21]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Extra Dark)")) { cols[22]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Extra Dark)")) { cols[24]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Red (Light)")) { cols[28]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Blue (Light)")) { cols[29]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Green (Light)")) { cols[30]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Yellow (Light)")) { cols[31]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Magenta (Light)")) { cols[32]++; } else if (colorsCombo.get(k).getSelectedItem().equals( "Cyan (Light)")) { cols[33]++; } if (shapesCombo.get(k).getSelectedItem().equals("Square")) { shaps[0]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) { shaps[1]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) { shaps[2]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) { shaps[3]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Circle (Half)")) { shaps[6]++; } else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) { shaps[7]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (shapesCombo.get(k).getSelectedItem().equals( "Arrow (Backwards)")) { shaps[9]++; } } } for (GraphSpecies graph : graphed) { if (graph.getShapeAndPaint().getPaintName().equals("Red")) { cols[0]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) { cols[1]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green")) { cols[2]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) { cols[3]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) { cols[4]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) { cols[5]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) { cols[6]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Gray (Dark)")) { cols[7]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) { cols[8]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Blue (Dark)")) { cols[9]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Dark)")) { cols[10]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Dark)")) { cols[11]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Dark)")) { cols[12]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Cyan (Dark)")) { cols[13]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Black")) { cols[14]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Red ")) { cols[15]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Blue ")) { cols[16]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Green ")) { cols[17]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Yellow ")) { cols[18]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Magenta ")) { cols[19]++; } else if (graph.getShapeAndPaint().getPaintName().equals("Cyan ")) { cols[20]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Gray (Light)")) { cols[21]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Red (Extra Dark)")) { cols[22]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Extra Dark)")) { cols[23]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Extra Dark)")) { cols[24]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Extra Dark)")) { cols[25]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Extra Dark)")) { cols[26]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Extra Dark)")) { cols[27]++; } else if (graph.getShapeAndPaint().getPaintName() .equals("Red (Light)")) { cols[28]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Blue (Light)")) { cols[29]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Green (Light)")) { cols[30]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Yellow (Light)")) { cols[31]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Magenta (Light)")) { cols[32]++; } else if (graph.getShapeAndPaint().getPaintName().equals( "Cyan (Light)")) { cols[33]++; } if (graph.getShapeAndPaint().getShapeName().equals("Square")) { shaps[0]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) { shaps[1]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) { shaps[2]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) { shaps[3]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Horizontal)")) { shaps[4]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Triangle (Upside Down)")) { shaps[5]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Circle (Half)")) { shaps[6]++; } else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) { shaps[7]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Rectangle (Vertical)")) { shaps[8]++; } else if (graph.getShapeAndPaint().getShapeName().equals( "Arrow (Backwards)")) { shaps[9]++; } } ((JCheckBox) e.getSource()).setSelected(true); series.get(i).setText(s); int colorSet = 0; for (int j = 1; j < cols.length; j++) { if (cols[j] < cols[colorSet]) { colorSet = j; } } int shapeSet = 0; for (int j = 1; j < shaps.length; j++) { if (shaps[j] < shaps[shapeSet]) { shapeSet = j; } } DefaultDrawingSupplier draw = new DefaultDrawingSupplier(); for (int j = 0; j < colorSet; j++) { draw.getNextPaint(); } Paint paint = draw.getNextPaint(); Object[] set = colory.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (paint == colory.get(set[j])) { colorsCombo.get(i).setSelectedItem(set[j]); } } for (int j = 0; j < shapeSet; j++) { draw.getNextShape(); } Shape shape = draw.getNextShape(); set = shapey.keySet().toArray(); for (int j = 0; j < set.length; j++) { if (shape == shapey.get(set[j])) { shapesCombo.get(i).setSelectedItem(set[j]); } } boolean allChecked = true; for (JCheckBox temp : boxes) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { use.setSelected(true); } graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i) .getSelectedItem()), colory.get(colorsCombo.get(i) .getSelectedItem()), filled.get(i).isSelected(), visible.get(i) .isSelected(), connected.get(i).isSelected(), selected, series.get( i).getText().trim(), i, directory)); } else { use.setSelected(false); colorsCombo.get(i).setSelectedIndex(0); shapesCombo.get(i).setSelectedIndex(0); ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { remove.add(g); } } for (GraphSpecies g : remove) { graphed.remove(g); } } } }); boxes.add(temp); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : visible) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { visibleLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(true); } } } else { visibleLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setVisible(false); } } } } }); visible.add(temp); visible.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : filled) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { filledLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(true); } } } else { filledLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setFilled(false); } } } } }); filled.add(temp); filled.get(i).setSelected(true); temp = new JCheckBox(); temp.setActionCommand("" + i); temp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); if (((JCheckBox) e.getSource()).isSelected()) { boolean allChecked = true; for (JCheckBox temp : connected) { if (!temp.isSelected()) { allChecked = false; } } if (allChecked) { connectedLabel.setSelected(true); } for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(true); } } } else { connectedLabel.setSelected(false); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setConnected(false); } } } } }); connected.add(temp); connected.get(i).setSelected(true); JTextField seriesName = new JTextField(graphSpecies.get(i + 1)); seriesName.setName("" + i); seriesName.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyReleased(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } public void keyTyped(KeyEvent e) { int i = Integer.parseInt(((JTextField) e.getSource()).getName()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setSpecies(((JTextField) e.getSource()).getText()); } } } }); series.add(seriesName); Object[] col = this.colors.keySet().toArray(); Arrays.sort(col); Object[] shap = this.shapes.keySet().toArray(); Arrays.sort(shap); JComboBox colBox = new JComboBox(col); colBox.setActionCommand("" + i); colBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); JComboBox shapBox = new JComboBox(shap); shapBox.setActionCommand("" + i); shapBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = Integer.parseInt(e.getActionCommand()); for (GraphSpecies g : graphed) { if (g.getRunNumber().equals(selected) && g.getNumber() == i && g.getDirectory().equals(directory)) { g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem()); } } } }); colorsCombo.add(colBox); shapesCombo.add(shapBox); speciesPanel1.add(boxes.get(i)); speciesPanel2.add(series.get(i)); speciesPanel2.add(colorsCombo.get(i)); speciesPanel2.add(shapesCombo.get(i)); speciesPanel3.add(connected.get(i)); speciesPanel3.add(visible.get(i)); speciesPanel3.add(filled.get(i)); } JPanel speciesPanel = new JPanel(new BorderLayout()); speciesPanel.add(speciesPanel1, "West"); speciesPanel.add(speciesPanel2, "Center"); speciesPanel.add(speciesPanel3, "East"); return speciesPanel; } private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) { chart = ChartFactory.createXYLineChart(title, x, y, dataset, PlotOrientation.VERTICAL, true, true, false); chart.addProgressListener(this); ChartPanel graph = new ChartPanel(chart); if (graphed.isEmpty()) { graph.setLayout(new GridLayout(1, 1)); JLabel edit = new JLabel("Click here to create graph"); Font font = edit.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); edit.setFont(font); edit.setHorizontalAlignment(SwingConstants.CENTER); graph.add(edit); } graph.addMouseListener(this); JPanel ButtonHolder = new JPanel(); save = new JButton("Save"); exportJPeg = new JButton("Export As JPEG"); exportPng = new JButton("Export As PNG"); exportPdf = new JButton("Export As PDF"); exportEps = new JButton("Export As EPS"); exportSvg = new JButton("Export As SVG"); save.addActionListener(this); exportJPeg.addActionListener(this); exportPng.addActionListener(this); exportPdf.addActionListener(this); exportEps.addActionListener(this); exportSvg.addActionListener(this); ButtonHolder.add(save); ButtonHolder.add(exportJPeg); ButtonHolder.add(exportPng); ButtonHolder.add(exportPdf); ButtonHolder.add(exportEps); ButtonHolder.add(exportSvg); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ButtonHolder, null); splitPane.setDividerSize(0); this.removeAll(); this.setLayout(new BorderLayout()); this.add(graph, "Center"); this.add(splitPane, "South"); this.revalidate(); } /** * This method saves the graph as a jpeg or as a png file. */ public void export(int output) { try { int width = -1; int height = -1; JPanel sizePanel = new JPanel(new GridLayout(2, 2)); JLabel heightLabel = new JLabel("Desired pixel height:"); JLabel widthLabel = new JLabel("Desired pixel width:"); JTextField heightField = new JTextField("400"); JTextField widthField = new JTextField("650"); sizePanel.add(widthLabel); sizePanel.add(widthField); sizePanel.add(heightLabel); sizePanel.add(heightField); Object[] options2 = { "Export", "Cancel" }; int value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); if (value == JOptionPane.YES_OPTION) { while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1)) try { width = Integer.parseInt(widthField.getText().trim()); height = Integer.parseInt(heightField.getText().trim()); if (width < 1 || height < 1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } catch (Exception e2) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Width and height must be positive integers!", "Error", JOptionPane.ERROR_MESSAGE); width = -1; height = -1; value = JOptionPane.showOptionDialog(biomodelsim.frame(), sizePanel, "Enter Size Of File", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]); } } if (value == JOptionPane.NO_OPTION) { return; } File file; if (savedPics != null) { file = new File(savedPics); } else { file = null; } String filename = Buttons.browse(biomodelsim.frame(), file, null, JFileChooser.FILES_ONLY, "Save"); if (!filename.equals("")) { if (output == 0) { if (filename.length() < 4) { filename += ".jpg"; } else if (filename.length() < 5 && !filename.substring((filename.length() - 4), filename.length()) .equals(".jpg")) { filename += ".jpg"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".jpg") || filename.substring((filename.length() - 5), filename.length()) .equals(".jpeg")) { } else { filename += ".jpg"; } } } else if (output == 1) { if (filename.length() < 4) { filename += ".png"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".png")) { } else { filename += ".png"; } } } else if (output == 2) { if (filename.length() < 4) { filename += ".pdf"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".pdf")) { } else { filename += ".pdf"; } } } else if (output == 3) { if (filename.length() < 4) { filename += ".eps"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".eps")) { } else { filename += ".eps"; } } } else if (output == 4) { if (filename.length() < 4) { filename += ".svg"; } else { if (filename.substring((filename.length() - 4), filename.length()).equals( ".svg")) { } else { filename += ".svg"; } } } file = new File(filename); if (file.exists()) { Object[] options = { "Overwrite", "Cancel" }; value = JOptionPane.showOptionDialog(biomodelsim.frame(), "File already exists." + " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation .getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator.setSVGCanvasSize(new Dimension(width, height)); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); } savedPics = filename; } } else { if (output == 0) { ChartUtilities.saveChartAsJPEG(file, chart, width, height); } else if (output == 1) { ChartUtilities.saveChartAsPNG(file, chart, width, height); } else if (output == 2) { Rectangle pagesize = new Rectangle(width, height); Document document = new Document(pagesize, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream( file)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(width, height); Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper()); chart.draw(g2, new java.awt.Rectangle(width, height)); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); } else if (output == 3) { Graphics2D g = new EpsGraphics2D(); chart.draw(g, new java.awt.Rectangle(width, height)); Writer out = new FileWriter(file); out.write(g.toString()); out.close(); } else if (output == 4) { DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); chart.draw(svgGenerator, new java.awt.Rectangle(width, height)); boolean useCSS = true; Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); } savedPics = filename; } } } catch (Exception e1) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Export File!", "Error", JOptionPane.ERROR_MESSAGE); } } private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile, String fileStem, int choice, String directory) { InputStream input; ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>(); try { input = new BufferedInputStream(new ProgressMonitorInputStream(biomodelsim.frame(), "Reading Reb2sac Output Data From " + new File(startFile).getName(), new FileInputStream(new File(startFile)))); boolean reading = true; char cha; int readCount = 0; while (reading) { String word = ""; boolean readWord = true; while (readWord) { int read = input.read(); readCount++; if (read == -1) { reading = false; readWord = false; } cha = (char) read; if (Character.isWhitespace(cha)) { input.mark(3); char next = (char) input.read(); char after = (char) input.read(); String check = "" + next + after; if (word.equals("") || word.equals("0") || check.equals("0,")) { readWord = false; } else { word += cha; } input.reset(); } else if (cha == ',' || cha == ':' || cha == ';' || cha == '!' || cha == '?' || cha == '\"' || cha == '\'' || cha == '(' || cha == ')' || cha == '{' || cha == '}' || cha == '[' || cha == ']' || cha == '<' || cha == '>' || cha == '*' || cha == '=' || cha == '#') { readWord = false; } else if (read != -1) { word += cha; } } int getNum; try { getNum = Integer.parseInt(word); if (getNum == 0) { boolean first = true; int runsToMake = 1; String[] findNum = startFile.split(File.separator); String search = findNum[findNum.length - 1]; int firstOne = Integer.parseInt(search.substring(4, search.length() - 4)); if (directory == null) { for (String f : new File(outDir).list()) { if (f.contains(fileStem)) { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f .length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } } } else { for (String f : new File(outDir + File.separator + directory).list()) { if (f.contains(fileStem)) { int tempNum = Integer.parseInt(f.substring(fileStem.length(), f .length() - 4)); if (tempNum > runsToMake) { runsToMake = tempNum; } } } } for (int i = 0; i < graphSpecies.size(); i++) { average.add(new ArrayList<Double>()); variance.add(new ArrayList<Double>()); } (average.get(0)).add(0.0); (variance.get(0)).add(0.0); int count = 0; int skip = firstOne; for (int j = 0; j < runsToMake; j++) { int counter = 1; if (!first) { if (firstOne != 1) { j--; firstOne = 1; } boolean loop = true; while (loop && j < runsToMake && (j + 1) != skip) { if (directory == null) { if (new File(outDir + File.separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { input = new BufferedInputStream( new ProgressMonitorInputStream( biomodelsim.frame(), "Reading Reb2sac Output Data From " + new File( outDir + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8)) .getName(), new FileInputStream( new File( outDir + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))))); for (int i = 0; i < readCount; i++) { input.read(); } loop = false; count++; } else { j++; } } else { if (new File(outDir + File.separator + directory + File.separator + fileStem + (j + 1) + "." + printer_id.substring(0, printer_id.length() - 8)) .exists()) { input = new BufferedInputStream( new ProgressMonitorInputStream( biomodelsim.frame(), "Reading Reb2sac Output Data From " + new File( outDir + File.separator + directory + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8)) .getName(), new FileInputStream( new File( outDir + File.separator + directory + File.separator + fileStem + (j + 1) + "." + printer_id .substring( 0, printer_id .length() - 8))))); for (int i = 0; i < readCount; i++) { input.read(); } loop = false; count++; } else { j++; } } } } reading = true; while (reading) { word = ""; readWord = true; int read; while (readWord) { read = input.read(); cha = (char) read; while (!Character.isWhitespace(cha) && cha != ',' && cha != ':' && cha != ';' && cha != '!' && cha != '?' && cha != '\"' && cha != '\'' && cha != '(' && cha != ')' && cha != '{' && cha != '}' && cha != '[' && cha != ']' && cha != '<' && cha != '>' && cha != '_' && cha != '*' && cha != '=' && read != -1) { word += cha; read = input.read(); cha = (char) read; } if (read == -1) { reading = false; first = false; } readWord = false; } int insert; if (!word.equals("")) { if (first) { if (counter < graphSpecies.size()) { insert = counter; (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)) .add(Double.parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } else { insert = counter % graphSpecies.size(); (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)) .add(Double.parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } } else { if (counter < graphSpecies.size()) { insert = counter; try { double old = (average.get(insert)).get(insert / graphSpecies.size()); (average.get(insert)) .set( insert / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); double newMean = (average.get(insert)).get(insert / graphSpecies.size()); if (insert == 0) { (variance.get(insert)) .set( insert / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); } else { double vary = (((count - 1) * (variance .get(insert)).get(insert / graphSpecies.size())) + (Double .parseDouble(word) - newMean) * (Double.parseDouble(word) - old)) / count; (variance.get(insert)).set(insert / graphSpecies.size(), vary); } } catch (Exception e2) { (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)).add(Double .parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } } else { insert = counter % graphSpecies.size(); try { double old = (average.get(insert)).get(counter / graphSpecies.size()); (average.get(insert)) .set( counter / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); double newMean = (average.get(insert)).get(counter / graphSpecies.size()); if (insert == 0) { (variance.get(insert)) .set( counter / graphSpecies.size(), old + ((Double .parseDouble(word) - old) / (count + 1))); } else { double vary = (((count - 1) * (variance .get(insert)).get(counter / graphSpecies.size())) + (Double .parseDouble(word) - newMean) * (Double.parseDouble(word) - old)) / count; (variance.get(insert)).set(counter / graphSpecies.size(), vary); } } catch (Exception e2) { (average.get(insert)).add(Double.parseDouble(word)); if (insert == 0) { (variance.get(insert)).add(Double .parseDouble(word)); } else { (variance.get(insert)).add(0.0); } } } } counter++; } } } } } catch (Exception e1) { } } deviation = new ArrayList<ArrayList<Double>>(); for (int i = 0; i < variance.size(); i++) { deviation.add(new ArrayList<Double>()); for (int j = 0; j < variance.get(i).size(); j++) { deviation.get(i).add(variance.get(i).get(j)); } } for (int i = 1; i < deviation.size(); i++) { for (int j = 0; j < deviation.get(i).size(); j++) { deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j))); } } } catch (Exception e) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Error Reading Data!" + "\nThere was an error reading the simulation output data.", "Error Reading Data", JOptionPane.ERROR_MESSAGE); } if (choice == 0) { return average; } else if (choice == 1) { return variance; } else { return deviation; } } public void save() { Properties graph = new Properties(); graph.setProperty("title", chart.getTitle().getText()); graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel()); graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel()); graph.setProperty("x.min", XMin.getText()); graph.setProperty("x.max", XMax.getText()); graph.setProperty("x.scale", XScale.getText()); graph.setProperty("y.min", YMin.getText()); graph.setProperty("y.max", YMax.getText()); graph.setProperty("y.scale", YScale.getText()); graph.setProperty("auto.resize", "" + resize.isSelected()); for (int i = 0; i < graphed.size(); i++) { graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected()); graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled()); graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber()); graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber()); graph.setProperty("species.name." + i, graphed.get(i).getSpecies()); graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible()); graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint() .getPaintName()); graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint() .getShapeName()); graph.setProperty("species.directory." + i, graphed.get(i).getDirectory()); } try { graph.store(new FileOutputStream(new File(outDir + File.separator + graphName)), "Graph Data"); log.addText("Creating graph file:\n" + outDir + File.separator + graphName + "\n"); } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Save Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } private void open(String filename) { Properties graph = new Properties(); try { graph.load(new FileInputStream(new File(filename))); XMin.setText(graph.getProperty("x.min")); XMax.setText(graph.getProperty("x.max")); XScale.setText(graph.getProperty("x.scale")); YMin.setText(graph.getProperty("y.min")); YMax.setText(graph.getProperty("y.max")); YScale.setText(graph.getProperty("y.scale")); chart.setTitle(graph.getProperty("title")); chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis")); chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis")); if (graph.getProperty("auto.resize").equals("true")) { resize.setSelected(true); } else { resize.setSelected(false); } int next = 0; while (graph.containsKey("species.name." + next)) { boolean connected, filled, visible; if (graph.getProperty("species.connected." + next).equals("true")) { connected = true; } else { connected = false; } if (graph.getProperty("species.filled." + next).equals("true")) { filled = true; } else { filled = false; } if (graph.getProperty("species.visible." + next).equals("true")) { visible = true; } else { visible = false; } graphed.add(new GraphSpecies( shapes.get(graph.getProperty("species.shape." + next)), colors.get(graph .getProperty("species.paint." + next)), filled, visible, connected, graph.getProperty("species.run.number." + next), graph .getProperty("species.name." + next), Integer.parseInt(graph .getProperty("species.number." + next)), graph .getProperty("species.directory." + next))); next++; } refresh(); } catch (Exception except) { JOptionPane.showMessageDialog(biomodelsim.frame(), "Unable To Load Graph!", "Error", JOptionPane.ERROR_MESSAGE); } } public void refresh() { double minY = 0; double maxY = 0; double scaleY = 0; double minX = 0; double maxX = 0; double scaleX = 0; try { minY = Double.parseDouble(YMin.getText().trim()); maxY = Double.parseDouble(YMax.getText().trim()); scaleY = Double.parseDouble(YScale.getText().trim()); minX = Double.parseDouble(XMin.getText().trim()); maxX = Double.parseDouble(XMax.getText().trim()); scaleX = Double.parseDouble(XScale.getText().trim()); NumberFormat num = NumberFormat.getInstance(); num.setMaximumFractionDigits(4); num.setGroupingUsed(false); minY = Double.parseDouble(num.format(minY)); maxY = Double.parseDouble(num.format(maxY)); scaleY = Double.parseDouble(num.format(scaleY)); minX = Double.parseDouble(num.format(minX)); maxX = Double.parseDouble(num.format(maxX)); scaleX = Double.parseDouble(num.format(scaleX)); } catch (Exception e1) { } ArrayList<XYSeries> graphData = new ArrayList<XYSeries>(); XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int thisOne = -1; for (int i = 1; i < graphed.size(); i++) { GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) && (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) { graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j, index); } ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>(); for (GraphSpecies g : graphed) { if (g.getDirectory().equals("")) { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir).list()) { if (s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (ableToGraph) { int nextOne = 1; while (!new File(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim.frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber().toLowerCase(), null); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } } else { thisOne++; rend.setSeriesVisible(thisOne, true); rend.setSeriesLinesVisible(thisOne, g.getConnected()); rend.setSeriesShapesFilled(thisOne, g.getFilled()); rend.setSeriesShapesVisible(thisOne, g.getVisible()); rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint()); rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance") && !g.getRunNumber().equals("Standard Deviation")) { if (new File(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + g.getRunNumber() + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber(), g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph = false; try { for (String s : new File(outDir + File.separator + g.getDirectory()).list()) { if (s.substring(0, 4).equals("run-")) { ableToGraph = true; } } } catch (Exception e) { ableToGraph = false; } if (ableToGraph) { int nextOne = 1; while (!new File(outDir + File.separator + g.getDirectory() + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8)).exists()) { nextOne++; } readGraphSpecies(outDir + File.separator + g.getDirectory() + File.separator + "run-" + nextOne + "." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame()); ArrayList<ArrayList<Double>> data = readData(outDir + File.separator + g.getDirectory() + File.separator + "run-1." + printer_id.substring(0, printer_id.length() - 8), biomodelsim .frame(), chart.getXYPlot().getRangeAxis().getLabel(), g .getRunNumber().toLowerCase(), g.getDirectory()); for (int i = 2; i < graphSpecies.size(); i++) { String index = graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index); data.set(j, index2); } if (g.getNumber() + 1 < graphSpecies.size()) { graphData.add(new XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i = 0; i < (data.get(0)).size(); i++) { graphData.get(graphData.size() - 1).add((data.get(0)).get(i), (data.get(g.getNumber() + 1)).get(i)); } } } else { unableToGraph.add(g); thisOne--; } } else { unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g : unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < graphData.size(); i++) { dataset.addSeries(graphData.get(i)); } fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(), chart .getXYPlot().getRangeAxis().getLabel(), dataset); chart.getXYPlot().setRenderer(rend); XYPlot plot = chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); } else { NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY); axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoTickUnitSelection(false); axis.setRange(minX, maxX); axis.setTickUnit(new NumberTickUnit(scaleX)); } } private class ShapeAndPaint { private Shape shape; private Paint paint; private ShapeAndPaint(Shape s, Paint p) { shape = s; paint = p; } private Shape getShape() { return shape; } private Paint getPaint() { return paint; } private String getShapeName() { Object[] set = shapes.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (shape == shapes.get(set[i])) { return (String) set[i]; } } return "Unknown Shape"; } private String getPaintName() { Object[] set = colors.keySet().toArray(); for (int i = 0; i < set.length; i++) { if (paint == colors.get(set[i])) { return (String) set[i]; } } return "Unknown Color"; } public void setPaint(String paint) { this.paint = colors.get(paint); } public void setShape(String shape) { this.shape = shapes.get(shape); } } private class GraphSpecies { private ShapeAndPaint sP; private boolean filled, visible, connected; private String runNumber, species, directory; private int number; private GraphSpecies(Shape s, Paint p, boolean filled, boolean visible, boolean connected, String runNumber, String species, int number, String directory) { sP = new ShapeAndPaint(s, p); this.filled = filled; this.visible = visible; this.connected = connected; this.runNumber = runNumber; this.species = species; this.number = number; this.directory = directory; } private void setSpecies(String species) { this.species = species; } private void setPaint(String paint) { sP.setPaint(paint); } private void setShape(String shape) { sP.setShape(shape); } private void setVisible(boolean b) { visible = b; } private void setFilled(boolean b) { filled = b; } private void setConnected(boolean b) { connected = b; } private int getNumber() { return number; } private String getSpecies() { return species; } private ShapeAndPaint getShapeAndPaint() { return sP; } private boolean getFilled() { return filled; } private boolean getVisible() { return visible; } private boolean getConnected() { return connected; } private String getRunNumber() { return runNumber; } private String getDirectory() { return directory; } } public void setDirectory(String newDirectory) { outDir = newDirectory; } public void setGraphName(String graphName) { this.graphName = graphName; } }
Fixed a small bug
gui/src/graph/Graph.java
Fixed a small bug
<ide><path>ui/src/graph/Graph.java <ide> boolean ableToGraph = false; <ide> try { <ide> for (String s : new File(outDir).list()) { <del> if (s.substring(0, 4).equals("run-")) { <add> if (s.length() > 3 && s.substring(0, 4).equals("run-")) { <ide> ableToGraph = true; <ide> } <ide> } <ide> try { <ide> for (String s : new File(outDir + File.separator <ide> + g.getDirectory()).list()) { <del> if (s.substring(0, 4).equals("run-")) { <add> if (s.length() > 3 && s.substring(0, 4).equals("run-")) { <ide> ableToGraph = true; <ide> } <ide> } <ide> boolean ableToGraph = false; <ide> try { <ide> for (String s : new File(outDir).list()) { <del> if (s.substring(0, 4).equals("run-")) { <add> if (s.length() > 3 && s.substring(0, 4).equals("run-")) { <ide> ableToGraph = true; <ide> } <ide> } <ide> boolean ableToGraph = false; <ide> try { <ide> for (String s : new File(outDir + File.separator + g.getDirectory()).list()) { <del> if (s.substring(0, 4).equals("run-")) { <add> if (s.length() > 3 && s.substring(0, 4).equals("run-")) { <ide> ableToGraph = true; <ide> } <ide> }
Java
apache-2.0
error: pathspec 'utils/custom-view/WrapListView.java' did not match any file(s) known to git
9207577ee2e7187609ade7f1ffaf143b1f89e650
1
layerlre/Android-Utility-Class
package utils; import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; /** * Created by layer on 9/8/2558. */ public class WrapListView extends ListView{ public WrapListView(Context context, AttributeSet attrs) { super(context, attrs); } public WrapListView(Context context) { super(context); } public WrapListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
utils/custom-view/WrapListView.java
update customview dir
utils/custom-view/WrapListView.java
update customview dir
<ide><path>tils/custom-view/WrapListView.java <add>package utils; <add> <add>import android.content.Context; <add>import android.util.AttributeSet; <add>import android.widget.ListView; <add> <add>/** <add> * Created by layer on 9/8/2558. <add> */ <add>public class WrapListView extends ListView{ <add> public WrapListView(Context context, AttributeSet attrs) { <add> super(context, attrs); <add> } <add> <add> public WrapListView(Context context) { <add> super(context); <add> } <add> <add> public WrapListView(Context context, AttributeSet attrs, int defStyle) { <add> super(context, attrs, defStyle); <add> } <add> <add> @Override <add> public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { <add> int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, <add> MeasureSpec.AT_MOST); <add> super.onMeasure(widthMeasureSpec, expandSpec); <add> } <add>}
Java
apache-2.0
6e252aef6a43a71c49b22b27bc61c2f1ddcc6e70
0
lucilecoutouly/heroic,spotify/heroic,OdenTech/heroic,lucilecoutouly/heroic,spotify/heroic,lucilecoutouly/heroic,zfrank/heroic,spotify/heroic,spotify/heroic
/* * Copyright (c) 2015 Spotify AB. * * 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.spotify.heroic.profile; import com.google.common.collect.ImmutableList; import com.spotify.heroic.ExtraParameters; import com.spotify.heroic.HeroicConfig; import com.spotify.heroic.ParameterSpecification; import com.spotify.heroic.analytics.bigtable.BigtableAnalyticsModule; import com.spotify.heroic.metric.bigtable.credentials.ComputeEngineCredentialsBuilder; import com.spotify.heroic.metric.bigtable.credentials.DefaultCredentialsBuilder; import com.spotify.heroic.metric.bigtable.credentials.JsonCredentialsBuilder; import com.spotify.heroic.metric.bigtable.credentials.ServiceAccountCredentialsBuilder; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.spotify.heroic.ParameterSpecification.parameter; public class BigtableAnalyticsProfile extends HeroicProfileBase { public static final String DEFAULT_CREDENTIALS = "default"; @Override public HeroicConfig.Builder build(final ExtraParameters params) throws Exception { final BigtableAnalyticsModule.Builder module = BigtableAnalyticsModule.builder(); params.get("project").map(module::project); params.get("instance").map(module::instance); final String credentials = params.get("credential").orElse(DEFAULT_CREDENTIALS); switch (credentials) { case "json": final JsonCredentialsBuilder.Builder j = JsonCredentialsBuilder.builder(); params.get("json").map(Paths::get).ifPresent(j::path); module.credentials(j.build()); break; case "service-account": final ServiceAccountCredentialsBuilder.Builder sa = ServiceAccountCredentialsBuilder.builder(); params.get("serviceAccount").ifPresent(sa::serviceAccount); params.get("keyFile").ifPresent(sa::keyFile); module.credentials(sa.build()); break; case "compute-engine": module.credentials(new ComputeEngineCredentialsBuilder()); break; case "default": module.credentials(new DefaultCredentialsBuilder()); break; default: throw new IllegalArgumentException( "bigtable-analytics.credentials: invalid value: " + credentials); } return HeroicConfig.builder().analytics(module); } @Override public String description() { return "Configures an analytics backend for Bigtable"; } @Override public Optional<String> scope() { return Optional.of("bigtable-analytics"); } @Override public List<ParameterSpecification> options() { // @formatter:off return ImmutableList.of( parameter("configure", "If set, will cause the cluster to be automatically " + "configured"), parameter("project", "Bigtable project to use", "<project>"), parameter("instance", "Bigtable instance to use", "<instance>"), parameter("credentials", "Credentials implementation to use, must be one of:" + " default, compute-engine, json, service-account", "<credentials>"), parameter("json", "Json file to use when using json credentials", "<file>"), parameter("serviceAccount", "Service account to use when using " + "service-account credentials", "<account>"), parameter("keyFile", "Key file to use when using service-account " + "credentials", "<file>") ); // @formatter:on } }
heroic-all/src/main/java/com/spotify/heroic/profile/BigtableAnalyticsProfile.java
/* * Copyright (c) 2015 Spotify AB. * * 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.spotify.heroic.profile; import com.google.common.collect.ImmutableList; import com.spotify.heroic.ExtraParameters; import com.spotify.heroic.HeroicConfig; import com.spotify.heroic.ParameterSpecification; import com.spotify.heroic.analytics.bigtable.BigtableAnalyticsModule; import com.spotify.heroic.metric.bigtable.credentials.ComputeEngineCredentialsBuilder; import com.spotify.heroic.metric.bigtable.credentials.JsonCredentialsBuilder; import com.spotify.heroic.metric.bigtable.credentials.ServiceAccountCredentialsBuilder; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.spotify.heroic.ParameterSpecification.parameter; public class BigtableAnalyticsProfile extends HeroicProfileBase { public static final String DEFAULT_CREDENTIALS = "json"; @Override public HeroicConfig.Builder build(final ExtraParameters params) throws Exception { final BigtableAnalyticsModule.Builder module = BigtableAnalyticsModule.builder(); params.get("project").map(module::project); params.get("instance").map(module::instance); final String credentials = params.get("credential").orElse(DEFAULT_CREDENTIALS); switch (credentials) { case "json": final JsonCredentialsBuilder.Builder j = JsonCredentialsBuilder.builder(); params.get("json").map(Paths::get).ifPresent(j::path); module.credentials(j.build()); break; case "service-account": final ServiceAccountCredentialsBuilder.Builder sa = ServiceAccountCredentialsBuilder.builder(); params.get("serviceAccount").ifPresent(sa::serviceAccount); params.get("keyFile").ifPresent(sa::keyFile); module.credentials(sa.build()); break; case "compute-engine": module.credentials(new ComputeEngineCredentialsBuilder()); break; default: throw new IllegalArgumentException( "bigtable-analytics.credentials: invalid value: " + credentials); } return HeroicConfig.builder().analytics(module); } @Override public String description() { return "Configures an analytics backend for Bigtable"; } @Override public Optional<String> scope() { return Optional.of("bigtable-analytics"); } @Override public List<ParameterSpecification> options() { // @formatter:off return ImmutableList.of( parameter("configure", "If set, will cause the cluster to be " + "automatically configured"), parameter("project", "Bigtable project to use", "<project>"), parameter("instance", "Bigtable instance to use", "<instance>"), parameter("credentials", "Credentials implementation to use, must " + "be one of: compute-engine (default), json, service-account", "<credentials>"), parameter("json", "Json file to use when using json credentials", "<file>"), parameter("serviceAccount", "Service account to use when using " + "service-account credentials", "<account>"), parameter("keyFile", "Key file to use when using service-account " + "credentials", "<file>") ); // @formatter:on } }
[all] add credentials=default to BigtableAnalyticsProfile Use it as default.
heroic-all/src/main/java/com/spotify/heroic/profile/BigtableAnalyticsProfile.java
[all] add credentials=default to BigtableAnalyticsProfile
<ide><path>eroic-all/src/main/java/com/spotify/heroic/profile/BigtableAnalyticsProfile.java <ide> import com.spotify.heroic.ParameterSpecification; <ide> import com.spotify.heroic.analytics.bigtable.BigtableAnalyticsModule; <ide> import com.spotify.heroic.metric.bigtable.credentials.ComputeEngineCredentialsBuilder; <add>import com.spotify.heroic.metric.bigtable.credentials.DefaultCredentialsBuilder; <ide> import com.spotify.heroic.metric.bigtable.credentials.JsonCredentialsBuilder; <ide> import com.spotify.heroic.metric.bigtable.credentials.ServiceAccountCredentialsBuilder; <ide> <ide> import static com.spotify.heroic.ParameterSpecification.parameter; <ide> <ide> public class BigtableAnalyticsProfile extends HeroicProfileBase { <del> public static final String DEFAULT_CREDENTIALS = "json"; <add> public static final String DEFAULT_CREDENTIALS = "default"; <ide> <ide> @Override <ide> public HeroicConfig.Builder build(final ExtraParameters params) throws Exception { <ide> case "compute-engine": <ide> module.credentials(new ComputeEngineCredentialsBuilder()); <ide> break; <add> case "default": <add> module.credentials(new DefaultCredentialsBuilder()); <add> break; <ide> default: <ide> throw new IllegalArgumentException( <ide> "bigtable-analytics.credentials: invalid value: " + credentials); <ide> public List<ParameterSpecification> options() { <ide> // @formatter:off <ide> return ImmutableList.of( <del> parameter("configure", "If set, will cause the cluster to be " + <del> "automatically configured"), <add> parameter("configure", "If set, will cause the cluster to be automatically " + <add> "configured"), <ide> parameter("project", "Bigtable project to use", "<project>"), <ide> parameter("instance", "Bigtable instance to use", "<instance>"), <del> parameter("credentials", "Credentials implementation to use, must " + <del> "be one of: compute-engine (default), json, service-account", "<credentials>"), <del> parameter("json", "Json file to use when using json credentials", <del> "<file>"), <add> parameter("credentials", "Credentials implementation to use, must be one of:" + <add> " default, compute-engine, json, service-account", "<credentials>"), <add> parameter("json", "Json file to use when using json credentials", "<file>"), <ide> parameter("serviceAccount", "Service account to use when using " + <ide> "service-account credentials", "<account>"), <ide> parameter("keyFile", "Key file to use when using service-account " +
Java
apache-2.0
38a32b7d3c6ddfd7d2f364db8cc2b33961c4c911
0
apache/jackrabbit,apache/jackrabbit,apache/jackrabbit
/* * $Id$ * * Copyright 1997-2005 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package org.apache.jackrabbit.jcr2spi.hierarchy; import org.apache.jackrabbit.jcr2spi.state.ItemState; import org.apache.jackrabbit.jcr2spi.state.ItemStateException; import org.apache.jackrabbit.jcr2spi.state.NoSuchItemStateException; import org.apache.jackrabbit.jcr2spi.state.TransientItemStateFactory; import org.apache.jackrabbit.name.Path; import org.apache.jackrabbit.spi.ItemId; import org.apache.jackrabbit.spi.IdFactory; import org.apache.jackrabbit.spi.NodeId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.ItemNotFoundException; /** * <code>HierarchyManagerImpl</code> implements the <code>HierarchyManager</code> * interface. */ public class HierarchyManagerImpl implements HierarchyManager { private static Logger log = LoggerFactory.getLogger(org.apache.jackrabbit.jcr2spi.hierarchy.HierarchyManagerImpl.class); private final NodeEntry rootEntry; private final UniqueIdResolver uniqueIdResolver; private final IdFactory idFactory; public HierarchyManagerImpl(TransientItemStateFactory isf, IdFactory idFactory) { uniqueIdResolver = new UniqueIdResolver(isf); rootEntry = new EntryFactory(isf, idFactory, uniqueIdResolver).createRootEntry(); this.idFactory = idFactory; } //---------------------------------------------------< HierarchyManager >--- /** * @see HierarchyManager#dispose() */ public void dispose() { uniqueIdResolver.dispose(); } /** * @see HierarchyManager#getRootEntry() */ public NodeEntry getRootEntry() { return rootEntry; } /** * @see HierarchyManager#lookup(ItemId) */ public HierarchyEntry lookup(ItemId itemId) { String uniqueID = itemId.getUniqueID(); if (uniqueID == null) { return PathResolver.lookup(rootEntry, itemId.getPath()); } else { NodeEntry nEntry = uniqueIdResolver.lookup(idFactory.createNodeId(uniqueID)); if (itemId.getPath() == null) { return nEntry; } else { return PathResolver.lookup(nEntry, itemId.getPath()); } } } /** * @see HierarchyManager#getHierarchyEntry(ItemId) */ public HierarchyEntry getHierarchyEntry(ItemId itemId) throws PathNotFoundException, RepositoryException { String uniqueID = itemId.getUniqueID(); if (uniqueID == null) { return getHierarchyEntry(itemId.getPath()); } else { if (itemId.getPath() == null) { NodeEntry nEntry = uniqueIdResolver.resolve((NodeId) itemId, rootEntry); return nEntry; } else { NodeEntry nEntry = uniqueIdResolver.resolve(idFactory.createNodeId(uniqueID), rootEntry); return nEntry.getDeepEntry(itemId.getPath()); } } } /** * @see HierarchyManager#getHierarchyEntry(Path) */ public HierarchyEntry getHierarchyEntry(Path qPath) throws PathNotFoundException, RepositoryException { NodeEntry rootEntry = getRootEntry(); // shortcut if (qPath.denotesRoot()) { return rootEntry; } if (!qPath.isCanonical()) { String msg = "Path is not canonical"; log.debug(msg); throw new RepositoryException(msg); } return rootEntry.getDeepEntry(qPath); } /** * @see HierarchyManager#getItemState(Path) */ public ItemState getItemState(Path qPath) throws PathNotFoundException, RepositoryException { HierarchyEntry entry = getHierarchyEntry(qPath); try { ItemState state = entry.getItemState(); if (state.isValid()) { return state; } else { throw new PathNotFoundException(); } } catch (NoSuchItemStateException e) { throw new PathNotFoundException(e); } catch (ItemStateException e) { throw new RepositoryException(e); } } /** * @see HierarchyManager#getDepth(HierarchyEntry) */ public int getDepth(HierarchyEntry hierarchyEntry) throws ItemNotFoundException, RepositoryException { int depth = Path.ROOT_DEPTH; NodeEntry parentEntry = hierarchyEntry.getParent(); while (parentEntry != null) { depth++; hierarchyEntry = parentEntry; parentEntry = hierarchyEntry.getParent(); } return depth; } /** * @see HierarchyManager#getRelativeDepth(NodeEntry, HierarchyEntry) */ public int getRelativeDepth(NodeEntry ancestor, HierarchyEntry descendant) throws ItemNotFoundException, RepositoryException { if (ancestor.equals(descendant)) { return 0; } int depth = 1; NodeEntry parent = descendant.getParent(); while (parent != null) { if (parent.equals(ancestor)) { return depth; } depth++; descendant = parent; parent = descendant.getParent(); } // not an ancestor return -1; } }
contrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/hierarchy/HierarchyManagerImpl.java
/* * $Id$ * * Copyright 1997-2005 Day Management AG * Barfuesserplatz 6, 4001 Basel, Switzerland * All Rights Reserved. * * This software is the confidential and proprietary information of * Day Management AG, ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Day. */ package org.apache.jackrabbit.jcr2spi.hierarchy; import org.apache.jackrabbit.jcr2spi.state.ItemState; import org.apache.jackrabbit.jcr2spi.state.ItemStateException; import org.apache.jackrabbit.jcr2spi.state.NoSuchItemStateException; import org.apache.jackrabbit.jcr2spi.state.TransientItemStateFactory; import org.apache.jackrabbit.jcr2spi.state.ItemStateFactory; import org.apache.jackrabbit.name.Path; import org.apache.jackrabbit.spi.ItemId; import org.apache.jackrabbit.spi.IdFactory; import org.apache.jackrabbit.spi.NodeId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.ItemNotFoundException; /** * <code>HierarchyManagerImpl</code> implements the <code>HierarchyManager</code> * interface. */ public class HierarchyManagerImpl implements HierarchyManager { private static Logger log = LoggerFactory.getLogger(org.apache.jackrabbit.jcr2spi.hierarchy.HierarchyManagerImpl.class); private final NodeEntry rootEntry; private final UniqueIdResolver uniqueIdResolver; private final ItemStateFactory isf; private final IdFactory idFactory; public HierarchyManagerImpl(TransientItemStateFactory isf, IdFactory idFactory) { uniqueIdResolver = new UniqueIdResolver(isf); rootEntry = new EntryFactory(isf, idFactory, uniqueIdResolver).createRootEntry(); this.isf = isf; this.idFactory = idFactory; } //---------------------------------------------------< HierarchyManager >--- /** * @see HierarchyManager#dispose() */ public void dispose() { uniqueIdResolver.dispose(); } /** * @see HierarchyManager#getRootEntry() */ public NodeEntry getRootEntry() { return rootEntry; } /** * @see HierarchyManager#lookup(ItemId) */ public HierarchyEntry lookup(ItemId itemId) { String uniqueID = itemId.getUniqueID(); if (uniqueID == null) { return PathResolver.lookup(rootEntry, itemId.getPath()); } else { NodeEntry nEntry = uniqueIdResolver.lookup(idFactory.createNodeId(uniqueID)); if (itemId.getPath() == null) { return nEntry; } else { return PathResolver.lookup(nEntry, itemId.getPath()); } } } /** * @see HierarchyManager#getHierarchyEntry(ItemId) */ public HierarchyEntry getHierarchyEntry(ItemId itemId) throws PathNotFoundException, RepositoryException { String uniqueID = itemId.getUniqueID(); if (uniqueID == null) { return getHierarchyEntry(itemId.getPath()); } else { if (itemId.getPath() == null) { NodeEntry nEntry = uniqueIdResolver.resolve((NodeId) itemId, rootEntry); return nEntry; } else { NodeEntry nEntry = uniqueIdResolver.resolve(idFactory.createNodeId(uniqueID), rootEntry); return nEntry.getDeepEntry(itemId.getPath()); } } } /** * @see HierarchyManager#getHierarchyEntry(Path) */ public HierarchyEntry getHierarchyEntry(Path qPath) throws PathNotFoundException, RepositoryException { NodeEntry rootEntry = getRootEntry(); // shortcut if (qPath.denotesRoot()) { return rootEntry; } if (!qPath.isCanonical()) { String msg = "Path is not canonical"; log.debug(msg); throw new RepositoryException(msg); } return rootEntry.getDeepEntry(qPath); } /** * @see HierarchyManager#getItemState(Path) */ public ItemState getItemState(Path qPath) throws PathNotFoundException, RepositoryException { HierarchyEntry entry = getHierarchyEntry(qPath); try { ItemState state = entry.getItemState(); if (state.isValid()) { return state; } else { throw new PathNotFoundException(); } } catch (NoSuchItemStateException e) { throw new PathNotFoundException(e); } catch (ItemStateException e) { throw new RepositoryException(e); } } /** * @see HierarchyManager#getDepth(HierarchyEntry) */ public int getDepth(HierarchyEntry hierarchyEntry) throws ItemNotFoundException, RepositoryException { int depth = Path.ROOT_DEPTH; NodeEntry parentEntry = hierarchyEntry.getParent(); while (parentEntry != null) { depth++; hierarchyEntry = parentEntry; parentEntry = hierarchyEntry.getParent(); } return depth; } /** * @see HierarchyManager#getRelativeDepth(NodeEntry, HierarchyEntry) */ public int getRelativeDepth(NodeEntry ancestor, HierarchyEntry descendant) throws ItemNotFoundException, RepositoryException { if (ancestor.equals(descendant)) { return 0; } int depth = 1; NodeEntry parent = descendant.getParent(); while (parent != null) { if (parent.equals(ancestor)) { return depth; } depth++; descendant = parent; parent = descendant.getParent(); } // not an ancestor return -1; } }
remove unused instance field git-svn-id: 02b679d096242155780e1604e997947d154ee04a@509447 13f79535-47bb-0310-9956-ffa450edef68
contrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/hierarchy/HierarchyManagerImpl.java
remove unused instance field
<ide><path>ontrib/spi/jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/hierarchy/HierarchyManagerImpl.java <ide> import org.apache.jackrabbit.jcr2spi.state.ItemStateException; <ide> import org.apache.jackrabbit.jcr2spi.state.NoSuchItemStateException; <ide> import org.apache.jackrabbit.jcr2spi.state.TransientItemStateFactory; <del>import org.apache.jackrabbit.jcr2spi.state.ItemStateFactory; <ide> import org.apache.jackrabbit.name.Path; <ide> import org.apache.jackrabbit.spi.ItemId; <ide> import org.apache.jackrabbit.spi.IdFactory; <ide> <ide> private final NodeEntry rootEntry; <ide> private final UniqueIdResolver uniqueIdResolver; <del> <del> private final ItemStateFactory isf; <ide> private final IdFactory idFactory; <ide> <ide> public HierarchyManagerImpl(TransientItemStateFactory isf, IdFactory idFactory) { <ide> uniqueIdResolver = new UniqueIdResolver(isf); <ide> rootEntry = new EntryFactory(isf, idFactory, uniqueIdResolver).createRootEntry(); <del> <del> this.isf = isf; <ide> this.idFactory = idFactory; <ide> } <ide>
Java
apache-2.0
50b76009c11bac7bfcf9441025f1fedf74dc0075
0
calrissian/accumulo-recipes
/* * Copyright (C) 2013 The Calrissian Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.calrissian.accumulorecipes.eventstore.impl; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.collect.Iterables; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.mock.MockInstance; import org.apache.accumulo.core.security.Authorizations; import org.calrissian.accumulorecipes.commons.domain.Auths; import org.calrissian.accumulorecipes.commons.support.tuple.MetadataBuilder; import org.calrissian.accumulorecipes.eventstore.EventStore; import org.calrissian.accumulorecipes.test.AccumuloTestUtils; import org.calrissian.mango.collect.CloseableIterable; import org.calrissian.mango.criteria.builder.QueryBuilder; import org.calrissian.mango.criteria.domain.Node; import org.calrissian.mango.domain.Tuple; import org.calrissian.mango.domain.event.BaseEvent; import org.calrissian.mango.domain.event.Event; import org.calrissian.mango.domain.event.EventIndex; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static com.google.common.collect.Iterables.size; import static java.lang.System.currentTimeMillis; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class AccumuloEventStoreTest { private Connector connector; private EventStore store; private Map<String, Object> meta = new MetadataBuilder().setVisibility("A").build(); private Auths DEFAULT_AUTHS = new Auths("A"); public static Connector getConnector() throws AccumuloSecurityException, AccumuloException { return new MockInstance().getConnector("root", "".getBytes()); } @Before public void setup() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { connector = getConnector(); connector.securityOperations().changeUserAuthorizations("root", new Authorizations("A")); store = new AccumuloEventStore(connector); } @Test public void testGet() throws Exception { long time = currentTimeMillis(); Event event = new BaseEvent(UUID.randomUUID().toString(), time); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), time); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); AccumuloTestUtils.dumpTable(connector, "eventStore_shard", new Authorizations("A")); CloseableIterable<Event> actualEvent = store.get(singletonList(new EventIndex(event.getId(), event.getTimestamp())), null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); Event actual = actualEvent.iterator().next(); assertEquals(new HashSet(actual.getTuples()), new HashSet(event.getTuples())); assertEquals(actual.getId(), event.getId()); System.out.println(actual); actualEvent = store.get(singletonList(new EventIndex(event.getId(), time)), null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); actual = actualEvent.iterator().next(); assertEquals(new HashSet(actual.getTuples()), new HashSet(event.getTuples())); assertEquals(actual.getId(), event.getId()); } @Test public void testVisibility() { Map<String, Object> shouldntSee = new MetadataBuilder().setVisibility("A&B").build(); Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", shouldntSee)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", shouldntSee)); store.save(asList(event, event2)); List<EventIndex> indexes = asList(new EventIndex[] { new EventIndex(event.getId(), event.getTimestamp()), new EventIndex(event2.getId(), event2.getTimestamp()) }); Iterable<Event> actualEvent1 = store.get(indexes, null, new Auths("A")); assertEquals(2, Iterables.size(actualEvent1)); assertEquals(1, Iterables.get(actualEvent1, 0).size()); assertEquals(1, Iterables.get(actualEvent1, 1).size()); } @Test public void testExpirationOfTuples_get() { Map<String, Object> shouldntSee = new MetadataBuilder().setExpiration(1).build(); Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", shouldntSee)); store.save(asList(event)); List<EventIndex> eventIndexes = Arrays.asList(new EventIndex(event.getId(), event.getTimestamp())); Iterable<Event> events = store.get(eventIndexes, null, DEFAULT_AUTHS); assertEquals(1, Iterables.size(events)); assertEquals(1, Iterables.get(events, 0).size()); } @Test public void testExpirationOfTuples_query() { Map<String, Object> shouldntSee = new MetadataBuilder().setExpiration(1).build(); Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", shouldntSee)); store.save(asList(event)); Node node = new QueryBuilder().eq("key1", "val1").build(); Iterable<Event> events = store.query( new Date(currentTimeMillis()-5000), new Date(currentTimeMillis()), node, null, DEFAULT_AUTHS); assertEquals(1, Iterables.size(events)); assertEquals(1, Iterables.get(events, 0).size()); } @Test public void testQueryKeyNotInIndex() { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().eq("key4", "val5").end().build(); Iterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS); assertEquals(0, Iterables.size(itr)); } @Test public void testQueryRangeNotInIndex() { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().range("key4", 0, 5).end().build(); Iterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS); assertEquals(0, Iterables.size(itr)); } @Test public void testGreaterThan() throws Exception { long time = currentTimeMillis(); Event event = new BaseEvent(UUID.randomUUID().toString(), time); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", 1, meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), time); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", 10, meta)); store.save(asList(event, event2)); store.flush(); CloseableIterable<Event> actualEvent = store.query(new Date(time-50), new Date(time+50), new QueryBuilder().greaterThan("key2", 9).build(), null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); Event actual = actualEvent.iterator().next(); assertEquals(new HashSet(event2.getTuples()), new HashSet(actual.getTuples())); assertEquals(actual.getId(), event2.getId()); actualEvent = store.query(new Date(time), new Date(time), new QueryBuilder().greaterThan("key2", 0).build(), null, DEFAULT_AUTHS); assertEquals(2, size(actualEvent)); } @Test public void test_TimeLimit() throws Exception { long currentTime = System.currentTimeMillis(); Event event = new BaseEvent(UUID.randomUUID().toString(), currentTime); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTime - 5000); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node node = new QueryBuilder().eq("key1", "val1").build(); CloseableIterable<Event> actualEvent = store.query(new Date(currentTime - 5001), new Date(currentTime + 500), node, null, DEFAULT_AUTHS); assertEquals(2, size(actualEvent)); actualEvent = store.query(new Date(currentTime - 3000), new Date(currentTime+50), node, null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); } @Test public void testGet_withSelection() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); CloseableIterable<Event> actualEvent = store.get(singletonList(new EventIndex(event.getId(), event.getTimestamp())), Collections.singleton("key1"), DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); assertNull(actualEvent.iterator().next().get("key2")); assertNotNull(actualEvent.iterator().next().get("key1")); } @Test public void testQuery_withSelection() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().eq("key1", "val1").eq("key2", "val2").end().build(); Iterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, Collections.singleton("key1"), DEFAULT_AUTHS); int count = 0; for (Event entry : itr) { count++; assertNull(entry.get("key2")); assertNotNull(entry.get("key1")); } assertEquals(2, count); } @Test public void testQuery_AndQuery() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().eq("key1", "val1").eq("key2", "val2").end().build(); Iterator<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); Event actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event.getTuples())); } else { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event2.getTuples())); } actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event.getTuples())); } else { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event2.getTuples())); } } @Test public void testQuery_OrQuery() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key3", "val3", meta)); store.save(asList(event, event2)); AccumuloTestUtils.dumpTable(connector, "eventStore_index"); AccumuloTestUtils.dumpTable(connector, "eventStore_shard"); Node query = new QueryBuilder().or().eq("key3", "val3").eq("key2", "val2").end().build(); Iterator<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); Event actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } } @Test public void testQuery_SingleEqualsQuery() throws Exception, AccumuloException, AccumuloSecurityException { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key3", "val3", meta)); store.save(asList(event, event2)); store.flush(); AccumuloTestUtils.dumpTable(connector, "eventStore_shard"); Node query = new QueryBuilder().eq("key1", "val1").build(); Iterator<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); Event actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } } @Test public void testQuery_emptyNodeReturnsNoResults() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { Node query = new QueryBuilder().and().end().build(); CloseableIterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS); assertEquals(0, size(itr)); } @Test public void testQuery_MultipleNotInQuery() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("hasIp", "true", meta)); event.put(new Tuple("ip", "1.1.1.1", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("hasIp", "true", meta)); event2.put(new Tuple("ip", "2.2.2.2", meta)); Event event3 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event3.put(new Tuple("hasIp", "true", meta)); event3.put(new Tuple("ip", "3.3.3.3", meta)); store.save(asList(event, event2, event3)); Node query = new QueryBuilder() .and() .notEq("ip", "1.1.1.1") .notEq("ip", "2.2.2.2") .notEq("ip", "4.4.4.4") .eq("hasIp", "true") .end().build(); Iterator<Event> itr = store.query( new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); int x = 0; while (itr.hasNext()) { x++; Event e = itr.next(); assertEquals("3.3.3.3", e.get("ip").getValue()); } assertEquals(1, x); } @Ignore @Test public void testQuery_has() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { Event event = new BaseEvent("id"); event.put(new Tuple("key1", "val1", meta)); store.save(asList(event)); Node node = new QueryBuilder().has("key1").build(); Iterable<Event> itr = store.query(new Date(0), new Date(), node, null, DEFAULT_AUTHS); assertEquals(1, Iterables.size(itr)); assertEquals(event, Iterables.get(itr, 0)); } @Ignore @Test public void testQuery_hasNot() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { Event event = new BaseEvent("id"); event.put(new Tuple("key1", "val1", meta)); store.save(asList(event)); Node node = new QueryBuilder().hasNot("key2").build(); Iterable<Event> itr = store.query(new Date(0), new Date(), node, null, DEFAULT_AUTHS); assertEquals(1, Iterables.size(itr)); assertEquals(event, Iterables.get(itr, 0)); } }
store/event-store/src/test/java/org/calrissian/accumulorecipes/eventstore/impl/AccumuloEventStoreTest.java
/* * Copyright (C) 2013 The Calrissian Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.calrissian.accumulorecipes.eventstore.impl; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.collect.Iterables; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.TableExistsException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.client.mock.MockInstance; import org.apache.accumulo.core.security.Authorizations; import org.calrissian.accumulorecipes.commons.domain.Auths; import org.calrissian.accumulorecipes.commons.support.tuple.MetadataBuilder; import org.calrissian.accumulorecipes.eventstore.EventStore; import org.calrissian.accumulorecipes.test.AccumuloTestUtils; import org.calrissian.mango.collect.CloseableIterable; import org.calrissian.mango.criteria.builder.QueryBuilder; import org.calrissian.mango.criteria.domain.Node; import org.calrissian.mango.domain.Tuple; import org.calrissian.mango.domain.event.BaseEvent; import org.calrissian.mango.domain.event.Event; import org.calrissian.mango.domain.event.EventIndex; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static com.google.common.collect.Iterables.size; import static java.lang.System.currentTimeMillis; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class AccumuloEventStoreTest { private Connector connector; private EventStore store; private Map<String, Object> meta = new MetadataBuilder().setVisibility("A").build(); private Auths DEFAULT_AUTHS = new Auths("A"); public static Connector getConnector() throws AccumuloSecurityException, AccumuloException { return new MockInstance().getConnector("root", "".getBytes()); } @Before public void setup() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { connector = getConnector(); connector.securityOperations().changeUserAuthorizations("root", new Authorizations("A")); store = new AccumuloEventStore(connector); } @Test public void testGet() throws Exception { long time = currentTimeMillis(); Event event = new BaseEvent(UUID.randomUUID().toString(), time); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), time); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); AccumuloTestUtils.dumpTable(connector, "eventStore_shard", new Authorizations("A")); CloseableIterable<Event> actualEvent = store.get(singletonList(new EventIndex(event.getId(), event.getTimestamp())), null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); Event actual = actualEvent.iterator().next(); assertEquals(new HashSet(actual.getTuples()), new HashSet(event.getTuples())); assertEquals(actual.getId(), event.getId()); System.out.println(actual); actualEvent = store.get(singletonList(new EventIndex(event.getId(), time)), null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); actual = actualEvent.iterator().next(); assertEquals(new HashSet(actual.getTuples()), new HashSet(event.getTuples())); assertEquals(actual.getId(), event.getId()); } @Test public void testVisibility() { Map<String, Object> shouldntSee = new MetadataBuilder().setVisibility("A&B").build(); Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", shouldntSee)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", shouldntSee)); store.save(asList(event, event2)); List<EventIndex> indexes = asList(new EventIndex[] { new EventIndex(event.getId(), event.getTimestamp()), new EventIndex(event2.getId(), event2.getTimestamp()) }); Iterable<Event> actualEvent1 = store.get(indexes, null, new Auths("A")); assertEquals(2, Iterables.size(actualEvent1)); assertEquals(1, Iterables.get(actualEvent1, 0).size()); assertEquals(1, Iterables.get(actualEvent1, 1).size()); } @Test public void testQueryKeyNotInIndex() { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().eq("key4", "val5").end().build(); Iterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS); assertEquals(0, Iterables.size(itr)); } @Test public void testQueryRangeNotInIndex() { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().range("key4", 0, 5).end().build(); Iterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS); assertEquals(0, Iterables.size(itr)); } @Test public void testGreaterThan() throws Exception { long time = currentTimeMillis(); Event event = new BaseEvent(UUID.randomUUID().toString(), time); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", 1, meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), time); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", 10, meta)); store.save(asList(event, event2)); store.flush(); CloseableIterable<Event> actualEvent = store.query(new Date(time-50), new Date(time+50), new QueryBuilder().greaterThan("key2", 9).build(), null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); Event actual = actualEvent.iterator().next(); assertEquals(new HashSet(event2.getTuples()), new HashSet(actual.getTuples())); assertEquals(actual.getId(), event2.getId()); actualEvent = store.query(new Date(time), new Date(time), new QueryBuilder().greaterThan("key2", 0).build(), null, DEFAULT_AUTHS); assertEquals(2, size(actualEvent)); } @Test public void test_TimeLimit() throws Exception { long currentTime = System.currentTimeMillis(); Event event = new BaseEvent(UUID.randomUUID().toString(), currentTime); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTime - 5000); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node node = new QueryBuilder().eq("key1", "val1").build(); CloseableIterable<Event> actualEvent = store.query(new Date(currentTime - 5001), new Date(currentTime + 500), node, null, DEFAULT_AUTHS); assertEquals(2, size(actualEvent)); actualEvent = store.query(new Date(currentTime - 3000), new Date(currentTime+50), node, null, DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); } @Test public void testGet_withSelection() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); CloseableIterable<Event> actualEvent = store.get(singletonList(new EventIndex(event.getId(), event.getTimestamp())), Collections.singleton("key1"), DEFAULT_AUTHS); assertEquals(1, size(actualEvent)); assertNull(actualEvent.iterator().next().get("key2")); assertNotNull(actualEvent.iterator().next().get("key1")); } @Test public void testQuery_withSelection() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().eq("key1", "val1").eq("key2", "val2").end().build(); Iterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, Collections.singleton("key1"), DEFAULT_AUTHS); int count = 0; for (Event entry : itr) { count++; assertNull(entry.get("key2")); assertNotNull(entry.get("key1")); } assertEquals(2, count); } @Test public void testQuery_AndQuery() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key2", "val2", meta)); store.save(asList(event, event2)); Node query = new QueryBuilder().and().eq("key1", "val1").eq("key2", "val2").end().build(); Iterator<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); Event actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event.getTuples())); } else { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event2.getTuples())); } actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event.getTuples())); } else { assertEquals(new HashSet(actualEvent.getTuples()), new HashSet(event2.getTuples())); } } @Test public void testQuery_OrQuery() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key3", "val3", meta)); store.save(asList(event, event2)); AccumuloTestUtils.dumpTable(connector, "eventStore_index"); AccumuloTestUtils.dumpTable(connector, "eventStore_shard"); Node query = new QueryBuilder().or().eq("key3", "val3").eq("key2", "val2").end().build(); Iterator<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); Event actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } } @Test public void testQuery_SingleEqualsQuery() throws Exception, AccumuloException, AccumuloSecurityException { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("key1", "val1", meta)); event.put(new Tuple("key2", "val2", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("key1", "val1", meta)); event2.put(new Tuple("key3", "val3", meta)); store.save(asList(event, event2)); store.flush(); AccumuloTestUtils.dumpTable(connector, "eventStore_shard"); Node query = new QueryBuilder().eq("key1", "val1").build(); Iterator<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); Event actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } actualEvent = itr.next(); if (actualEvent.getId().equals(event.getId())) { assertEquals(new HashSet(event.getTuples()), new HashSet(actualEvent.getTuples())); } else { assertEquals(new HashSet(event2.getTuples()), new HashSet(actualEvent.getTuples())); } } @Test public void testQuery_emptyNodeReturnsNoResults() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { Node query = new QueryBuilder().and().end().build(); CloseableIterable<Event> itr = store.query(new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS); assertEquals(0, size(itr)); } @Test public void testQuery_MultipleNotInQuery() throws Exception { Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event.put(new Tuple("hasIp", "true", meta)); event.put(new Tuple("ip", "1.1.1.1", meta)); Event event2 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event2.put(new Tuple("hasIp", "true", meta)); event2.put(new Tuple("ip", "2.2.2.2", meta)); Event event3 = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); event3.put(new Tuple("hasIp", "true", meta)); event3.put(new Tuple("ip", "3.3.3.3", meta)); store.save(asList(event, event2, event3)); Node query = new QueryBuilder() .and() .notEq("ip", "1.1.1.1") .notEq("ip", "2.2.2.2") .notEq("ip", "4.4.4.4") .eq("hasIp", "true") .end().build(); Iterator<Event> itr = store.query( new Date(currentTimeMillis() - 5000), new Date(), query, null, DEFAULT_AUTHS).iterator(); int x = 0; while (itr.hasNext()) { x++; Event e = itr.next(); assertEquals("3.3.3.3", e.get("ip").getValue()); } assertEquals(1, x); } @Ignore @Test public void testQuery_has() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { Event event = new BaseEvent("id"); event.put(new Tuple("key1", "val1", meta)); store.save(asList(event)); Node node = new QueryBuilder().has("key1").build(); Iterable<Event> itr = store.query(new Date(0), new Date(), node, null, DEFAULT_AUTHS); assertEquals(1, Iterables.size(itr)); assertEquals(event, Iterables.get(itr, 0)); } @Ignore @Test public void testQuery_hasNot() throws AccumuloSecurityException, AccumuloException, TableExistsException, TableNotFoundException { Event event = new BaseEvent("id"); event.put(new Tuple("key1", "val1", meta)); store.save(asList(event)); Node node = new QueryBuilder().hasNot("key2").build(); Iterable<Event> itr = store.query(new Date(0), new Date(), node, null, DEFAULT_AUTHS); assertEquals(1, Iterables.size(itr)); assertEquals(event, Iterables.get(itr, 0)); } }
Adding expiration test methods for the event store
store/event-store/src/test/java/org/calrissian/accumulorecipes/eventstore/impl/AccumuloEventStoreTest.java
Adding expiration test methods for the event store
<ide><path>tore/event-store/src/test/java/org/calrissian/accumulorecipes/eventstore/impl/AccumuloEventStoreTest.java <ide> */ <ide> package org.calrissian.accumulorecipes.eventstore.impl; <ide> <add>import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.Date; <ide> import java.util.HashSet; <ide> assertEquals(1, Iterables.get(actualEvent1, 1).size()); <ide> } <ide> <add> @Test <add> public void testExpirationOfTuples_get() { <add> <add> Map<String, Object> shouldntSee = new MetadataBuilder().setExpiration(1).build(); <add> <add> Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); <add> event.put(new Tuple("key1", "val1", meta)); <add> event.put(new Tuple("key2", "val2", shouldntSee)); <add> <add> <add> store.save(asList(event)); <add> <add> List<EventIndex> eventIndexes = Arrays.asList(new EventIndex(event.getId(), event.getTimestamp())); <add> <add> Iterable<Event> events = store.get(eventIndexes, null, DEFAULT_AUTHS); <add> <add> assertEquals(1, Iterables.size(events)); <add> assertEquals(1, Iterables.get(events, 0).size()); <add> } <add> <add> @Test <add> public void testExpirationOfTuples_query() { <add> <add> Map<String, Object> shouldntSee = new MetadataBuilder().setExpiration(1).build(); <add> <add> Event event = new BaseEvent(UUID.randomUUID().toString(), currentTimeMillis()); <add> event.put(new Tuple("key1", "val1", meta)); <add> event.put(new Tuple("key2", "val2", shouldntSee)); <add> <add> <add> store.save(asList(event)); <add> <add> Node node = new QueryBuilder().eq("key1", "val1").build(); <add> <add> Iterable<Event> events = store.query( <add> new Date(currentTimeMillis()-5000), new Date(currentTimeMillis()), node, null, DEFAULT_AUTHS); <add> <add> assertEquals(1, Iterables.size(events)); <add> assertEquals(1, Iterables.get(events, 0).size()); <add> } <add> <add> <ide> <ide> <ide> @Test
JavaScript
mit
063da498dc56f9cd6ea51ee7d65173faa8c34468
0
acenter2507/first,acenter2507/first,acenter2507/first
'use strict'; angular.module('polls').controller('PollsSearchController', [ '$location', '$scope', '$state', 'Authentication', 'CategorysService', 'Action', '$stateParams', 'Storages', 'Constants', function ($location, $scope, $state, Authentication, Categorys, Action, $stateParams, Storages, Constants) { $scope.user = Authentication.user; $scope.isLogged = ($scope.user) ? true : false; $scope.detailToggle = -1; $scope.form = {}; $scope.categorys = Categorys.query(); $scope.condition = {}; $scope.condition.key = $stateParams.key; $scope.condition.in = $stateParams.in; $scope.condition.status = $stateParams.status; $scope.condition.by = $stateParams.by; $scope.condition.ctgr = $stateParams.ctgr; $scope.condition.cmt = $stateParams.cmt; $scope.condition.compare = $stateParams.compare; $scope.condition.created = $stateParams.created; $scope.condition.timing = $stateParams.timing; $scope.condition.sort = $stateParams.sort; $scope.condition.sortkind = $stateParams.sortkind; $scope.search = () => { $state.go('search', $scope.condition); }; $scope.busy = false; $scope.polls = []; excute(); function excute() { if (check_params()) { $scope.busy = true; Action.search($scope.condition) .then(res => { console.log(res); $scope.polls = res.data; var promise = []; $scope.polls.forEach(function(item) { promise.push(get_owner_follow(item.poll)); promise.push(get_reported(item.poll)); promise.push(get_bookmarked(item.poll)); }, this); }) .then(res => { $scope.busy = false; }) .catch(err => { console.log(err); $scope.busy = false; }); } else { $scope.condition = JSON.parse(Storages.get_local(Constants.storages.preferences, JSON.stringify({}))); } } function check_params() { if ($scope.condition.key || $scope.condition.status || $scope.condition.by || $scope.condition.ctgr || $scope.condition.cmt || $scope.condition.created) { return true; } return false; } function aaa() { if ($scope.condition.key) { } } function get_owner_follow(poll) { return new Promise((resolve, reject) => { if (!$scope.isLogged) { poll.follow = {}; return resolve(); } Action.get_follow(poll._id) .then(res => { poll.follow = res.data || { poll: poll._id }; return resolve(res.data); }) .catch(err => { return reject(err); }); }); } function get_reported(poll) { return new Promise((resolve, reject) => { if (!$scope.isLogged) { poll.reported = false; return resolve(); } Action.get_report(poll._id) .then(res => { poll.reported = (res.data) ? res.data : false; return resolve(res.data); }) .catch(err => { return reject(err); }); }); } function get_bookmarked(poll) { return new Promise((resolve, reject) => { if (!$scope.isLogged) { poll.bookmarked = false; return resolve(); } Action.get_bookmark(poll._id) .then(res => { poll.bookmarked = (res.data) ? res.data : false; return resolve(res.data); }) .catch(err => { return reject(err); }); }); } $scope.clear_preferences = () => { $scope.condition = {}; Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition)); $location.url($location.path()); }; $scope.save_preferences = () => { Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition)); }; } ]);
modules/polls/client/controllers/search.client.controller.js
'use strict'; angular.module('polls').controller('PollsSearchController', [ '$location', '$scope', '$state', 'Authentication', 'CategorysService', 'Action', '$stateParams', 'Storages', 'Constants', function ($location, $scope, $state, Authentication, Categorys, Action, $stateParams, Storages, Constants) { $scope.user = Authentication.user; $scope.isLogged = ($scope.user) ? true : false; $scope.detailToggle = -1; $scope.form = {}; $scope.categorys = Categorys.query(); $scope.condition = {}; $scope.condition.key = $stateParams.key; $scope.condition.in = $stateParams.in; $scope.condition.status = $stateParams.status; $scope.condition.by = $stateParams.by; $scope.condition.ctgr = $stateParams.ctgr; $scope.condition.cmt = $stateParams.cmt; $scope.condition.compare = $stateParams.compare; $scope.condition.created = $stateParams.created; $scope.condition.timing = $stateParams.timing; $scope.condition.sort = $stateParams.sort; $scope.condition.sortkind = $stateParams.sortkind; $scope.search = () => { $state.go('search', $scope.condition); }; $scope.busy = false; $scope.polls = []; excute(); function excute() { if (check_params()) { $scope.busy = true; Action.search($scope.condition) .then(res => { console.log(res); $scope.polls = res.data; var promise = []; $scope.polls.forEach(function(item) { promise.push(get_owner_follow(item.poll)); promise.push(get_reported(item.poll)); promise.push(get_bookmarked(item.poll)); }, this); }) .then(res => { $scope.busy = false; }) .catch(err => { console.log(err); $scope.busy = false; }); } else { $scope.condition = JSON.parse(Storages.get_local(Constants.storages.preferences, JSON.stringify({}))); } } function check_params() { if ($scope.condition.key || $scope.condition.status || $scope.condition.by || $scope.condition.ctgr || $scope.condition.cmt || $scope.condition.created) { return true; } return false; } function get_owner_follow(poll) { return new Promise((resolve, reject) => { if (!$scope.isLogged) { poll.follow = {}; return resolve(); } Action.get_follow(poll._id) .then(res => { poll.follow = res.data || { poll: poll._id }; return resolve(res.data); }) .catch(err => { return reject(err); }); }); } function get_reported(poll) { return new Promise((resolve, reject) => { if (!$scope.isLogged) { poll.reported = false; return resolve(); } Action.get_report(poll._id) .then(res => { poll.reported = (res.data) ? res.data : false; return resolve(res.data); }) .catch(err => { return reject(err); }); }); } function get_bookmarked(poll) { return new Promise((resolve, reject) => { if (!$scope.isLogged) { poll.bookmarked = false; return resolve(); } Action.get_bookmark(poll._id) .then(res => { poll.bookmarked = (res.data) ? res.data : false; return resolve(res.data); }) .catch(err => { return reject(err); }); }); } $scope.clear_preferences = () => { $scope.condition = {}; Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition)); $location.url($location.path()); }; $scope.save_preferences = () => { Storages.set_local(Constants.storages.preferences, JSON.stringify($scope.condition)); }; } ]);
Commited from lenh at Fri, Jul 21, 2017 1:45:36 PM
modules/polls/client/controllers/search.client.controller.js
Commited from lenh at Fri, Jul 21, 2017 1:45:36 PM
<ide><path>odules/polls/client/controllers/search.client.controller.js <ide> } <ide> return false; <ide> } <add> function aaa() { <add> if ($scope.condition.key) { <add> <add> } <add> } <ide> <ide> function get_owner_follow(poll) { <ide> return new Promise((resolve, reject) => {
Java
apache-2.0
0e84ca884742a10cecc5f96e73447405b6d3ecb0
0
lgirndt/infowall,lgirndt/infowall,lgirndt/infowall
/* * 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 infowall.domain.persistence.sql; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.List; import javax.annotation.Resource; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import infowall.domain.model.ItemRef; import infowall.domain.model.ItemValue; /** * */ @Ignore @ContextConfiguration(locations = "classpath:/spring/test-context.xml") public class ItemValueDaoTest extends AbstractTransactionalJUnit4SpringContextTests /*AbstractJUnit4SpringContextTests*/ { @Resource private ItemValueDao itemValueDao; @Before public void setUp() throws Exception { this.executeSqlScript("/sql/create-schema.sql",false); } @Test public void insert(){ ItemRef itemRef = new ItemRef("d","i"); ItemValue itemValue = new ItemValue(); itemValue.setItemRef(itemRef); itemValue.setCreation(new DateTime()); itemValue.setLastUpdate(new DateTime()); itemValueDao.insert(itemValue); } @Test public void findExisting() throws Exception { ItemRef itemRef = new ItemRef("d", "i"); String data = "{\"foo\":\"bar\"}"; ItemValue val = itemValue(itemRef, data); itemValueDao.insert(val); ItemValue actual = itemValueDao.findMostRecent(itemRef); assertNotNull(actual.getId()); } @Test public void findNotExisting() throws Exception { ItemValue val = someItemValue(); itemValueDao.insert(val); assertNull( itemValueDao.findMostRecent(new ItemRef("a","b")) ); } @Test public void findMostRecent() throws Exception{ ItemRef itemRef = new ItemRef("d", "i"); String data = "{\"foo\":\"bar\"}"; ItemValue val = itemValue(itemRef, data); itemValueDao.insert(val); ItemValue actual = itemValueDao.findMostRecent(itemRef); assertNotNull(actual.getId()); } @Test public void findMostRecentItemValues() throws Exception { ItemValue first = itemValueWithData("{\"d\":\"first\"}"); ItemValue second = itemValueWithData("{\"d\":\"second\"}"); ItemValue third = itemValueWithData("{\"d\":\"third\"}"); itemValueDao.insert(first); itemValueDao.insert(second); itemValueDao.insert(third); List<ItemValue> result = itemValueDao.findMostRecentItemValues(first.getItemRef(),2); assertThat(result.size(), is(2)); assertThat(result.get(0).getData(),is(third.getData())); assertThat(result.get(1).getData(),is(second.getData())); } private ItemValue someItemValue() throws IOException { String data = "{\"foo\":\"bar\"}"; return itemValueWithData(data); } private ItemValue itemValueWithData(final String data) throws IOException { ItemRef itemRef = new ItemRef("d", "i"); return itemValue(itemRef, data); } @Test public void update() throws Exception{ ItemValue itemValue = someItemValue(); itemValueDao.insert(itemValue); ItemValue withId = itemValueDao.findMostRecent(itemValue.getItemRef()); withId.update(new DateTime()); itemValueDao.update(withId); } private ItemValue itemValue(ItemRef itemRef, String data) throws IOException { ObjectMapper mapper = new ObjectMapper(); ItemValue val = new ItemValue(); val.setItemRef(itemRef); val.setCreation(new DateTime()); val.setUpdateCount(0); val.setLastUpdate(new DateTime()); val.setData(mapper.readValue(data, ObjectNode.class)); return val; } }
src/test/java/infowall/domain/persistence/sql/ItemValueDaoTest.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 infowall.domain.persistence.sql; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.List; import javax.annotation.Resource; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.node.ObjectNode; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import infowall.domain.model.ItemRef; import infowall.domain.model.ItemValue; /** * */ @ContextConfiguration(locations = "classpath:/spring/test-context.xml") public class ItemValueDaoTest extends AbstractTransactionalJUnit4SpringContextTests /*AbstractJUnit4SpringContextTests*/ { @Resource private ItemValueDao itemValueDao; @Before public void setUp() throws Exception { this.executeSqlScript("/sql/create-schema.sql",false); } @Test public void insert(){ ItemRef itemRef = new ItemRef("d","i"); ItemValue itemValue = new ItemValue(); itemValue.setItemRef(itemRef); itemValue.setCreation(new DateTime()); itemValue.setLastUpdate(new DateTime()); itemValueDao.insert(itemValue); } @Test public void findExisting() throws Exception { ItemRef itemRef = new ItemRef("d", "i"); String data = "{\"foo\":\"bar\"}"; ItemValue val = itemValue(itemRef, data); itemValueDao.insert(val); ItemValue actual = itemValueDao.findMostRecent(itemRef); assertNotNull(actual.getId()); } @Test public void findNotExisting() throws Exception { ItemValue val = someItemValue(); itemValueDao.insert(val); assertNull( itemValueDao.findMostRecent(new ItemRef("a","b")) ); } @Test public void findMostRecent() throws Exception{ ItemRef itemRef = new ItemRef("d", "i"); String data = "{\"foo\":\"bar\"}"; ItemValue val = itemValue(itemRef, data); itemValueDao.insert(val); ItemValue actual = itemValueDao.findMostRecent(itemRef); assertNotNull(actual.getId()); } @Test public void findMostRecentItemValues() throws Exception { ItemValue first = itemValueWithData("{\"d\":\"first\"}"); ItemValue second = itemValueWithData("{\"d\":\"second\"}"); ItemValue third = itemValueWithData("{\"d\":\"third\"}"); itemValueDao.insert(first); itemValueDao.insert(second); itemValueDao.insert(third); List<ItemValue> result = itemValueDao.findMostRecentItemValues(first.getItemRef(),2); assertThat(result.size(), is(2)); assertThat(result.get(0).getData(),is(third.getData())); assertThat(result.get(1).getData(),is(second.getData())); } private ItemValue someItemValue() throws IOException { String data = "{\"foo\":\"bar\"}"; return itemValueWithData(data); } private ItemValue itemValueWithData(final String data) throws IOException { ItemRef itemRef = new ItemRef("d", "i"); return itemValue(itemRef, data); } @Test public void update() throws Exception{ ItemValue itemValue = someItemValue(); itemValueDao.insert(itemValue); ItemValue withId = itemValueDao.findMostRecent(itemValue.getItemRef()); withId.update(new DateTime()); itemValueDao.update(withId); } private ItemValue itemValue(ItemRef itemRef, String data) throws IOException { ObjectMapper mapper = new ObjectMapper(); ItemValue val = new ItemValue(); val.setItemRef(itemRef); val.setCreation(new DateTime()); val.setUpdateCount(0); val.setLastUpdate(new DateTime()); val.setData(mapper.readValue(data, ObjectNode.class)); return val; } }
Ignore the DB tests for now. Until we introduced Daleq.
src/test/java/infowall/domain/persistence/sql/ItemValueDaoTest.java
Ignore the DB tests for now. Until we introduced Daleq.
<ide><path>rc/test/java/infowall/domain/persistence/sql/ItemValueDaoTest.java <ide> import org.codehaus.jackson.node.ObjectNode; <ide> import org.joda.time.DateTime; <ide> import org.junit.Before; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.springframework.test.context.ContextConfiguration; <ide> import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; <ide> /** <ide> * <ide> */ <add>@Ignore <ide> @ContextConfiguration(locations = "classpath:/spring/test-context.xml") <ide> public class ItemValueDaoTest extends AbstractTransactionalJUnit4SpringContextTests <ide> /*AbstractJUnit4SpringContextTests*/ {
Java
apache-2.0
52cc1162c9ab83007409159b7b320ec45653eede
0
nwonwo/jv4qa_u1
package nwo.stqa.addressbook.appmanager; import nwo.stqa.addressbook.model.GroupData; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; public class GroupHelper { private FirefoxDriver wd; public GroupHelper(FirefoxDriver wd) { this.wd = wd; } public void returnToGroupPage() { wd.findElement(By.linkText("group page")).click(); } public void submitGroupCreation() { wd.findElement(By.name("submit")).click(); } public void fillGroupForm(GroupData groupData) { wd.findElement(By.name("group_name")).click(); wd.findElement(By.name("group_name")).clear(); wd.findElement(By.name("group_name")).sendKeys(groupData.getName()); wd.findElement(By.name("group_header")).click(); wd.findElement(By.name("group_header")).clear(); wd.findElement(By.name("group_header")).sendKeys(groupData.getHeader()); wd.findElement(By.name("group_footer")).click(); wd.findElement(By.name("group_footer")).clear(); wd.findElement(By.name("group_footer")).sendKeys(groupData.getFooter()); wd.findElement(By.name("group_footer")).click(); } public void initGroupCreation() { wd.findElement(By.name("new")).click(); } public void deleteSelectedGroups() { wd.findElement(By.name("delete")).click(); } public void selectGroup() { wd.findElement(By.name("selected[]")).click(); } }
addressbook-web-tests/src/test/java/nwo/stqa/addressbook/appmanager/GroupHelper.java
package nwo.stqa.addressbook.appmanager; import nwo.stqa.addressbook.model.GroupData; import org.openqa.selenium.By; import org.openqa.selenium.firefox.FirefoxDriver; public class GroupHelper { private FirefoxDriver wd; private BaseHelper baseHelper; public GroupHelper(FirefoxDriver wd) { this.wd = wd; baseHelper = new BaseHelper(wd); } public void returnToGroupPage() { wd.findElement(By.linkText("group page")).click(); } public void submitGroupCreation() { wd.findElement(By.name("submit")).click(); } public void fillGroupForm(GroupData groupData) { baseHelper.selectGroupName(); baseHelper.setGroupName(groupData); baseHelper.selectGroupHeader(); baseHelper.setGroupHeader(groupData); baseHelper.selectGroupFooter(); baseHelper.setGroupFooter(groupData); } public void initGroupCreation() { wd.findElement(By.name("new")).click(); } public void deleteSelectedGroups() { wd.findElement(By.name("delete")).click(); } public void selectGroup() { wd.findElement(By.name("selected[]")).click(); } public BaseHelper getBaseHelper() { return baseHelper; } }
Revert "Grouphelper small changes" This reverts commit 0d5618c227e72d18a8403e8072334303d960c3e9.
addressbook-web-tests/src/test/java/nwo/stqa/addressbook/appmanager/GroupHelper.java
Revert "Grouphelper small changes"
<ide><path>ddressbook-web-tests/src/test/java/nwo/stqa/addressbook/appmanager/GroupHelper.java <ide> public class GroupHelper { <ide> private FirefoxDriver wd; <ide> <del> private BaseHelper baseHelper; <del> <ide> public GroupHelper(FirefoxDriver wd) { <ide> this.wd = wd; <del> baseHelper = new BaseHelper(wd); <ide> } <ide> <ide> public void returnToGroupPage() { <ide> } <ide> <ide> public void fillGroupForm(GroupData groupData) { <del> baseHelper.selectGroupName(); <del> baseHelper.setGroupName(groupData); <del> baseHelper.selectGroupHeader(); <del> baseHelper.setGroupHeader(groupData); <del> baseHelper.selectGroupFooter(); <del> baseHelper.setGroupFooter(groupData); <add> wd.findElement(By.name("group_name")).click(); <add> wd.findElement(By.name("group_name")).clear(); <add> wd.findElement(By.name("group_name")).sendKeys(groupData.getName()); <add> wd.findElement(By.name("group_header")).click(); <add> wd.findElement(By.name("group_header")).clear(); <add> wd.findElement(By.name("group_header")).sendKeys(groupData.getHeader()); <add> wd.findElement(By.name("group_footer")).click(); <add> wd.findElement(By.name("group_footer")).clear(); <add> wd.findElement(By.name("group_footer")).sendKeys(groupData.getFooter()); <add> wd.findElement(By.name("group_footer")).click(); <ide> } <ide> <ide> public void initGroupCreation() { <ide> public void selectGroup() { <ide> wd.findElement(By.name("selected[]")).click(); <ide> } <del> <del> public BaseHelper getBaseHelper() { <del> return baseHelper; <del> } <ide> }
Java
apache-2.0
cfa26c943908aa373fe4ce401027cdba8aa7e113
0
vert-x3/vertx-auth,vert-x3/vertx-auth
/* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.auth.webauthn.impl; import com.fasterxml.jackson.core.JsonParser; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.PRNG; import io.vertx.ext.auth.User; import io.vertx.ext.auth.impl.UserImpl; import io.vertx.ext.auth.webauthn.*; import io.vertx.ext.auth.webauthn.impl.attestation.Attestation; import io.vertx.ext.auth.webauthn.impl.attestation.AttestationException; import io.vertx.ext.jwt.JWK; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class WebAuthnImpl implements WebAuthn { private static final Logger LOG = LoggerFactory.getLogger(WebAuthnImpl.class); // codecs private final Base64.Encoder b64enc = Base64.getUrlEncoder().withoutPadding(); private final Base64.Decoder b64dec = Base64.getUrlDecoder(); private final MessageDigest sha256; private final PRNG random; private final WebAuthnOptions options; private final CredentialStore store; private final Map<String, Attestation> attestations = new HashMap<>(); public WebAuthnImpl(Vertx vertx, WebAuthnOptions options, CredentialStore store) { random = new PRNG(vertx); this.options = options; this.store = store; if (options == null || store == null) { throw new IllegalArgumentException("options and store cannot be null!"); } ServiceLoader<Attestation> attestationServiceLoader = ServiceLoader.load(Attestation.class); for (Attestation att : attestationServiceLoader) { attestations.put(att.fmt(), att); } try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsae) { throw new IllegalStateException("SHA-256 is not available", nsae); } } private String randomBase64URLBuffer(int length) { final byte[] buff = new byte[length]; random.nextBytes(buff); return b64enc.encodeToString(buff); } @Override public WebAuthn createCredentialsOptions(JsonObject user, Handler<AsyncResult<JsonObject>> handler) { store.getUserCredentialsByName(user.getString("name"), getUserCredentials -> { if (getUserCredentials.failed()) { handler.handle(Future.failedFuture(getUserCredentials.cause())); return; } List<JsonObject> credentials = getUserCredentials.result(); if (credentials == null || credentials.size() == 0) { // generate a new ID for this new potential user final String id = store.generateId(); // STEP 2 Generate Credential Challenge final JsonObject authenticatorSelection = options.getAuthenticatorSelection(); final JsonArray pubKeyCredParams = new JsonArray(); for (String pubKeyCredParam : options.getPubKeyCredParams()) { switch (pubKeyCredParam) { case "ES256": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -7)); break; case "ES384": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -35)); break; case "ES512": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -36)); break; case "RS256": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -257)); break; case "RS384": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -258)); break; case "RS512": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -259)); break; case "RS1": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -65535)); break; default: LOG.warn("Unsupported algorithm: " + pubKeyCredParam); } } // user configuration final JsonObject _user = new JsonObject() .put("id", id) .put("name", user.getString("name")) .put("displayName", user.getString("displayName")); if (user.getString("icon") != null) { _user.put("icon", user.getString("icon")); } // final assembly final JsonObject publicKey = new JsonObject() .put("challenge", randomBase64URLBuffer(options.getChallengeLength())) .put("rp", options.getRelayParty().toJson()) .put("user", _user) .put("authenticatorSelection", authenticatorSelection) .put("pubKeyCredParams", pubKeyCredParams); if (options.getAttestation() != null) { publicKey.put("attestation", options.getAttestation().toString()); } if (options.getTimeout() > 0) { publicKey.put("timeout", options.getTimeout()); } handler.handle(Future.succeededFuture(publicKey)); } else { handler.handle(Future.failedFuture("User exists!")); } }); return this; } @Override public WebAuthn getCredentialsOptions(String username, Handler<AsyncResult<JsonObject>> handler) { // we allow Resident Credentials or (RK) requests // this means that username is not required if (options.getRequireResidentKey() != null && options.getRequireResidentKey()) { if (username == null) { handler.handle(Future.succeededFuture( new JsonObject() .put("challenge", randomBase64URLBuffer(options.getChallengeLength())))); return this; } } // fallback to non RK requests store.getUserCredentialsByName(username, getUserCredentials -> { if (getUserCredentials.failed()) { handler.handle(Future.failedFuture(getUserCredentials.cause())); return; } List<JsonObject> credentials = getUserCredentials.result(); if (credentials == null) { handler.handle(Future.failedFuture("Invalid username/account disabled.")); return; } JsonArray allowCredentials = new JsonArray(); JsonArray transports = new JsonArray(); for (String transport : options.getTransports()) { transports.add(transport); } // STEP 19 Return allow credential ID for (JsonObject cred : credentials) { String credId = cred.getString("credID"); if (credId != null) { allowCredentials .add(new JsonObject() .put("type", "public-key") .put("id", credId) .put("transports", transports)); } } handler.handle(Future.succeededFuture( new JsonObject() .put("challenge", randomBase64URLBuffer(options.getChallengeLength())) .put("allowCredentials", allowCredentials) )); }); return this; } @Override public void authenticate(WebAuthnInfo authInfo, Handler<AsyncResult<User>> handler) { // { // "rawId": "base64url", // "id": "base64url", // "response": { // "attestationObject": "base64url", // "clientDataJSON": "base64url" // }, // "getClientExtensionResults": {}, // "type": "public-key" // } final JsonObject webauthnResp = authInfo.getWebauthn(); if (webauthnResp == null) { handler.handle(Future.failedFuture("webauthn can't be null!")); return; } // response can't be null final JsonObject response = webauthnResp.getJsonObject("response"); if (response == null) { handler.handle(Future.failedFuture("wenauthn response can't be null!")); return; } byte[] clientDataJSON = b64dec.decode(response.getString("clientDataJSON")); JsonObject clientData = new JsonObject(Buffer.buffer(clientDataJSON)); // Verify challenge is match with session if (!clientData.getString("challenge").equals(authInfo.getChallenge())) { handler.handle(Future.failedFuture("Challenges don't match!")); return; } // STEP 9 Verify origin is match with session if (!clientData.getString("origin").equals(options.getOrigin())) { handler.handle(Future.failedFuture("Origins don't match!")); return; } final String username = authInfo.getUsername(); switch (clientData.getString("type")) { case "webauthn.create": // we always need a username to register if (username == null) { handler.handle(Future.failedFuture("username can't be null!")); return; } try { final JsonObject authrInfo = verifyWebAuthNCreate(webauthnResp, clientDataJSON, clientData); // the principal for vertx-auth JsonObject principal = new JsonObject() .put("credID", authrInfo.getString("credID")) .put("publicKey", authrInfo.getString("publicKey")) .put("counter", authrInfo.getLong("counter", 0L)); // by default the store can upsert if a credential is missing, the user has been verified so it is valid // the store however might dissallow this operation JsonObject storeItem = new JsonObject() .mergeIn(principal) .put("username", username); store.updateUserCredential(authrInfo.getString("credID"), storeItem, true, updateUserCredential -> { if (updateUserCredential.failed()) { handler.handle(Future.failedFuture(updateUserCredential.cause())); } else { handler.handle(Future.succeededFuture(new UserImpl(principal))); } }); } catch (RuntimeException | IOException e) { handler.handle(Future.failedFuture(e)); } return; case "webauthn.get": final Handler<AsyncResult<List<JsonObject>>> onGetUserCredentialsByAny = getUserCredentials -> { if (getUserCredentials.failed()) { handler.handle(Future.failedFuture(getUserCredentials.cause())); } else { List<JsonObject> authenticators = getUserCredentials.result(); if (authenticators == null) { authenticators = Collections.emptyList(); } // STEP 24 Query public key base on user ID Optional<JsonObject> authenticator = authenticators.stream() .filter(authr -> webauthnResp.getString("id").equals(authr.getValue("credID"))) .findFirst(); if (!authenticator.isPresent()) { handler.handle(Future.failedFuture("Cannot find an authenticator with id: " + webauthnResp.getString("rawId"))); return; } try { final JsonObject json = authenticator.get(); final long counter = verifyWebAuthNGet(webauthnResp, clientDataJSON, clientData, json); // update the counter on the authenticator json.put("counter", counter); // update the credential (the important here is to update the counter) store.updateUserCredential(webauthnResp.getString("rawId"), json, false, updateUserCredential -> { if (updateUserCredential.failed()) { handler.handle(Future.failedFuture(updateUserCredential.cause())); return; } handler.handle(Future.succeededFuture(new UserImpl(json))); }); } catch (RuntimeException | IOException e) { handler.handle(Future.failedFuture(e)); } } }; if (options.getRequireResidentKey() != null && options.getRequireResidentKey()) { // username are not provided (RK) we now need to lookup by rawId store.getUserCredentialsById(webauthnResp.getString("rawId"), onGetUserCredentialsByAny); } else { // username can't be null if (username == null) { handler.handle(Future.failedFuture("username can't be null!")); return; } store.getUserCredentialsByName(username, onGetUserCredentialsByAny); } return; default: handler.handle(Future.failedFuture("Can not determine type of response!")); } } /** * Verify creadentials from client * * @param webAuthnResponse - Data from navigator.credentials.create */ private JsonObject verifyWebAuthNCreate(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject clientData) throws AttestationException, IOException { JsonObject response = webAuthnResponse.getJsonObject("response"); // STEP 11 Extract attestation Object try (JsonParser parser = CBOR.cborParser(response.getString("attestationObject"))) { // { // "fmt": "fido-u2f", // "authData": "cbor", // "attStmt": { // "sig": "cbor", // "x5c": [ // "cbor" // ] // } // } JsonObject ctapMakeCredResp = new JsonObject(CBOR.<Map>parse(parser)); // STEP 12 Extract auth data AuthenticatorData authrDataStruct = new AuthenticatorData(ctapMakeCredResp.getString("authData")); // STEP 13 Extract public key byte[] publicKey = authrDataStruct.getCredentialPublicKey(); final String fmt = ctapMakeCredResp.getString("fmt"); // STEP 14 Verify attestation based on type of device final Attestation attestation = attestations.get(fmt); if (attestation == null) { throw new AttestationException("Unknown attestation fmt: " + fmt); } else { // perform the verification attestation.verify(webAuthnResponse, clientDataJSON, ctapMakeCredResp, authrDataStruct); } // STEP 15 Create data for save to database return new JsonObject() .put("fmt", fmt) .put("publicKey", b64enc.encodeToString(publicKey)) .put("counter", authrDataStruct.getSignCounter()) .put("credID", b64enc.encodeToString(authrDataStruct.getCredentialId())); } } /** * @param webAuthnResponse - Data from navigator.credentials.get * @param authr - Credential from Database */ private long verifyWebAuthNGet(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject clientData, JsonObject authr) throws IOException, AttestationException { JsonObject response = webAuthnResponse.getJsonObject("response"); // STEP 25 parse auth data byte[] authenticatorData = b64dec.decode(response.getString("authenticatorData")); AuthenticatorData authrDataStruct = new AuthenticatorData(authenticatorData); if (!authrDataStruct.is(AuthenticatorData.USER_PRESENT)) { throw new RuntimeException("User was NOT present durring authentication!"); } // TODO: assert the algorithm to be SHA-256 clientData.getString("hashAlgorithm") ? // STEP 26 hash clientDataJSON with sha256 byte[] clientDataHash = hash(clientDataJSON); // STEP 27 create signature base by concat authenticatorData and clientDataHash Buffer signatureBase = Buffer.buffer() .appendBytes(authenticatorData) .appendBytes(clientDataHash); // STEP 28 format public key try (JsonParser parser = CBOR.cborParser(authr.getString("publicKey"))) { // the decoded credential primary as a JWK JWK publicKey = COSE.toJWK(CBOR.parse(parser)); // STEP 29 convert signature to buffer byte[] signature = b64dec.decode(response.getString("signature")); // STEP 30 verify signature boolean verified = publicKey.verify(signature, signatureBase.getBytes()); if (!verified) { throw new AttestationException("Failed to verify the signature!"); } if (authrDataStruct.getSignCounter() <= authr.getLong("counter")) { throw new AttestationException("Authr counter did not increase!"); } // return the counter so it can be updated on the store return authrDataStruct.getSignCounter(); } } private byte[] hash(byte[] data) { synchronized (sha256) { sha256.update(data); return sha256.digest(); } } }
vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/WebAuthnImpl.java
/* * Copyright 2019 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.auth.webauthn.impl; import com.fasterxml.jackson.core.JsonParser; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.PRNG; import io.vertx.ext.auth.User; import io.vertx.ext.auth.impl.UserImpl; import io.vertx.ext.auth.webauthn.*; import io.vertx.ext.auth.webauthn.impl.attestation.Attestation; import io.vertx.ext.auth.webauthn.impl.attestation.AttestationException; import io.vertx.ext.jwt.JWK; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class WebAuthnImpl implements WebAuthn { private static final Logger LOG = LoggerFactory.getLogger(WebAuthnImpl.class); // codecs private final Base64.Encoder b64enc = Base64.getUrlEncoder().withoutPadding(); private final Base64.Decoder b64dec = Base64.getUrlDecoder(); private final MessageDigest sha256; private final PRNG random; private final WebAuthnOptions options; private final CredentialStore store; private final Map<String, Attestation> attestations = new HashMap<>(); public WebAuthnImpl(Vertx vertx, WebAuthnOptions options, CredentialStore store) { random = new PRNG(vertx); this.options = options; this.store = store; if (options == null || store == null) { throw new IllegalArgumentException("options and store cannot be null!"); } ServiceLoader<Attestation> attestationServiceLoader = ServiceLoader.load(Attestation.class); for (Attestation att : attestationServiceLoader) { attestations.put(att.fmt(), att); } try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException nsae) { throw new IllegalStateException("SHA-256 is not available", nsae); } } private String randomBase64URLBuffer(int length) { final byte[] buff = new byte[length]; random.nextBytes(buff); return b64enc.encodeToString(buff); } @Override public WebAuthn createCredentialsOptions(JsonObject user, Handler<AsyncResult<JsonObject>> handler) { store.getUserCredentialsByName(user.getString("name"), getUserCredentials -> { if (getUserCredentials.failed()) { handler.handle(Future.failedFuture(getUserCredentials.cause())); return; } List<JsonObject> credentials = getUserCredentials.result(); if (credentials == null || credentials.size() == 0) { // generate a new ID for this new potential user final String id = store.generateId(); // STEP 2 Generate Credential Challenge final JsonObject authenticatorSelection = options.getAuthenticatorSelection(); final JsonArray pubKeyCredParams = new JsonArray(); for (String pubKeyCredParam : options.getPubKeyCredParams()) { switch (pubKeyCredParam) { case "ES256": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -7)); break; case "ES384": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -35)); break; case "ES512": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -36)); break; case "RS256": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -257)); break; case "RS384": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -258)); break; case "RS512": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -259)); break; case "RS1": pubKeyCredParams.add( new JsonObject() .put("type", "public-key") .put("alg", -65535)); break; default: LOG.warn("Unsupported algorithm: " + pubKeyCredParam); } } // user configuration final JsonObject _user = new JsonObject() .put("id", id) .put("name", user.getString("name")) .put("displayName", user.getString("displayName")); if (user.getString("icon") != null) { _user.put("icon", user.getString("icon")); } // final assembly final JsonObject publicKey = new JsonObject() .put("challenge", randomBase64URLBuffer(options.getChallengeLength())) .put("rp", options.getRelayParty()) .put("user", _user) .put("authenticatorSelection", authenticatorSelection) .put("pubKeyCredParams", pubKeyCredParams); if (options.getAttestation() != null) { publicKey.put("attestation", options.getAttestation().toString()); } if (options.getTimeout() > 0) { publicKey.put("timeout", options.getTimeout()); } handler.handle(Future.succeededFuture(publicKey)); } else { handler.handle(Future.failedFuture("User exists!")); } }); return this; } @Override public WebAuthn getCredentialsOptions(String username, Handler<AsyncResult<JsonObject>> handler) { // we allow Resident Credentials or (RK) requests // this means that username is not required if (options.getRequireResidentKey() != null && options.getRequireResidentKey()) { if (username == null) { handler.handle(Future.succeededFuture( new JsonObject() .put("challenge", randomBase64URLBuffer(options.getChallengeLength())))); return this; } } // fallback to non RK requests store.getUserCredentialsByName(username, getUserCredentials -> { if (getUserCredentials.failed()) { handler.handle(Future.failedFuture(getUserCredentials.cause())); return; } List<JsonObject> credentials = getUserCredentials.result(); if (credentials == null) { handler.handle(Future.failedFuture("Invalid username/account disabled.")); return; } JsonArray allowCredentials = new JsonArray(); JsonArray transports = new JsonArray(); for (String transport : options.getTransports()) { transports.add(transport); } // STEP 19 Return allow credential ID for (JsonObject cred : credentials) { String credId = cred.getString("credID"); if (credId != null) { allowCredentials .add(new JsonObject() .put("type", "public-key") .put("id", credId) .put("transports", transports)); } } handler.handle(Future.succeededFuture( new JsonObject() .put("challenge", randomBase64URLBuffer(options.getChallengeLength())) .put("allowCredentials", allowCredentials) )); }); return this; } @Override public void authenticate(WebAuthnInfo authInfo, Handler<AsyncResult<User>> handler) { // { // "rawId": "base64url", // "id": "base64url", // "response": { // "attestationObject": "base64url", // "clientDataJSON": "base64url" // }, // "getClientExtensionResults": {}, // "type": "public-key" // } final JsonObject webauthnResp = authInfo.getWebauthn(); if (webauthnResp == null) { handler.handle(Future.failedFuture("webauthn can't be null!")); return; } // response can't be null final JsonObject response = webauthnResp.getJsonObject("response"); if (response == null) { handler.handle(Future.failedFuture("wenauthn response can't be null!")); return; } byte[] clientDataJSON = b64dec.decode(response.getString("clientDataJSON")); JsonObject clientData = new JsonObject(Buffer.buffer(clientDataJSON)); // Verify challenge is match with session if (!clientData.getString("challenge").equals(authInfo.getChallenge())) { handler.handle(Future.failedFuture("Challenges don't match!")); return; } // STEP 9 Verify origin is match with session if (!clientData.getString("origin").equals(options.getOrigin())) { handler.handle(Future.failedFuture("Origins don't match!")); return; } final String username = authInfo.getUsername(); switch (clientData.getString("type")) { case "webauthn.create": // we always need a username to register if (username == null) { handler.handle(Future.failedFuture("username can't be null!")); return; } try { final JsonObject authrInfo = verifyWebAuthNCreate(webauthnResp, clientDataJSON, clientData); // the principal for vertx-auth JsonObject principal = new JsonObject() .put("credID", authrInfo.getString("credID")) .put("publicKey", authrInfo.getString("publicKey")) .put("counter", authrInfo.getLong("counter", 0L)); // by default the store can upsert if a credential is missing, the user has been verified so it is valid // the store however might dissallow this operation JsonObject storeItem = new JsonObject() .mergeIn(principal) .put("username", username); store.updateUserCredential(authrInfo.getString("credID"), storeItem, true, updateUserCredential -> { if (updateUserCredential.failed()) { handler.handle(Future.failedFuture(updateUserCredential.cause())); } else { handler.handle(Future.succeededFuture(new UserImpl(principal))); } }); } catch (RuntimeException | IOException e) { handler.handle(Future.failedFuture(e)); } return; case "webauthn.get": final Handler<AsyncResult<List<JsonObject>>> onGetUserCredentialsByAny = getUserCredentials -> { if (getUserCredentials.failed()) { handler.handle(Future.failedFuture(getUserCredentials.cause())); } else { List<JsonObject> authenticators = getUserCredentials.result(); if (authenticators == null) { authenticators = Collections.emptyList(); } // STEP 24 Query public key base on user ID Optional<JsonObject> authenticator = authenticators.stream() .filter(authr -> webauthnResp.getString("id").equals(authr.getValue("credID"))) .findFirst(); if (!authenticator.isPresent()) { handler.handle(Future.failedFuture("Cannot find an authenticator with id: " + webauthnResp.getString("rawId"))); return; } try { final JsonObject json = authenticator.get(); final long counter = verifyWebAuthNGet(webauthnResp, clientDataJSON, clientData, json); // update the counter on the authenticator json.put("counter", counter); // update the credential (the important here is to update the counter) store.updateUserCredential(webauthnResp.getString("rawId"), json, false, updateUserCredential -> { if (updateUserCredential.failed()) { handler.handle(Future.failedFuture(updateUserCredential.cause())); return; } handler.handle(Future.succeededFuture(new UserImpl(json))); }); } catch (RuntimeException | IOException e) { handler.handle(Future.failedFuture(e)); } } }; if (options.getRequireResidentKey() != null && options.getRequireResidentKey()) { // username are not provided (RK) we now need to lookup by rawId store.getUserCredentialsById(webauthnResp.getString("rawId"), onGetUserCredentialsByAny); } else { // username can't be null if (username == null) { handler.handle(Future.failedFuture("username can't be null!")); return; } store.getUserCredentialsByName(username, onGetUserCredentialsByAny); } return; default: handler.handle(Future.failedFuture("Can not determine type of response!")); } } /** * Verify creadentials from client * * @param webAuthnResponse - Data from navigator.credentials.create */ private JsonObject verifyWebAuthNCreate(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject clientData) throws AttestationException, IOException { JsonObject response = webAuthnResponse.getJsonObject("response"); // STEP 11 Extract attestation Object try (JsonParser parser = CBOR.cborParser(response.getString("attestationObject"))) { // { // "fmt": "fido-u2f", // "authData": "cbor", // "attStmt": { // "sig": "cbor", // "x5c": [ // "cbor" // ] // } // } JsonObject ctapMakeCredResp = new JsonObject(CBOR.<Map>parse(parser)); // STEP 12 Extract auth data AuthenticatorData authrDataStruct = new AuthenticatorData(ctapMakeCredResp.getString("authData")); // STEP 13 Extract public key byte[] publicKey = authrDataStruct.getCredentialPublicKey(); final String fmt = ctapMakeCredResp.getString("fmt"); // STEP 14 Verify attestation based on type of device final Attestation attestation = attestations.get(fmt); if (attestation == null) { throw new AttestationException("Unknown attestation fmt: " + fmt); } else { // perform the verification attestation.verify(webAuthnResponse, clientDataJSON, ctapMakeCredResp, authrDataStruct); } // STEP 15 Create data for save to database return new JsonObject() .put("fmt", fmt) .put("publicKey", b64enc.encodeToString(publicKey)) .put("counter", authrDataStruct.getSignCounter()) .put("credID", b64enc.encodeToString(authrDataStruct.getCredentialId())); } } /** * @param webAuthnResponse - Data from navigator.credentials.get * @param authr - Credential from Database */ private long verifyWebAuthNGet(JsonObject webAuthnResponse, byte[] clientDataJSON, JsonObject clientData, JsonObject authr) throws IOException, AttestationException { JsonObject response = webAuthnResponse.getJsonObject("response"); // STEP 25 parse auth data byte[] authenticatorData = b64dec.decode(response.getString("authenticatorData")); AuthenticatorData authrDataStruct = new AuthenticatorData(authenticatorData); if (!authrDataStruct.is(AuthenticatorData.USER_PRESENT)) { throw new RuntimeException("User was NOT present durring authentication!"); } // TODO: assert the algorithm to be SHA-256 clientData.getString("hashAlgorithm") ? // STEP 26 hash clientDataJSON with sha256 byte[] clientDataHash = hash(clientDataJSON); // STEP 27 create signature base by concat authenticatorData and clientDataHash Buffer signatureBase = Buffer.buffer() .appendBytes(authenticatorData) .appendBytes(clientDataHash); // STEP 28 format public key try (JsonParser parser = CBOR.cborParser(authr.getString("publicKey"))) { // the decoded credential primary as a JWK JWK publicKey = COSE.toJWK(CBOR.parse(parser)); // STEP 29 convert signature to buffer byte[] signature = b64dec.decode(response.getString("signature")); // STEP 30 verify signature boolean verified = publicKey.verify(signature, signatureBase.getBytes()); if (!verified) { throw new AttestationException("Failed to verify the signature!"); } if (authrDataStruct.getSignCounter() <= authr.getLong("counter")) { throw new AttestationException("Authr counter did not increase!"); } // return the counter so it can be updated on the store return authrDataStruct.getSignCounter(); } } private byte[] hash(byte[] data) { synchronized (sha256) { sha256.update(data); return sha256.digest(); } } }
explicit cast to json
vertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/WebAuthnImpl.java
explicit cast to json
<ide><path>ertx-auth-webauthn/src/main/java/io/vertx/ext/auth/webauthn/impl/WebAuthnImpl.java <ide> // final assembly <ide> final JsonObject publicKey = new JsonObject() <ide> .put("challenge", randomBase64URLBuffer(options.getChallengeLength())) <del> .put("rp", options.getRelayParty()) <add> .put("rp", options.getRelayParty().toJson()) <ide> .put("user", _user) <ide> .put("authenticatorSelection", authenticatorSelection) <ide> .put("pubKeyCredParams", pubKeyCredParams);
Java
apache-2.0
426c8c7e63d11657b26942ee42f5a1c55c3e526a
0
lemire/simplebitmapbenchmark,lemire/simplebitmapbenchmark
package bitmapbenchmarks.synth; import it.uniroma3.mat.extendedset.intset.ConciseSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Iterator; import java.util.TreeSet; import org.roaringbitmap.*; import org.devbrat.util.WAHBitSet; import sparsebitmap.SparseBitmap; import com.googlecode.javaewah.EWAHCompressedBitmap; import com.googlecode.javaewah32.EWAHCompressedBitmap32; import com.zaxxer.sparsebits.*; public class Benchmark { public static void main(String args[]) { test(10, 18, 10); System.out .println("Remaining tests are 'stress tests' over many bitmaps."); test(10 * 16 * 4, 10, 2); } public static long testWAH32(int[][] data, int repeat, DecimalFormat df) { System.out.println("# WAH 32 bit using the compressedbitset library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); WAHBitSet[] bitmap = new WAHBitSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new WAHBitSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += bitmap[k].memSize() * 4; } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = new int[bitmap[k].cardinality()]; int c = 0; for (@SuppressWarnings("unchecked") Iterator<Integer> i = bitmap[k].iterator(); i.hasNext(); array[c++] = i .next().intValue()) { } } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { WAHBitSet bitmapor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapor = bitmapor.or(bitmap[j]); } int[] array = new int[bitmapor.cardinality()]; int c = 0; for (@SuppressWarnings("unchecked") Iterator<Integer> i = bitmapor.iterator(); i.hasNext(); array[c++] = i .next().intValue()) { } bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { WAHBitSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.and(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int c = 0; for (@SuppressWarnings("unchecked") Iterator<Integer> i = bitmapand.iterator(); i.hasNext(); array[c++] = i .next().intValue()) { } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testRoaringBitmap(int[][] data, int repeat, DecimalFormat df) { System.out.println("# RoaringBitmap"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections and xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); RoaringBitmap[] bitmap = new RoaringBitmap[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new RoaringBitmap(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += bitmap[k].getSizeInBytes(); } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { RoaringBitmap bitmapor = FastAggregation.horizontal_or(Arrays.copyOf(bitmap, k+1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { RoaringBitmap bitmapand = FastAggregation.and(Arrays.copyOf(bitmap, k+1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { RoaringBitmap bitmapxor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapxor = RoaringBitmap.xor(bitmapxor,bitmap[j]); } int[] array = bitmapxor.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } private static long estimateSizeInBytes(Object bs) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); // Note: you could use a file output steam instead of ByteArrayOutputStream ObjectOutputStream oo; try { oo = new ObjectOutputStream(bos); oo.writeObject(bs); oo.close(); return bos.toByteArray().length; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; } public static long testSparseBitSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# SparseBitSet"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections and xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); SparseBitSet[] bitmap = new SparseBitSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new SparseBitSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = new int[bitmap[k].cardinality()]; int pos = 0; for (int i = bitmap[k].nextSetBit(0); i >= 0; i = bitmap[k] .nextSetBit(i + 1)) { array[pos++] = i; } } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitSet bitmapor = bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapor.or(bitmap[j]); } int[] array = new int[bitmapor.cardinality()]; int pos = 0; for (int i = bitmapor.nextSetBit(0); i >= 0; i = bitmapor .nextSetBit(i + 1)) { array[pos++] = i; } bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitSet bitmapand = bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.and(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitSet bitmapand = bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.xor(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } @SuppressWarnings("unchecked") public static long testTreeSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# Tree Set"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); TreeSet<Integer>[] bitmap = new TreeSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new TreeSet<Integer>(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { TreeSet<Integer> bitmapor = new TreeSet<Integer>(); for (int j = 0; j < k + 1; ++j) { bitmapor.addAll(bitmap[k]); } bogus += bitmapor.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { TreeSet<Integer> bitmapand = (TreeSet<Integer>) bitmap[0] .clone(); for (int j = 1; j < k; ++j) { bitmapand.retainAll(bitmap[j]); } bogus += bitmapand.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } @SuppressWarnings("unchecked") public static long testHashSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# Hash Set"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); HashSet<Integer>[] bitmap = new HashSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new HashSet<Integer>(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { HashSet<Integer> bitmapor = new HashSet<Integer>(); for (int j = 0; j < k + 1; ++j) { bitmapor.addAll(bitmap[k]); } bogus += bitmapor.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { HashSet<Integer> bitmapand = (HashSet<Integer>) bitmap[0] .clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.retainAll(bitmap[j]); } bogus += bitmapand.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testInts(int[][] data, int repeat, DecimalFormat df) { System.out.println("# Ints"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += data[k].length * 4; } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[][] b = Arrays.copyOf(data, k + 1); int[] union = IntUtil.unite(b); bogus += union[union.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[][] b = Arrays.copyOf(data, k + 1); int[] inter = IntUtil.intersect(b); if (inter.length > 0) bogus += inter[inter.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testConciseSet(int[][] data, int repeat, DecimalFormat df) { System.out .println("# ConciseSet 32 bit using the extendedset_2.2 library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); ConciseSet[] bitmap = new ConciseSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new ConciseSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += (int) (bitmap[k].size() * bitmap[k] .collectionCompressionRatio()) * 4; } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapor = bitmapor.union(bitmap[j]); } int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.intersection(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.symmetricDifference(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testWAHViaConciseSet(int[][] data, int repeat, DecimalFormat df) { System.out .println("# WAH 32 bit using the extendedset_2.2 library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); ConciseSet[] bitmap = new ConciseSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new ConciseSet(true); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += (int) (bitmap[k].size() * bitmap[k] .collectionCompressionRatio()) * 4; } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapor = bitmapor.union(bitmap[j]); } int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.intersection(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.symmetricDifference(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testSparse(int[][] data, int repeat, DecimalFormat df) { System.out.println("# simple sparse bitmap implementation"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); SparseBitmap[] bitmap = new SparseBitmap[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new SparseBitmap(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += bitmap[k].sizeInBytes(); } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitmap bitmapor = SparseBitmap.or(Arrays.copyOfRange( bitmap, 0, k + 1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitmap bitmapand = SparseBitmap.materialize(SparseBitmap .fastand(Arrays.copyOfRange(bitmap, 0, k + 1))); int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitmap bitmapand = SparseBitmap .xor(Arrays.copyOfRange(bitmap, 0, k + 1)); int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testBitSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# BitSet"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); BitSet[] bitmap = new BitSet[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { bitmap[k] = new BitSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += bitmap[k].size() / 8; } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = new int[bitmap[k].cardinality()]; int pos = 0; for (int i = bitmap[k].nextSetBit(0); i >= 0; i = bitmap[k] .nextSetBit(i + 1)) { array[pos++] = i; } } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { BitSet bitmapor = (BitSet) bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapor.or(bitmap[j]); } int[] array = new int[bitmapor.cardinality()]; int pos = 0; for (int i = bitmapor.nextSetBit(0); i >= 0; i = bitmapor .nextSetBit(i + 1)) { array[pos++] = i; } bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { BitSet bitmapand = (BitSet) bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.and(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { BitSet bitmapand = (BitSet) bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.xor(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testEWAH64(int[][] data, int repeat, DecimalFormat df) { System.out.println("# EWAH using the javaewah library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor"); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); EWAHCompressedBitmap[] ewah = new EWAHCompressedBitmap[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { ewah[k] = new EWAHCompressedBitmap(); for (int x = 0; x < data[k].length; ++x) { ewah[k].set(data[k][x]); } ewah[k].trim(); } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += ewah[k].sizeInBytes(); } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = ewah[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap bitmapor = EWAHCompressedBitmap.or(Arrays .copyOf(ewah, k + 1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical and + retrieval 2-by-2 bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap bitmapand = EWAHCompressedBitmap .and(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical xor + retrieval 2-by-2 bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap bitmapand = EWAHCompressedBitmap .xor(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testEWAH32(int[][] data, int repeat, DecimalFormat df) { System.out.println("# EWAH 32-bit using the javaewah library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); EWAHCompressedBitmap32[] ewah = new EWAHCompressedBitmap32[N]; for (int r = 0; r < repeat; ++r) { for (int k = 0; k < N; ++k) { ewah[k] = new EWAHCompressedBitmap32(); for (int x = 0; x < data[k].length; ++x) { ewah[k].set(data[k][x]); } ewah[k].trim(); } } aft = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += ewah[k].sizeInBytes(); } line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = ewah[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap32 bitmapor = EWAHCompressedBitmap32 .or(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap32 bitmapand = EWAHCompressedBitmap32 .and(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap32 bitmapand = EWAHCompressedBitmap32 .xor(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } @SuppressWarnings("unused") public static void test(int N, int nbr, int repeat) { System.out.println("# running test with N = "+N+" nbr = "+ nbr+ " repeat = "+repeat); DecimalFormat df = new DecimalFormat("0.###"); ClusteredDataGenerator cdg = new ClusteredDataGenerator(); System.out .println("# For each instance, we report the size, the construction time, "); System.out.println("# the time required to recover the set bits,"); System.out .println("# and the time required to compute logical ors (unions) between lots of bitmaps."); for (int sparsity = 1; sparsity < 30 - nbr; sparsity += 4) { int[][] data = new int[N][]; int Max = (1 << (nbr + sparsity)); System.out.println("# generating random data..."); int[] inter = cdg.generateClustered(1 << (nbr / 2), Max); int counter = 0; for (int k = 0; k < N; ++k) { data[k] = IntUtil.unite(inter, cdg.generateClustered(1 << nbr, Max)); counter += data[k].length; } System.out.println("# generating random data... ok."); System.out.println("# average set bit per 32-bit word = " + df.format((counter / (data.length / 32.0 * Max)))); // building testRoaringBitmap(data, repeat, df); testInts(data, repeat, df); testBitSet(data, repeat, df); testSparseBitSet(data, repeat, df); testSparse(data, repeat, df); testConciseSet(data, repeat, df); testWAHViaConciseSet(data, repeat, df); testWAH32(data, repeat, df); testEWAH64(data, repeat, df); testEWAH32(data, repeat, df); System.out.println(); } } }
src/bitmapbenchmarks/synth/Benchmark.java
package bitmapbenchmarks.synth; import it.uniroma3.mat.extendedset.intset.ConciseSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.text.DecimalFormat; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Iterator; import java.util.TreeSet; import org.roaringbitmap.*; import org.devbrat.util.WAHBitSet; import sparsebitmap.SparseBitmap; import com.googlecode.javaewah.EWAHCompressedBitmap; import com.googlecode.javaewah32.EWAHCompressedBitmap32; import com.zaxxer.sparsebits.*; public class Benchmark { public static void main(String args[]) { test(10, 18, 10); System.out .println("Remaining tests are 'stress tests' over many bitmaps."); test(10 * 16 * 4, 10, 2); } public static long testWAH32(int[][] data, int repeat, DecimalFormat df) { System.out.println("# WAH 32 bit using the compressedbitset library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); WAHBitSet[] bitmap = new WAHBitSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new WAHBitSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } size += bitmap[k].memSize() * 4; } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = new int[bitmap[k].cardinality()]; int c = 0; for (@SuppressWarnings("unchecked") Iterator<Integer> i = bitmap[k].iterator(); i.hasNext(); array[c++] = i .next().intValue()) { } } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { WAHBitSet bitmapor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapor = bitmapor.or(bitmap[j]); } int[] array = new int[bitmapor.cardinality()]; int c = 0; for (@SuppressWarnings("unchecked") Iterator<Integer> i = bitmapor.iterator(); i.hasNext(); array[c++] = i .next().intValue()) { } bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { WAHBitSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.and(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int c = 0; for (@SuppressWarnings("unchecked") Iterator<Integer> i = bitmapand.iterator(); i.hasNext(); array[c++] = i .next().intValue()) { } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testRoaringBitmap(int[][] data, int repeat, DecimalFormat df) { System.out.println("# RoaringBitmap"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections and xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); RoaringBitmap[] bitmap = new RoaringBitmap[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new RoaringBitmap(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } size += bitmap[k].getSizeInBytes(); } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { RoaringBitmap bitmapor = FastAggregation.horizontal_or(Arrays.copyOf(bitmap, k+1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { RoaringBitmap bitmapand = FastAggregation.and(Arrays.copyOf(bitmap, k+1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { RoaringBitmap bitmapxor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapxor = RoaringBitmap.xor(bitmapxor,bitmap[j]); } int[] array = bitmapxor.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } private static long estimateSizeInBytes(SparseBitSet sbs) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); // Note: you could use a file output steam instead of ByteArrayOutputStream ObjectOutputStream oo; try { oo = new ObjectOutputStream(bos); oo.writeObject(sbs); oo.close(); return bos.toByteArray().length; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; } public static long testSparseBitSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# SparseBitSet"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections and xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); SparseBitSet[] bitmap = new SparseBitSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new SparseBitSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = new int[bitmap[k].cardinality()]; int pos = 0; for (int i = bitmap[k].nextSetBit(0); i >= 0; i = bitmap[k] .nextSetBit(i + 1)) { array[pos++] = i; } } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitSet bitmapor = bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapor.or(bitmap[j]); } int[] array = new int[bitmapor.cardinality()]; int pos = 0; for (int i = bitmapor.nextSetBit(0); i >= 0; i = bitmapor .nextSetBit(i + 1)) { array[pos++] = i; } bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitSet bitmapand = bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.and(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitSet bitmapand = bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.xor(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } @SuppressWarnings("unchecked") public static long testTreeSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# Tree Set"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); TreeSet<Integer>[] bitmap = new TreeSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new TreeSet<Integer>(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { TreeSet<Integer> bitmapor = new TreeSet<Integer>(); for (int j = 0; j < k + 1; ++j) { bitmapor.addAll(bitmap[k]); } bogus += bitmapor.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { TreeSet<Integer> bitmapand = (TreeSet<Integer>) bitmap[0] .clone(); for (int j = 1; j < k; ++j) { bitmapand.retainAll(bitmap[j]); } bogus += bitmapand.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } @SuppressWarnings("unchecked") public static long testHashSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# Hash Set"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); HashSet<Integer>[] bitmap = new HashSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new HashSet<Integer>(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { HashSet<Integer> bitmapor = new HashSet<Integer>(); for (int j = 0; j < k + 1; ++j) { bitmapor.addAll(bitmap[k]); } bogus += bitmapor.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + extraction bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { HashSet<Integer> bitmapand = (HashSet<Integer>) bitmap[0] .clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.retainAll(bitmap[j]); } bogus += bitmapand.size(); } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testInts(int[][] data, int repeat, DecimalFormat df) { System.out.println("# Ints"); System.out .println("# size, construction time, time to recover set bits, time to compute unions and intersections "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); int size = 0; for (int k = 0; k < N; ++k) { size += data[k].length * 4; } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[][] b = Arrays.copyOf(data, k + 1); int[] union = IntUtil.unite(b); bogus += union[union.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[][] b = Arrays.copyOf(data, k + 1); int[] inter = IntUtil.intersect(b); if (inter.length > 0) bogus += inter[inter.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testConciseSet(int[][] data, int repeat, DecimalFormat df) { System.out .println("# ConciseSet 32 bit using the extendedset_2.2 library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); ConciseSet[] bitmap = new ConciseSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new ConciseSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } size += (int) (bitmap[k].size() * bitmap[k] .collectionCompressionRatio()) * 4; } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapor = bitmapor.union(bitmap[j]); } int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.intersection(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.symmetricDifference(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testWAHViaConciseSet(int[][] data, int repeat, DecimalFormat df) { System.out .println("# WAH 32 bit using the extendedset_2.2 library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); ConciseSet[] bitmap = new ConciseSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new ConciseSet(true); for (int x = 0; x < data[k].length; ++x) { bitmap[k].add(data[k][x]); } size += (int) (bitmap[k].size() * bitmap[k] .collectionCompressionRatio()) * 4; } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapor = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapor = bitmapor.union(bitmap[j]); } int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.intersection(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { ConciseSet bitmapand = bitmap[0]; for (int j = 1; j < k + 1; ++j) { bitmapand = bitmapand.symmetricDifference(bitmap[j]); } int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testSparse(int[][] data, int repeat, DecimalFormat df) { System.out.println("# simple sparse bitmap implementation"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); SparseBitmap[] bitmap = new SparseBitmap[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new SparseBitmap(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } size += bitmap[k].sizeInBytes(); } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = bitmap[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitmap bitmapor = SparseBitmap.or(Arrays.copyOfRange( bitmap, 0, k + 1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitmap bitmapand = SparseBitmap.materialize(SparseBitmap .fastand(Arrays.copyOfRange(bitmap, 0, k + 1))); int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { SparseBitmap bitmapand = SparseBitmap .xor(Arrays.copyOfRange(bitmap, 0, k + 1)); int[] array = bitmapand.toArray(); if (array != null) if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testBitSet(int[][] data, int repeat, DecimalFormat df) { System.out.println("# BitSet"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); BitSet[] bitmap = new BitSet[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { bitmap[k] = new BitSet(); for (int x = 0; x < data[k].length; ++x) { bitmap[k].set(data[k][x]); } size += bitmap[k].size() / 8; } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = new int[bitmap[k].cardinality()]; int pos = 0; for (int i = bitmap[k].nextSetBit(0); i >= 0; i = bitmap[k] .nextSetBit(i + 1)) { array[pos++] = i; } } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { BitSet bitmapor = (BitSet) bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapor.or(bitmap[j]); } int[] array = new int[bitmapor.cardinality()]; int pos = 0; for (int i = bitmapor.nextSetBit(0); i >= 0; i = bitmapor .nextSetBit(i + 1)) { array[pos++] = i; } bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { BitSet bitmapand = (BitSet) bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.and(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { BitSet bitmapand = (BitSet) bitmap[0].clone(); for (int j = 1; j < k + 1; ++j) { bitmapand.xor(bitmap[j]); } int[] array = new int[bitmapand.cardinality()]; int pos = 0; for (int i = bitmapand.nextSetBit(0); i >= 0; i = bitmapand .nextSetBit(i + 1)) { array[pos++] = i; } if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testEWAH64(int[][] data, int repeat, DecimalFormat df) { System.out.println("# EWAH using the javaewah library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor"); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); EWAHCompressedBitmap[] ewah = new EWAHCompressedBitmap[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { ewah[k] = new EWAHCompressedBitmap(); for (int x = 0; x < data[k].length; ++x) { ewah[k].set(data[k][x]); } ewah[k].trim(); size += ewah[k].sizeInBytes(); } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = ewah[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap bitmapor = EWAHCompressedBitmap.or(Arrays .copyOf(ewah, k + 1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical and + retrieval 2-by-2 bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap bitmapand = EWAHCompressedBitmap .and(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical xor + retrieval 2-by-2 bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap bitmapand = EWAHCompressedBitmap .xor(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } public static long testEWAH32(int[][] data, int repeat, DecimalFormat df) { System.out.println("# EWAH 32-bit using the javaewah library"); System.out .println("# size, construction time, time to recover set bits, time to compute unions, intersections, xor "); long bef, aft; String line = ""; long bogus = 0; int N = data.length; bef = System.currentTimeMillis(); EWAHCompressedBitmap32[] ewah = new EWAHCompressedBitmap32[N]; int size = 0; for (int r = 0; r < repeat; ++r) { size = 0; for (int k = 0; k < N; ++k) { ewah[k] = new EWAHCompressedBitmap32(); for (int x = 0; x < data[k].length; ++x) { ewah[k].set(data[k][x]); } ewah[k].trim(); size += ewah[k].sizeInBytes(); } } aft = System.currentTimeMillis(); line += "\t" + size / 1024; line += "\t" + df.format((aft - bef) / 1000.0); // uncompressing bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { int[] array = ewah[k].toArray(); bogus += array.length; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical or + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap32 bitmapor = EWAHCompressedBitmap32 .or(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapor.toArray(); bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical and + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap32 bitmapand = EWAHCompressedBitmap32 .and(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); // fast logical xor + retrieval bef = System.currentTimeMillis(); for (int r = 0; r < repeat; ++r) for (int k = 0; k < N; ++k) { EWAHCompressedBitmap32 bitmapand = EWAHCompressedBitmap32 .xor(Arrays.copyOf(ewah, k + 1)); int[] array = bitmapand.toArray(); if (array.length > 0) bogus += array[array.length - 1]; } aft = System.currentTimeMillis(); line += "\t" + df.format((aft - bef) / 1000.0); System.out.println(line); return bogus; } @SuppressWarnings("unused") public static void test(int N, int nbr, int repeat) { System.out.println("# running test with N = "+N+" nbr = "+ nbr+ " repeat = "+repeat); DecimalFormat df = new DecimalFormat("0.###"); ClusteredDataGenerator cdg = new ClusteredDataGenerator(); System.out .println("# For each instance, we report the size, the construction time, "); System.out.println("# the time required to recover the set bits,"); System.out .println("# and the time required to compute logical ors (unions) between lots of bitmaps."); for (int sparsity = 1; sparsity < 30 - nbr; sparsity += 4) { int[][] data = new int[N][]; int Max = (1 << (nbr + sparsity)); System.out.println("# generating random data..."); int[] inter = cdg.generateClustered(1 << (nbr / 2), Max); int counter = 0; for (int k = 0; k < N; ++k) { data[k] = IntUtil.unite(inter, cdg.generateClustered(1 << nbr, Max)); counter += data[k].length; } System.out.println("# generating random data... ok."); System.out.println("# average set bit per 32-bit word = " + df.format((counter / (data.length / 32.0 * Max)))); // building testRoaringBitmap(data, repeat, df); testInts(data, repeat, df); testBitSet(data, repeat, df); testSparseBitSet(data, repeat, df); testSparse(data, repeat, df); testConciseSet(data, repeat, df); testWAHViaConciseSet(data, repeat, df); testWAH32(data, repeat, df); testEWAH64(data, repeat, df); testEWAH32(data, repeat, df); System.out.println(); } } }
Removed size calculation off the construction loop
src/bitmapbenchmarks/synth/Benchmark.java
Removed size calculation off the construction loop
<ide><path>rc/bitmapbenchmarks/synth/Benchmark.java <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> WAHBitSet[] bitmap = new WAHBitSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new WAHBitSet(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].set(data[k][x]); <ide> } <del> size += bitmap[k].memSize() * 4; <del> } <del> } <del> aft = System.currentTimeMillis(); <add> } <add> } <add> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += bitmap[k].memSize() * 4; <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> RoaringBitmap[] bitmap = new RoaringBitmap[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new RoaringBitmap(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].add(data[k][x]); <ide> } <del> size += bitmap[k].getSizeInBytes(); <ide> } <ide> } <ide> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += bitmap[k].getSizeInBytes(); <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> return bogus; <ide> } <ide> <del> private static long estimateSizeInBytes(SparseBitSet sbs) { <add> private static long estimateSizeInBytes(Object bs) { <ide> ByteArrayOutputStream bos = new ByteArrayOutputStream(); <ide> // Note: you could use a file output steam instead of ByteArrayOutputStream <ide> ObjectOutputStream oo; <ide> try { <ide> oo = new ObjectOutputStream(bos); <del> oo.writeObject(sbs); <add> oo.writeObject(bs); <ide> oo.close(); <ide> return bos.toByteArray().length; <ide> <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> SparseBitSet[] bitmap = new SparseBitSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new SparseBitSet(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].set(data[k][x]); <ide> } <del> size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? <ide> } <ide> } <ide> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> TreeSet<Integer>[] bitmap = new TreeSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new TreeSet<Integer>(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> } <ide> } <ide> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> HashSet<Integer>[] bitmap = new HashSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new HashSet<Integer>(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> } <ide> } <ide> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += estimateSizeInBytes(bitmap[k]);// no straight-forward way to estimate memory usage? <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> long bogus = 0; <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <add> aft = System.currentTimeMillis(); <ide> int size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> size += data[k].length * 4; <ide> } <del> <del> aft = System.currentTimeMillis(); <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> ConciseSet[] bitmap = new ConciseSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new ConciseSet(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].add(data[k][x]); <ide> } <del> size += (int) (bitmap[k].size() * bitmap[k] <del> .collectionCompressionRatio()) * 4; <del> } <del> } <del> aft = System.currentTimeMillis(); <add> } <add> } <add> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += (int) (bitmap[k].size() * bitmap[k] <add> .collectionCompressionRatio()) * 4; <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> ConciseSet[] bitmap = new ConciseSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new ConciseSet(true); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].add(data[k][x]); <ide> } <del> size += (int) (bitmap[k].size() * bitmap[k] <del> .collectionCompressionRatio()) * 4; <ide> } <ide> } <ide> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += (int) (bitmap[k].size() * bitmap[k] <add> .collectionCompressionRatio()) * 4; <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> SparseBitmap[] bitmap = new SparseBitmap[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new SparseBitmap(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].set(data[k][x]); <ide> } <del> size += bitmap[k].sizeInBytes(); <del> } <del> } <del> aft = System.currentTimeMillis(); <add> } <add> } <add> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += bitmap[k].sizeInBytes(); <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> BitSet[] bitmap = new BitSet[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> bitmap[k] = new BitSet(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> bitmap[k].set(data[k][x]); <ide> } <del> size += bitmap[k].size() / 8; <del> } <del> } <del> aft = System.currentTimeMillis(); <add> } <add> } <add> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += bitmap[k].size() / 8; <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> EWAHCompressedBitmap[] ewah = new EWAHCompressedBitmap[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> ewah[k] = new EWAHCompressedBitmap(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> ewah[k].set(data[k][x]); <ide> } <ide> ewah[k].trim(); <del> size += ewah[k].sizeInBytes(); <del> } <del> } <del> aft = System.currentTimeMillis(); <add> } <add> } <add> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += ewah[k].sizeInBytes(); <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing <ide> int N = data.length; <ide> bef = System.currentTimeMillis(); <ide> EWAHCompressedBitmap32[] ewah = new EWAHCompressedBitmap32[N]; <del> int size = 0; <ide> for (int r = 0; r < repeat; ++r) { <del> size = 0; <ide> for (int k = 0; k < N; ++k) { <ide> ewah[k] = new EWAHCompressedBitmap32(); <ide> for (int x = 0; x < data[k].length; ++x) { <ide> ewah[k].set(data[k][x]); <ide> } <ide> ewah[k].trim(); <del> size += ewah[k].sizeInBytes(); <del> } <del> } <del> aft = System.currentTimeMillis(); <add> } <add> } <add> aft = System.currentTimeMillis(); <add> int size = 0; <add> for (int k = 0; k < N; ++k) { <add> size += ewah[k].sizeInBytes(); <add> } <ide> line += "\t" + size / 1024; <ide> line += "\t" + df.format((aft - bef) / 1000.0); <ide> // uncompressing
Java
mit
c232df81471762f77a30b991a8a47d6a5a3d6449
0
detectlanguage/detectlanguage-java
package com.detectlanguage; import com.detectlanguage.errors.APIError; import org.junit.Test; import java.util.Random; import static org.junit.Assert.assertEquals; /** * Copyright 2014 Getty Images * User: dbabichev * Date: 6/23/2014 * Time: 12:41 PM */ public class MultithreadedTest extends BaseTest { public static final String[] SAMPLES = {"Labas rytas", "Hello world", "Buenos dias"}; public static final String[] SAMPLE_CODES = {"lt", "en", "es"}; public static int TEST_THREADS = 10; @Test public void multithreadedRequestExecution() throws InterruptedException { // create a thread for each request RequestThread[] threads = new RequestThread[TEST_THREADS]; for (int i = 0; i < threads.length; i++) { threads[i] = new RequestThread(); } // start the threads for (RequestThread thread : threads) { thread.start(); } // join the threads for (RequestThread thread : threads) { thread.join(); } for (RequestThread thread : threads) { assertEquals(thread.expectedLanguage, thread.detectedLanguage); } } static class RequestThread extends Thread { public String detectedLanguage; public String expectedLanguage; @Override public void run() { try { int n = (new Random()).nextInt(SAMPLES.length); expectedLanguage = SAMPLE_CODES[n]; sleep((new Random()).nextInt(10000)); detectedLanguage = DetectLanguage.simpleDetect(SAMPLES[n]); } catch (InterruptedException e) { } catch (APIError apiError) { apiError.printStackTrace(); } } } }
src/test/java/com/detectlanguage/MultithreadedTest.java
package com.detectlanguage; import com.detectlanguage.errors.APIError; import org.junit.Test; import java.util.Random; import static org.junit.Assert.assertEquals; /** * Copyright 2014 Getty Images * User: dbabichev * Date: 6/23/2014 * Time: 12:41 PM */ public class MultithreadedTest extends BaseTest { public static final String[] SAMPLES = {"Labas rytas", "Hello world", "Buenos dias"}; public static final String[] SAMPLE_CODES = {"lt", "en", "es"}; public static int TEST_THREADS = 20; @Test public void multithreadedRequestExecution() throws InterruptedException { // create a thread for each request RequestThread[] threads = new RequestThread[TEST_THREADS]; for (int i = 0; i < threads.length; i++) { threads[i] = new RequestThread(); } // start the threads for (RequestThread thread : threads) { thread.start(); } // join the threads for (RequestThread thread : threads) { thread.join(); } for (RequestThread thread : threads) { assertEquals(thread.expectedLanguage, thread.detectedLanguage); } } static class RequestThread extends Thread { public String detectedLanguage; public String expectedLanguage; @Override public void run() { try { int n = (new Random()).nextInt(SAMPLES.length); expectedLanguage = SAMPLE_CODES[n]; sleep((new Random()).nextInt(10000)); detectedLanguage = DetectLanguage.simpleDetect(SAMPLES[n]); } catch (InterruptedException e) { } catch (APIError apiError) { apiError.printStackTrace(); } } } }
Decrease number of threads in multithreaded test
src/test/java/com/detectlanguage/MultithreadedTest.java
Decrease number of threads in multithreaded test
<ide><path>rc/test/java/com/detectlanguage/MultithreadedTest.java <ide> public static final String[] SAMPLES = {"Labas rytas", "Hello world", "Buenos dias"}; <ide> public static final String[] SAMPLE_CODES = {"lt", "en", "es"}; <ide> <del> public static int TEST_THREADS = 20; <add> public static int TEST_THREADS = 10; <ide> <ide> @Test <ide> public void multithreadedRequestExecution() throws InterruptedException {
JavaScript
mit
0f8d44e5d17b886070955a211d93b7a0f800d582
0
cape-io/redux-history-sync
import { HISTORY_CREATE, HISTORY_RESTORE, create } from './actions' const initialState = { activeKey: null, firstKey: null, length: 0, key: {}, } /** * This reducer will update the state with the most recent history key and location. */ export default function reducer(state = initialState, action) { if (!action.type) { return state } const { payload, type } = action const { key, title } = payload switch (type) { case HISTORY_RESTORE: return { ...state, activeKey: payload } case HISTORY_CREATE: return { firstKey: state.firstKey || key, activeKey: key, length: state.length + 1, key: { ...state.key, [key]: { index: state.length, key, title, location, }, }, } default: return state } } export function getInitState(location, title) { const action = create(location, title) const state = reducer(undefined, action) return state } export function makeHydratable(reducer) { return function hydratableReducer(state, action) { switch (action.type) { case HISTORY_RESTORE: // Replace state with that of history. return reducer(action.state, action) default: return reducer(state, action) } } } export function selectHistoryState(state) { return state.history } export function selectActiveKey(historyState) { const { activeKey, key } = historyState return key[activeKey] } export function selectActiveKeyDefault(state) { return selectActiveKey(selectHistoryState(state)) }
src/reducer.js
import { HISTORY_CREATE, HISTORY_RESTORE, create } from './actions' const initialState = { activeKey: null, firstKey: null, length: 0, key: {} } /** * This reducer will update the state with the most recent history key and location. */ export default function reducer(state = initialState, action) { switch (action.type) { case HISTORY_RESTORE: return { ...state, activeKey: action.payload } case HISTORY_CREATE: const { payload: { key, location, title } } = action return { firstKey: state.firstKey || key, activeKey: key, length: state.length + 1, key: { ...state.key, [key]: { index: state.length, key, title, location } } } default: return state } } export function getInitState(location, title) { const action = create(location, title) const state = reducer(undefined, action) return state } export function makeHydratable(reducer) { return function hydratableReducer(state, action) { switch (action.type) { case HISTORY_RESTORE: // Replace state with that of history. return reducer(action.state, action) default: return reducer(state, action) } } } export function selectHistoryState(state) { return state.history } export function selectActiveKey(historyState) { const { activeKey, key } = historyState return key[activeKey] } export function selectActiveKeyDefault(state) { return selectActiveKey(selectHistoryState(state)) }
Is this better or worse?
src/reducer.js
Is this better or worse?
<ide><path>rc/reducer.js <ide> activeKey: null, <ide> firstKey: null, <ide> length: 0, <del> key: {} <add> key: {}, <ide> } <ide> /** <ide> * This reducer will update the state with the most recent history key and location. <ide> */ <ide> export default function reducer(state = initialState, action) { <del> switch (action.type) { <add> if (!action.type) { <add> return state <add> } <add> const { payload, type } = action <add> const { key, title } = payload <add> switch (type) { <ide> case HISTORY_RESTORE: <del> return { ...state, activeKey: action.payload } <add> return { ...state, activeKey: payload } <ide> case HISTORY_CREATE: <del> const { payload: { key, location, title } } = action <ide> return { <ide> firstKey: state.firstKey || key, <ide> activeKey: key, <ide> index: state.length, <ide> key, <ide> title, <del> location <del> } <del> } <add> location, <add> }, <add> }, <ide> } <ide> default: <ide> return state
JavaScript
mit
b121a99e0751704742adf123d772526fba7dfcf4
0
benjohnson77/arcmark,benjohnson77/arcmark,benjohnson77/arcmark
//= require jquery/jquery //= require raphael //= require_tree . $(document).ready(function(){ function arcs(id,n,type,mod,size){ var top = $(id).position().top; var height = $(id).height(); var width = $(id).width(); var center = width/2; var R = 100; var paper = Raphael(0, top, width, height); xmod = 0; for (i = 0; i < n; i++) { var xmod = xmod + mod; switch(type) { case 1: var startx = center+xmod; var starty = height+xmod; var spin = -90; var angle = 90; var elx = size-(xmod*4); var ely = size+(size*0.25)-(xmod*4); var dir = 1; var quad = 1; break; case 2: var startx = 0; var starty = height/2+xmod; var spin = -90; var angle = 90; var elx = size-xmod*4; var ely = size+(size*0.25)-(xmod*4); var dir = 0; var quad = 1; break; case 3: var startx = center+xmod; var starty = height+xmod; var spin = 90; var angle = 90; var elx = size-(xmod*4); var ely = size+(size*0.25)-(xmod*4); var dir = 0; var quad = 1; break; case 4: var startx = center+xmod; var starty = -(height/2); var spin = 90; var angle = 180; var elx = size-xmod*4; var ely = size+(size*0.25)-(xmod*4); var dir = 1; var quad = 1; break; default: var startx = center+xmod; var starty = height+xmod; break; } var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle]; var arcs = paper.path(path_string); arcs.attr("stroke", "#4babe0"); arcs.toBack(); }; }; // ElementID , number of arcs, arctype, offset, size var a = arcs('#overview',5,1,15,1500); var a = arcs('#overview',5,2,30,2500); var a = arcs('#overview',5,3,15,2000); var a = arcs('#overview',5,4,15,1000); });
source/js/all.js
//= require jquery/jquery //= require raphael //= require_tree . $(document).ready(function(){ function arcs(n){ var top = $('#overview').position().top; var height = $('#overview').height(); var y = top+height ; var x = $('#overview').width(); var center = x/2; var R = 100; var paper_1 = Raphael(0, top, x, height); xmod = 60; for (i = 0; i < n; i++) { var xmod = xmod + 25; var arcs = paper_1.path(['m', center+xmod, height+xmod, 'a', 1100-xmod*2, 1600-xmod*2, 1, 1, 1, -90, 90]); arcs.attr("stroke", "#ccc"); //arcs.animate({path: arcs}, 1000); }; }; var a = arcs(6); });
added arc types, 1-4
source/js/all.js
added arc types, 1-4
<ide><path>ource/js/all.js <ide> <ide> $(document).ready(function(){ <ide> <del> function arcs(n){ <del> var top = $('#overview').position().top; <del> var height = $('#overview').height(); <del> var y = top+height ; <del> var x = $('#overview').width(); <del> var center = x/2; <add> function arcs(id,n,type,mod,size){ <add> var top = $(id).position().top; <add> var height = $(id).height(); <add> var width = $(id).width(); <add> var center = width/2; <ide> var R = 100; <ide> <del> var paper_1 = Raphael(0, top, x, height); <del> xmod = 60; <add> var paper = Raphael(0, top, width, height); <add> xmod = 0; <ide> for (i = 0; i < n; i++) { <del> var xmod = xmod + 25; <del> <del> var arcs = paper_1.path(['m', center+xmod, height+xmod, 'a', 1100-xmod*2, 1600-xmod*2, 1, 1, 1, -90, 90]); <del> arcs.attr("stroke", "#ccc"); <del> //arcs.animate({path: arcs}, 1000); <add> var xmod = xmod + mod; <add> <add> switch(type) { <add> case 1: <add> var startx = center+xmod; <add> var starty = height+xmod; <add> var spin = -90; <add> var angle = 90; <add> var elx = size-(xmod*4); <add> var ely = size+(size*0.25)-(xmod*4); <add> var dir = 1; <add> var quad = 1; <add> break; <add> case 2: <add> var startx = 0; <add> var starty = height/2+xmod; <add> var spin = -90; <add> var angle = 90; <add> var elx = size-xmod*4; <add> var ely = size+(size*0.25)-(xmod*4); <add> var dir = 0; <add> var quad = 1; <add> break; <add> case 3: <add> var startx = center+xmod; <add> var starty = height+xmod; <add> var spin = 90; <add> var angle = 90; <add> var elx = size-(xmod*4); <add> var ely = size+(size*0.25)-(xmod*4); <add> var dir = 0; <add> var quad = 1; <add> break; <add> case 4: <add> var startx = center+xmod; <add> var starty = -(height/2); <add> var spin = 90; <add> var angle = 180; <add> var elx = size-xmod*4; <add> var ely = size+(size*0.25)-(xmod*4); <add> var dir = 1; <add> var quad = 1; <add> break; <add> default: <add> var startx = center+xmod; <add> var starty = height+xmod; <add> break; <add> } <add> <add> var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle]; <add> var arcs = paper.path(path_string); <add> arcs.attr("stroke", "#4babe0"); <add> arcs.toBack(); <add> <ide> }; <ide> }; <del> <del> var a = arcs(6); <add> // ElementID , number of arcs, arctype, offset, size <add> var a = arcs('#overview',5,1,15,1500); <add> var a = arcs('#overview',5,2,30,2500); <add> var a = arcs('#overview',5,3,15,2000); <add> var a = arcs('#overview',5,4,15,1000); <ide> });
Java
apache-2.0
304cfbc588977f669a544e21c53b3df9498abe87
0
zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services
package org.sagebionetworks.repo.web.migration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.EvaluationStatus; import org.sagebionetworks.evaluation.model.Submission; import org.sagebionetworks.evaluation.model.SubmissionContributor; import org.sagebionetworks.ids.IdGenerator; import org.sagebionetworks.ids.IdGenerator.TYPE; import org.sagebionetworks.repo.manager.StorageQuotaManager; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.manager.UserProfileManager; import org.sagebionetworks.repo.manager.migration.MigrationManager; import org.sagebionetworks.repo.model.ACCESS_TYPE; import org.sagebionetworks.repo.model.AccessApproval; import org.sagebionetworks.repo.model.AccessRequirement; import org.sagebionetworks.repo.model.AuthenticationDAO; import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL; import org.sagebionetworks.repo.model.Challenge; import org.sagebionetworks.repo.model.ChallengeDAO; import org.sagebionetworks.repo.model.ChallengeTeam; import org.sagebionetworks.repo.model.ChallengeTeamDAO; import org.sagebionetworks.repo.model.CommentDAO; import org.sagebionetworks.repo.model.DatastoreException; import org.sagebionetworks.repo.model.DomainType; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Folder; import org.sagebionetworks.repo.model.GroupMembersDAO; import org.sagebionetworks.repo.model.IdList; import org.sagebionetworks.repo.model.MembershipInvtnSubmission; import org.sagebionetworks.repo.model.MembershipInvtnSubmissionDAO; import org.sagebionetworks.repo.model.MembershipRqstSubmission; import org.sagebionetworks.repo.model.MembershipRqstSubmissionDAO; import org.sagebionetworks.repo.model.MessageDAO; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.ProjectSettingsDAO; import org.sagebionetworks.repo.model.ProjectStat; import org.sagebionetworks.repo.model.ProjectStatsDAO; import org.sagebionetworks.repo.model.QuizResponseDAO; import org.sagebionetworks.repo.model.RestrictableObjectDescriptor; import org.sagebionetworks.repo.model.RestrictableObjectType; import org.sagebionetworks.repo.model.StorageLocationDAO; import org.sagebionetworks.repo.model.StorageQuotaAdminDao; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.TeamDAO; import org.sagebionetworks.repo.model.TermsOfUseAccessApproval; import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupDAO; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.VerificationDAO; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.bootstrap.EntityBootstrapper; import org.sagebionetworks.repo.model.daemon.BackupRestoreStatus; import org.sagebionetworks.repo.model.daemon.DaemonStatus; import org.sagebionetworks.repo.model.daemon.RestoreSubmission; import org.sagebionetworks.repo.model.dao.FileHandleDao; import org.sagebionetworks.repo.model.dao.discussion.DiscussionReplyDAO; import org.sagebionetworks.repo.model.dao.discussion.DiscussionThreadDAO; import org.sagebionetworks.repo.model.dao.discussion.ForumDAO; import org.sagebionetworks.repo.model.dao.subscription.SubscriptionDAO; import org.sagebionetworks.repo.model.dao.table.ColumnModelDAO; import org.sagebionetworks.repo.model.dao.table.TableRowTruthDAO; import org.sagebionetworks.repo.model.dbo.DBOBasicDao; import org.sagebionetworks.repo.model.dbo.dao.table.TableModelTestUtils; import org.sagebionetworks.repo.model.dbo.file.CompositeMultipartUploadStatus; import org.sagebionetworks.repo.model.dbo.file.CreateMultipartRequest; import org.sagebionetworks.repo.model.dbo.file.MultipartUploadDAO; import org.sagebionetworks.repo.model.dbo.persistence.DBOSessionToken; import org.sagebionetworks.repo.model.dbo.persistence.DBOTermsOfUseAgreement; import org.sagebionetworks.repo.model.file.ExternalFileHandle; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.PreviewFileHandle; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.repo.model.jdo.KeyFactory; import org.sagebionetworks.repo.model.message.Comment; import org.sagebionetworks.repo.model.message.MessageToUser; import org.sagebionetworks.repo.model.migration.ListBucketProvider; import org.sagebionetworks.repo.model.migration.MigrationType; import org.sagebionetworks.repo.model.migration.MigrationTypeCount; import org.sagebionetworks.repo.model.migration.MigrationTypeCounts; import org.sagebionetworks.repo.model.migration.MigrationTypeList; import org.sagebionetworks.repo.model.migration.MigrationUtils; import org.sagebionetworks.repo.model.migration.RowMetadata; import org.sagebionetworks.repo.model.migration.RowMetadataResult; import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.S3StorageLocationSetting; import org.sagebionetworks.repo.model.project.UploadDestinationListSetting; import org.sagebionetworks.repo.model.provenance.Activity; import org.sagebionetworks.repo.model.quiz.PassingRecord; import org.sagebionetworks.repo.model.quiz.QuizResponse; import org.sagebionetworks.repo.model.subscription.SubscriptionObjectType; import org.sagebionetworks.repo.model.table.ColumnMapper; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.RawRowSet; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.v2.dao.V2WikiPageDao; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import org.sagebionetworks.repo.model.verification.AttachmentMetadata; import org.sagebionetworks.repo.model.verification.VerificationSubmission; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.repo.web.controller.AbstractAutowiredControllerTestBase; import org.sagebionetworks.repo.web.service.ServiceProvider; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.table.cluster.utils.TableModelUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import com.google.common.collect.Lists; /** * This is an integration test to test the migration of all tables from start to finish. * * The test does the following: 1. the before() method creates at least one object for every type object that must * migrate. 2. Create a backup copy of all data. 3. Delete all data in the system. 4. Restore all data from the backup. * * NOTE: Whenever a new migration type is added this test must be extended to test that objects migration. * * * * @author jmhill * */ @DirtiesContext public class MigrationIntegrationAutowireTest extends AbstractAutowiredControllerTestBase { public static final long MAX_WAIT_MS = 45 * 1000; // 45 sec. @Autowired private DBOBasicDao basicDao; @Autowired private UserManager userManager; @Autowired private FileHandleDao fileMetadataDao; @Autowired private UserProfileManager userProfileManager; @Autowired private ServiceProvider serviceProvider; @Autowired private EntityBootstrapper entityBootstrapper; @Autowired private MigrationManager migrationManager; @Autowired private StorageQuotaManager storageQuotaManager; @Autowired private StorageQuotaAdminDao storageQuotaAdminDao; @Autowired private UserGroupDAO userGroupDAO; @Autowired private PrincipalAliasDAO principalAliasDAO; @Autowired private GroupMembersDAO groupMembersDAO; @Autowired private TeamDAO teamDAO; @Autowired private AuthenticationDAO authDAO; @Autowired private MessageDAO messageDAO; @Autowired private CommentDAO commentDAO; @Autowired private MembershipRqstSubmissionDAO membershipRqstSubmissionDAO; @Autowired private MembershipInvtnSubmissionDAO membershipInvtnSubmissionDAO; @Autowired private ColumnModelDAO columnModelDao; @Autowired private TableRowTruthDAO tableRowTruthDao; @Autowired private V2WikiPageDao v2wikiPageDAO; @Autowired private QuizResponseDAO quizResponseDAO; @Autowired private ProjectSettingsDAO projectSettingsDAO; @Autowired private StorageLocationDAO storageLocationDAO; @Autowired private ProjectStatsDAO projectStatsDAO; @Autowired private ChallengeDAO challengeDAO; @Autowired private ChallengeTeamDAO challengeTeamDAO; @Autowired private VerificationDAO verificationDao; @Autowired private ForumDAO forumDao; @Autowired private DiscussionThreadDAO threadDao; @Autowired private DiscussionReplyDAO replyDao; @Autowired private SubscriptionDAO subscriptionDao; @Autowired private IdGenerator idGenerator; @Autowired private MultipartUploadDAO multipartUploadDAO; private Team team; private Long adminUserId; private String adminUserIdString; private UserInfo adminUserInfo; // Activity private Activity activity; // Entities private Project project; private FileEntity fileEntity; private Folder folderToTrash; // requirement private AccessRequirement accessRequirement; // approval private AccessApproval accessApproval; // V2 Wiki page private V2WikiPage v2RootWiki; private V2WikiPage v2SubWiki; // File Handles private S3FileHandle handleOne; private S3FileHandle markdownOne; private PreviewFileHandle preview; private ExternalFileHandle sftpFileHandle; // Evaluation private Evaluation evaluation; private Submission submission; private HttpServletRequest mockRequest; private Challenge challenge; private ChallengeTeam challengeTeam; private String forumId; private String threadId; @Before public void before() throws Exception { mockRequest = Mockito.mock(HttpServletRequest.class); when(mockRequest.getServletPath()).thenReturn("/repo/v1"); // get user IDs adminUserId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId(); adminUserIdString = adminUserId.toString(); adminUserInfo = userManager.getUserInfo(adminUserId); resetDatabase(); createNewUser(); String sampleFileHandleId = createFileHandles(); createActivity(); createEntities(); createFavorite(); createProjectSetting(); createProjectStat(); createEvaluation(); createAccessRequirement(); createAccessApproval(); createV2WikiPages(); createDoi(); createStorageQuota(); UserGroup sampleGroup = createUserGroups(1); createTeamsRequestsAndInvitations(sampleGroup); createCredentials(sampleGroup); createSessionToken(sampleGroup); createTermsOfUseAgreement(sampleGroup); createMessages(sampleGroup, sampleFileHandleId); createColumnModel(); createUserGroups(2); createQuizResponse(); createChallengeAndRegisterTeam(); createVerificationSubmission(); createThread(); createThreadView(); createReply(); createMultipartUpload(); createSubscription(); } private void createMultipartUpload(){ CreateMultipartRequest request = new CreateMultipartRequest(); request.setBucket("someBucket"); request.setHash("someHash"); request.setKey("someKey"); request.setNumberOfParts(1); request.setUploadToken("uploadToken"); request.setRequestBody("someRequestBody"); request.setUserId(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId()); // main row CompositeMultipartUploadStatus composite = multipartUploadDAO.createUploadStatus(request); // secondary row int partNumber =1; String partMD5Hex = "548c050497fb361742b85e0712b0cc96"; multipartUploadDAO.addPartToUpload(composite.getMultipartUploadStatus().getUploadId(), partNumber, partMD5Hex); } private void createThread() { threadId = idGenerator.generateNewId(TYPE.DISCUSSION_THREAD_ID).toString(); threadDao.createThread(forumId, threadId, "title", "fakeMessageUrl", adminUserId); } private void createThreadView() { threadDao.updateThreadView(Long.parseLong(threadId), adminUserId); } private void createReply() { String replyId = idGenerator.generateNewId(TYPE.DISCUSSION_REPLY_ID).toString(); replyDao.createReply(threadId, replyId, "messageKey", adminUserId); } private void createSubscription() { subscriptionDao.create(adminUserIdString, threadId, SubscriptionObjectType.DISCUSSION_THREAD); } private void createVerificationSubmission() { VerificationSubmission dto = new VerificationSubmission(); dto.setCreatedBy(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId().toString()); dto.setCreatedOn(new Date()); AttachmentMetadata attachmentMetadata = new AttachmentMetadata(); attachmentMetadata.setId(handleOne.getId()); dto.setAttachments(Collections.singletonList(attachmentMetadata)); verificationDao.createVerificationSubmission(dto); } private void createChallengeAndRegisterTeam() { challenge = new Challenge(); challenge.setParticipantTeamId(team.getId()); challenge.setProjectId(project.getId()); challenge = challengeDAO.create(challenge); challengeTeam = new ChallengeTeam(); challengeTeam.setChallengeId(challenge.getId()); // this is nonsensical: We are registering a team which is the challenge // participant team. However it does the job of exercising object migration. challengeTeam.setTeamId(team.getId()); challengeTeam = challengeTeamDAO.create(challengeTeam); } private void createProjectSetting() { S3StorageLocationSetting destination = new S3StorageLocationSetting(); destination.setDescription("upload normal"); destination.setUploadType(UploadType.S3); destination.setBanner("warning"); destination.setCreatedOn(new Date()); destination.setCreatedBy(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId()); Long uploadId = storageLocationDAO.create(destination); UploadDestinationListSetting settings = new UploadDestinationListSetting(); settings.setProjectId(project.getId()); settings.setSettingsType(ProjectSettingsType.upload); settings.setLocations(Collections.singletonList(uploadId)); projectSettingsDAO.create(settings); } private void createProjectStat() { ProjectStat projectStat = new ProjectStat(KeyFactory.stringToKey(project.getId()), adminUserId, new Date()); projectStatsDAO.update(projectStat); } private void createQuizResponse() { QuizResponse dto = new QuizResponse(); PassingRecord passingRecord = new PassingRecord(); passingRecord.setPassed(true); passingRecord.setPassedOn(new Date()); passingRecord.setQuizId(101L); passingRecord.setResponseId(222L); passingRecord.setScore(7L); passingRecord.setUserId(adminUserId.toString()); adminUserId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId(); dto.setCreatedBy(adminUserId.toString()); dto.setCreatedOn(new Date()); dto.setQuizId(101L); quizResponseDAO.create(dto, passingRecord); } private void createColumnModel() throws DatastoreException, NotFoundException, IOException { String tableId = "syn123"; // Create some test column models List<ColumnModel> start = TableModelTestUtils.createOneOfEachType(); // Create each one List<ColumnModel> models = new LinkedList<ColumnModel>(); for (ColumnModel cm : start) { models.add(columnModelDao.createColumnModel(cm)); } ColumnMapper mapper = TableModelUtils.createColumnModelColumnMapper(models, false); List<Long> headers = TableModelUtils.getIds(models); // bind the columns to the entity columnModelDao.bindColumnToObject(Lists.transform(headers, TableModelUtils.LONG_TO_STRING), tableId); // create some test rows. List<Row> rows = TableModelTestUtils.createRows(models, 5); RawRowSet set = new RawRowSet(TableModelUtils.getIds(models), null, tableId, rows); // Append the rows to the table tableRowTruthDao.appendRowSetToTable(adminUserIdString, tableId, mapper, set); // Append some more rows rows = TableModelTestUtils.createRows(models, 6); set = new RawRowSet(TableModelUtils.getIds(models), null, tableId, rows); tableRowTruthDao.appendRowSetToTable(adminUserIdString, tableId, mapper, set); } public void createNewUser() throws NotFoundException { NewUser user = new NewUser(); user.setUserName(UUID.randomUUID().toString()); user.setEmail(user.getUserName() + "@test.com"); Long id = userManager.createUser(user); userManager.getUserInfo(id); } private void resetDatabase() throws Exception { // This gives us a chance to also delete the S3 for table rows tableRowTruthDao.truncateAllRowData(); // Before we start this test we want to start with a clean database migrationManager.deleteAllData(adminUserInfo); // bootstrap to put back the bootstrap data entityBootstrapper.bootstrapAll(); storageQuotaAdminDao.clear(); } private void createFavorite() { userProfileManager.addFavorite(adminUserInfo, fileEntity.getId()); } private void createDoi() throws Exception { serviceProvider.getDoiService().createDoi(adminUserId, project.getId(), ObjectType.ENTITY, 1L); } private void createActivity() throws Exception { activity = new Activity(); activity.setDescription("some desc"); activity = serviceProvider.getActivityService().createActivity(adminUserId, activity); } private void createEvaluation() throws Exception { // initialize Evaluations evaluation = new Evaluation(); evaluation.setName("name"); evaluation.setDescription("description"); evaluation.setContentSource(project.getId()); evaluation.setStatus(EvaluationStatus.PLANNED); evaluation.setSubmissionInstructionsMessage("instructions"); evaluation.setSubmissionReceiptMessage("receipt"); evaluation = serviceProvider.getEvaluationService().createEvaluation(adminUserId, evaluation); evaluation = new Evaluation(); evaluation.setName("name2"); evaluation.setDescription("description"); evaluation.setContentSource(project.getId()); evaluation.setStatus(EvaluationStatus.OPEN); evaluation.setSubmissionInstructionsMessage("instructions"); evaluation.setSubmissionReceiptMessage("receipt"); evaluation = serviceProvider.getEvaluationService().createEvaluation(adminUserId, evaluation); // initialize Participants serviceProvider.getEvaluationService().addParticipant(adminUserId, evaluation.getId()); // initialize Submissions submission = new Submission(); submission.setName("submission1"); submission.setVersionNumber(1L); submission.setEntityId(fileEntity.getId()); submission.setUserId(adminUserIdString); submission.setEvaluationId(evaluation.getId()); SubmissionContributor contributor = new SubmissionContributor(); contributor.setPrincipalId(adminUserIdString); submission.setContributors(Collections.singleton(contributor)); submission = entityServletHelper.createSubmission(submission, adminUserId, fileEntity.getEtag()); } public void createAccessApproval() throws Exception { accessApproval = newToUAccessApproval(accessRequirement.getId(), adminUserIdString); accessApproval = servletTestHelper.createAccessApproval(dispatchServlet, accessApproval, adminUserId, new HashMap<String, String>()); } public void createAccessRequirement() throws Exception { // Add an access requirement to this entity accessRequirement = newAccessRequirement(); String entityId = project.getId(); RestrictableObjectDescriptor entitySubjectId = new RestrictableObjectDescriptor(); entitySubjectId.setId(entityId); entitySubjectId.setType(RestrictableObjectType.ENTITY); RestrictableObjectDescriptor evaluationSubjectId = new RestrictableObjectDescriptor(); assertNotNull(evaluation); assertNotNull(evaluation.getId()); evaluationSubjectId.setId(evaluation.getId()); evaluationSubjectId.setType(RestrictableObjectType.EVALUATION); accessRequirement.setSubjectIds(Arrays.asList(new RestrictableObjectDescriptor[] { entitySubjectId, evaluationSubjectId })); accessRequirement = servletTestHelper.createAccessRequirement(dispatchServlet, accessRequirement, adminUserId, new HashMap<String, String>()); } private TermsOfUseAccessApproval newToUAccessApproval(Long requirementId, String accessorId) { TermsOfUseAccessApproval aa = new TermsOfUseAccessApproval(); aa.setAccessorId(accessorId); aa.setConcreteType(TermsOfUseAccessApproval.class.getName()); aa.setRequirementId(requirementId); return aa; } public void createV2WikiPages() throws NotFoundException { // Using wikiPageDao until wiki service is created // Create a V2 Wiki page v2RootWiki = new V2WikiPage(); v2RootWiki.setCreatedBy(adminUserIdString); v2RootWiki.setModifiedBy(adminUserIdString); v2RootWiki.setAttachmentFileHandleIds(new LinkedList<String>()); v2RootWiki.getAttachmentFileHandleIds().add(handleOne.getId()); v2RootWiki.setTitle("Root title"); v2RootWiki.setMarkdownFileHandleId(markdownOne.getId()); Map<String, FileHandle> map = new HashMap<String, FileHandle>(); map.put(handleOne.getFileName(), handleOne); List<String> newIds = new ArrayList<String>(); newIds.add(handleOne.getId()); v2RootWiki = v2wikiPageDAO.create(v2RootWiki, map, fileEntity.getId(), ObjectType.ENTITY, newIds); // Create a child v2SubWiki = new V2WikiPage(); v2SubWiki.setCreatedBy(adminUserIdString); v2SubWiki.setModifiedBy(adminUserIdString); v2SubWiki.setParentWikiId(v2RootWiki.getId()); v2SubWiki.setTitle("V2 Sub-wiki-title"); v2SubWiki.setMarkdownFileHandleId(markdownOne.getId()); v2SubWiki = v2wikiPageDAO.create(v2SubWiki, new HashMap<String, FileHandle>(), fileEntity.getId(), ObjectType.ENTITY, new ArrayList<String>()); } /** * Create the entities used by this test. * * @throws JSONObjectAdapterException * @throws ServletException * @throws IOException * @throws NotFoundException */ public void createEntities() throws JSONObjectAdapterException, ServletException, IOException, NotFoundException { // Create a project project = new Project(); project.setName("MigrationIntegrationAutowireTest.Project"); project.setEntityType(Project.class.getName()); project = serviceProvider.getEntityService().createEntity(adminUserId, project, null, mockRequest); forumId = forumDao.getForumByProjectId(project.getId()).getId(); // Create a file entity fileEntity = new FileEntity(); fileEntity.setName("MigrationIntegrationAutowireTest.FileEntity"); fileEntity.setEntityType(FileEntity.class.getName()); fileEntity.setParentId(project.getId()); fileEntity.setDataFileHandleId(handleOne.getId()); fileEntity = serviceProvider.getEntityService().createEntity(adminUserId, fileEntity, activity.getId(), mockRequest); // Create a folder to trash folderToTrash = new Folder(); folderToTrash.setName("boundForTheTrashCan"); folderToTrash.setParentId(project.getId()); folderToTrash = serviceProvider.getEntityService().createEntity(adminUserId, folderToTrash, null, mockRequest); // Send it to the trash can serviceProvider.getTrashService().moveToTrash(adminUserId, folderToTrash.getId()); } private AccessRequirement newAccessRequirement() { TermsOfUseAccessRequirement dto = new TermsOfUseAccessRequirement(); dto.setConcreteType(dto.getClass().getName()); dto.setAccessType(ACCESS_TYPE.DOWNLOAD); dto.setTermsOfUse("foo"); return dto; } /** * Create the file handles used by this test. * * @throws NotFoundException */ public String createFileHandles() throws NotFoundException { // Create a file handle handleOne = new S3FileHandle(); handleOne.setCreatedBy(adminUserIdString); handleOne.setCreatedOn(new Date()); handleOne.setBucketName("bucket"); handleOne.setKey("mainFileKey"); handleOne.setEtag("etag"); handleOne.setFileName("foo.bar"); handleOne = fileMetadataDao.createFile(handleOne); // Create markdown content markdownOne = new S3FileHandle(); markdownOne.setCreatedBy(adminUserIdString); markdownOne.setCreatedOn(new Date()); markdownOne.setBucketName("bucket"); markdownOne.setKey("markdownFileKey"); markdownOne.setEtag("etag"); markdownOne.setFileName("markdown1"); markdownOne = fileMetadataDao.createFile(markdownOne); // Create a preview preview = new PreviewFileHandle(); preview.setCreatedBy(adminUserIdString); preview.setCreatedOn(new Date()); preview.setBucketName("bucket"); preview.setKey("previewFileKey"); preview.setEtag("etag"); preview.setFileName("bar.txt"); preview = fileMetadataDao.createFile(preview); // Set two as the preview of one fileMetadataDao.setPreviewId(handleOne.getId(), preview.getId()); return handleOne.getId(); } private void createStorageQuota() { storageQuotaManager.setQuotaForUser(adminUserInfo, adminUserInfo, 3000); } // returns a group for use in a team private UserGroup createUserGroups(int index) throws NotFoundException { List<String> adder = new ArrayList<String>(); // Make one group UserGroup parentGroup = new UserGroup(); parentGroup.setIsIndividual(false); parentGroup.setId(userGroupDAO.create(parentGroup).toString()); // Make two users UserGroup parentUser = new UserGroup(); parentUser.setIsIndividual(true); parentUser.setId(userGroupDAO.create(parentUser).toString()); UserGroup siblingUser = new UserGroup(); siblingUser.setIsIndividual(true); siblingUser.setId(userGroupDAO.create(siblingUser).toString()); // Nest one group and two users within the parent group adder.add(parentUser.getId()); adder.add(siblingUser.getId()); groupMembersDAO.addMembers(parentGroup.getId(), adder); return parentGroup; } private void createCredentials(UserGroup group) throws Exception { Long principalId = Long.parseLong(group.getId()); authDAO.changePassword(principalId, "ThisIsMySuperSecurePassword"); authDAO.changeSecretKey(principalId); authDAO.changeSessionToken(principalId, null, DomainType.SYNAPSE); } private void createSessionToken(UserGroup group) throws Exception { DBOSessionToken token = new DBOSessionToken(); token.setDomain(DomainType.SYNAPSE); token.setPrincipalId(Long.parseLong(group.getId())); token.setSessionToken(UUID.randomUUID().toString()); token.setValidatedOn(new Date()); basicDao.createOrUpdate(token); } private void createTermsOfUseAgreement(UserGroup group) throws Exception { DBOTermsOfUseAgreement tou = new DBOTermsOfUseAgreement(); tou.setPrincipalId(Long.parseLong(group.getId())); tou.setAgreesToTermsOfUse(Boolean.TRUE); tou.setDomain(DomainType.SYNAPSE); basicDao.createNew(tou); } @SuppressWarnings("serial") private void createMessages(final UserGroup group, String fileHandleId) { MessageToUser dto = new MessageToUser(); // Note: ID is auto generated dto.setCreatedBy(group.getId()); dto.setFileHandleId(fileHandleId); // Note: CreatedOn is set by the DAO dto.setSubject("See you on the other side?"); dto.setRecipients(new HashSet<String>() { { add(group.getId()); } }); dto.setInReplyTo(null); // Note: InReplyToRoot is calculated by the DAO dto = messageDAO.createMessage(dto); messageDAO.createMessageStatus_NewTransaction(dto.getId(), group.getId(), null); Comment dto2 = new Comment(); dto2.setCreatedBy(group.getId()); dto2.setFileHandleId(fileHandleId); dto2.setTargetId("1337"); dto2.setTargetType(ObjectType.ENTITY); commentDAO.createComment(dto2); } private void createTeamsRequestsAndInvitations(UserGroup group) { String otherUserId = BOOTSTRAP_PRINCIPAL.ANONYMOUS_USER.getPrincipalId().toString(); team = new Team(); team.setId(group.getId()); team.setName(UUID.randomUUID().toString()); team.setDescription("test team"); team = teamDAO.create(team); // create a MembershipRqstSubmission MembershipRqstSubmission mrs = new MembershipRqstSubmission(); Date createdOn = new Date(); Date expiresOn = new Date(); mrs.setCreatedOn(createdOn); mrs.setExpiresOn(expiresOn); mrs.setMessage("Please let me join the team."); mrs.setTeamId("" + group.getId()); // need another valid user group mrs.setUserId(otherUserId); membershipRqstSubmissionDAO.create(mrs); // create a MembershipInvtnSubmission MembershipInvtnSubmission mis = new MembershipInvtnSubmission(); mis.setCreatedOn(createdOn); mis.setExpiresOn(expiresOn); mis.setMessage("Please join the team."); mis.setTeamId("" + group.getId()); // need another valid user group mis.setInviteeId(otherUserId); membershipInvtnSubmissionDAO.create(mis); } @After public void after() throws Exception { // to cleanup for this test we delete all in the database resetDatabase(); } // test that if we create a group with members, back it up, // add members, and restore, the extra members are removed // (This was broken in PLFM-2757) @Test public void testCertifiedUsersGroupMigration() throws Exception { String groupId = BOOTSTRAP_PRINCIPAL.CERTIFIED_USERS.getPrincipalId().toString(); List<UserGroup> members = groupMembersDAO.getMembers(groupId); List<BackupInfo> backupList = backupAllOfType(MigrationType.PRINCIPAL); // add new member(s) UserGroup yetAnotherUser = new UserGroup(); yetAnotherUser.setIsIndividual(true); yetAnotherUser.setId(userGroupDAO.create(yetAnotherUser).toString()); groupMembersDAO.addMembers(groupId, Collections.singletonList(yetAnotherUser.getId())); // membership is different because new user has been added assertFalse(members.equals(groupMembersDAO.getMembers(groupId))); // Now restore all of the data for (BackupInfo info : backupList) { String fileName = info.getFileName(); assertNotNull("Did not find a backup file name for type: " + info.getType(), fileName); restoreFromBackup(info.getType(), fileName); } // should be back to normal assertEquals(members, groupMembersDAO.getMembers(groupId)); } /** * This is the actual test. The rest of the class is setup and tear down. * * @throws Exception */ @Test public void testRoundTrip() throws Exception { // Get the list of primary types MigrationTypeList primaryTypesList = entityServletHelper.getPrimaryMigrationTypes(adminUserId); assertNotNull(primaryTypesList); assertNotNull(primaryTypesList.getList()); assertTrue(primaryTypesList.getList().size() > 0); // Get the counts before we start MigrationTypeCounts startCounts = entityServletHelper.getMigrationTypeCounts(adminUserId); validateStartingCount(startCounts); // This test will backup all data, delete it, then restore it. List<BackupInfo> backupList = new ArrayList<BackupInfo>(); for (MigrationType type : primaryTypesList.getList()) { // Backup each type backupList.addAll(backupAllOfType(type)); } // Now delete all data in reverse order for (int i = primaryTypesList.getList().size() - 1; i >= 0; i--) { MigrationType type = primaryTypesList.getList().get(i); deleteAllOfType(type); } // After deleting, the counts should be 0 except for a few special cases MigrationTypeCounts afterDeleteCounts = entityServletHelper.getMigrationTypeCounts(adminUserId); assertNotNull(afterDeleteCounts); assertNotNull(afterDeleteCounts.getList()); for (int i = 0; i < afterDeleteCounts.getList().size(); i++) { MigrationTypeCount afterDelete = afterDeleteCounts.getList().get(i); // Special cases for the not-deleted migration admin if (afterDelete.getType() == MigrationType.PRINCIPAL) { assertEquals("There should be 4 UserGroups remaining after the delete: " + BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER + ", " + "Administrators" + ", " + BOOTSTRAP_PRINCIPAL.PUBLIC_GROUP + ", and " + BOOTSTRAP_PRINCIPAL.AUTHENTICATED_USERS_GROUP, new Long(4), afterDelete.getCount()); } else if (afterDelete.getType() == MigrationType.GROUP_MEMBERS || afterDelete.getType() == MigrationType.CREDENTIAL) { assertEquals("Counts do not match for: " + afterDelete.getType().name(), new Long(1), afterDelete.getCount()); } else { assertEquals("Counts are non-zero for: " + afterDelete.getType().name(), new Long(0), afterDelete.getCount()); } } // Now restore all of the data for (BackupInfo info : backupList) { String fileName = info.getFileName(); assertNotNull("Did not find a backup file name for type: " + info.getType(), fileName); restoreFromBackup(info.getType(), fileName); } // The counts should all be back MigrationTypeCounts finalCounts = entityServletHelper.getMigrationTypeCounts(adminUserId); for (int i = 1; i < finalCounts.getList().size(); i++) { MigrationTypeCount startCount = startCounts.getList().get(i); MigrationTypeCount afterRestore = finalCounts.getList().get(i); assertEquals("Count for " + startCount.getType().name() + " does not match.", startCount.getCount(), afterRestore.getCount()); } } private static class BackupInfo { MigrationType type; String fileName; public BackupInfo(MigrationType type, String fileName) { super(); this.type = type; this.fileName = fileName; } public MigrationType getType() { return type; } public String getFileName() { return fileName; } } /** * There must be at least one object for every type of migratable object. * * @param startCounts */ private void validateStartingCount(MigrationTypeCounts startCounts) { assertNotNull(startCounts); assertNotNull(startCounts.getList()); List<MigrationType> typesToMigrate = new LinkedList<MigrationType>(); for (MigrationType tm : MigrationType.values()) { if (migrationManager.isMigrationTypeUsed(adminUserInfo, tm)) { typesToMigrate.add(tm); } } assertEquals( "This test requires at least one object to exist for each MigrationType. Please create a new object of the new MigrationType in the before() method of this test.", typesToMigrate.size(), startCounts.getList().size()); for (MigrationTypeCount count : startCounts.getList()) { assertTrue("This test requires at least one object to exist for each MigrationType. Please create a new object of type: " + count.getType() + " in the before() method of this test.", count.getCount() > 0); } } /** * Extract the filename from the full url. * * @param fullUrl * @return */ public String getFileNameFromUrl(String fullUrl) { ; int index = fullUrl.lastIndexOf("/"); return fullUrl.substring(index + 1, fullUrl.length()); } /** * Backup all data * * @param type * @return * @throws Exception */ private List<BackupInfo> backupAllOfType(MigrationType type) throws Exception { RowMetadataResult list = entityServletHelper.getRowMetadata(adminUserId, type, Long.MAX_VALUE, 0); if (list == null) return null; // Backup batches by their level in the tree ListBucketProvider provider = new ListBucketProvider(); MigrationUtils.bucketByTreeLevel(list.getList().iterator(), provider); List<BackupInfo> result = new ArrayList<BackupInfo>(); List<List<Long>> listOfBuckets = provider.getListOfBuckets(); for (List<Long> batch : listOfBuckets) { if (batch.size() > 0) { String fileName = backup(type, batch); result.add(new BackupInfo(type, fileName)); } } return result; } private String backup(MigrationType type, List<Long> tobackup) throws Exception { // Start the backup job IdList ids = new IdList(); ids.setList(tobackup); BackupRestoreStatus status = entityServletHelper.startBackup(adminUserId, type, ids); // wait for it.. waitForDaemon(status); status = entityServletHelper.getBackupRestoreStatus(adminUserId, status.getId()); assertNotNull(status.getBackupUrl()); return getFileNameFromUrl(status.getBackupUrl()); } private void restoreFromBackup(MigrationType type, String fileName) throws Exception { RestoreSubmission sub = new RestoreSubmission(); sub.setFileName(fileName); BackupRestoreStatus status = entityServletHelper.startRestore(adminUserId, type, sub); // wait for it waitForDaemon(status); } /** * Delete all data for a type. * * @param type * @throws ServletException * @throws IOException * @throws JSONObjectAdapterException */ private void deleteAllOfType(MigrationType type) throws Exception { IdList idList = getIdListOfAllOfType(type); if (idList == null) return; MigrationTypeCount result = entityServletHelper.deleteMigrationType(adminUserId, type, idList); System.out.println("Deleted: " + result); } /** * List all of the IDs for a type. * * @param type * @return * @throws ServletException * @throws IOException * @throws JSONObjectAdapterException */ private IdList getIdListOfAllOfType(MigrationType type) throws Exception { RowMetadataResult list = entityServletHelper.getRowMetadata(adminUserId, type, Long.MAX_VALUE, 0); if (list.getTotalCount() < 1) return null; // Create the backup list List<Long> toBackup = new LinkedList<Long>(); for (RowMetadata row : list.getList()) { toBackup.add(row.getId()); } IdList idList = new IdList(); idList.setList(toBackup); return idList; } /** * Wait for a deamon to process a a job. * * @param status * @throws InterruptedException * @throws JSONObjectAdapterException * @throws IOException * @throws ServletException */ private void waitForDaemon(BackupRestoreStatus status) throws Exception { long start = System.currentTimeMillis(); while (DaemonStatus.COMPLETED != status.getStatus()) { assertFalse("Daemon failed " + status.getErrorDetails(), DaemonStatus.FAILED == status.getStatus()); System.out.println("Waiting for backup/restore daemon. Message: " + status.getProgresssMessage()); Thread.sleep(1000); long elapse = System.currentTimeMillis() - start; assertTrue("Timed out waiting for a backup/restore daemon", elapse < MAX_WAIT_MS); status = entityServletHelper.getBackupRestoreStatus(adminUserId, status.getId()); } } }
services/repository/src/test/java/org/sagebionetworks/repo/web/migration/MigrationIntegrationAutowireTest.java
package org.sagebionetworks.repo.web.migration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.sagebionetworks.evaluation.model.Evaluation; import org.sagebionetworks.evaluation.model.EvaluationStatus; import org.sagebionetworks.evaluation.model.Submission; import org.sagebionetworks.evaluation.model.SubmissionContributor; import org.sagebionetworks.ids.IdGenerator; import org.sagebionetworks.ids.IdGenerator.TYPE; import org.sagebionetworks.repo.manager.StorageQuotaManager; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.manager.UserProfileManager; import org.sagebionetworks.repo.manager.migration.MigrationManager; import org.sagebionetworks.repo.model.ACCESS_TYPE; import org.sagebionetworks.repo.model.AccessApproval; import org.sagebionetworks.repo.model.AccessRequirement; import org.sagebionetworks.repo.model.AuthenticationDAO; import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL; import org.sagebionetworks.repo.model.Challenge; import org.sagebionetworks.repo.model.ChallengeDAO; import org.sagebionetworks.repo.model.ChallengeTeam; import org.sagebionetworks.repo.model.ChallengeTeamDAO; import org.sagebionetworks.repo.model.CommentDAO; import org.sagebionetworks.repo.model.DatastoreException; import org.sagebionetworks.repo.model.DomainType; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.Folder; import org.sagebionetworks.repo.model.GroupMembersDAO; import org.sagebionetworks.repo.model.IdList; import org.sagebionetworks.repo.model.MembershipInvtnSubmission; import org.sagebionetworks.repo.model.MembershipInvtnSubmissionDAO; import org.sagebionetworks.repo.model.MembershipRqstSubmission; import org.sagebionetworks.repo.model.MembershipRqstSubmissionDAO; import org.sagebionetworks.repo.model.MessageDAO; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.ProjectSettingsDAO; import org.sagebionetworks.repo.model.ProjectStat; import org.sagebionetworks.repo.model.ProjectStatsDAO; import org.sagebionetworks.repo.model.QuizResponseDAO; import org.sagebionetworks.repo.model.RestrictableObjectDescriptor; import org.sagebionetworks.repo.model.RestrictableObjectType; import org.sagebionetworks.repo.model.StorageLocationDAO; import org.sagebionetworks.repo.model.StorageQuotaAdminDao; import org.sagebionetworks.repo.model.Team; import org.sagebionetworks.repo.model.TeamDAO; import org.sagebionetworks.repo.model.TermsOfUseAccessApproval; import org.sagebionetworks.repo.model.TermsOfUseAccessRequirement; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupDAO; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.VerificationDAO; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.bootstrap.EntityBootstrapper; import org.sagebionetworks.repo.model.daemon.BackupRestoreStatus; import org.sagebionetworks.repo.model.daemon.DaemonStatus; import org.sagebionetworks.repo.model.daemon.RestoreSubmission; import org.sagebionetworks.repo.model.dao.FileHandleDao; import org.sagebionetworks.repo.model.dao.discussion.DiscussionReplyDAO; import org.sagebionetworks.repo.model.dao.discussion.DiscussionThreadDAO; import org.sagebionetworks.repo.model.dao.discussion.ForumDAO; import org.sagebionetworks.repo.model.dao.subscription.SubscriptionDAO; import org.sagebionetworks.repo.model.dao.table.ColumnModelDAO; import org.sagebionetworks.repo.model.dao.table.TableRowTruthDAO; import org.sagebionetworks.repo.model.dbo.DBOBasicDao; import org.sagebionetworks.repo.model.dbo.dao.table.TableModelTestUtils; import org.sagebionetworks.repo.model.dbo.file.CompositeMultipartUploadStatus; import org.sagebionetworks.repo.model.dbo.file.CreateMultipartRequest; import org.sagebionetworks.repo.model.dbo.file.MultipartUploadDAO; import org.sagebionetworks.repo.model.dbo.persistence.DBOSessionToken; import org.sagebionetworks.repo.model.dbo.persistence.DBOTermsOfUseAgreement; import org.sagebionetworks.repo.model.file.ExternalFileHandle; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.PreviewFileHandle; import org.sagebionetworks.repo.model.file.S3FileHandle; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.repo.model.jdo.KeyFactory; import org.sagebionetworks.repo.model.message.Comment; import org.sagebionetworks.repo.model.message.MessageToUser; import org.sagebionetworks.repo.model.migration.ListBucketProvider; import org.sagebionetworks.repo.model.migration.MigrationType; import org.sagebionetworks.repo.model.migration.MigrationTypeCount; import org.sagebionetworks.repo.model.migration.MigrationTypeCounts; import org.sagebionetworks.repo.model.migration.MigrationTypeList; import org.sagebionetworks.repo.model.migration.MigrationUtils; import org.sagebionetworks.repo.model.migration.RowMetadata; import org.sagebionetworks.repo.model.migration.RowMetadataResult; import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO; import org.sagebionetworks.repo.model.project.ProjectSettingsType; import org.sagebionetworks.repo.model.project.S3StorageLocationSetting; import org.sagebionetworks.repo.model.project.UploadDestinationListSetting; import org.sagebionetworks.repo.model.provenance.Activity; import org.sagebionetworks.repo.model.quiz.PassingRecord; import org.sagebionetworks.repo.model.quiz.QuizResponse; import org.sagebionetworks.repo.model.subscription.SubscriptionObjectType; import org.sagebionetworks.repo.model.table.ColumnMapper; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.RawRowSet; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.v2.dao.V2WikiPageDao; import org.sagebionetworks.repo.model.v2.wiki.V2WikiPage; import org.sagebionetworks.repo.model.verification.AttachmentMetadata; import org.sagebionetworks.repo.model.verification.VerificationSubmission; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.repo.web.controller.AbstractAutowiredControllerTestBase; import org.sagebionetworks.repo.web.service.ServiceProvider; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.table.cluster.utils.TableModelUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import com.google.common.collect.Lists; /** * This is an integration test to test the migration of all tables from start to finish. * * The test does the following: 1. the before() method creates at least one object for every type object that must * migrate. 2. Create a backup copy of all data. 3. Delete all data in the system. 4. Restore all data from the backup. * * NOTE: Whenever a new migration type is added this test must be extended to test that objects migration. * * * * @author jmhill * */ @DirtiesContext public class MigrationIntegrationAutowireTest extends AbstractAutowiredControllerTestBase { public static final long MAX_WAIT_MS = 45 * 1000; // 45 sec. @Autowired private DBOBasicDao basicDao; @Autowired private UserManager userManager; @Autowired private FileHandleDao fileMetadataDao; @Autowired private UserProfileManager userProfileManager; @Autowired private ServiceProvider serviceProvider; @Autowired private EntityBootstrapper entityBootstrapper; @Autowired private MigrationManager migrationManager; @Autowired private StorageQuotaManager storageQuotaManager; @Autowired private StorageQuotaAdminDao storageQuotaAdminDao; @Autowired private UserGroupDAO userGroupDAO; @Autowired private PrincipalAliasDAO principalAliasDAO; @Autowired private GroupMembersDAO groupMembersDAO; @Autowired private TeamDAO teamDAO; @Autowired private AuthenticationDAO authDAO; @Autowired private MessageDAO messageDAO; @Autowired private CommentDAO commentDAO; @Autowired private MembershipRqstSubmissionDAO membershipRqstSubmissionDAO; @Autowired private MembershipInvtnSubmissionDAO membershipInvtnSubmissionDAO; @Autowired private ColumnModelDAO columnModelDao; @Autowired private TableRowTruthDAO tableRowTruthDao; @Autowired private V2WikiPageDao v2wikiPageDAO; @Autowired private QuizResponseDAO quizResponseDAO; @Autowired private ProjectSettingsDAO projectSettingsDAO; @Autowired private StorageLocationDAO storageLocationDAO; @Autowired private ProjectStatsDAO projectStatsDAO; @Autowired private ChallengeDAO challengeDAO; @Autowired private ChallengeTeamDAO challengeTeamDAO; @Autowired private VerificationDAO verificationDao; @Autowired private ForumDAO forumDao; @Autowired private DiscussionThreadDAO threadDao; @Autowired private DiscussionReplyDAO replyDao; @Autowired private SubscriptionDAO subscriptionDao; @Autowired private IdGenerator idGenerator; @Autowired private MultipartUploadDAO multipartUploadDAO; private Team team; private Long adminUserId; private String adminUserIdString; private UserInfo adminUserInfo; // Activity private Activity activity; // Entities private Project project; private FileEntity fileEntity; private Folder folderToTrash; // requirement private AccessRequirement accessRequirement; // approval private AccessApproval accessApproval; // V2 Wiki page private V2WikiPage v2RootWiki; private V2WikiPage v2SubWiki; // File Handles private S3FileHandle handleOne; private S3FileHandle markdownOne; private PreviewFileHandle preview; private ExternalFileHandle sftpFileHandle; // Evaluation private Evaluation evaluation; private Submission submission; private HttpServletRequest mockRequest; private Challenge challenge; private ChallengeTeam challengeTeam; private String forumId; private String threadId; @Before public void before() throws Exception { mockRequest = Mockito.mock(HttpServletRequest.class); when(mockRequest.getServletPath()).thenReturn("/repo/v1"); // get user IDs adminUserId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId(); adminUserIdString = adminUserId.toString(); adminUserInfo = userManager.getUserInfo(adminUserId); resetDatabase(); createNewUser(); String sampleFileHandleId = createFileHandles(); createActivity(); createEntities(); createFavorite(); createProjectSetting(); createProjectStat(); createEvaluation(); createAccessRequirement(); createAccessApproval(); createV2WikiPages(); createDoi(); createStorageQuota(); UserGroup sampleGroup = createUserGroups(1); createTeamsRequestsAndInvitations(sampleGroup); createCredentials(sampleGroup); createSessionToken(sampleGroup); createTermsOfUseAgreement(sampleGroup); createMessages(sampleGroup, sampleFileHandleId); createColumnModel(); createUserGroups(2); createQuizResponse(); createChallengeAndRegisterTeam(); createVerificationSubmission(); createForum(); createThread(); createThreadView(); createReply(); createMultipartUpload(); createSubscription(); } private void createMultipartUpload(){ CreateMultipartRequest request = new CreateMultipartRequest(); request.setBucket("someBucket"); request.setHash("someHash"); request.setKey("someKey"); request.setNumberOfParts(1); request.setUploadToken("uploadToken"); request.setRequestBody("someRequestBody"); request.setUserId(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId()); // main row CompositeMultipartUploadStatus composite = multipartUploadDAO.createUploadStatus(request); // secondary row int partNumber =1; String partMD5Hex = "548c050497fb361742b85e0712b0cc96"; multipartUploadDAO.addPartToUpload(composite.getMultipartUploadStatus().getUploadId(), partNumber, partMD5Hex); } private void createForum() { forumId = forumDao.createForum(project.getId()).getId(); } private void createThread() { threadId = idGenerator.generateNewId(TYPE.DISCUSSION_THREAD_ID).toString(); threadDao.createThread(forumId, threadId, "title", "fakeMessageUrl", adminUserId); } private void createThreadView() { threadDao.updateThreadView(Long.parseLong(threadId), adminUserId); } private void createReply() { String replyId = idGenerator.generateNewId(TYPE.DISCUSSION_REPLY_ID).toString(); replyDao.createReply(threadId, replyId, "messageKey", adminUserId); } private void createSubscription() { subscriptionDao.create(adminUserIdString, threadId, SubscriptionObjectType.DISCUSSION_THREAD); } private void createVerificationSubmission() { VerificationSubmission dto = new VerificationSubmission(); dto.setCreatedBy(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId().toString()); dto.setCreatedOn(new Date()); AttachmentMetadata attachmentMetadata = new AttachmentMetadata(); attachmentMetadata.setId(handleOne.getId()); dto.setAttachments(Collections.singletonList(attachmentMetadata)); verificationDao.createVerificationSubmission(dto); } private void createChallengeAndRegisterTeam() { challenge = new Challenge(); challenge.setParticipantTeamId(team.getId()); challenge.setProjectId(project.getId()); challenge = challengeDAO.create(challenge); challengeTeam = new ChallengeTeam(); challengeTeam.setChallengeId(challenge.getId()); // this is nonsensical: We are registering a team which is the challenge // participant team. However it does the job of exercising object migration. challengeTeam.setTeamId(team.getId()); challengeTeam = challengeTeamDAO.create(challengeTeam); } private void createProjectSetting() { S3StorageLocationSetting destination = new S3StorageLocationSetting(); destination.setDescription("upload normal"); destination.setUploadType(UploadType.S3); destination.setBanner("warning"); destination.setCreatedOn(new Date()); destination.setCreatedBy(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId()); Long uploadId = storageLocationDAO.create(destination); UploadDestinationListSetting settings = new UploadDestinationListSetting(); settings.setProjectId(project.getId()); settings.setSettingsType(ProjectSettingsType.upload); settings.setLocations(Collections.singletonList(uploadId)); projectSettingsDAO.create(settings); } private void createProjectStat() { ProjectStat projectStat = new ProjectStat(KeyFactory.stringToKey(project.getId()), adminUserId, new Date()); projectStatsDAO.update(projectStat); } private void createQuizResponse() { QuizResponse dto = new QuizResponse(); PassingRecord passingRecord = new PassingRecord(); passingRecord.setPassed(true); passingRecord.setPassedOn(new Date()); passingRecord.setQuizId(101L); passingRecord.setResponseId(222L); passingRecord.setScore(7L); passingRecord.setUserId(adminUserId.toString()); adminUserId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId(); dto.setCreatedBy(adminUserId.toString()); dto.setCreatedOn(new Date()); dto.setQuizId(101L); quizResponseDAO.create(dto, passingRecord); } private void createColumnModel() throws DatastoreException, NotFoundException, IOException { String tableId = "syn123"; // Create some test column models List<ColumnModel> start = TableModelTestUtils.createOneOfEachType(); // Create each one List<ColumnModel> models = new LinkedList<ColumnModel>(); for (ColumnModel cm : start) { models.add(columnModelDao.createColumnModel(cm)); } ColumnMapper mapper = TableModelUtils.createColumnModelColumnMapper(models, false); List<Long> headers = TableModelUtils.getIds(models); // bind the columns to the entity columnModelDao.bindColumnToObject(Lists.transform(headers, TableModelUtils.LONG_TO_STRING), tableId); // create some test rows. List<Row> rows = TableModelTestUtils.createRows(models, 5); RawRowSet set = new RawRowSet(TableModelUtils.getIds(models), null, tableId, rows); // Append the rows to the table tableRowTruthDao.appendRowSetToTable(adminUserIdString, tableId, mapper, set); // Append some more rows rows = TableModelTestUtils.createRows(models, 6); set = new RawRowSet(TableModelUtils.getIds(models), null, tableId, rows); tableRowTruthDao.appendRowSetToTable(adminUserIdString, tableId, mapper, set); } public void createNewUser() throws NotFoundException { NewUser user = new NewUser(); user.setUserName(UUID.randomUUID().toString()); user.setEmail(user.getUserName() + "@test.com"); Long id = userManager.createUser(user); userManager.getUserInfo(id); } private void resetDatabase() throws Exception { // This gives us a chance to also delete the S3 for table rows tableRowTruthDao.truncateAllRowData(); // Before we start this test we want to start with a clean database migrationManager.deleteAllData(adminUserInfo); // bootstrap to put back the bootstrap data entityBootstrapper.bootstrapAll(); storageQuotaAdminDao.clear(); } private void createFavorite() { userProfileManager.addFavorite(adminUserInfo, fileEntity.getId()); } private void createDoi() throws Exception { serviceProvider.getDoiService().createDoi(adminUserId, project.getId(), ObjectType.ENTITY, 1L); } private void createActivity() throws Exception { activity = new Activity(); activity.setDescription("some desc"); activity = serviceProvider.getActivityService().createActivity(adminUserId, activity); } private void createEvaluation() throws Exception { // initialize Evaluations evaluation = new Evaluation(); evaluation.setName("name"); evaluation.setDescription("description"); evaluation.setContentSource(project.getId()); evaluation.setStatus(EvaluationStatus.PLANNED); evaluation.setSubmissionInstructionsMessage("instructions"); evaluation.setSubmissionReceiptMessage("receipt"); evaluation = serviceProvider.getEvaluationService().createEvaluation(adminUserId, evaluation); evaluation = new Evaluation(); evaluation.setName("name2"); evaluation.setDescription("description"); evaluation.setContentSource(project.getId()); evaluation.setStatus(EvaluationStatus.OPEN); evaluation.setSubmissionInstructionsMessage("instructions"); evaluation.setSubmissionReceiptMessage("receipt"); evaluation = serviceProvider.getEvaluationService().createEvaluation(adminUserId, evaluation); // initialize Participants serviceProvider.getEvaluationService().addParticipant(adminUserId, evaluation.getId()); // initialize Submissions submission = new Submission(); submission.setName("submission1"); submission.setVersionNumber(1L); submission.setEntityId(fileEntity.getId()); submission.setUserId(adminUserIdString); submission.setEvaluationId(evaluation.getId()); SubmissionContributor contributor = new SubmissionContributor(); contributor.setPrincipalId(adminUserIdString); submission.setContributors(Collections.singleton(contributor)); submission = entityServletHelper.createSubmission(submission, adminUserId, fileEntity.getEtag()); } public void createAccessApproval() throws Exception { accessApproval = newToUAccessApproval(accessRequirement.getId(), adminUserIdString); accessApproval = servletTestHelper.createAccessApproval(dispatchServlet, accessApproval, adminUserId, new HashMap<String, String>()); } public void createAccessRequirement() throws Exception { // Add an access requirement to this entity accessRequirement = newAccessRequirement(); String entityId = project.getId(); RestrictableObjectDescriptor entitySubjectId = new RestrictableObjectDescriptor(); entitySubjectId.setId(entityId); entitySubjectId.setType(RestrictableObjectType.ENTITY); RestrictableObjectDescriptor evaluationSubjectId = new RestrictableObjectDescriptor(); assertNotNull(evaluation); assertNotNull(evaluation.getId()); evaluationSubjectId.setId(evaluation.getId()); evaluationSubjectId.setType(RestrictableObjectType.EVALUATION); accessRequirement.setSubjectIds(Arrays.asList(new RestrictableObjectDescriptor[] { entitySubjectId, evaluationSubjectId })); accessRequirement = servletTestHelper.createAccessRequirement(dispatchServlet, accessRequirement, adminUserId, new HashMap<String, String>()); } private TermsOfUseAccessApproval newToUAccessApproval(Long requirementId, String accessorId) { TermsOfUseAccessApproval aa = new TermsOfUseAccessApproval(); aa.setAccessorId(accessorId); aa.setConcreteType(TermsOfUseAccessApproval.class.getName()); aa.setRequirementId(requirementId); return aa; } public void createV2WikiPages() throws NotFoundException { // Using wikiPageDao until wiki service is created // Create a V2 Wiki page v2RootWiki = new V2WikiPage(); v2RootWiki.setCreatedBy(adminUserIdString); v2RootWiki.setModifiedBy(adminUserIdString); v2RootWiki.setAttachmentFileHandleIds(new LinkedList<String>()); v2RootWiki.getAttachmentFileHandleIds().add(handleOne.getId()); v2RootWiki.setTitle("Root title"); v2RootWiki.setMarkdownFileHandleId(markdownOne.getId()); Map<String, FileHandle> map = new HashMap<String, FileHandle>(); map.put(handleOne.getFileName(), handleOne); List<String> newIds = new ArrayList<String>(); newIds.add(handleOne.getId()); v2RootWiki = v2wikiPageDAO.create(v2RootWiki, map, fileEntity.getId(), ObjectType.ENTITY, newIds); // Create a child v2SubWiki = new V2WikiPage(); v2SubWiki.setCreatedBy(adminUserIdString); v2SubWiki.setModifiedBy(adminUserIdString); v2SubWiki.setParentWikiId(v2RootWiki.getId()); v2SubWiki.setTitle("V2 Sub-wiki-title"); v2SubWiki.setMarkdownFileHandleId(markdownOne.getId()); v2SubWiki = v2wikiPageDAO.create(v2SubWiki, new HashMap<String, FileHandle>(), fileEntity.getId(), ObjectType.ENTITY, new ArrayList<String>()); } /** * Create the entities used by this test. * * @throws JSONObjectAdapterException * @throws ServletException * @throws IOException * @throws NotFoundException */ public void createEntities() throws JSONObjectAdapterException, ServletException, IOException, NotFoundException { // Create a project project = new Project(); project.setName("MigrationIntegrationAutowireTest.Project"); project.setEntityType(Project.class.getName()); project = serviceProvider.getEntityService().createEntity(adminUserId, project, null, mockRequest); // Create a file entity fileEntity = new FileEntity(); fileEntity.setName("MigrationIntegrationAutowireTest.FileEntity"); fileEntity.setEntityType(FileEntity.class.getName()); fileEntity.setParentId(project.getId()); fileEntity.setDataFileHandleId(handleOne.getId()); fileEntity = serviceProvider.getEntityService().createEntity(adminUserId, fileEntity, activity.getId(), mockRequest); // Create a folder to trash folderToTrash = new Folder(); folderToTrash.setName("boundForTheTrashCan"); folderToTrash.setParentId(project.getId()); folderToTrash = serviceProvider.getEntityService().createEntity(adminUserId, folderToTrash, null, mockRequest); // Send it to the trash can serviceProvider.getTrashService().moveToTrash(adminUserId, folderToTrash.getId()); } private AccessRequirement newAccessRequirement() { TermsOfUseAccessRequirement dto = new TermsOfUseAccessRequirement(); dto.setConcreteType(dto.getClass().getName()); dto.setAccessType(ACCESS_TYPE.DOWNLOAD); dto.setTermsOfUse("foo"); return dto; } /** * Create the file handles used by this test. * * @throws NotFoundException */ public String createFileHandles() throws NotFoundException { // Create a file handle handleOne = new S3FileHandle(); handleOne.setCreatedBy(adminUserIdString); handleOne.setCreatedOn(new Date()); handleOne.setBucketName("bucket"); handleOne.setKey("mainFileKey"); handleOne.setEtag("etag"); handleOne.setFileName("foo.bar"); handleOne = fileMetadataDao.createFile(handleOne); // Create markdown content markdownOne = new S3FileHandle(); markdownOne.setCreatedBy(adminUserIdString); markdownOne.setCreatedOn(new Date()); markdownOne.setBucketName("bucket"); markdownOne.setKey("markdownFileKey"); markdownOne.setEtag("etag"); markdownOne.setFileName("markdown1"); markdownOne = fileMetadataDao.createFile(markdownOne); // Create a preview preview = new PreviewFileHandle(); preview.setCreatedBy(adminUserIdString); preview.setCreatedOn(new Date()); preview.setBucketName("bucket"); preview.setKey("previewFileKey"); preview.setEtag("etag"); preview.setFileName("bar.txt"); preview = fileMetadataDao.createFile(preview); // Set two as the preview of one fileMetadataDao.setPreviewId(handleOne.getId(), preview.getId()); return handleOne.getId(); } private void createStorageQuota() { storageQuotaManager.setQuotaForUser(adminUserInfo, adminUserInfo, 3000); } // returns a group for use in a team private UserGroup createUserGroups(int index) throws NotFoundException { List<String> adder = new ArrayList<String>(); // Make one group UserGroup parentGroup = new UserGroup(); parentGroup.setIsIndividual(false); parentGroup.setId(userGroupDAO.create(parentGroup).toString()); // Make two users UserGroup parentUser = new UserGroup(); parentUser.setIsIndividual(true); parentUser.setId(userGroupDAO.create(parentUser).toString()); UserGroup siblingUser = new UserGroup(); siblingUser.setIsIndividual(true); siblingUser.setId(userGroupDAO.create(siblingUser).toString()); // Nest one group and two users within the parent group adder.add(parentUser.getId()); adder.add(siblingUser.getId()); groupMembersDAO.addMembers(parentGroup.getId(), adder); return parentGroup; } private void createCredentials(UserGroup group) throws Exception { Long principalId = Long.parseLong(group.getId()); authDAO.changePassword(principalId, "ThisIsMySuperSecurePassword"); authDAO.changeSecretKey(principalId); authDAO.changeSessionToken(principalId, null, DomainType.SYNAPSE); } private void createSessionToken(UserGroup group) throws Exception { DBOSessionToken token = new DBOSessionToken(); token.setDomain(DomainType.SYNAPSE); token.setPrincipalId(Long.parseLong(group.getId())); token.setSessionToken(UUID.randomUUID().toString()); token.setValidatedOn(new Date()); basicDao.createOrUpdate(token); } private void createTermsOfUseAgreement(UserGroup group) throws Exception { DBOTermsOfUseAgreement tou = new DBOTermsOfUseAgreement(); tou.setPrincipalId(Long.parseLong(group.getId())); tou.setAgreesToTermsOfUse(Boolean.TRUE); tou.setDomain(DomainType.SYNAPSE); basicDao.createNew(tou); } @SuppressWarnings("serial") private void createMessages(final UserGroup group, String fileHandleId) { MessageToUser dto = new MessageToUser(); // Note: ID is auto generated dto.setCreatedBy(group.getId()); dto.setFileHandleId(fileHandleId); // Note: CreatedOn is set by the DAO dto.setSubject("See you on the other side?"); dto.setRecipients(new HashSet<String>() { { add(group.getId()); } }); dto.setInReplyTo(null); // Note: InReplyToRoot is calculated by the DAO dto = messageDAO.createMessage(dto); messageDAO.createMessageStatus_NewTransaction(dto.getId(), group.getId(), null); Comment dto2 = new Comment(); dto2.setCreatedBy(group.getId()); dto2.setFileHandleId(fileHandleId); dto2.setTargetId("1337"); dto2.setTargetType(ObjectType.ENTITY); commentDAO.createComment(dto2); } private void createTeamsRequestsAndInvitations(UserGroup group) { String otherUserId = BOOTSTRAP_PRINCIPAL.ANONYMOUS_USER.getPrincipalId().toString(); team = new Team(); team.setId(group.getId()); team.setName(UUID.randomUUID().toString()); team.setDescription("test team"); team = teamDAO.create(team); // create a MembershipRqstSubmission MembershipRqstSubmission mrs = new MembershipRqstSubmission(); Date createdOn = new Date(); Date expiresOn = new Date(); mrs.setCreatedOn(createdOn); mrs.setExpiresOn(expiresOn); mrs.setMessage("Please let me join the team."); mrs.setTeamId("" + group.getId()); // need another valid user group mrs.setUserId(otherUserId); membershipRqstSubmissionDAO.create(mrs); // create a MembershipInvtnSubmission MembershipInvtnSubmission mis = new MembershipInvtnSubmission(); mis.setCreatedOn(createdOn); mis.setExpiresOn(expiresOn); mis.setMessage("Please join the team."); mis.setTeamId("" + group.getId()); // need another valid user group mis.setInviteeId(otherUserId); membershipInvtnSubmissionDAO.create(mis); } @After public void after() throws Exception { // to cleanup for this test we delete all in the database resetDatabase(); } // test that if we create a group with members, back it up, // add members, and restore, the extra members are removed // (This was broken in PLFM-2757) @Test public void testCertifiedUsersGroupMigration() throws Exception { String groupId = BOOTSTRAP_PRINCIPAL.CERTIFIED_USERS.getPrincipalId().toString(); List<UserGroup> members = groupMembersDAO.getMembers(groupId); List<BackupInfo> backupList = backupAllOfType(MigrationType.PRINCIPAL); // add new member(s) UserGroup yetAnotherUser = new UserGroup(); yetAnotherUser.setIsIndividual(true); yetAnotherUser.setId(userGroupDAO.create(yetAnotherUser).toString()); groupMembersDAO.addMembers(groupId, Collections.singletonList(yetAnotherUser.getId())); // membership is different because new user has been added assertFalse(members.equals(groupMembersDAO.getMembers(groupId))); // Now restore all of the data for (BackupInfo info : backupList) { String fileName = info.getFileName(); assertNotNull("Did not find a backup file name for type: " + info.getType(), fileName); restoreFromBackup(info.getType(), fileName); } // should be back to normal assertEquals(members, groupMembersDAO.getMembers(groupId)); } /** * This is the actual test. The rest of the class is setup and tear down. * * @throws Exception */ @Test public void testRoundTrip() throws Exception { // Get the list of primary types MigrationTypeList primaryTypesList = entityServletHelper.getPrimaryMigrationTypes(adminUserId); assertNotNull(primaryTypesList); assertNotNull(primaryTypesList.getList()); assertTrue(primaryTypesList.getList().size() > 0); // Get the counts before we start MigrationTypeCounts startCounts = entityServletHelper.getMigrationTypeCounts(adminUserId); validateStartingCount(startCounts); // This test will backup all data, delete it, then restore it. List<BackupInfo> backupList = new ArrayList<BackupInfo>(); for (MigrationType type : primaryTypesList.getList()) { // Backup each type backupList.addAll(backupAllOfType(type)); } // Now delete all data in reverse order for (int i = primaryTypesList.getList().size() - 1; i >= 0; i--) { MigrationType type = primaryTypesList.getList().get(i); deleteAllOfType(type); } // After deleting, the counts should be 0 except for a few special cases MigrationTypeCounts afterDeleteCounts = entityServletHelper.getMigrationTypeCounts(adminUserId); assertNotNull(afterDeleteCounts); assertNotNull(afterDeleteCounts.getList()); for (int i = 0; i < afterDeleteCounts.getList().size(); i++) { MigrationTypeCount afterDelete = afterDeleteCounts.getList().get(i); // Special cases for the not-deleted migration admin if (afterDelete.getType() == MigrationType.PRINCIPAL) { assertEquals("There should be 4 UserGroups remaining after the delete: " + BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER + ", " + "Administrators" + ", " + BOOTSTRAP_PRINCIPAL.PUBLIC_GROUP + ", and " + BOOTSTRAP_PRINCIPAL.AUTHENTICATED_USERS_GROUP, new Long(4), afterDelete.getCount()); } else if (afterDelete.getType() == MigrationType.GROUP_MEMBERS || afterDelete.getType() == MigrationType.CREDENTIAL) { assertEquals("Counts do not match for: " + afterDelete.getType().name(), new Long(1), afterDelete.getCount()); } else { assertEquals("Counts are non-zero for: " + afterDelete.getType().name(), new Long(0), afterDelete.getCount()); } } // Now restore all of the data for (BackupInfo info : backupList) { String fileName = info.getFileName(); assertNotNull("Did not find a backup file name for type: " + info.getType(), fileName); restoreFromBackup(info.getType(), fileName); } // The counts should all be back MigrationTypeCounts finalCounts = entityServletHelper.getMigrationTypeCounts(adminUserId); for (int i = 1; i < finalCounts.getList().size(); i++) { MigrationTypeCount startCount = startCounts.getList().get(i); MigrationTypeCount afterRestore = finalCounts.getList().get(i); assertEquals("Count for " + startCount.getType().name() + " does not match.", startCount.getCount(), afterRestore.getCount()); } } private static class BackupInfo { MigrationType type; String fileName; public BackupInfo(MigrationType type, String fileName) { super(); this.type = type; this.fileName = fileName; } public MigrationType getType() { return type; } public String getFileName() { return fileName; } } /** * There must be at least one object for every type of migratable object. * * @param startCounts */ private void validateStartingCount(MigrationTypeCounts startCounts) { assertNotNull(startCounts); assertNotNull(startCounts.getList()); List<MigrationType> typesToMigrate = new LinkedList<MigrationType>(); for (MigrationType tm : MigrationType.values()) { if (migrationManager.isMigrationTypeUsed(adminUserInfo, tm)) { typesToMigrate.add(tm); } } assertEquals( "This test requires at least one object to exist for each MigrationType. Please create a new object of the new MigrationType in the before() method of this test.", typesToMigrate.size(), startCounts.getList().size()); for (MigrationTypeCount count : startCounts.getList()) { assertTrue("This test requires at least one object to exist for each MigrationType. Please create a new object of type: " + count.getType() + " in the before() method of this test.", count.getCount() > 0); } } /** * Extract the filename from the full url. * * @param fullUrl * @return */ public String getFileNameFromUrl(String fullUrl) { ; int index = fullUrl.lastIndexOf("/"); return fullUrl.substring(index + 1, fullUrl.length()); } /** * Backup all data * * @param type * @return * @throws Exception */ private List<BackupInfo> backupAllOfType(MigrationType type) throws Exception { RowMetadataResult list = entityServletHelper.getRowMetadata(adminUserId, type, Long.MAX_VALUE, 0); if (list == null) return null; // Backup batches by their level in the tree ListBucketProvider provider = new ListBucketProvider(); MigrationUtils.bucketByTreeLevel(list.getList().iterator(), provider); List<BackupInfo> result = new ArrayList<BackupInfo>(); List<List<Long>> listOfBuckets = provider.getListOfBuckets(); for (List<Long> batch : listOfBuckets) { if (batch.size() > 0) { String fileName = backup(type, batch); result.add(new BackupInfo(type, fileName)); } } return result; } private String backup(MigrationType type, List<Long> tobackup) throws Exception { // Start the backup job IdList ids = new IdList(); ids.setList(tobackup); BackupRestoreStatus status = entityServletHelper.startBackup(adminUserId, type, ids); // wait for it.. waitForDaemon(status); status = entityServletHelper.getBackupRestoreStatus(adminUserId, status.getId()); assertNotNull(status.getBackupUrl()); return getFileNameFromUrl(status.getBackupUrl()); } private void restoreFromBackup(MigrationType type, String fileName) throws Exception { RestoreSubmission sub = new RestoreSubmission(); sub.setFileName(fileName); BackupRestoreStatus status = entityServletHelper.startRestore(adminUserId, type, sub); // wait for it waitForDaemon(status); } /** * Delete all data for a type. * * @param type * @throws ServletException * @throws IOException * @throws JSONObjectAdapterException */ private void deleteAllOfType(MigrationType type) throws Exception { IdList idList = getIdListOfAllOfType(type); if (idList == null) return; MigrationTypeCount result = entityServletHelper.deleteMigrationType(adminUserId, type, idList); System.out.println("Deleted: " + result); } /** * List all of the IDs for a type. * * @param type * @return * @throws ServletException * @throws IOException * @throws JSONObjectAdapterException */ private IdList getIdListOfAllOfType(MigrationType type) throws Exception { RowMetadataResult list = entityServletHelper.getRowMetadata(adminUserId, type, Long.MAX_VALUE, 0); if (list.getTotalCount() < 1) return null; // Create the backup list List<Long> toBackup = new LinkedList<Long>(); for (RowMetadata row : list.getList()) { toBackup.add(row.getId()); } IdList idList = new IdList(); idList.setList(toBackup); return idList; } /** * Wait for a deamon to process a a job. * * @param status * @throws InterruptedException * @throws JSONObjectAdapterException * @throws IOException * @throws ServletException */ private void waitForDaemon(BackupRestoreStatus status) throws Exception { long start = System.currentTimeMillis(); while (DaemonStatus.COMPLETED != status.getStatus()) { assertFalse("Daemon failed " + status.getErrorDetails(), DaemonStatus.FAILED == status.getStatus()); System.out.println("Waiting for backup/restore daemon. Message: " + status.getProgresssMessage()); Thread.sleep(1000); long elapse = System.currentTimeMillis() - start; assertTrue("Timed out waiting for a backup/restore daemon", elapse < MAX_WAIT_MS); status = entityServletHelper.getBackupRestoreStatus(adminUserId, status.getId()); } } }
update test now that we do not need to create a forum anymore
services/repository/src/test/java/org/sagebionetworks/repo/web/migration/MigrationIntegrationAutowireTest.java
update test now that we do not need to create a forum anymore
<ide><path>ervices/repository/src/test/java/org/sagebionetworks/repo/web/migration/MigrationIntegrationAutowireTest.java <ide> createQuizResponse(); <ide> createChallengeAndRegisterTeam(); <ide> createVerificationSubmission(); <del> createForum(); <ide> createThread(); <ide> createThreadView(); <ide> createReply(); <ide> int partNumber =1; <ide> String partMD5Hex = "548c050497fb361742b85e0712b0cc96"; <ide> multipartUploadDAO.addPartToUpload(composite.getMultipartUploadStatus().getUploadId(), partNumber, partMD5Hex); <del> } <del> <del> private void createForum() { <del> forumId = forumDao.createForum(project.getId()).getId(); <ide> } <ide> <ide> private void createThread() { <ide> project.setName("MigrationIntegrationAutowireTest.Project"); <ide> project.setEntityType(Project.class.getName()); <ide> project = serviceProvider.getEntityService().createEntity(adminUserId, project, null, mockRequest); <add> <add> forumId = forumDao.getForumByProjectId(project.getId()).getId(); <ide> <ide> // Create a file entity <ide> fileEntity = new FileEntity();
Java
apache-2.0
5c2c9a4ffc08b400076a8a06d62f4f3602c5a01d
0
tommyettinger/sarong
/* * Copyright (c) 2014, Oracle America, Inc. * 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 Oracle 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 sarong; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Results for all benchmarks on an i7-8750H CPU clocked at 2.20GHz : * <br> * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureAltThrustDetermine avgt 5 2.636 ± 0.006 ns/op * RNGBenchmark.measureBasicRandom32 avgt 5 2.966 ± 0.004 ns/op * RNGBenchmark.measureBasicRandom32Int avgt 5 2.178 ± 0.021 ns/op * RNGBenchmark.measureBasicRandom32IntR avgt 5 2.383 ± 0.027 ns/op * RNGBenchmark.measureBasicRandom32R avgt 5 3.212 ± 0.010 ns/op * RNGBenchmark.measureBasicRandom64 avgt 5 2.549 ± 0.020 ns/op * RNGBenchmark.measureBasicRandom64Int avgt 5 2.660 ± 0.009 ns/op * RNGBenchmark.measureBasicRandom64IntR avgt 5 2.896 ± 0.006 ns/op * RNGBenchmark.measureBasicRandom64R avgt 5 2.822 ± 0.015 ns/op * RNGBenchmark.measureChurro32 avgt 5 6.071 ± 0.052 ns/op * RNGBenchmark.measureChurro32Int avgt 5 3.663 ± 0.003 ns/op * RNGBenchmark.measureChurro32IntR avgt 5 4.460 ± 0.021 ns/op * RNGBenchmark.measureChurro32R avgt 5 8.272 ± 0.056 ns/op * RNGBenchmark.measureDervish avgt 5 3.133 ± 0.038 ns/op * RNGBenchmark.measureDervishInt avgt 5 3.248 ± 0.042 ns/op * RNGBenchmark.measureDervishIntR avgt 5 3.588 ± 0.009 ns/op * RNGBenchmark.measureDervishR avgt 5 3.575 ± 0.117 ns/op * RNGBenchmark.measureDirk avgt 5 3.137 ± 0.006 ns/op * RNGBenchmark.measureDirkDetermine avgt 5 3.016 ± 0.011 ns/op * RNGBenchmark.measureDirkInt avgt 5 3.135 ± 0.017 ns/op * RNGBenchmark.measureDirkIntR avgt 5 3.576 ± 0.013 ns/op * RNGBenchmark.measureDirkR avgt 5 3.559 ± 0.022 ns/op * RNGBenchmark.measureDizzy32 avgt 5 5.429 ± 0.066 ns/op * RNGBenchmark.measureDizzy32Int avgt 5 3.382 ± 0.011 ns/op * RNGBenchmark.measureDizzy32IntNative1 avgt 5 3.479 ± 0.029 ns/op * RNGBenchmark.measureDizzy32IntNative2 avgt 5 3.479 ± 0.009 ns/op * RNGBenchmark.measureDizzy32IntR avgt 5 3.949 ± 0.037 ns/op * RNGBenchmark.measureDizzy32R avgt 5 6.154 ± 0.076 ns/op * RNGBenchmark.measureFlap avgt 5 2.857 ± 0.014 ns/op * RNGBenchmark.measureFlapInt avgt 5 2.380 ± 0.038 ns/op * RNGBenchmark.measureFlapIntR avgt 5 2.703 ± 0.052 ns/op * RNGBenchmark.measureFlapR avgt 5 3.210 ± 0.018 ns/op * RNGBenchmark.measureGWT avgt 5 4.293 ± 0.026 ns/op * RNGBenchmark.measureGWTInt avgt 5 2.918 ± 0.040 ns/op * RNGBenchmark.measureGWTNextInt avgt 5 2.914 ± 0.020 ns/op * RNGBenchmark.measureIsaac avgt 5 5.141 ± 0.012 ns/op * RNGBenchmark.measureIsaac32 avgt 5 8.779 ± 0.069 ns/op * RNGBenchmark.measureIsaac32Int avgt 5 5.242 ± 0.021 ns/op * RNGBenchmark.measureIsaac32IntR avgt 5 5.682 ± 0.018 ns/op * RNGBenchmark.measureIsaac32R avgt 5 9.753 ± 0.066 ns/op * RNGBenchmark.measureIsaacInt avgt 5 5.229 ± 0.037 ns/op * RNGBenchmark.measureIsaacIntR avgt 5 5.590 ± 0.064 ns/op * RNGBenchmark.measureIsaacR avgt 5 5.540 ± 0.190 ns/op * RNGBenchmark.measureJDK avgt 5 17.561 ± 0.054 ns/op * RNGBenchmark.measureJDKInt avgt 5 8.767 ± 0.052 ns/op * RNGBenchmark.measureJab63 avgt 5 2.397 ± 0.011 ns/op * RNGBenchmark.measureJab63Int avgt 5 2.512 ± 0.013 ns/op * RNGBenchmark.measureJab63IntR avgt 5 2.761 ± 0.043 ns/op * RNGBenchmark.measureJab63R avgt 5 2.691 ± 0.030 ns/op * RNGBenchmark.measureLap avgt 5 2.415 ± 0.027 ns/op * RNGBenchmark.measureLapInt avgt 5 2.530 ± 0.024 ns/op * RNGBenchmark.measureLapIntR avgt 5 2.892 ± 0.065 ns/op * RNGBenchmark.measureLapR avgt 5 2.761 ± 0.013 ns/op * RNGBenchmark.measureLathe32 avgt 5 4.296 ± 0.005 ns/op * RNGBenchmark.measureLathe32Int avgt 5 2.915 ± 0.022 ns/op * RNGBenchmark.measureLathe32IntR avgt 5 3.244 ± 0.070 ns/op * RNGBenchmark.measureLathe32R avgt 5 4.873 ± 0.028 ns/op * RNGBenchmark.measureLathe64 avgt 5 2.917 ± 0.028 ns/op * RNGBenchmark.measureLathe64Int avgt 5 3.021 ± 0.036 ns/op * RNGBenchmark.measureLathe64IntR avgt 5 3.432 ± 0.011 ns/op * RNGBenchmark.measureLathe64R avgt 5 3.192 ± 0.008 ns/op * RNGBenchmark.measureLight avgt 5 2.826 ± 0.017 ns/op * RNGBenchmark.measureLight32 avgt 5 4.672 ± 0.038 ns/op * RNGBenchmark.measureLight32Int avgt 5 2.881 ± 0.665 ns/op * RNGBenchmark.measureLight32IntR avgt 5 3.280 ± 0.640 ns/op * RNGBenchmark.measureLight32R avgt 5 5.463 ± 0.008 ns/op * RNGBenchmark.measureLightDetermine avgt 5 2.805 ± 0.007 ns/op * RNGBenchmark.measureLightInt avgt 5 2.830 ± 0.007 ns/op * RNGBenchmark.measureLightIntR avgt 5 3.192 ± 0.032 ns/op * RNGBenchmark.measureLightR avgt 5 3.151 ± 0.027 ns/op * RNGBenchmark.measureLinnorm avgt 5 2.620 ± 0.026 ns/op * RNGBenchmark.measureLinnormDetermine avgt 5 2.770 ± 0.019 ns/op * RNGBenchmark.measureLinnormInt avgt 5 2.665 ± 0.018 ns/op * RNGBenchmark.measureLinnormIntR avgt 5 2.875 ± 0.009 ns/op * RNGBenchmark.measureLinnormR avgt 5 2.989 ± 0.014 ns/op * RNGBenchmark.measureLobster32 avgt 5 4.654 ± 0.178 ns/op * RNGBenchmark.measureLobster32Int avgt 5 3.039 ± 0.026 ns/op * RNGBenchmark.measureLobster32IntR avgt 5 3.346 ± 0.029 ns/op * RNGBenchmark.measureLobster32R avgt 5 5.140 ± 0.025 ns/op * RNGBenchmark.measureLongPeriod avgt 5 3.530 ± 0.011 ns/op * RNGBenchmark.measureLongPeriodInt avgt 5 3.607 ± 0.031 ns/op * RNGBenchmark.measureLongPeriodIntR avgt 5 4.095 ± 0.018 ns/op * RNGBenchmark.measureLongPeriodR avgt 5 3.955 ± 0.038 ns/op * RNGBenchmark.measureMesh avgt 5 3.298 ± 0.022 ns/op * RNGBenchmark.measureMeshInt avgt 5 3.243 ± 0.008 ns/op * RNGBenchmark.measureMeshIntR avgt 5 3.718 ± 0.068 ns/op * RNGBenchmark.measureMeshR avgt 5 3.701 ± 0.010 ns/op * RNGBenchmark.measureMiniMover64 avgt 5 2.398 ± 0.006 ns/op * RNGBenchmark.measureMiniMover64Int avgt 5 2.447 ± 0.010 ns/op * RNGBenchmark.measureMiniMover64IntR avgt 5 2.635 ± 0.017 ns/op * RNGBenchmark.measureMiniMover64R avgt 5 2.634 ± 0.020 ns/op * RNGBenchmark.measureMizuchi avgt 5 2.673 ± 0.019 ns/op * RNGBenchmark.measureMizuchiInt avgt 5 2.704 ± 0.012 ns/op * RNGBenchmark.measureMizuchiIntR avgt 5 2.939 ± 0.010 ns/op * RNGBenchmark.measureMizuchiR avgt 5 3.008 ± 0.042 ns/op * RNGBenchmark.measureMolerat32 avgt 5 5.033 ± 0.040 ns/op * RNGBenchmark.measureMolerat32Int avgt 5 3.050 ± 0.009 ns/op * RNGBenchmark.measureMolerat32IntR avgt 5 3.480 ± 0.012 ns/op * RNGBenchmark.measureMolerat32R avgt 5 5.426 ± 0.010 ns/op * RNGBenchmark.measureMotor avgt 5 3.768 ± 0.023 ns/op * RNGBenchmark.measureMotorInt avgt 5 3.701 ± 0.007 ns/op * RNGBenchmark.measureMotorIntR avgt 5 4.201 ± 0.012 ns/op * RNGBenchmark.measureMotorR avgt 5 4.098 ± 0.006 ns/op * RNGBenchmark.measureMover32 avgt 5 3.822 ± 0.015 ns/op * RNGBenchmark.measureMover32Int avgt 5 2.621 ± 0.013 ns/op * RNGBenchmark.measureMover32IntR avgt 5 2.775 ± 0.032 ns/op * RNGBenchmark.measureMover32R avgt 5 4.209 ± 0.063 ns/op * RNGBenchmark.measureMover64 avgt 5 2.619 ± 0.025 ns/op * RNGBenchmark.measureMover64Int avgt 5 2.636 ± 0.033 ns/op * RNGBenchmark.measureMover64IntR avgt 5 2.772 ± 0.032 ns/op * RNGBenchmark.measureMover64R avgt 5 2.733 ± 0.169 ns/op * RNGBenchmark.measureMoverCounter64 avgt 5 2.463 ± 0.006 ns/op * RNGBenchmark.measureMoverCounter64Int avgt 5 2.466 ± 0.016 ns/op * RNGBenchmark.measureMoverCounter64IntR avgt 5 2.691 ± 0.017 ns/op * RNGBenchmark.measureMoverCounter64R avgt 5 2.687 ± 0.016 ns/op * RNGBenchmark.measureOrbit avgt 5 2.916 ± 0.012 ns/op * RNGBenchmark.measureOrbitA avgt 5 2.914 ± 0.005 ns/op * RNGBenchmark.measureOrbitB avgt 5 3.027 ± 0.010 ns/op * RNGBenchmark.measureOrbitC avgt 5 3.003 ± 0.021 ns/op * RNGBenchmark.measureOrbitD avgt 5 2.914 ± 0.031 ns/op * RNGBenchmark.measureOrbitE avgt 5 3.260 ± 0.027 ns/op * RNGBenchmark.measureOrbitF avgt 5 2.905 ± 0.026 ns/op * RNGBenchmark.measureOrbitG avgt 5 3.027 ± 0.013 ns/op * RNGBenchmark.measureOrbitH avgt 5 2.905 ± 0.026 ns/op * RNGBenchmark.measureOrbitI avgt 5 3.017 ± 0.012 ns/op * RNGBenchmark.measureOrbitInt avgt 5 3.018 ± 0.017 ns/op * RNGBenchmark.measureOrbitIntR avgt 5 3.357 ± 0.009 ns/op * RNGBenchmark.measureOrbitJ avgt 5 2.781 ± 0.009 ns/op * RNGBenchmark.measureOrbitK avgt 5 2.895 ± 0.011 ns/op * RNGBenchmark.measureOrbitL avgt 5 2.753 ± 0.012 ns/op * RNGBenchmark.measureOrbitM avgt 5 3.141 ± 0.011 ns/op * RNGBenchmark.measureOrbitN avgt 5 3.147 ± 0.022 ns/op * RNGBenchmark.measureOrbitO avgt 5 3.008 ± 0.031 ns/op * RNGBenchmark.measureOrbitR avgt 5 3.297 ± 0.019 ns/op * RNGBenchmark.measureOriole32 avgt 5 4.691 ± 0.005 ns/op * RNGBenchmark.measureOriole32Int avgt 5 3.134 ± 0.040 ns/op * RNGBenchmark.measureOriole32IntR avgt 5 3.522 ± 0.017 ns/op * RNGBenchmark.measureOriole32R avgt 5 5.153 ± 0.070 ns/op * RNGBenchmark.measureOtter32 avgt 5 4.958 ± 0.009 ns/op * RNGBenchmark.measureOtter32Int avgt 5 3.121 ± 0.031 ns/op * RNGBenchmark.measureOtter32IntR avgt 5 3.509 ± 0.020 ns/op * RNGBenchmark.measureOtter32R avgt 5 5.633 ± 0.023 ns/op * RNGBenchmark.measureOverdrive64 avgt 5 2.493 ± 0.022 ns/op * RNGBenchmark.measureOverdrive64Int avgt 5 2.558 ± 0.084 ns/op * RNGBenchmark.measureOverdrive64IntR avgt 5 2.735 ± 0.022 ns/op * RNGBenchmark.measureOverdrive64R avgt 5 2.716 ± 0.025 ns/op * RNGBenchmark.measurePaperweight avgt 5 3.370 ± 0.029 ns/op * RNGBenchmark.measurePaperweightInt avgt 5 3.400 ± 0.019 ns/op * RNGBenchmark.measurePaperweightIntR avgt 5 3.879 ± 0.019 ns/op * RNGBenchmark.measurePaperweightR avgt 5 3.796 ± 0.026 ns/op * RNGBenchmark.measureQuixotic avgt 5 2.608 ± 0.020 ns/op * RNGBenchmark.measureQuixoticInt avgt 5 2.660 ± 0.012 ns/op * RNGBenchmark.measureQuixoticIntR avgt 5 2.923 ± 0.012 ns/op * RNGBenchmark.measureQuixoticR avgt 5 2.892 ± 0.023 ns/op * RNGBenchmark.measureSFC64 avgt 5 3.214 ± 0.011 ns/op * RNGBenchmark.measureSFC64Int avgt 5 3.307 ± 0.025 ns/op * RNGBenchmark.measureSFC64IntR avgt 5 3.725 ± 0.023 ns/op * RNGBenchmark.measureSFC64R avgt 5 3.909 ± 0.156 ns/op * RNGBenchmark.measureSeaSlater32 avgt 5 4.992 ± 0.110 ns/op * RNGBenchmark.measureSeaSlater32Int avgt 5 3.063 ± 0.011 ns/op * RNGBenchmark.measureSeaSlater32IntR avgt 5 3.430 ± 0.026 ns/op * RNGBenchmark.measureSeaSlater32R avgt 5 5.585 ± 0.100 ns/op * RNGBenchmark.measureSeaSlater64 avgt 5 3.074 ± 0.039 ns/op * RNGBenchmark.measureSeaSlater64Int avgt 5 3.161 ± 0.009 ns/op * RNGBenchmark.measureSeaSlater64IntR avgt 5 3.544 ± 0.058 ns/op * RNGBenchmark.measureSeaSlater64R avgt 5 3.457 ± 0.075 ns/op * RNGBenchmark.measureSpiral avgt 5 3.471 ± 0.031 ns/op * RNGBenchmark.measureSpiralA avgt 5 3.475 ± 0.025 ns/op * RNGBenchmark.measureSpiralB avgt 5 3.159 ± 0.008 ns/op * RNGBenchmark.measureSpiralC avgt 5 3.290 ± 0.011 ns/op * RNGBenchmark.measureSpiralD avgt 5 3.203 ± 0.073 ns/op * RNGBenchmark.measureSpiralE avgt 5 3.223 ± 0.010 ns/op * RNGBenchmark.measureSpiralF avgt 5 3.001 ± 0.029 ns/op * RNGBenchmark.measureSpiralG avgt 5 3.082 ± 0.062 ns/op * RNGBenchmark.measureSpiralH avgt 5 3.169 ± 0.031 ns/op * RNGBenchmark.measureSpiralI avgt 5 2.669 ± 0.034 ns/op * RNGBenchmark.measureSpiralInt avgt 5 3.513 ± 0.050 ns/op * RNGBenchmark.measureSpiralIntR avgt 5 4.234 ± 0.010 ns/op * RNGBenchmark.measureSpiralR avgt 5 3.991 ± 0.037 ns/op * RNGBenchmark.measureStarfish32 avgt 5 4.449 ± 0.056 ns/op * RNGBenchmark.measureStarfish32Int avgt 5 3.016 ± 0.017 ns/op * RNGBenchmark.measureStarfish32IntR avgt 5 3.208 ± 0.014 ns/op * RNGBenchmark.measureStarfish32NextInt avgt 5 2.997 ± 0.052 ns/op * RNGBenchmark.measureStarfish32R avgt 5 5.013 ± 0.157 ns/op * RNGBenchmark.measureTangle avgt 5 2.572 ± 0.029 ns/op * RNGBenchmark.measureTangleA avgt 5 2.582 ± 0.008 ns/op * RNGBenchmark.measureTangleB avgt 5 2.734 ± 0.004 ns/op * RNGBenchmark.measureTangleC avgt 5 2.762 ± 0.018 ns/op * RNGBenchmark.measureTangleD avgt 5 2.838 ± 0.015 ns/op * RNGBenchmark.measureTangleInt avgt 5 2.651 ± 0.008 ns/op * RNGBenchmark.measureTangleIntR avgt 5 2.978 ± 0.039 ns/op * RNGBenchmark.measureTangleR avgt 5 2.963 ± 0.009 ns/op * RNGBenchmark.measureThrust avgt 5 2.508 ± 0.024 ns/op * RNGBenchmark.measureThrustAlt avgt 5 2.516 ± 0.012 ns/op * RNGBenchmark.measureThrustAlt32 avgt 5 4.363 ± 0.009 ns/op * RNGBenchmark.measureThrustAlt32Int avgt 5 2.792 ± 0.009 ns/op * RNGBenchmark.measureThrustAlt32IntR avgt 5 3.151 ± 0.020 ns/op * RNGBenchmark.measureThrustAlt32R avgt 5 5.111 ± 0.150 ns/op * RNGBenchmark.measureThrustAltInt avgt 5 2.522 ± 0.006 ns/op * RNGBenchmark.measureThrustAltIntR avgt 5 2.811 ± 0.009 ns/op * RNGBenchmark.measureThrustAltR avgt 5 2.823 ± 0.066 ns/op * RNGBenchmark.measureThrustInt avgt 5 2.511 ± 0.010 ns/op * RNGBenchmark.measureThrustIntR avgt 5 2.790 ± 0.038 ns/op * RNGBenchmark.measureThrustR avgt 5 2.791 ± 0.011 ns/op * RNGBenchmark.measureThunder avgt 5 2.653 ± 0.035 ns/op * RNGBenchmark.measureThunderInt avgt 5 2.761 ± 0.022 ns/op * RNGBenchmark.measureThunderIntR avgt 5 3.023 ± 0.015 ns/op * RNGBenchmark.measureThunderR avgt 5 2.984 ± 0.015 ns/op * RNGBenchmark.measureVortex avgt 5 2.928 ± 0.003 ns/op * RNGBenchmark.measureVortexInt avgt 5 3.026 ± 0.028 ns/op * RNGBenchmark.measureVortexIntR avgt 5 3.401 ± 0.027 ns/op * RNGBenchmark.measureVortexR avgt 5 3.342 ± 0.104 ns/op * RNGBenchmark.measureXoRo avgt 5 2.763 ± 0.011 ns/op * RNGBenchmark.measureXoRo32 avgt 5 3.785 ± 0.007 ns/op * RNGBenchmark.measureXoRo32Int avgt 5 2.770 ± 0.030 ns/op * RNGBenchmark.measureXoRo32IntR avgt 5 3.114 ± 0.050 ns/op * RNGBenchmark.measureXoRo32R avgt 5 4.409 ± 0.012 ns/op * RNGBenchmark.measureXoRoInt avgt 5 2.881 ± 0.025 ns/op * RNGBenchmark.measureXoRoIntR avgt 5 3.129 ± 0.026 ns/op * RNGBenchmark.measureXoRoR avgt 5 2.991 ± 0.007 ns/op * RNGBenchmark.measureXoshiroAra32 avgt 5 4.929 ± 0.190 ns/op * RNGBenchmark.measureXoshiroAra32Int avgt 5 3.257 ± 0.024 ns/op * RNGBenchmark.measureXoshiroAra32IntR avgt 5 3.675 ± 0.024 ns/op * RNGBenchmark.measureXoshiroAra32R avgt 5 5.349 ± 0.062 ns/op * RNGBenchmark.measureXoshiroStarPhi32 avgt 5 5.117 ± 0.021 ns/op * RNGBenchmark.measureXoshiroStarPhi32Int avgt 5 3.381 ± 0.009 ns/op * RNGBenchmark.measureXoshiroStarPhi32IntR avgt 5 3.767 ± 0.012 ns/op * RNGBenchmark.measureXoshiroStarPhi32R avgt 5 5.477 ± 0.022 ns/op * RNGBenchmark.measureXoshiroStarStar32 avgt 5 5.257 ± 0.070 ns/op * RNGBenchmark.measureXoshiroStarStar32Int avgt 5 3.466 ± 0.046 ns/op * RNGBenchmark.measureXoshiroStarStar32IntR avgt 5 3.836 ± 0.096 ns/op * RNGBenchmark.measureXoshiroStarStar32R avgt 5 5.747 ± 0.016 ns/op * RNGBenchmark.measureXoshiroXara32 avgt 5 5.080 ± 0.014 ns/op * RNGBenchmark.measureXoshiroXara32Int avgt 5 3.319 ± 0.011 ns/op * RNGBenchmark.measureXoshiroXara32IntR avgt 5 3.748 ± 0.064 ns/op * RNGBenchmark.measureXoshiroXara32R avgt 5 5.512 ± 0.149 ns/op * RNGBenchmark.measureZag32 avgt 5 6.304 ± 0.107 ns/op * RNGBenchmark.measureZag32Int avgt 5 3.366 ± 0.011 ns/op * RNGBenchmark.measureZag32IntR avgt 5 3.875 ± 0.107 ns/op * RNGBenchmark.measureZag32R avgt 5 6.411 ± 0.103 ns/op * RNGBenchmark.measureZig32 avgt 5 5.908 ± 0.084 ns/op * RNGBenchmark.measureZig32Int avgt 5 3.498 ± 0.043 ns/op * RNGBenchmark.measureZig32IntR avgt 5 4.031 ± 0.063 ns/op * RNGBenchmark.measureZig32R avgt 5 6.505 ± 0.056 ns/op * RNGBenchmark.measureZog32 avgt 5 5.206 ± 0.076 ns/op * RNGBenchmark.measureZog32Int avgt 5 3.216 ± 0.018 ns/op * RNGBenchmark.measureZog32IntR avgt 5 3.693 ± 0.035 ns/op * RNGBenchmark.measureZog32R avgt 5 5.770 ± 0.020 ns/op * </pre> * <br> * The fastest generator depends on your target platform, but on a desktop or laptop using an OpenJDK-based Java * installation, Jab63RNG and MiniMover64RNG are virtually tied for first place. Neither is at all equidistributed; for * generators that are capable of producing all outputs with equal likelihood, LinnormRNG, MizuchiRNG, and QuixoticRNG * are all about the same, with DiverRNG probably a little faster (but it was added after this benchmark was run, so its * results wouldn't be from the same circumstances). DiverRNG and possibly QuixoticRNG are likely to have higher quality * than LinnormRNG and MizuchiRNG, since the last two fail one PractRand test after 16TB while at least DiverRNG does * not have that issue. * <br> * GWT-compatible generators need to work with an "int" type that isn't equivalent to Java's "int" and is closer to a * Java "double" that gets cast to an int when bitwise operations are used on it. This JS int is about 10x-20x faster to * do math operations on than GWT's "long" type, which is emulated using three JS numbers internally, but you need to be * vigilant about the possibility of exceeding the limits of Integer.MAX_VALUE and Integer.MIN_VALUE, since math won't * overflow, and about precision loss if you do exceed those limits severely, since JS numbers are floating-point. So, * you can't safely multiply by too large of an int (I limit my multipliers to 20 bits), you need to follow up normal * math with bitwise math to bring any overflowing numbers back to the 32-bit range, and you should avoid longs and math * on them whenever possible. The GWT-safe generators are in the bulk results above; the ones that are GWT-safe are (an * asterisk marks a generator that doesn't pass many statistical tests): Churro32RNG, Dizzy32RNG, Lathe32RNG, * Lobster32RNG, Molerat32RNG, Mover32RNG, Oriole32RNG, SeaSlater32RNG*, Starfish32RNG, XoRo32RNG*, XoshiroAra32RNG, * XoshiroStarPhi32RNG, XoshiroStarStar32RNG, XoshiroXara32RNG, Zag32RNG, Zig32RNG, and Zog32RNG. GWTRNG is a special * case because it uses Starfish32RNG's algorithm verbatim, but implements IRNG instead of just RandomnessSource and so * has some extra optimizations it can use when producing 32-bit values. Starfish32RNG and all of the Xoshiro-based * generators are probably the best choices for 32-bit generators, with Starfish having a smaller and possibly more * manageable state size, and Xoshiro variants having much longer periods. * <br> * You can benchmark most of these in GWT for yourself on * <a href="https://tommyettinger.github.io/SquidLib-Demos/bench/rng/">this SquidLib-Demos page</a>; comparing "runs" * where higher is better is a good way of estimating how fast a generator is. Each "run" is 10,000 generated numbers. * Lathe32RNG is by far the best on speed if you consider both desktop and GWT, but it can't generate all possible * "long" values, while XoshiroAra can generate all possible "long" values with equal frequency, and even all possible * pairs of "long" values (less one). XoshiroAra is also surprisingly fast compared to similar Xoshiro-based generators, * especially since it does just as well in PractRand testing. The equidistribution comment at the end of each line * refers to that specific method; calling {@code myOriole32RNG.next(32)} repeatedly will produce all ints with equal * frequency over the full period of that generator, ((2 to the 64) - 1) * (2 to the 32), but the same is not true of * calling {@code myOriole32RNG.nextLong()}, which would produce some longs more frequently than others (and probably * would not produce some longs at all). The Xoshiro-based generators have the best period and equidistribution * qualities, with XoshiroAra having the best performance (all of them pass 32TB of PractRand). The Xoroshiro-based * generators tend to be faster, but only Starfish has better equidistribution of the bunch (it can produce all longs * except one, while Lathe can't and Oriole won't with equal frequency). Starfish seems to have comparable quality and * speed relative to Oriole (excellent and pretty good, respectively), but improves on its distribution at the expense * of its period, and has a smaller state. */ @State(Scope.Thread) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Fork(1) @Warmup(iterations = 5, time = 5) @Measurement(iterations = 5, time = 5) public class RNGBenchmark { private long state = 9000, stream = 9001, oddState = 9999L; // public long doThunder() // { // ThunderRNG rng = new ThunderRNG(seed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunder() throws InterruptedException { // seed = 9000; // doThunder(); // } // // public int doThunderInt() // { // ThunderRNG rng = new ThunderRNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunderInt() throws InterruptedException { // iseed = 9000; // doThunderInt(); // } // public long doThunderR() // { // RNG rng = new RNG(new ThunderRNG(seed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunderR() throws InterruptedException { // seed = 9000; // doThunderR(); // } // // public int doThunderIntR() // { // RNG rng = new RNG(new ThunderRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunderIntR() throws InterruptedException { // iseed = 9000; // doThunderIntR(); // } private XoRoRNG XoRo = new XoRoRNG(9999L); private RNG XoRoR = new RNG(XoRo); @Benchmark public long measureXoRo() { return XoRo.nextLong(); } @Benchmark public int measureXoRoInt() { return XoRo.next(32); } @Benchmark public long measureXoRoR() { return XoRoR.nextLong(); } @Benchmark public int measureXoRoIntR() { return XoRoR.nextInt(); } private Lathe64RNG Lathe64 = new Lathe64RNG(9999L); private RNG Lathe64R = new RNG(Lathe64); @Benchmark public long measureLathe64() { return Lathe64.nextLong(); } @Benchmark public int measureLathe64Int() { return Lathe64.next(32); } @Benchmark public long measureLathe64R() { return Lathe64R.nextLong(); } @Benchmark public int measureLathe64IntR() { return Lathe64R.nextInt(); } /* public long doXar() { XarRNG rng = new XarRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXar() throws InterruptedException { seed = 9000; doXar(); } public int doXarInt() { XarRNG rng = new XarRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXarInt() throws InterruptedException { iseed = 9000; doXarInt(); } public long doXarR() { RNG rng = new RNG(new XarRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXarR() throws InterruptedException { seed = 9000; doXarR(); } public int doXarIntR() { RNG rng = new RNG(new XarRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXarIntR() throws InterruptedException { iseed = 9000; doXarIntR(); } */ private LongPeriodRNG LongPeriod = new LongPeriodRNG(9999L); private RNG LongPeriodR = new RNG(LongPeriod); @Benchmark public long measureLongPeriod() { return LongPeriod.nextLong(); } @Benchmark public int measureLongPeriodInt() { return LongPeriod.next(32); } @Benchmark public long measureLongPeriodR() { return LongPeriodR.nextLong(); } @Benchmark public int measureLongPeriodIntR() { return LongPeriodR.nextInt(); } private LightRNG Light = new LightRNG(9999L); private RNG LightR = new RNG(Light); @Benchmark public long measureLight() { return Light.nextLong(); } @Benchmark public int measureLightInt() { return Light.next(32); } @Benchmark public long measureLightR() { return LightR.nextLong(); } @Benchmark public int measureLightIntR() { return LightR.nextInt(); } private PaperweightRNG Paperweight = new PaperweightRNG(9999L); private RNG PaperweightR = new RNG(Paperweight); @Benchmark public long measurePaperweight() { return Paperweight.nextLong(); } @Benchmark public int measurePaperweightInt() { return Paperweight.next(32); } @Benchmark public long measurePaperweightR() { return PaperweightR.nextLong(); } @Benchmark public int measurePaperweightIntR() { return PaperweightR.nextInt(); } private FlapRNG Flap = new FlapRNG(9999L); private RNG FlapR = new RNG(Flap); @Benchmark public long measureFlap() { return Flap.nextLong(); } @Benchmark public int measureFlapInt() { return Flap.next(32); } @Benchmark public long measureFlapR() { return FlapR.nextLong(); } @Benchmark public int measureFlapIntR() { return FlapR.nextInt(); } private LapRNG Lap = new LapRNG(9999L); private RNG LapR = new RNG(Lap); @Benchmark public long measureLap() { return Lap.nextLong(); } @Benchmark public int measureLapInt() { return Lap.next(32); } @Benchmark public long measureLapR() { return LapR.nextLong(); } private ThunderRNG Thunder = new ThunderRNG(9999L); private RNG ThunderR = new RNG(Thunder); @Benchmark public long measureThunder() { return Thunder.nextLong(); } @Benchmark public int measureThunderInt() { return Thunder.next(32); } @Benchmark public long measureThunderR() { return ThunderR.nextLong(); } @Benchmark public int measureThunderIntR() { return ThunderR.nextInt(); } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public int measureLapIntR() { return LapR.nextInt(); } private SeaSlater64RNG SeaSlater64 = new SeaSlater64RNG(9999L); private RNG SeaSlater64R = new RNG(SeaSlater64); @Benchmark public long measureSeaSlater64() { return SeaSlater64.nextLong(); } @Benchmark public int measureSeaSlater64Int() { return SeaSlater64.next(32); } @Benchmark public long measureSeaSlater64R() { return SeaSlater64R.nextLong(); } @Benchmark public int measureSeaSlater64IntR() { return SeaSlater64R.nextInt(); } private ThrustRNG Thrust = new ThrustRNG(9999L); private RNG ThrustR = new RNG(Thrust); @Benchmark public long measureThrust() { return Thrust.nextLong(); } @Benchmark public int measureThrustInt() { return Thrust.next(32); } @Benchmark public long measureThrustR() { return ThrustR.nextLong(); } @Benchmark public int measureThrustIntR() { return ThrustR.nextInt(); } //@Benchmark public long measureInlineThrust() { long z = (state += 0x9E3779B97F4A7C15L); z = (z ^ z >>> 26) * 0x2545F4914F6CDD1DL; return z ^ z >>> 28; } /* public long doThrust3() { ThrustAltRNG rng = new ThrustAltRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong3(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust3() throws InterruptedException { seed = 9000; doThrust3(); } public int doThrust3Int() { ThrustAltRNG rng = new ThrustAltRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next3(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust3Int() throws InterruptedException { iseed = 9000; doThrust3Int(); } public long doThrust2() { ThrustAltRNG rng = new ThrustAltRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong2(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust2() throws InterruptedException { seed = 9000; doThrust2(); } public int doThrust2Int() { ThrustAltRNG rng = new ThrustAltRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next2(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust2Int() throws InterruptedException { iseed = 9000; doThrust2Int(); } public long doThrust4() { ThrustAltRNG rng = new ThrustAltRNG(seed|1L); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong4(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureAltThrust4() throws InterruptedException { seed = 9000; doThrust4(); } public int doThrust4Int() { ThrustAltRNG rng = new ThrustAltRNG(iseed|1L); for (int i = 0; i < 1000000007; i++) { iseed += rng.next4(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureAltThrust4Int() throws InterruptedException { iseed = 9000; doThrust4Int(); } */ @Benchmark public long measureAltThrustDetermine() { return ThrustAltRNG.determine(state++); } // // // @Benchmark // public long measureDervishDetermine() { // return DervishRNG.determine(state++); // } // @Benchmark public long measureLightDetermine() { return LightRNG.determine(state++); } @Benchmark public long measureLinnormDetermine() { return LinnormRNG.determine(state++); } @Benchmark public long measureDirkDetermine() { return DirkRNG.determine(state++); } // @Benchmark // public long measureMotorDetermine() { // return MotorRNG.determine(state++); // } // // //@Benchmark // public long measureVortexDetermine() { // return VortexRNG.determine(state++); // } // // //@Benchmark // public long measureVortexDetermineBare() { // return VortexRNG.determineBare(state += 0x6C8E9CF570932BD5L); // } // // @Benchmark // public long measureAltThrustRandomize() { // return ThrustAltRNG.randomize(state += 0x6C8E9CF570932BD5L); // } // // @Benchmark // public long measureLinnormRandomize() { return LinnormRNG.randomize(state += 0x632BE59BD9B4E019L); } private ThrustAltRNG ThrustAlt = new ThrustAltRNG(9999L); private RNG ThrustAltR = new RNG(ThrustAlt); @Benchmark public long measureThrustAlt() { return ThrustAlt.nextLong(); } @Benchmark public int measureThrustAltInt() { return ThrustAlt.next(32); } @Benchmark public long measureThrustAltR() { return ThrustAltR.nextLong(); } @Benchmark public int measureThrustAltIntR() { return ThrustAltR.nextInt(); } // @Benchmark // public long measureThrustAltInline() // { // final long s = (state += 0x6C8E9CF570932BD5L); // final long z = (s ^ (s >>> 25)) * (s | 0xA529L); // return z ^ (z >>> 22); // } // @Benchmark // public long measureInlineThrustAltOther() // { // long z = (state += 0x6C8E9CF570932BD5L); // z = (z ^ (z >>> 25)) * (z | 0xA529L); // return z ^ (z >>> 22); // } private Jab63RNG Jab63 = new Jab63RNG(9999L); private RNG Jab63R = new RNG(Jab63); @Benchmark public long measureJab63() { return Jab63.nextLong(); } @Benchmark public int measureJab63Int() { return Jab63.next(32); } @Benchmark public long measureJab63R() { return Jab63R.nextLong(); } @Benchmark public int measureJab63IntR() { return Jab63R.nextInt(); } // @Benchmark // public long measureInlineJab63() // { // long z = (oddState += 0x3C6EF372FE94F82AL); // z *= (z ^ (z >>> 21)); // return z - (z >>> 28); // } // // // @Benchmark // public long measureInlineVortex() // { // long z = (state += 0x6C8E9CF970932BD5L); // z = (z ^ z >>> 25) * 0x2545F4914F6CDD1DL; // z ^= ((z << 19) | (z >>> 45)) ^ ((z << 53) | (z >>> 11)); // return z ^ (z >>> 25); // } private VortexRNG Vortex = new VortexRNG(9999L); private RNG VortexR = new RNG(Vortex); @Benchmark public long measureVortex() { return Vortex.nextLong(); } @Benchmark public int measureVortexInt() { return Vortex.next(32); } @Benchmark public long measureVortexR() { return VortexR.nextLong(); } @Benchmark public int measureVortexIntR() { return VortexR.nextInt(); } private BasicRandom64 BasicRandom64 = new BasicRandom64(1L); private RNG BasicRandom64R = new RNG(BasicRandom64); @Benchmark public long measureBasicRandom64() { return BasicRandom64.nextLong(); } @Benchmark public int measureBasicRandom64Int() { return BasicRandom64.next(32); } @Benchmark public long measureBasicRandom64R() { return BasicRandom64R.nextLong(); } @Benchmark public int measureBasicRandom64IntR() { return BasicRandom64R.nextInt(); } private BasicRandom32 BasicRandom32 = new BasicRandom32(1); private RNG BasicRandom32R = new RNG(BasicRandom32); @Benchmark public long measureBasicRandom32() { return BasicRandom32.nextLong(); } @Benchmark public int measureBasicRandom32Int() { return BasicRandom32.next(32); } @Benchmark public long measureBasicRandom32R() { return BasicRandom32R.nextLong(); } @Benchmark public int measureBasicRandom32IntR() { return BasicRandom32R.nextInt(); } private MotorRNG Motor = new MotorRNG(9999L); private RNG MotorR = new RNG(Motor); @Benchmark public long measureMotor() { return Motor.nextLong(); } @Benchmark public int measureMotorInt() { return Motor.next(32); } @Benchmark public long measureMotorR() { return MotorR.nextLong(); } @Benchmark public int measureMotorIntR() { return MotorR.nextInt(); } private MeshRNG Mesh = new MeshRNG(9999L); private RNG MeshR = new RNG(Mesh); @Benchmark public long measureMesh() { return Mesh.nextLong(); } @Benchmark public int measureMeshInt() { return Mesh.next(32); } @Benchmark public long measureMeshR() { return MeshR.nextLong(); } @Benchmark public int measureMeshIntR() { return MeshR.nextInt(); } private SpiralRNG Spiral = new SpiralRNG(9999L); private RNG SpiralR = new RNG(Spiral); @Benchmark public long measureSpiral() { return Spiral.nextLong(); } @Benchmark public int measureSpiralInt() { return Spiral.next(32); } @Benchmark public long measureSpiralR() { return SpiralR.nextLong(); } @Benchmark public int measureSpiralIntR() { return SpiralR.nextInt(); } private SpiralRNG spiralA = new SpiralRNG(9999L, 1337L), spiralB = new SpiralRNG(9999L, 1337L), spiralC = new SpiralRNG(9999L, 1337L), spiralD = new SpiralRNG(9999L, 1337L), spiralE = new SpiralRNG(9999L, 1337L), spiralF = new SpiralRNG(9999L, 1337L), spiralG = new SpiralRNG(9999L, 1337L), spiralH = new SpiralRNG(9999L, 1337L), spiralI = new SpiralRNG(9999L, 1337L); @Benchmark public long measureSpiralA() { return spiralA.nextLongOld(); } @Benchmark public long measureSpiralB() { return spiralB.nextLongAlt(); } @Benchmark public long measureSpiralC() { return spiralC.nextLongNew(); } @Benchmark public long measureSpiralD() { return spiralD.nextLongAgain(); } @Benchmark public long measureSpiralE() { return spiralE.nextLongAgain3(); } @Benchmark public long measureSpiralF() { return spiralF.nextLongAgain4(); } @Benchmark public long measureSpiralG() { return spiralG.nextLongAgain5(); } @Benchmark public long measureSpiralH() { return spiralH.nextLongAgain6(); } @Benchmark public long measureSpiralI() { return spiralI.nextLongAgain7(); } private OrbitRNG Orbit = new OrbitRNG(9999L, 1337L); private RNG OrbitR = new RNG(Orbit); @Benchmark public long measureOrbit() { return Orbit.nextLong(); } @Benchmark public int measureOrbitInt() { return Orbit.next(32); } @Benchmark public long measureOrbitR() { return OrbitR.nextLong(); } @Benchmark public int measureOrbitIntR() { return OrbitR.nextInt(); } private TangleRNG Tangle = new TangleRNG(9999L, 1337L); private RNG TangleR = new RNG(Tangle); @Benchmark public long measureTangle() { return Tangle.nextLong(); } @Benchmark public int measureTangleInt() { return Tangle.next(32); } @Benchmark public long measureTangleR() { return TangleR.nextLong(); } @Benchmark public int measureTangleIntR() { return TangleR.nextInt(); } private OrbitRNG OrbitA = new OrbitRNG(9999L, 1337L), OrbitB = new OrbitRNG(9999L, 1337L), OrbitC = new OrbitRNG(9999L, 1337L), OrbitD = new OrbitRNG(9999L, 1337L), OrbitE = new OrbitRNG(9999L, 1337L), OrbitF = new OrbitRNG(9999L, 1337L), OrbitG = new OrbitRNG(9999L, 1337L), OrbitH = new OrbitRNG(9999L, 1337L), OrbitI = new OrbitRNG(9999L, 1337L), OrbitJ = new OrbitRNG(9999L, 1337L), OrbitK = new OrbitRNG(9999L, 1337L), OrbitL = new OrbitRNG(9999L, 1337L), OrbitM = new OrbitRNG(9999L, 1337L), OrbitN = new OrbitRNG(9999L, 1337L), OrbitO = new OrbitRNG(9999L, 1337L); @Benchmark public long measureOrbitA() { return OrbitA.nextLong1(); } @Benchmark public long measureOrbitB() { return OrbitB.nextLong2(); } @Benchmark public long measureOrbitC() { return OrbitC.nextLong3(); } @Benchmark public long measureOrbitD() { return OrbitD.nextLong4(); } @Benchmark public long measureOrbitE() { return OrbitE.nextLong5(); } @Benchmark public long measureOrbitF() { return OrbitF.nextLong6(); } @Benchmark public long measureOrbitG() { return OrbitG.nextLong7(); } @Benchmark public long measureOrbitH() { return OrbitH.nextLong8(); } @Benchmark public long measureOrbitI() { return OrbitI.nextLong9(); } @Benchmark public long measureOrbitJ() { return OrbitJ.nextLong10(); } @Benchmark public long measureOrbitK() { return OrbitK.nextLong11(); } @Benchmark public long measureOrbitL() { return OrbitL.nextLong12(); } @Benchmark public long measureOrbitM() { return OrbitM.nextLong13(); } @Benchmark public long measureOrbitN() { return OrbitN.nextLong14(); } @Benchmark public long measureOrbitO() { return OrbitO.nextLong15(); } private TangleRNG TangleA = new TangleRNG(9999L, 1337L), TangleB = new TangleRNG(9999L, 1337L), TangleC = new TangleRNG(9999L, 1337L), TangleD = new TangleRNG(9999L, 1337L); @Benchmark public long measureTangleA() { return TangleA.nextLong1(); } @Benchmark public long measureTangleB() { return TangleB.nextLong2(); } @Benchmark public long measureTangleC() { return TangleC.nextLong3(); } @Benchmark public long measureTangleD() { return TangleD.nextLong4(); } private Mover32RNG Mover32 = new Mover32RNG(0); private RNG Mover32R = new RNG(Mover32); @Benchmark public long measureMover32() { return Mover32.nextLong(); } @Benchmark public int measureMover32Int() { return Mover32.next(32); } @Benchmark public long measureMover32R() { return Mover32R.nextLong(); } @Benchmark public int measureMover32IntR() { return Mover32R.nextInt(); } // private Mover32RNG Mover32A = new Mover32RNG(0); // @Benchmark // public long measureMover32A() // { // return Mover32A.nextIntA(); // } // // private Mover32RNG Mover32B = new Mover32RNG(0); // @Benchmark // public long measureMover32B() // { // return Mover32B.nextIntB(); // } // private Mover32RNG Mover32C = new Mover32RNG(0); // @Benchmark // public long measureMover32C() // { // return Mover32C.nextIntC(); // } private Mover64RNG Mover64 = new Mover64RNG(0); private RNG Mover64R = new RNG(Mover64); @Benchmark public long measureMover64() { return Mover64.nextLong(); } @Benchmark public int measureMover64Int() { return Mover64.next(32); } @Benchmark public long measureMover64R() { return Mover64R.nextLong(); } @Benchmark public int measureMover64IntR() { return Mover64R.nextInt(); } private Molerat32RNG Molerat32 = new Molerat32RNG(0); private RNG Molerat32R = new RNG(Molerat32); @Benchmark public long measureMolerat32() { return Molerat32.nextLong(); } @Benchmark public int measureMolerat32Int() { return Molerat32.next(32); } @Benchmark public long measureMolerat32R() { return Molerat32R.nextLong(); } @Benchmark public int measureMolerat32IntR() { return Molerat32R.nextInt(); } private MiniMover64RNG MiniMover64 = new MiniMover64RNG(0); private RNG MiniMover64R = new RNG(MiniMover64); @Benchmark public long measureMiniMover64() { return MiniMover64.nextLong(); } @Benchmark public int measureMiniMover64Int() { return MiniMover64.next(32); } @Benchmark public long measureMiniMover64R() { return MiniMover64R.nextLong(); } @Benchmark public int measureMiniMover64IntR() { return MiniMover64R.nextInt(); } private SFC64RNG SFC64 = new SFC64RNG(9999L); private RNG SFC64R = new RNG(SFC64); @Benchmark public long measureSFC64() { return SFC64.nextLong(); } @Benchmark public int measureSFC64Int() { return SFC64.next(32); } @Benchmark public long measureSFC64R() { return SFC64R.nextLong(); } @Benchmark public int measureSFC64IntR() { return SFC64R.nextInt(); } private Overdrive64RNG Overdrive64 = new Overdrive64RNG(0); private RNG Overdrive64R = new RNG(Overdrive64); @Benchmark public long measureOverdrive64() { return Overdrive64.nextLong(); } @Benchmark public int measureOverdrive64Int() { return Overdrive64.next(32); } @Benchmark public long measureOverdrive64R() { return Overdrive64R.nextLong(); } @Benchmark public int measureOverdrive64IntR() { return Overdrive64R.nextInt(); } private MoverCounter64RNG MoverCounter64 = new MoverCounter64RNG(9999L); private RNG MoverCounter64R = new RNG(MoverCounter64); @Benchmark public long measureMoverCounter64() { return MoverCounter64.nextLong(); } @Benchmark public int measureMoverCounter64Int() { return MoverCounter64.next(32); } @Benchmark public long measureMoverCounter64R() { return MoverCounter64R.nextLong(); } @Benchmark public int measureMoverCounter64IntR() { return MoverCounter64R.nextInt(); } private DirkRNG Dirk = new DirkRNG(9999L); private RNG DirkR = new RNG(Dirk); @Benchmark public long measureDirk() { return Dirk.nextLong(); } @Benchmark public int measureDirkInt() { return Dirk.next(32); } @Benchmark public long measureDirkR() { return DirkR.nextLong(); } @Benchmark public int measureDirkIntR() { return DirkR.nextInt(); } // private Overdrive64RNG Overdrive1 = new Overdrive64RNG(0); // private Overdrive64RNG Overdrive2 = new Overdrive64RNG(0); // private Overdrive64RNG Overdrive3 = new Overdrive64RNG(0); // private Overdrive64RNG Overdrive4 = new Overdrive64RNG(0); // // @Benchmark // public long measureOverdrive1() // { // return Overdrive1.nextLong1(); // } // @Benchmark // public long measureOverdrive2() // { // return Overdrive2.nextLong2(); // } // @Benchmark // public long measureOverdrive3() // { // return Overdrive3.nextLong3(); // } // @Benchmark // public long measureOverdrive4() // { // return Overdrive4.nextLong4(); // } // private Thrust32RNG Thrust32 = new Thrust32RNG(9999); // private RNG Thrust32R = new RNG(Thrust32); // // @Benchmark // public long measureThrust32() // { // return Thrust32.nextLong(); // } // // @Benchmark // public int measureThrust32Int() // { // return Thrust32.next(32); // } // @Benchmark // public long measureThrust32R() // { // return Thrust32R.nextLong(); // } // // @Benchmark // public int measureThrust32IntR() // { // return Thrust32R.nextInt(); // } // // private ThrustAlt32RNG ThrustAlt32 = new ThrustAlt32RNG(9999); private RNG ThrustAlt32R = new RNG(ThrustAlt32); @Benchmark public long measureThrustAlt32() { return ThrustAlt32.nextLong(); } @Benchmark public int measureThrustAlt32Int() { return ThrustAlt32.next(32); } @Benchmark public long measureThrustAlt32R() { return ThrustAlt32R.nextLong(); } @Benchmark public int measureThrustAlt32IntR() { return ThrustAlt32R.nextInt(); } private Light32RNG Light32 = new Light32RNG(9999); private RNG Light32R = new RNG(Light32); @Benchmark public long measureLight32() { return Light32.nextLong(); } @Benchmark public int measureLight32Int() { return Light32.next(32); } @Benchmark public long measureLight32R() { return Light32R.nextLong(); } @Benchmark public int measureLight32IntR() { return Light32R.nextInt(); } private Zig32RNG Zig32 = new Zig32RNG(9999L); private RNG Zig32R = new RNG(Zig32); @Benchmark public long measureZig32() { return Zig32.nextLong(); } @Benchmark public int measureZig32Int() { return Zig32.next(32); } @Benchmark public long measureZig32R() { return Zig32R.nextLong(); } @Benchmark public int measureZig32IntR() { return Zig32R.nextInt(); } private Zag32RNG Zag32 = new Zag32RNG(9999L); private RNG Zag32R = new RNG(Zag32); @Benchmark public long measureZag32() { return Zag32.nextLong(); } @Benchmark public int measureZag32Int() { return Zag32.next(32); } @Benchmark public long measureZag32R() { return Zag32R.nextLong(); } @Benchmark public int measureZag32IntR() { return Zag32R.nextInt(); } private Zog32RNG Zog32 = new Zog32RNG(9999L); private RNG Zog32R = new RNG(Zog32); @Benchmark public long measureZog32() { return Zog32.nextLong(); } @Benchmark public int measureZog32Int() { return Zog32.next(32); } @Benchmark public long measureZog32R() { return Zog32R.nextLong(); } @Benchmark public int measureZog32IntR() { return Zog32R.nextInt(); } private XoRo32RNG XoRo32 = new XoRo32RNG(9999L); private RNG XoRo32R = new RNG(XoRo32); @Benchmark public long measureXoRo32() { return XoRo32.nextLong(); } @Benchmark public int measureXoRo32Int() { return XoRo32.next(32); } @Benchmark public long measureXoRo32R() { return XoRo32R.nextLong(); } @Benchmark public int measureXoRo32IntR() { return XoRo32R.nextInt(); } private Oriole32RNG Oriole32 = new Oriole32RNG(9999, 999, 99); private RNG Oriole32R = new RNG(Oriole32); @Benchmark public long measureOriole32() { return Oriole32.nextLong(); } @Benchmark public int measureOriole32Int() { return Oriole32.next(32); } @Benchmark public long measureOriole32R() { return Oriole32R.nextLong(); } @Benchmark public int measureOriole32IntR() { return Oriole32R.nextInt(); } private Lathe32RNG Lathe32 = new Lathe32RNG(9999, 999); private RNG Lathe32R = new RNG(Lathe32); @Benchmark public long measureLathe32() { return Lathe32.nextLong(); } @Benchmark public int measureLathe32Int() { return Lathe32.next(32); } @Benchmark public long measureLathe32R() { return Lathe32R.nextLong(); } @Benchmark public int measureLathe32IntR() { return Lathe32R.nextInt(); } private Starfish32RNG Starfish32 = new Starfish32RNG(9999, 999); private RNG Starfish32R = new RNG(Starfish32); @Benchmark public long measureStarfish32() { return Starfish32.nextLong(); } @Benchmark public int measureStarfish32Int() { return Starfish32.next(32); } @Benchmark public int measureStarfish32NextInt() { return Starfish32.nextInt(); } @Benchmark public long measureStarfish32R() { return Starfish32R.nextLong(); } @Benchmark public int measureStarfish32IntR() { return Starfish32R.nextInt(); } private GWTRNG GWT = new GWTRNG(9999, 999); @Benchmark public long measureGWT() { return GWT.nextLong(); } @Benchmark public int measureGWTInt() { return GWT.next(32); } @Benchmark public int measureGWTNextInt() { return GWT.nextInt(); } private Otter32RNG Otter32 = new Otter32RNG(9999, 999); private RNG Otter32R = new RNG(Otter32); @Benchmark public long measureOtter32() { return Otter32.nextLong(); } @Benchmark public int measureOtter32Int() { return Otter32.next(32); } @Benchmark public long measureOtter32R() { return Otter32R.nextLong(); } @Benchmark public int measureOtter32IntR() { return Otter32R.nextInt(); } private Lobster32RNG Lobster32 = new Lobster32RNG(9999, 999); private RNG Lobster32R = new RNG(Lobster32); @Benchmark public long measureLobster32() { return Lobster32.nextLong(); } @Benchmark public int measureLobster32Int() { return Lobster32.next(32); } @Benchmark public long measureLobster32R() { return Lobster32R.nextLong(); } @Benchmark public int measureLobster32IntR() { return Lobster32R.nextInt(); } private SeaSlater32RNG SeaSlater32 = new SeaSlater32RNG(9999, 999); private RNG SeaSlater32R = new RNG(SeaSlater32); @Benchmark public long measureSeaSlater32() { return SeaSlater32.nextLong(); } @Benchmark public int measureSeaSlater32Int() { return SeaSlater32.next(32); } @Benchmark public long measureSeaSlater32R() { return SeaSlater32R.nextLong(); } @Benchmark public int measureSeaSlater32IntR() { return SeaSlater32R.nextInt(); } private Churro32RNG Churro32 = new Churro32RNG(9999, 999, 99); private RNG Churro32R = new RNG(Churro32); @Benchmark public long measureChurro32() { return Churro32.nextLong(); } @Benchmark public int measureChurro32Int() { return Churro32.next(32); } @Benchmark public long measureChurro32R() { return Churro32R.nextLong(); } @Benchmark public int measureChurro32IntR() { return Churro32R.nextInt(); } private Dizzy32RNG Dizzy32 = new Dizzy32RNG(9999, 999, 99); private RNG Dizzy32R = new RNG(Dizzy32); @Benchmark public long measureDizzy32() { return Dizzy32.nextLong(); } @Benchmark public int measureDizzy32Int() { return Dizzy32.next(32); } @Benchmark public long measureDizzy32R() { return Dizzy32R.nextLong(); } @Benchmark public int measureDizzy32IntR() { return Dizzy32R.nextInt(); } @Benchmark public long measureDizzy32IntNative1() { return Dizzy32.nextInt(); } @Benchmark public long measureDizzy32IntNative2() { return Dizzy32.nextInt2(); } private XoshiroStarStar32RNG XoshiroStarStar32 = new XoshiroStarStar32RNG(9999); private RNG XoshiroStarStar32R = new RNG(XoshiroStarStar32); @Benchmark public long measureXoshiroStarStar32() { return XoshiroStarStar32.nextLong(); } @Benchmark public int measureXoshiroStarStar32Int() { return XoshiroStarStar32.next(32); } @Benchmark public long measureXoshiroStarStar32R() { return XoshiroStarStar32R.nextLong(); } @Benchmark public int measureXoshiroStarStar32IntR() { return XoshiroStarStar32R.nextInt(); } private XoshiroStarPhi32RNG XoshiroStarPhi32 = new XoshiroStarPhi32RNG(9999); private RNG XoshiroStarPhi32R = new RNG(XoshiroStarPhi32); @Benchmark public long measureXoshiroStarPhi32() { return XoshiroStarPhi32.nextLong(); } @Benchmark public int measureXoshiroStarPhi32Int() { return XoshiroStarPhi32.next(32); } @Benchmark public long measureXoshiroStarPhi32R() { return XoshiroStarPhi32R.nextLong(); } @Benchmark public int measureXoshiroStarPhi32IntR() { return XoshiroStarPhi32R.nextInt(); } private XoshiroXara32RNG XoshiroXara32 = new XoshiroXara32RNG(9999); private RNG XoshiroXara32R = new RNG(XoshiroXara32); @Benchmark public long measureXoshiroXara32() { return XoshiroXara32.nextLong(); } @Benchmark public int measureXoshiroXara32Int() { return XoshiroXara32.next(32); } @Benchmark public long measureXoshiroXara32R() { return XoshiroXara32R.nextLong(); } @Benchmark public int measureXoshiroXara32IntR() { return XoshiroXara32R.nextInt(); } private XoshiroAra32RNG XoshiroAra32 = new XoshiroAra32RNG(9999); private RNG XoshiroAra32R = new RNG(XoshiroAra32); @Benchmark public long measureXoshiroAra32() { return XoshiroAra32.nextLong(); } @Benchmark public int measureXoshiroAra32Int() { return XoshiroAra32.next(32); } @Benchmark public long measureXoshiroAra32R() { return XoshiroAra32R.nextLong(); } @Benchmark public int measureXoshiroAra32IntR() { return XoshiroAra32R.nextInt(); } private DervishRNG Dervish = new DervishRNG(9999L); private RNG DervishR = new RNG(Dervish); @Benchmark public long measureDervish() { return Dervish.nextLong(); } @Benchmark public int measureDervishInt() { return Dervish.next(32); } @Benchmark public long measureDervishR() { return DervishR.nextLong(); } @Benchmark public int measureDervishIntR() { return DervishR.nextInt(); } private LinnormRNG Linnorm = new LinnormRNG(9999L); private RNG LinnormR = new RNG(Linnorm); @Benchmark public long measureLinnorm() { return Linnorm.nextLong(); } @Benchmark public int measureLinnormInt() { return Linnorm.next(32); } @Benchmark public long measureLinnormR() { return LinnormR.nextLong(); } @Benchmark public int measureLinnormIntR() { return LinnormR.nextInt(); } private MizuchiRNG Mizuchi = new MizuchiRNG(9999L); private RNG MizuchiR = new RNG(Mizuchi); @Benchmark public long measureMizuchi() { return Mizuchi.nextLong(); } @Benchmark public int measureMizuchiInt() { return Mizuchi.next(32); } @Benchmark public long measureMizuchiR() { return MizuchiR.nextLong(); } @Benchmark public int measureMizuchiIntR() { return MizuchiR.nextInt(); } private QuixoticRNG Quixotic = new QuixoticRNG(9999L); private RNG QuixoticR = new RNG(Quixotic); @Benchmark public long measureQuixotic() { return Quixotic.nextLong(); } @Benchmark public int measureQuixoticInt() { return Quixotic.next(32); } @Benchmark public long measureQuixoticR() { return QuixoticR.nextLong(); } @Benchmark public int measureQuixoticIntR() { return QuixoticR.nextInt(); } private IsaacRNG Isaac = new IsaacRNG(9999L); private RNG IsaacR = new RNG(Isaac); @Benchmark public long measureIsaac() { return Isaac.nextLong(); } @Benchmark public long measureIsaacInt() { return Isaac.next(32); } @Benchmark public long measureIsaacR() { return IsaacR.nextLong(); } @Benchmark public long measureIsaacIntR() { return IsaacR.nextInt(); } private Isaac32RNG Isaac32 = new Isaac32RNG(9999L); private RNG Isaac32R = new RNG(Isaac32); @Benchmark public long measureIsaac32() { return Isaac32.nextLong(); } @Benchmark public long measureIsaac32Int() { return Isaac32.next(32); } @Benchmark public long measureIsaac32R() { return Isaac32R.nextLong(); } @Benchmark public long measureIsaac32IntR() { return Isaac32R.nextInt(); } /* public long doJet() { JetRNG rng = new JetRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJet() { seed = 9000; doJet(); } public int doJetInt() { JetRNG rng = new JetRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJetInt() { iseed = 9000; doJetInt(); } public long doJetR() { RNG rng = new RNG(new JetRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJetR() { seed = 9000; doJetR(); } public int doJetIntR() { RNG rng = new RNG(new JetRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJetIntR() { iseed = 9000; doJetIntR(); } public long doLunge32() { Lunge32RNG rng = new Lunge32RNG(iseed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32() { seed = 9000; doLunge32(); } public int doLunge32Int() { Lunge32RNG rng = new Lunge32RNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32Int() { iseed = 9000; doLunge32Int(); } public long doLunge32R() { RNG rng = new RNG(new Lunge32RNG(iseed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32R() { seed = 9000; doLunge32R(); } public int doLunge32IntR() { RNG rng = new RNG(new Lunge32RNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32IntR() { iseed = 9000; doLunge32IntR(); } @Benchmark @Warmup(iterations = 10) @Measurement(iterations = 8) @Fork(1) public void a________measureThrustAltDetermine() { seed = 9000; long state = 9000L; for (int i = 0; i < 1000000007; i++) { seed += ThrustAltRNG.determine(++state); } } // // Performs rather poorly, surprisingly. JIT needs method calls rather than inlined code, it looks like. // @Benchmark // @Warmup(iterations = 10) @Measurement(iterations = 8) @Fork(1) // public void a________measureDetermineBare() { // seed = 9000; // long running = seed, state = 9000L; // for (int i = 0; i < 1000000007; i++) { // seed += ((state = ((running += 0x6C8E9CF570932BD5L) ^ (state >>> 25)) * (state | 0xA529L)) ^ (state >>> 22)); // } // } @Benchmark @Warmup(iterations = 10) @Measurement(iterations = 8) @Fork(1) public void a________measureRandomness() { seed = 9000; ThrustAltRNG rng = new ThrustAltRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } } */ // public long doVortex() // { // VortexRNG rng = new VortexRNG(seed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortex() { // seed = 9000; // doVortex(); // } // // public int doVortexInt() // { // VortexRNG rng = new VortexRNG(iseed); // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortexInt() { // iseed = 9000; // doVortexInt(); // } // public long doVortexR() // { // RNG rng = new RNG(new VortexRNG(seed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortexR() { // seed = 9000; // doVortexR(); // } // // public int doVortexIntR() // { // RNG rng = new RNG(new VortexRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortexIntR() { // iseed = 9000; // doVortexIntR(); // } // public long doSquirrel() // { // SquirrelRNG rng = new SquirrelRNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrel() throws InterruptedException { // seed = 9000; // doSquirrel(); // } // // public int doSquirrelInt() // { // SquirrelRNG rng = new SquirrelRNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrelInt() throws InterruptedException { // iseed = 9000; // doSquirrelInt(); // } // // public long doSquirrelR() // { // RNG rng = new RNG(new SquirrelRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrelR() throws InterruptedException { // seed = 9000; // doSquirrelR(); // } // // public int doSquirrelIntR() // { // RNG rng = new RNG(new SquirrelRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrelIntR() throws InterruptedException { // iseed = 9000; // doSquirrelIntR(); // } // public long doRule90() // { // Rule90RNG rng = new Rule90RNG(seed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90() throws InterruptedException { // seed = 9000; // doRule90(); // } // // public int doRule90Int() // { // Rule90RNG rng = new Rule90RNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90Int() throws InterruptedException { // iseed = 9000; // doRule90Int(); // } // // public long doRule90R() // { // RNG rng = new RNG(new Rule90RNG(seed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90R() throws InterruptedException { // seed = 9000; // doRule90R(); // } // // public int doRule90IntR() // { // RNG rng = new RNG(new Rule90RNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90IntR() throws InterruptedException { // iseed = 9000; // doRule90IntR(); // } /* public long doZap() { ZapRNG rng = new ZapRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZap() throws InterruptedException { seed = 9000; doZap(); } public int doZapInt() { ZapRNG rng = new ZapRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZapInt() throws InterruptedException { iseed = 9000; doZapInt(); } public long doZapR() { RNG rng = new RNG(new ZapRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZapR() throws InterruptedException { seed = 9000; doZapR(); } public int doZapIntR() { RNG rng = new RNG(new ZapRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZapIntR() throws InterruptedException { iseed = 9000; doZapIntR(); } public long doSlap() { SlapRNG rng = new SlapRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlap() throws InterruptedException { seed = 9000; doSlap(); } public int doSlapInt() { SlapRNG rng = new SlapRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlapInt() throws InterruptedException { iseed = 9000; doSlapInt(); } public long doSlapR() { RNG rng = new RNG(new SlapRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlapR() throws InterruptedException { seed = 9000; doSlapR(); } public int doSlapIntR() { RNG rng = new RNG(new SlapRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlapIntR() throws InterruptedException { iseed = 9000; doSlapIntR(); } */ /* public long doPlaceholder() { PlaceholderRNG rng = new PlaceholderRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholder() throws InterruptedException { seed = 9000; doPlaceholder(); } public int doPlaceholderInt() { PlaceholderRNG rng = new PlaceholderRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholderInt() throws InterruptedException { iseed = 9000; doPlaceholderInt(); } public long doPlaceholderR() { RNG rng = new RNG(new PlaceholderRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholderR() throws InterruptedException { seed = 9000; doPlaceholderR(); } public int doPlaceholderIntR() { RNG rng = new RNG(new PlaceholderRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholderIntR() throws InterruptedException { iseed = 9000; doPlaceholderIntR(); } */ private Random JDK = new Random(9999L); @Benchmark public long measureJDK() { return JDK.nextLong(); } @Benchmark public int measureJDKInt() { return JDK.nextInt(); } /* mvn clean install java -jar target/benchmarks.jar RNGBenchmark -wi 5 -i 5 -f 1 -gc true */ public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(RNGBenchmark.class.getSimpleName()) .timeout(TimeValue.seconds(30)) .warmupIterations(5) .measurementIterations(5) .forks(1) .build(); new Runner(opt).run(); } }
sarong-benchmarks/src/main/java/sarong/RNGBenchmark.java
/* * Copyright (c) 2014, Oracle America, Inc. * 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 Oracle 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 sarong; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Results: * <br> * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureAltThrustDetermine avgt 5 3.887 ± 0.055 ns/op * RNGBenchmark.measureAltThrustRandomize avgt 5 3.532 ± 0.035 ns/op * RNGBenchmark.measureFlap avgt 5 3.938 ± 0.024 ns/op * RNGBenchmark.measureFlapInt avgt 5 3.491 ± 0.047 ns/op * RNGBenchmark.measureFlapIntR avgt 5 3.951 ± 0.028 ns/op * RNGBenchmark.measureFlapR avgt 5 4.511 ± 0.038 ns/op * RNGBenchmark.measureInlineJab63 avgt 5 3.194 ± 0.032 ns/op :) best speed, not well-distributed * RNGBenchmark.measureInlineThrust avgt 5 3.354 ± 0.026 ns/op * RNGBenchmark.measureInlineThrustAlt avgt 5 3.532 ± 0.033 ns/op * RNGBenchmark.measureInlineThrustAltOther avgt 5 3.527 ± 0.039 ns/op * RNGBenchmark.measureInlineVortex avgt 5 3.622 ± 0.046 ns/op * RNGBenchmark.measureJDK avgt 5 24.726 ± 0.174 ns/op :( worst speed * RNGBenchmark.measureJDKInt avgt 5 12.352 ± 0.057 ns/op * RNGBenchmark.measureJab63 avgt 5 3.373 ± 0.016 ns/op * RNGBenchmark.measureJab63Int avgt 5 3.566 ± 0.033 ns/op * RNGBenchmark.measureJab63IntR avgt 5 4.069 ± 0.037 ns/op * RNGBenchmark.measureJab63R avgt 5 3.756 ± 0.045 ns/op * RNGBenchmark.measureLap avgt 5 3.367 ± 0.028 ns/op * RNGBenchmark.measureLapInt avgt 5 3.674 ± 0.079 ns/op * RNGBenchmark.measureLapIntR avgt 5 4.128 ± 0.038 ns/op * RNGBenchmark.measureLapR avgt 5 3.870 ± 0.019 ns/op * RNGBenchmark.measureLight avgt 5 3.978 ± 0.034 ns/op * RNGBenchmark.measureLightInt avgt 5 4.340 ± 0.135 ns/op * RNGBenchmark.measureLightIntR avgt 5 4.892 ± 0.026 ns/op * RNGBenchmark.measureLightR avgt 5 4.449 ± 0.027 ns/op * RNGBenchmark.measureLongPeriod avgt 5 4.963 ± 0.058 ns/op * RNGBenchmark.measureLongPeriodInt avgt 5 5.276 ± 0.044 ns/op * RNGBenchmark.measureLongPeriodIntR avgt 5 5.947 ± 0.046 ns/op * RNGBenchmark.measureLongPeriodR avgt 5 5.571 ± 0.026 ns/op * RNGBenchmark.measureThrust avgt 5 3.542 ± 0.137 ns/op :? unusual Error result * RNGBenchmark.measureThrustAlt avgt 5 3.541 ± 0.018 ns/op :) best quality/speed/distribution mix * RNGBenchmark.measureThrustAltInt avgt 5 3.746 ± 0.045 ns/op * RNGBenchmark.measureThrustAltIntR avgt 5 4.143 ± 0.019 ns/op * RNGBenchmark.measureThrustAltR avgt 5 3.982 ± 0.184 ns/op * RNGBenchmark.measureThrustInt avgt 5 3.609 ± 0.058 ns/op * RNGBenchmark.measureThrustIntR avgt 5 4.118 ± 0.010 ns/op * RNGBenchmark.measureThrustR avgt 5 3.930 ± 0.031 ns/op * RNGBenchmark.measureVortex avgt 5 3.750 ± 0.018 ns/op * RNGBenchmark.measureVortexDetermine avgt 5 4.595 ± 0.053 ns/op * RNGBenchmark.measureVortexDetermineBare avgt 5 3.627 ± 0.071 ns/op * RNGBenchmark.measureVortexInt avgt 5 4.075 ± 0.039 ns/op * RNGBenchmark.measureVortexIntR avgt 5 4.831 ± 0.047 ns/op * RNGBenchmark.measureVortexR avgt 5 4.298 ± 0.070 ns/op * RNGBenchmark.measureXoRo avgt 5 3.890 ± 0.016 ns/op * RNGBenchmark.measureXoRoInt avgt 5 4.206 ± 0.049 ns/op * RNGBenchmark.measureXoRoIntR avgt 5 4.674 ± 0.069 ns/op * RNGBenchmark.measureXoRoR avgt 5 4.206 ± 0.053 ns/op * </pre> * <br> * ThrustAltRNG is the fastest so far that passes stringent quality tests (no failures with gjrand on many seeds and few * seeds cause severe failures, none systematically; 32TB PractRand testing completed without failure). Jab63, inlined * in particular, is faster and still tests as having high quality, but neither it nor ThrustAltRNG can produce all * possible 64-bit longs. LightRNG passes PractRand but has more frequent issues with gjrand. XoRo fails PractRand * unless you disregard binary matrix rank tests, as the author recommends; because gjrand can't take a test out of * consideration, XoRo probably fails it fully. ThrustRNG does reasonably well on gjrand but fails on PractRand at only * 32GB. VortexRNG does very well on gjrand and passes PractRand at 32TB, but it's also slower than XoRo with a smaller * period on the same state. * <br> * As for the recently-added GWT-friendly generators Zig32RNG, Zag32RNG, Zog32RNG, and XoRo32RNG, the first three all * perform about equally well on GWT and pass PractRand, while XoRo32RNG performs very well on GWT but fails a few tests * in PractRand fairly early on (There are ways to eliminate the statistical quality issues, but they also slow down the * generator significantly). Even though Zig and Zag are similar, Zog32RNG performs quite a bit better on desktop: * <br> * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureXoRo32 avgt 5 5.148 ± 0.352 ns/op * RNGBenchmark.measureXoRo32Int avgt 5 3.825 ± 0.427 ns/op * RNGBenchmark.measureXoRo32IntR avgt 5 4.111 ± 0.396 ns/op * RNGBenchmark.measureXoRo32R avgt 5 6.029 ± 1.172 ns/op * RNGBenchmark.measureZag32 avgt 5 7.638 ± 1.260 ns/op * RNGBenchmark.measureZag32Int avgt 5 4.732 ± 0.851 ns/op * RNGBenchmark.measureZag32IntR avgt 5 5.393 ± 0.919 ns/op * RNGBenchmark.measureZag32R avgt 5 8.506 ± 1.333 ns/op * RNGBenchmark.measureZig32 avgt 5 8.167 ± 1.734 ns/op * RNGBenchmark.measureZig32Int avgt 5 4.843 ± 0.582 ns/op * RNGBenchmark.measureZig32IntR avgt 5 5.573 ± 0.647 ns/op * RNGBenchmark.measureZig32R avgt 5 9.015 ± 1.248 ns/op * RNGBenchmark.measureZog32 avgt 5 7.151 ± 1.485 ns/op * RNGBenchmark.measureZog32Int avgt 5 4.488 ± 0.899 ns/op * RNGBenchmark.measureZog32IntR avgt 5 5.248 ± 0.758 ns/op * RNGBenchmark.measureZog32R avgt 5 7.950 ± 1.415 ns/op * </pre> * * Testing the newly-added variants on XoRo32RNG called Oriole32RNG and Lathe32RNG, Lathe is the faster of the two, and * both beat Zog on speed (Oriole very narrowly, Lathe comfortably) while all three have about the same quality. * Lathe, Oriole, and Zog trounce XoRo32 on quality but are still slower than it. Oriole also has the best period of the * group, but isn't a StatefulRandomness, while Lathe has the same period as XoRo32 and is a StatefulRandomness. * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureLathe32 avgt 10 5.692 ± 0.054 ns/op * RNGBenchmark.measureLathe32Int avgt 10 3.971 ± 0.022 ns/op * RNGBenchmark.measureLathe32IntR avgt 10 4.684 ± 0.460 ns/op * RNGBenchmark.measureLathe32R avgt 10 6.456 ± 0.109 ns/op * RNGBenchmark.measureOriole32 avgt 10 6.168 ± 0.029 ns/op * RNGBenchmark.measureOriole32Int avgt 10 4.262 ± 0.020 ns/op * RNGBenchmark.measureOriole32IntR avgt 10 4.816 ± 0.038 ns/op * RNGBenchmark.measureOriole32R avgt 10 6.884 ± 0.101 ns/op * RNGBenchmark.measureXoRo32 avgt 10 5.047 ± 0.026 ns/op * RNGBenchmark.measureXoRo32Int avgt 10 3.717 ± 0.022 ns/op * RNGBenchmark.measureXoRo32IntR avgt 10 4.034 ± 0.029 ns/op * RNGBenchmark.measureXoRo32R avgt 10 5.749 ± 0.024 ns/op * RNGBenchmark.measureZog32 avgt 10 6.839 ± 0.029 ns/op * RNGBenchmark.measureZog32Int avgt 10 4.305 ± 0.026 ns/op * RNGBenchmark.measureZog32IntR avgt 10 4.967 ± 0.028 ns/op * RNGBenchmark.measureZog32R avgt 10 7.586 ± 0.065 ns/op * </pre> * <br> * Testing the top 3 contenders among one-dimensionally equidistributed generators (LightRNG and LinnormRNG pass 32TB on * PractRand but XoRoRNG reliably fails one group of tests and sometimes fails others): * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureLight avgt 5 3.763 ± 0.204 ns/op * RNGBenchmark.measureLightInt avgt 5 4.047 ± 0.008 ns/op * RNGBenchmark.measureLinnorm avgt 5 3.442 ± 0.018 ns/op * RNGBenchmark.measureLinnormInt avgt 5 3.668 ± 0.010 ns/op * RNGBenchmark.measureXoRo avgt 5 3.656 ± 0.028 ns/op * RNGBenchmark.measureXoRoInt avgt 5 3.941 ± 0.034 ns/op * ...and one result for the non-equidistributed ThrustAltRNG... * RNGBenchmark.measureThrustAlt avgt 5 3.322 ± 0.053 ns/op * </pre> * Linnorm is the new best generator we have, except that it isn't a SkippingRandomness and its period is "just" 2 to * the 64. Every other need seems to be met by its high speed, easily-stored state, unsurpassed statistical quality, and * ability to produce all long values. ThrustAltRNG may be faster, but since it isn't known how many numbers it is * incapable of producing, it probably shouldn't be used for procedural generation. If you need to target GWT, though, * your needs are suddenly completely different... * <br> * GWT-compatible generators need to work with an "int" type that isn't equivalent to Java's "int" and is closer to a * Java "double" that gets cast to an int when bitwise operations are used on it. This JS int is about 10x-20x faster to * do math operations on than GWT's "long" type, which is emulated using three JS numbers internally, but you need to be * vigilant about the possibility of exceeding the limits of Integer.MAX_VALUE and Integer.MIN_VALUE, since math won't * overflow, and about precision loss if you do exceed those limits severely, since JS numbers are floating-point. So, * you can't safely multiply by too large of an int (I limit my multipliers to 20 bits), you need to follow up normal * math with bitwise math to bring any overflowing numbers back to the 32-bit range, and you should avoid longs and math * on them whenever possible. So here's some GWT-safe generators, measured on a desktop JDK: * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureDizzy32 avgt 3 7.742 ± 0.144 ns/op // 1D equidistribution * RNGBenchmark.measureDizzy32Int avgt 3 5.094 ± 0.084 ns/op // 2D equidistribution * RNGBenchmark.measureDizzy32IntR avgt 3 5.826 ± 0.113 ns/op // 2D equidistribution * RNGBenchmark.measureDizzy32R avgt 3 8.636 ± 0.079 ns/op // 1D equidistribution * RNGBenchmark.measureLathe32 avgt 3 6.181 ± 0.159 ns/op // no equidistribution * RNGBenchmark.measureLathe32Int avgt 3 4.409 ± 0.024 ns/op // 1D equidistribution * RNGBenchmark.measureLathe32IntR avgt 3 4.791 ± 0.242 ns/op // 1D equidistribution * RNGBenchmark.measureLathe32R avgt 3 7.147 ± 0.013 ns/op // no equidistribution * RNGBenchmark.measureOriole32 avgt 3 6.578 ± 0.058 ns/op // no equidstribution * RNGBenchmark.measureOriole32Int avgt 3 4.640 ± 0.118 ns/op // 1D equidistribution * RNGBenchmark.measureOriole32IntR avgt 3 5.352 ± 0.098 ns/op // 1D equidistribution * RNGBenchmark.measureOriole32R avgt 3 7.729 ± 0.127 ns/op // no equidistribution * RNGBenchmark.measureXoshiroAra32 avgt 3 7.175 ± 0.696 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroAra32Int avgt 3 4.953 ± 0.132 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroAra32IntR avgt 3 5.513 ± 0.227 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroAra32R avgt 3 7.770 ± 0.215 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroStarPhi32 avgt 3 7.294 ± 0.386 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroStarPhi32Int avgt 3 5.032 ± 0.045 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroStarPhi32IntR avgt 3 5.618 ± 0.064 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroStarPhi32R avgt 3 8.017 ± 0.202 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroStarStar32 avgt 3 7.690 ± 0.127 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroStarStar32Int avgt 3 5.210 ± 0.102 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroStarStar32IntR avgt 3 5.856 ± 0.291 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroStarStar32R avgt 3 8.475 ± 0.266 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroXara32 avgt 3 7.309 ± 0.083 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroXara32Int avgt 3 5.027 ± 0.139 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroXara32IntR avgt 3 5.567 ± 0.186 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroXara32R avgt 3 8.075 ± 0.131 ns/op // 2D equidistribution * </pre> * And here's some of the best GWT-safe generators compared against each other, including the new Starfish generator * (these benchmarks were performed while a multi-threaded test was also running, so they are slower): * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureLathe32 avgt 3 8.073 ± 0.388 ns/op // no equidistribution * RNGBenchmark.measureLathe32Int avgt 3 5.780 ± 0.976 ns/op // 1D equidistribution * RNGBenchmark.measureLathe32IntR avgt 3 6.358 ± 0.823 ns/op // 1D equidistribution * RNGBenchmark.measureLathe32R avgt 3 9.102 ± 1.079 ns/op // no equidistribution * RNGBenchmark.measureStarfish32 avgt 3 8.285 ± 0.439 ns/op // 1D equidistribution * RNGBenchmark.measureStarfish32Int avgt 3 5.866 ± 0.699 ns/op // 2D equidistribution * RNGBenchmark.measureStarfish32IntR avgt 3 6.448 ± 1.158 ns/op // 2D equidistribution * RNGBenchmark.measureStarfish32R avgt 3 9.297 ± 1.122 ns/op // 1D equidistribution * RNGBenchmark.measureXoshiroAra32 avgt 3 9.048 ± 1.296 ns/op // 2D equidistribution * RNGBenchmark.measureXoshiroAra32Int avgt 3 6.440 ± 0.188 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroAra32IntR avgt 3 7.181 ± 0.497 ns/op // 4D equidistribution * RNGBenchmark.measureXoshiroAra32R avgt 3 9.879 ± 1.205 ns/op // 2D equidistribution * </pre> * And testing (under load, again) Starfish vs. the newer Otter generator; Otter tends to be faster on GWT because * multiplication isn't as fast in browsers, but it is a little slower on desktop. * <pre> * Benchmark Mode Cnt Score Error Units * RNGBenchmark.measureLathe32 avgt 3 6.328 ± 0.568 ns/op * RNGBenchmark.measureLathe32Int avgt 3 4.455 ± 0.165 ns/op * RNGBenchmark.measureLobster32 avgt 3 6.793 ± 0.461 ns/op * RNGBenchmark.measureLobster32Int avgt 3 4.601 ± 0.056 ns/op * RNGBenchmark.measureStarfish32 avgt 3 6.503 ± 0.109 ns/op * RNGBenchmark.measureStarfish32Int avgt 3 4.505 ± 1.135 ns/op * </pre> * You can benchmark most of these in GWT for yourself on * <a href="https://tommyettinger.github.io/SquidLib-Demos/bench/rng/">this SquidLib-Demos page</a>; comparing "runs" * where higher is better is a good way of estimating how fast a generator is. Each "run" is 10,000 generated numbers. * Lathe32RNG is by far the best on speed if you consider both desktop and GWT, but it can't generate all possible * "long" values, while XoshiroAra can generate all possible "long" values with equal frequency, and even all possible * pairs of "long" values (less one). XoshiroAra is also surprisingly fast compared to similar Xoshiro-based generators, * especially since it does just as well in PractRand testing. The equidistribution comment at the end of each line * refers to that specific method; calling {@code myOriole32RNG.next(32)} repeatedly will produce all ints with equal * frequency over the full period of that generator, ((2 to the 64) - 1) * (2 to the 32), but the same is not true of * calling {@code myOriole32RNG.nextLong()}, which would produce some longs more frequently than others (and probably * would not produce some longs at all). The Xoshiro-based generators have the best period and equidistribution * qualities, with XoshiroAra having the best performance (all of them pass 32TB of PractRand). The Xoroshiro-based * generators tend to be faster, but only Starfish has better equidistribution of the bunch (it can produce all longs * except one, while Lathe can't and Oriole won't with equal frequency). Starfish seems to have comparable quality and * speed relative to Oriole (excellent and pretty good, respectively), but improves on its distribution at the expense * of its period, and has a smaller state. */ @State(Scope.Thread) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Fork(1) @Warmup(iterations = 5, time = 5) @Measurement(iterations = 5, time = 5) public class RNGBenchmark { private long state = 9000, stream = 9001, oddState = 9999L; // public long doThunder() // { // ThunderRNG rng = new ThunderRNG(seed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunder() throws InterruptedException { // seed = 9000; // doThunder(); // } // // public int doThunderInt() // { // ThunderRNG rng = new ThunderRNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunderInt() throws InterruptedException { // iseed = 9000; // doThunderInt(); // } // public long doThunderR() // { // RNG rng = new RNG(new ThunderRNG(seed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunderR() throws InterruptedException { // seed = 9000; // doThunderR(); // } // // public int doThunderIntR() // { // RNG rng = new RNG(new ThunderRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void measureThunderIntR() throws InterruptedException { // iseed = 9000; // doThunderIntR(); // } private XoRoRNG XoRo = new XoRoRNG(9999L); private RNG XoRoR = new RNG(XoRo); @Benchmark public long measureXoRo() { return XoRo.nextLong(); } @Benchmark public int measureXoRoInt() { return XoRo.next(32); } @Benchmark public long measureXoRoR() { return XoRoR.nextLong(); } @Benchmark public int measureXoRoIntR() { return XoRoR.nextInt(); } private Lathe64RNG Lathe64 = new Lathe64RNG(9999L); private RNG Lathe64R = new RNG(Lathe64); @Benchmark public long measureLathe64() { return Lathe64.nextLong(); } @Benchmark public int measureLathe64Int() { return Lathe64.next(32); } @Benchmark public long measureLathe64R() { return Lathe64R.nextLong(); } @Benchmark public int measureLathe64IntR() { return Lathe64R.nextInt(); } /* public long doXar() { XarRNG rng = new XarRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXar() throws InterruptedException { seed = 9000; doXar(); } public int doXarInt() { XarRNG rng = new XarRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXarInt() throws InterruptedException { iseed = 9000; doXarInt(); } public long doXarR() { RNG rng = new RNG(new XarRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXarR() throws InterruptedException { seed = 9000; doXarR(); } public int doXarIntR() { RNG rng = new RNG(new XarRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a____measureXarIntR() throws InterruptedException { iseed = 9000; doXarIntR(); } */ private LongPeriodRNG LongPeriod = new LongPeriodRNG(9999L); private RNG LongPeriodR = new RNG(LongPeriod); @Benchmark public long measureLongPeriod() { return LongPeriod.nextLong(); } @Benchmark public int measureLongPeriodInt() { return LongPeriod.next(32); } @Benchmark public long measureLongPeriodR() { return LongPeriodR.nextLong(); } @Benchmark public int measureLongPeriodIntR() { return LongPeriodR.nextInt(); } private LightRNG Light = new LightRNG(9999L); private RNG LightR = new RNG(Light); @Benchmark public long measureLight() { return Light.nextLong(); } @Benchmark public int measureLightInt() { return Light.next(32); } @Benchmark public long measureLightR() { return LightR.nextLong(); } @Benchmark public int measureLightIntR() { return LightR.nextInt(); } private PaperweightRNG Paperweight = new PaperweightRNG(9999L); private RNG PaperweightR = new RNG(Paperweight); @Benchmark public long measurePaperweight() { return Paperweight.nextLong(); } @Benchmark public int measurePaperweightInt() { return Paperweight.next(32); } @Benchmark public long measurePaperweightR() { return PaperweightR.nextLong(); } @Benchmark public int measurePaperweightIntR() { return PaperweightR.nextInt(); } private FlapRNG Flap = new FlapRNG(9999L); private RNG FlapR = new RNG(Flap); @Benchmark public long measureFlap() { return Flap.nextLong(); } @Benchmark public int measureFlapInt() { return Flap.next(32); } @Benchmark public long measureFlapR() { return FlapR.nextLong(); } @Benchmark public int measureFlapIntR() { return FlapR.nextInt(); } private LapRNG Lap = new LapRNG(9999L); private RNG LapR = new RNG(Lap); @Benchmark public long measureLap() { return Lap.nextLong(); } @Benchmark public int measureLapInt() { return Lap.next(32); } @Benchmark public long measureLapR() { return LapR.nextLong(); } private ThunderRNG Thunder = new ThunderRNG(9999L); private RNG ThunderR = new RNG(Thunder); @Benchmark public long measureThunder() { return Thunder.nextLong(); } @Benchmark public int measureThunderInt() { return Thunder.next(32); } @Benchmark public long measureThunderR() { return ThunderR.nextLong(); } @Benchmark public int measureThunderIntR() { return ThunderR.nextInt(); } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public int measureLapIntR() { return LapR.nextInt(); } private SeaSlater64RNG SeaSlater64 = new SeaSlater64RNG(9999L); private RNG SeaSlater64R = new RNG(SeaSlater64); @Benchmark public long measureSeaSlater64() { return SeaSlater64.nextLong(); } @Benchmark public int measureSeaSlater64Int() { return SeaSlater64.next(32); } @Benchmark public long measureSeaSlater64R() { return SeaSlater64R.nextLong(); } @Benchmark public int measureSeaSlater64IntR() { return SeaSlater64R.nextInt(); } private ThrustRNG Thrust = new ThrustRNG(9999L); private RNG ThrustR = new RNG(Thrust); @Benchmark public long measureThrust() { return Thrust.nextLong(); } @Benchmark public int measureThrustInt() { return Thrust.next(32); } @Benchmark public long measureThrustR() { return ThrustR.nextLong(); } @Benchmark public int measureThrustIntR() { return ThrustR.nextInt(); } //@Benchmark public long measureInlineThrust() { long z = (state += 0x9E3779B97F4A7C15L); z = (z ^ z >>> 26) * 0x2545F4914F6CDD1DL; return z ^ z >>> 28; } /* public long doThrust3() { ThrustAltRNG rng = new ThrustAltRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong3(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust3() throws InterruptedException { seed = 9000; doThrust3(); } public int doThrust3Int() { ThrustAltRNG rng = new ThrustAltRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next3(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust3Int() throws InterruptedException { iseed = 9000; doThrust3Int(); } public long doThrust2() { ThrustAltRNG rng = new ThrustAltRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong2(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust2() throws InterruptedException { seed = 9000; doThrust2(); } public int doThrust2Int() { ThrustAltRNG rng = new ThrustAltRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next2(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureThrust2Int() throws InterruptedException { iseed = 9000; doThrust2Int(); } public long doThrust4() { ThrustAltRNG rng = new ThrustAltRNG(seed|1L); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong4(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureAltThrust4() throws InterruptedException { seed = 9000; doThrust4(); } public int doThrust4Int() { ThrustAltRNG rng = new ThrustAltRNG(iseed|1L); for (int i = 0; i < 1000000007; i++) { iseed += rng.next4(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void a______measureAltThrust4Int() throws InterruptedException { iseed = 9000; doThrust4Int(); } */ @Benchmark public long measureAltThrustDetermine() { return ThrustAltRNG.determine(state++); } // // // @Benchmark // public long measureDervishDetermine() { // return DervishRNG.determine(state++); // } // @Benchmark public long measureLightDetermine() { return LightRNG.determine(state++); } @Benchmark public long measureLinnormDetermine() { return LinnormRNG.determine(state++); } @Benchmark public long measureDirkDetermine() { return DirkRNG.determine(state++); } // @Benchmark // public long measureMotorDetermine() { // return MotorRNG.determine(state++); // } // // //@Benchmark // public long measureVortexDetermine() { // return VortexRNG.determine(state++); // } // // //@Benchmark // public long measureVortexDetermineBare() { // return VortexRNG.determineBare(state += 0x6C8E9CF570932BD5L); // } // // @Benchmark // public long measureAltThrustRandomize() { // return ThrustAltRNG.randomize(state += 0x6C8E9CF570932BD5L); // } // // @Benchmark // public long measureLinnormRandomize() { return LinnormRNG.randomize(state += 0x632BE59BD9B4E019L); } private ThrustAltRNG ThrustAlt = new ThrustAltRNG(9999L); private RNG ThrustAltR = new RNG(ThrustAlt); @Benchmark public long measureThrustAlt() { return ThrustAlt.nextLong(); } @Benchmark public int measureThrustAltInt() { return ThrustAlt.next(32); } @Benchmark public long measureThrustAltR() { return ThrustAltR.nextLong(); } @Benchmark public int measureThrustAltIntR() { return ThrustAltR.nextInt(); } // @Benchmark // public long measureThrustAltInline() // { // final long s = (state += 0x6C8E9CF570932BD5L); // final long z = (s ^ (s >>> 25)) * (s | 0xA529L); // return z ^ (z >>> 22); // } // @Benchmark // public long measureInlineThrustAltOther() // { // long z = (state += 0x6C8E9CF570932BD5L); // z = (z ^ (z >>> 25)) * (z | 0xA529L); // return z ^ (z >>> 22); // } private Jab63RNG Jab63 = new Jab63RNG(9999L); private RNG Jab63R = new RNG(Jab63); @Benchmark public long measureJab63() { return Jab63.nextLong(); } @Benchmark public int measureJab63Int() { return Jab63.next(32); } @Benchmark public long measureJab63R() { return Jab63R.nextLong(); } @Benchmark public int measureJab63IntR() { return Jab63R.nextInt(); } // @Benchmark // public long measureInlineJab63() // { // long z = (oddState += 0x3C6EF372FE94F82AL); // z *= (z ^ (z >>> 21)); // return z - (z >>> 28); // } // // // @Benchmark // public long measureInlineVortex() // { // long z = (state += 0x6C8E9CF970932BD5L); // z = (z ^ z >>> 25) * 0x2545F4914F6CDD1DL; // z ^= ((z << 19) | (z >>> 45)) ^ ((z << 53) | (z >>> 11)); // return z ^ (z >>> 25); // } private VortexRNG Vortex = new VortexRNG(9999L); private RNG VortexR = new RNG(Vortex); @Benchmark public long measureVortex() { return Vortex.nextLong(); } @Benchmark public int measureVortexInt() { return Vortex.next(32); } @Benchmark public long measureVortexR() { return VortexR.nextLong(); } @Benchmark public int measureVortexIntR() { return VortexR.nextInt(); } private BasicRandom64 BasicRandom64 = new BasicRandom64(1L); private RNG BasicRandom64R = new RNG(BasicRandom64); @Benchmark public long measureBasicRandom64() { return BasicRandom64.nextLong(); } @Benchmark public int measureBasicRandom64Int() { return BasicRandom64.next(32); } @Benchmark public long measureBasicRandom64R() { return BasicRandom64R.nextLong(); } @Benchmark public int measureBasicRandom64IntR() { return BasicRandom64R.nextInt(); } private BasicRandom32 BasicRandom32 = new BasicRandom32(1); private RNG BasicRandom32R = new RNG(BasicRandom32); @Benchmark public long measureBasicRandom32() { return BasicRandom32.nextLong(); } @Benchmark public int measureBasicRandom32Int() { return BasicRandom32.next(32); } @Benchmark public long measureBasicRandom32R() { return BasicRandom32R.nextLong(); } @Benchmark public int measureBasicRandom32IntR() { return BasicRandom32R.nextInt(); } private MotorRNG Motor = new MotorRNG(9999L); private RNG MotorR = new RNG(Motor); @Benchmark public long measureMotor() { return Motor.nextLong(); } @Benchmark public int measureMotorInt() { return Motor.next(32); } @Benchmark public long measureMotorR() { return MotorR.nextLong(); } @Benchmark public int measureMotorIntR() { return MotorR.nextInt(); } private MeshRNG Mesh = new MeshRNG(9999L); private RNG MeshR = new RNG(Mesh); @Benchmark public long measureMesh() { return Mesh.nextLong(); } @Benchmark public int measureMeshInt() { return Mesh.next(32); } @Benchmark public long measureMeshR() { return MeshR.nextLong(); } @Benchmark public int measureMeshIntR() { return MeshR.nextInt(); } private SpiralRNG Spiral = new SpiralRNG(9999L); private RNG SpiralR = new RNG(Spiral); @Benchmark public long measureSpiral() { return Spiral.nextLong(); } @Benchmark public int measureSpiralInt() { return Spiral.next(32); } @Benchmark public long measureSpiralR() { return SpiralR.nextLong(); } @Benchmark public int measureSpiralIntR() { return SpiralR.nextInt(); } private SpiralRNG spiralA = new SpiralRNG(9999L, 1337L), spiralB = new SpiralRNG(9999L, 1337L), spiralC = new SpiralRNG(9999L, 1337L), spiralD = new SpiralRNG(9999L, 1337L), spiralE = new SpiralRNG(9999L, 1337L), spiralF = new SpiralRNG(9999L, 1337L), spiralG = new SpiralRNG(9999L, 1337L), spiralH = new SpiralRNG(9999L, 1337L), spiralI = new SpiralRNG(9999L, 1337L); @Benchmark public long measureSpiralA() { return spiralA.nextLongOld(); } @Benchmark public long measureSpiralB() { return spiralB.nextLongAlt(); } @Benchmark public long measureSpiralC() { return spiralC.nextLongNew(); } @Benchmark public long measureSpiralD() { return spiralD.nextLongAgain(); } @Benchmark public long measureSpiralE() { return spiralE.nextLongAgain3(); } @Benchmark public long measureSpiralF() { return spiralF.nextLongAgain4(); } @Benchmark public long measureSpiralG() { return spiralG.nextLongAgain5(); } @Benchmark public long measureSpiralH() { return spiralH.nextLongAgain6(); } @Benchmark public long measureSpiralI() { return spiralI.nextLongAgain7(); } private OrbitRNG Orbit = new OrbitRNG(9999L, 1337L); private RNG OrbitR = new RNG(Orbit); @Benchmark public long measureOrbit() { return Orbit.nextLong(); } @Benchmark public int measureOrbitInt() { return Orbit.next(32); } @Benchmark public long measureOrbitR() { return OrbitR.nextLong(); } @Benchmark public int measureOrbitIntR() { return OrbitR.nextInt(); } private TangleRNG Tangle = new TangleRNG(9999L, 1337L); private RNG TangleR = new RNG(Tangle); @Benchmark public long measureTangle() { return Tangle.nextLong(); } @Benchmark public int measureTangleInt() { return Tangle.next(32); } @Benchmark public long measureTangleR() { return TangleR.nextLong(); } @Benchmark public int measureTangleIntR() { return TangleR.nextInt(); } private OrbitRNG OrbitA = new OrbitRNG(9999L, 1337L), OrbitB = new OrbitRNG(9999L, 1337L), OrbitC = new OrbitRNG(9999L, 1337L), OrbitD = new OrbitRNG(9999L, 1337L), OrbitE = new OrbitRNG(9999L, 1337L), OrbitF = new OrbitRNG(9999L, 1337L), OrbitG = new OrbitRNG(9999L, 1337L), OrbitH = new OrbitRNG(9999L, 1337L), OrbitI = new OrbitRNG(9999L, 1337L), OrbitJ = new OrbitRNG(9999L, 1337L), OrbitK = new OrbitRNG(9999L, 1337L), OrbitL = new OrbitRNG(9999L, 1337L), OrbitM = new OrbitRNG(9999L, 1337L), OrbitN = new OrbitRNG(9999L, 1337L), OrbitO = new OrbitRNG(9999L, 1337L); @Benchmark public long measureOrbitA() { return OrbitA.nextLong1(); } @Benchmark public long measureOrbitB() { return OrbitB.nextLong2(); } @Benchmark public long measureOrbitC() { return OrbitC.nextLong3(); } @Benchmark public long measureOrbitD() { return OrbitD.nextLong4(); } @Benchmark public long measureOrbitE() { return OrbitE.nextLong5(); } @Benchmark public long measureOrbitF() { return OrbitF.nextLong6(); } @Benchmark public long measureOrbitG() { return OrbitG.nextLong7(); } @Benchmark public long measureOrbitH() { return OrbitH.nextLong8(); } @Benchmark public long measureOrbitI() { return OrbitI.nextLong9(); } @Benchmark public long measureOrbitJ() { return OrbitJ.nextLong10(); } @Benchmark public long measureOrbitK() { return OrbitK.nextLong11(); } @Benchmark public long measureOrbitL() { return OrbitL.nextLong12(); } @Benchmark public long measureOrbitM() { return OrbitM.nextLong13(); } @Benchmark public long measureOrbitN() { return OrbitN.nextLong14(); } @Benchmark public long measureOrbitO() { return OrbitO.nextLong15(); } private TangleRNG TangleA = new TangleRNG(9999L, 1337L), TangleB = new TangleRNG(9999L, 1337L), TangleC = new TangleRNG(9999L, 1337L), TangleD = new TangleRNG(9999L, 1337L); @Benchmark public long measureTangleA() { return TangleA.nextLong1(); } @Benchmark public long measureTangleB() { return TangleB.nextLong2(); } @Benchmark public long measureTangleC() { return TangleC.nextLong3(); } @Benchmark public long measureTangleD() { return TangleD.nextLong4(); } private Mover32RNG Mover32 = new Mover32RNG(0); private RNG Mover32R = new RNG(Mover32); @Benchmark public long measureMover32() { return Mover32.nextLong(); } @Benchmark public int measureMover32Int() { return Mover32.next(32); } @Benchmark public long measureMover32R() { return Mover32R.nextLong(); } @Benchmark public int measureMover32IntR() { return Mover32R.nextInt(); } // private Mover32RNG Mover32A = new Mover32RNG(0); // @Benchmark // public long measureMover32A() // { // return Mover32A.nextIntA(); // } // // private Mover32RNG Mover32B = new Mover32RNG(0); // @Benchmark // public long measureMover32B() // { // return Mover32B.nextIntB(); // } // private Mover32RNG Mover32C = new Mover32RNG(0); // @Benchmark // public long measureMover32C() // { // return Mover32C.nextIntC(); // } private Mover64RNG Mover64 = new Mover64RNG(0); private RNG Mover64R = new RNG(Mover64); @Benchmark public long measureMover64() { return Mover64.nextLong(); } @Benchmark public int measureMover64Int() { return Mover64.next(32); } @Benchmark public long measureMover64R() { return Mover64R.nextLong(); } @Benchmark public int measureMover64IntR() { return Mover64R.nextInt(); } private Molerat32RNG Molerat32 = new Molerat32RNG(0); private RNG Molerat32R = new RNG(Molerat32); @Benchmark public long measureMolerat32() { return Molerat32.nextLong(); } @Benchmark public int measureMolerat32Int() { return Molerat32.next(32); } @Benchmark public long measureMolerat32R() { return Molerat32R.nextLong(); } @Benchmark public int measureMolerat32IntR() { return Molerat32R.nextInt(); } private MiniMover64RNG MiniMover64 = new MiniMover64RNG(0); private RNG MiniMover64R = new RNG(MiniMover64); @Benchmark public long measureMiniMover64() { return MiniMover64.nextLong(); } @Benchmark public int measureMiniMover64Int() { return MiniMover64.next(32); } @Benchmark public long measureMiniMover64R() { return MiniMover64R.nextLong(); } @Benchmark public int measureMiniMover64IntR() { return MiniMover64R.nextInt(); } private SFC64RNG SFC64 = new SFC64RNG(9999L); private RNG SFC64R = new RNG(SFC64); @Benchmark public long measureSFC64() { return SFC64.nextLong(); } @Benchmark public int measureSFC64Int() { return SFC64.next(32); } @Benchmark public long measureSFC64R() { return SFC64R.nextLong(); } @Benchmark public int measureSFC64IntR() { return SFC64R.nextInt(); } private Overdrive64RNG Overdrive64 = new Overdrive64RNG(0); private RNG Overdrive64R = new RNG(Overdrive64); @Benchmark public long measureOverdrive64() { return Overdrive64.nextLong(); } @Benchmark public int measureOverdrive64Int() { return Overdrive64.next(32); } @Benchmark public long measureOverdrive64R() { return Overdrive64R.nextLong(); } @Benchmark public int measureOverdrive64IntR() { return Overdrive64R.nextInt(); } private MoverCounter64RNG MoverCounter64 = new MoverCounter64RNG(9999L); private RNG MoverCounter64R = new RNG(MoverCounter64); @Benchmark public long measureMoverCounter64() { return MoverCounter64.nextLong(); } @Benchmark public int measureMoverCounter64Int() { return MoverCounter64.next(32); } @Benchmark public long measureMoverCounter64R() { return MoverCounter64R.nextLong(); } @Benchmark public int measureMoverCounter64IntR() { return MoverCounter64R.nextInt(); } private DirkRNG Dirk = new DirkRNG(9999L); private RNG DirkR = new RNG(Dirk); @Benchmark public long measureDirk() { return Dirk.nextLong(); } @Benchmark public int measureDirkInt() { return Dirk.next(32); } @Benchmark public long measureDirkR() { return DirkR.nextLong(); } @Benchmark public int measureDirkIntR() { return DirkR.nextInt(); } // private Overdrive64RNG Overdrive1 = new Overdrive64RNG(0); // private Overdrive64RNG Overdrive2 = new Overdrive64RNG(0); // private Overdrive64RNG Overdrive3 = new Overdrive64RNG(0); // private Overdrive64RNG Overdrive4 = new Overdrive64RNG(0); // // @Benchmark // public long measureOverdrive1() // { // return Overdrive1.nextLong1(); // } // @Benchmark // public long measureOverdrive2() // { // return Overdrive2.nextLong2(); // } // @Benchmark // public long measureOverdrive3() // { // return Overdrive3.nextLong3(); // } // @Benchmark // public long measureOverdrive4() // { // return Overdrive4.nextLong4(); // } // private Thrust32RNG Thrust32 = new Thrust32RNG(9999); // private RNG Thrust32R = new RNG(Thrust32); // // @Benchmark // public long measureThrust32() // { // return Thrust32.nextLong(); // } // // @Benchmark // public int measureThrust32Int() // { // return Thrust32.next(32); // } // @Benchmark // public long measureThrust32R() // { // return Thrust32R.nextLong(); // } // // @Benchmark // public int measureThrust32IntR() // { // return Thrust32R.nextInt(); // } // // private ThrustAlt32RNG ThrustAlt32 = new ThrustAlt32RNG(9999); private RNG ThrustAlt32R = new RNG(ThrustAlt32); @Benchmark public long measureThrustAlt32() { return ThrustAlt32.nextLong(); } @Benchmark public int measureThrustAlt32Int() { return ThrustAlt32.next(32); } @Benchmark public long measureThrustAlt32R() { return ThrustAlt32R.nextLong(); } @Benchmark public int measureThrustAlt32IntR() { return ThrustAlt32R.nextInt(); } private Light32RNG Light32 = new Light32RNG(9999); private RNG Light32R = new RNG(Light32); @Benchmark public long measureLight32() { return Light32.nextLong(); } @Benchmark public int measureLight32Int() { return Light32.next(32); } @Benchmark public long measureLight32R() { return Light32R.nextLong(); } @Benchmark public int measureLight32IntR() { return Light32R.nextInt(); } private Zig32RNG Zig32 = new Zig32RNG(9999L); private RNG Zig32R = new RNG(Zig32); @Benchmark public long measureZig32() { return Zig32.nextLong(); } @Benchmark public int measureZig32Int() { return Zig32.next(32); } @Benchmark public long measureZig32R() { return Zig32R.nextLong(); } @Benchmark public int measureZig32IntR() { return Zig32R.nextInt(); } private Zag32RNG Zag32 = new Zag32RNG(9999L); private RNG Zag32R = new RNG(Zag32); @Benchmark public long measureZag32() { return Zag32.nextLong(); } @Benchmark public int measureZag32Int() { return Zag32.next(32); } @Benchmark public long measureZag32R() { return Zag32R.nextLong(); } @Benchmark public int measureZag32IntR() { return Zag32R.nextInt(); } private Zog32RNG Zog32 = new Zog32RNG(9999L); private RNG Zog32R = new RNG(Zog32); @Benchmark public long measureZog32() { return Zog32.nextLong(); } @Benchmark public int measureZog32Int() { return Zog32.next(32); } @Benchmark public long measureZog32R() { return Zog32R.nextLong(); } @Benchmark public int measureZog32IntR() { return Zog32R.nextInt(); } private XoRo32RNG XoRo32 = new XoRo32RNG(9999L); private RNG XoRo32R = new RNG(XoRo32); @Benchmark public long measureXoRo32() { return XoRo32.nextLong(); } @Benchmark public int measureXoRo32Int() { return XoRo32.next(32); } @Benchmark public long measureXoRo32R() { return XoRo32R.nextLong(); } @Benchmark public int measureXoRo32IntR() { return XoRo32R.nextInt(); } private Oriole32RNG Oriole32 = new Oriole32RNG(9999, 999, 99); private RNG Oriole32R = new RNG(Oriole32); @Benchmark public long measureOriole32() { return Oriole32.nextLong(); } @Benchmark public int measureOriole32Int() { return Oriole32.next(32); } @Benchmark public long measureOriole32R() { return Oriole32R.nextLong(); } @Benchmark public int measureOriole32IntR() { return Oriole32R.nextInt(); } private Lathe32RNG Lathe32 = new Lathe32RNG(9999, 999); private RNG Lathe32R = new RNG(Lathe32); @Benchmark public long measureLathe32() { return Lathe32.nextLong(); } @Benchmark public int measureLathe32Int() { return Lathe32.next(32); } @Benchmark public long measureLathe32R() { return Lathe32R.nextLong(); } @Benchmark public int measureLathe32IntR() { return Lathe32R.nextInt(); } private Starfish32RNG Starfish32 = new Starfish32RNG(9999, 999); private RNG Starfish32R = new RNG(Starfish32); @Benchmark public long measureStarfish32() { return Starfish32.nextLong(); } @Benchmark public int measureStarfish32Int() { return Starfish32.next(32); } @Benchmark public int measureStarfish32NextInt() { return Starfish32.nextInt(); } @Benchmark public long measureStarfish32R() { return Starfish32R.nextLong(); } @Benchmark public int measureStarfish32IntR() { return Starfish32R.nextInt(); } private GWTRNG GWT = new GWTRNG(9999, 999); @Benchmark public long measureGWT() { return GWT.nextLong(); } @Benchmark public int measureGWTInt() { return GWT.next(32); } @Benchmark public int measureGWTNextInt() { return GWT.nextInt(); } private Otter32RNG Otter32 = new Otter32RNG(9999, 999); private RNG Otter32R = new RNG(Otter32); @Benchmark public long measureOtter32() { return Otter32.nextLong(); } @Benchmark public int measureOtter32Int() { return Otter32.next(32); } @Benchmark public long measureOtter32R() { return Otter32R.nextLong(); } @Benchmark public int measureOtter32IntR() { return Otter32R.nextInt(); } private Lobster32RNG Lobster32 = new Lobster32RNG(9999, 999); private RNG Lobster32R = new RNG(Lobster32); @Benchmark public long measureLobster32() { return Lobster32.nextLong(); } @Benchmark public int measureLobster32Int() { return Lobster32.next(32); } @Benchmark public long measureLobster32R() { return Lobster32R.nextLong(); } @Benchmark public int measureLobster32IntR() { return Lobster32R.nextInt(); } private SeaSlater32RNG SeaSlater32 = new SeaSlater32RNG(9999, 999); private RNG SeaSlater32R = new RNG(SeaSlater32); @Benchmark public long measureSeaSlater32() { return SeaSlater32.nextLong(); } @Benchmark public int measureSeaSlater32Int() { return SeaSlater32.next(32); } @Benchmark public long measureSeaSlater32R() { return SeaSlater32R.nextLong(); } @Benchmark public int measureSeaSlater32IntR() { return SeaSlater32R.nextInt(); } private Churro32RNG Churro32 = new Churro32RNG(9999, 999, 99); private RNG Churro32R = new RNG(Churro32); @Benchmark public long measureChurro32() { return Churro32.nextLong(); } @Benchmark public int measureChurro32Int() { return Churro32.next(32); } @Benchmark public long measureChurro32R() { return Churro32R.nextLong(); } @Benchmark public int measureChurro32IntR() { return Churro32R.nextInt(); } private Dizzy32RNG Dizzy32 = new Dizzy32RNG(9999, 999, 99); private RNG Dizzy32R = new RNG(Dizzy32); @Benchmark public long measureDizzy32() { return Dizzy32.nextLong(); } @Benchmark public int measureDizzy32Int() { return Dizzy32.next(32); } @Benchmark public long measureDizzy32R() { return Dizzy32R.nextLong(); } @Benchmark public int measureDizzy32IntR() { return Dizzy32R.nextInt(); } @Benchmark public long measureDizzy32IntNative1() { return Dizzy32.nextInt(); } @Benchmark public long measureDizzy32IntNative2() { return Dizzy32.nextInt2(); } private XoshiroStarStar32RNG XoshiroStarStar32 = new XoshiroStarStar32RNG(9999); private RNG XoshiroStarStar32R = new RNG(XoshiroStarStar32); @Benchmark public long measureXoshiroStarStar32() { return XoshiroStarStar32.nextLong(); } @Benchmark public int measureXoshiroStarStar32Int() { return XoshiroStarStar32.next(32); } @Benchmark public long measureXoshiroStarStar32R() { return XoshiroStarStar32R.nextLong(); } @Benchmark public int measureXoshiroStarStar32IntR() { return XoshiroStarStar32R.nextInt(); } private XoshiroStarPhi32RNG XoshiroStarPhi32 = new XoshiroStarPhi32RNG(9999); private RNG XoshiroStarPhi32R = new RNG(XoshiroStarPhi32); @Benchmark public long measureXoshiroStarPhi32() { return XoshiroStarPhi32.nextLong(); } @Benchmark public int measureXoshiroStarPhi32Int() { return XoshiroStarPhi32.next(32); } @Benchmark public long measureXoshiroStarPhi32R() { return XoshiroStarPhi32R.nextLong(); } @Benchmark public int measureXoshiroStarPhi32IntR() { return XoshiroStarPhi32R.nextInt(); } private XoshiroXara32RNG XoshiroXara32 = new XoshiroXara32RNG(9999); private RNG XoshiroXara32R = new RNG(XoshiroXara32); @Benchmark public long measureXoshiroXara32() { return XoshiroXara32.nextLong(); } @Benchmark public int measureXoshiroXara32Int() { return XoshiroXara32.next(32); } @Benchmark public long measureXoshiroXara32R() { return XoshiroXara32R.nextLong(); } @Benchmark public int measureXoshiroXara32IntR() { return XoshiroXara32R.nextInt(); } private XoshiroAra32RNG XoshiroAra32 = new XoshiroAra32RNG(9999); private RNG XoshiroAra32R = new RNG(XoshiroAra32); @Benchmark public long measureXoshiroAra32() { return XoshiroAra32.nextLong(); } @Benchmark public int measureXoshiroAra32Int() { return XoshiroAra32.next(32); } @Benchmark public long measureXoshiroAra32R() { return XoshiroAra32R.nextLong(); } @Benchmark public int measureXoshiroAra32IntR() { return XoshiroAra32R.nextInt(); } private DervishRNG Dervish = new DervishRNG(9999L); private RNG DervishR = new RNG(Dervish); @Benchmark public long measureDervish() { return Dervish.nextLong(); } @Benchmark public int measureDervishInt() { return Dervish.next(32); } @Benchmark public long measureDervishR() { return DervishR.nextLong(); } @Benchmark public int measureDervishIntR() { return DervishR.nextInt(); } private LinnormRNG Linnorm = new LinnormRNG(9999L); private RNG LinnormR = new RNG(Linnorm); @Benchmark public long measureLinnorm() { return Linnorm.nextLong(); } @Benchmark public int measureLinnormInt() { return Linnorm.next(32); } @Benchmark public long measureLinnormR() { return LinnormR.nextLong(); } @Benchmark public int measureLinnormIntR() { return LinnormR.nextInt(); } private MizuchiRNG Mizuchi = new MizuchiRNG(9999L); private RNG MizuchiR = new RNG(Mizuchi); @Benchmark public long measureMizuchi() { return Mizuchi.nextLong(); } @Benchmark public int measureMizuchiInt() { return Mizuchi.next(32); } @Benchmark public long measureMizuchiR() { return MizuchiR.nextLong(); } @Benchmark public int measureMizuchiIntR() { return MizuchiR.nextInt(); } private QuixoticRNG Quixotic = new QuixoticRNG(9999L); private RNG QuixoticR = new RNG(Quixotic); @Benchmark public long measureQuixotic() { return Quixotic.nextLong(); } @Benchmark public int measureQuixoticInt() { return Quixotic.next(32); } @Benchmark public long measureQuixoticR() { return QuixoticR.nextLong(); } @Benchmark public int measureQuixoticIntR() { return QuixoticR.nextInt(); } private IsaacRNG Isaac = new IsaacRNG(9999L); private RNG IsaacR = new RNG(Isaac); @Benchmark public long measureIsaac() { return Isaac.nextLong(); } @Benchmark public long measureIsaacInt() { return Isaac.next(32); } @Benchmark public long measureIsaacR() { return IsaacR.nextLong(); } @Benchmark public long measureIsaacIntR() { return IsaacR.nextInt(); } private Isaac32RNG Isaac32 = new Isaac32RNG(9999L); private RNG Isaac32R = new RNG(Isaac32); @Benchmark public long measureIsaac32() { return Isaac32.nextLong(); } @Benchmark public long measureIsaac32Int() { return Isaac32.next(32); } @Benchmark public long measureIsaac32R() { return Isaac32R.nextLong(); } @Benchmark public long measureIsaac32IntR() { return Isaac32R.nextInt(); } /* public long doJet() { JetRNG rng = new JetRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJet() { seed = 9000; doJet(); } public int doJetInt() { JetRNG rng = new JetRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJetInt() { iseed = 9000; doJetInt(); } public long doJetR() { RNG rng = new RNG(new JetRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJetR() { seed = 9000; doJetR(); } public int doJetIntR() { RNG rng = new RNG(new JetRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureJetIntR() { iseed = 9000; doJetIntR(); } public long doLunge32() { Lunge32RNG rng = new Lunge32RNG(iseed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32() { seed = 9000; doLunge32(); } public int doLunge32Int() { Lunge32RNG rng = new Lunge32RNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32Int() { iseed = 9000; doLunge32Int(); } public long doLunge32R() { RNG rng = new RNG(new Lunge32RNG(iseed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32R() { seed = 9000; doLunge32R(); } public int doLunge32IntR() { RNG rng = new RNG(new Lunge32RNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureLunge32IntR() { iseed = 9000; doLunge32IntR(); } @Benchmark @Warmup(iterations = 10) @Measurement(iterations = 8) @Fork(1) public void a________measureThrustAltDetermine() { seed = 9000; long state = 9000L; for (int i = 0; i < 1000000007; i++) { seed += ThrustAltRNG.determine(++state); } } // // Performs rather poorly, surprisingly. JIT needs method calls rather than inlined code, it looks like. // @Benchmark // @Warmup(iterations = 10) @Measurement(iterations = 8) @Fork(1) // public void a________measureDetermineBare() { // seed = 9000; // long running = seed, state = 9000L; // for (int i = 0; i < 1000000007; i++) { // seed += ((state = ((running += 0x6C8E9CF570932BD5L) ^ (state >>> 25)) * (state | 0xA529L)) ^ (state >>> 22)); // } // } @Benchmark @Warmup(iterations = 10) @Measurement(iterations = 8) @Fork(1) public void a________measureRandomness() { seed = 9000; ThrustAltRNG rng = new ThrustAltRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } } */ // public long doVortex() // { // VortexRNG rng = new VortexRNG(seed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortex() { // seed = 9000; // doVortex(); // } // // public int doVortexInt() // { // VortexRNG rng = new VortexRNG(iseed); // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortexInt() { // iseed = 9000; // doVortexInt(); // } // public long doVortexR() // { // RNG rng = new RNG(new VortexRNG(seed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortexR() { // seed = 9000; // doVortexR(); // } // // public int doVortexIntR() // { // RNG rng = new RNG(new VortexRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a________measureVortexIntR() { // iseed = 9000; // doVortexIntR(); // } // public long doSquirrel() // { // SquirrelRNG rng = new SquirrelRNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrel() throws InterruptedException { // seed = 9000; // doSquirrel(); // } // // public int doSquirrelInt() // { // SquirrelRNG rng = new SquirrelRNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrelInt() throws InterruptedException { // iseed = 9000; // doSquirrelInt(); // } // // public long doSquirrelR() // { // RNG rng = new RNG(new SquirrelRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrelR() throws InterruptedException { // seed = 9000; // doSquirrelR(); // } // // public int doSquirrelIntR() // { // RNG rng = new RNG(new SquirrelRNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measureSquirrelIntR() throws InterruptedException { // iseed = 9000; // doSquirrelIntR(); // } // public long doRule90() // { // Rule90RNG rng = new Rule90RNG(seed); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90() throws InterruptedException { // seed = 9000; // doRule90(); // } // // public int doRule90Int() // { // Rule90RNG rng = new Rule90RNG(iseed); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.next(32); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90Int() throws InterruptedException { // iseed = 9000; // doRule90Int(); // } // // public long doRule90R() // { // RNG rng = new RNG(new Rule90RNG(seed)); // // for (int i = 0; i < 1000000007; i++) { // seed += rng.nextLong(); // } // return seed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90R() throws InterruptedException { // seed = 9000; // doRule90R(); // } // // public int doRule90IntR() // { // RNG rng = new RNG(new Rule90RNG(iseed)); // // for (int i = 0; i < 1000000007; i++) { // iseed += rng.nextInt(); // } // return iseed; // } // // @Benchmark // // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) // public void a__measure90IntR() throws InterruptedException { // iseed = 9000; // doRule90IntR(); // } /* public long doZap() { ZapRNG rng = new ZapRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZap() throws InterruptedException { seed = 9000; doZap(); } public int doZapInt() { ZapRNG rng = new ZapRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZapInt() throws InterruptedException { iseed = 9000; doZapInt(); } public long doZapR() { RNG rng = new RNG(new ZapRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZapR() throws InterruptedException { seed = 9000; doZapR(); } public int doZapIntR() { RNG rng = new RNG(new ZapRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measureZapIntR() throws InterruptedException { iseed = 9000; doZapIntR(); } public long doSlap() { SlapRNG rng = new SlapRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlap() throws InterruptedException { seed = 9000; doSlap(); } public int doSlapInt() { SlapRNG rng = new SlapRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlapInt() throws InterruptedException { iseed = 9000; doSlapInt(); } public long doSlapR() { RNG rng = new RNG(new SlapRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlapR() throws InterruptedException { seed = 9000; doSlapR(); } public int doSlapIntR() { RNG rng = new RNG(new SlapRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void measureSlapIntR() throws InterruptedException { iseed = 9000; doSlapIntR(); } */ /* public long doPlaceholder() { PlaceholderRNG rng = new PlaceholderRNG(seed); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholder() throws InterruptedException { seed = 9000; doPlaceholder(); } public int doPlaceholderInt() { PlaceholderRNG rng = new PlaceholderRNG(iseed); for (int i = 0; i < 1000000007; i++) { iseed += rng.next(32); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholderInt() throws InterruptedException { iseed = 9000; doPlaceholderInt(); } public long doPlaceholderR() { RNG rng = new RNG(new PlaceholderRNG(seed)); for (int i = 0; i < 1000000007; i++) { seed += rng.nextLong(); } return seed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholderR() throws InterruptedException { seed = 9000; doPlaceholderR(); } public int doPlaceholderIntR() { RNG rng = new RNG(new PlaceholderRNG(iseed)); for (int i = 0; i < 1000000007; i++) { iseed += rng.nextInt(); } return iseed; } @Benchmark // @Warmup(iterations = 4) @Measurement(iterations = 4) @Fork(1) public void aa_measurePlaceholderIntR() throws InterruptedException { iseed = 9000; doPlaceholderIntR(); } */ private Random JDK = new Random(9999L); @Benchmark public long measureJDK() { return JDK.nextLong(); } @Benchmark public int measureJDKInt() { return JDK.nextInt(); } /* mvn clean install java -jar target/benchmarks.jar RNGBenchmark -wi 5 -i 5 -f 1 -gc true */ public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(RNGBenchmark.class.getSimpleName()) .timeout(TimeValue.seconds(30)) .warmupIterations(5) .measurementIterations(5) .forks(1) .build(); new Runner(opt).run(); } }
Add huge 3-hour+ benchmark results
sarong-benchmarks/src/main/java/sarong/RNGBenchmark.java
Add huge 3-hour+ benchmark results
<ide><path>arong-benchmarks/src/main/java/sarong/RNGBenchmark.java <ide> import java.util.concurrent.TimeUnit; <ide> <ide> /** <del> * Results: <add> * Results for all benchmarks on an i7-8750H CPU clocked at 2.20GHz : <ide> * <br> <ide> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureAltThrustDetermine avgt 5 3.887 ± 0.055 ns/op <del> * RNGBenchmark.measureAltThrustRandomize avgt 5 3.532 ± 0.035 ns/op <del> * RNGBenchmark.measureFlap avgt 5 3.938 ± 0.024 ns/op <del> * RNGBenchmark.measureFlapInt avgt 5 3.491 ± 0.047 ns/op <del> * RNGBenchmark.measureFlapIntR avgt 5 3.951 ± 0.028 ns/op <del> * RNGBenchmark.measureFlapR avgt 5 4.511 ± 0.038 ns/op <del> * RNGBenchmark.measureInlineJab63 avgt 5 3.194 ± 0.032 ns/op :) best speed, not well-distributed <del> * RNGBenchmark.measureInlineThrust avgt 5 3.354 ± 0.026 ns/op <del> * RNGBenchmark.measureInlineThrustAlt avgt 5 3.532 ± 0.033 ns/op <del> * RNGBenchmark.measureInlineThrustAltOther avgt 5 3.527 ± 0.039 ns/op <del> * RNGBenchmark.measureInlineVortex avgt 5 3.622 ± 0.046 ns/op <del> * RNGBenchmark.measureJDK avgt 5 24.726 ± 0.174 ns/op :( worst speed <del> * RNGBenchmark.measureJDKInt avgt 5 12.352 ± 0.057 ns/op <del> * RNGBenchmark.measureJab63 avgt 5 3.373 ± 0.016 ns/op <del> * RNGBenchmark.measureJab63Int avgt 5 3.566 ± 0.033 ns/op <del> * RNGBenchmark.measureJab63IntR avgt 5 4.069 ± 0.037 ns/op <del> * RNGBenchmark.measureJab63R avgt 5 3.756 ± 0.045 ns/op <del> * RNGBenchmark.measureLap avgt 5 3.367 ± 0.028 ns/op <del> * RNGBenchmark.measureLapInt avgt 5 3.674 ± 0.079 ns/op <del> * RNGBenchmark.measureLapIntR avgt 5 4.128 ± 0.038 ns/op <del> * RNGBenchmark.measureLapR avgt 5 3.870 ± 0.019 ns/op <del> * RNGBenchmark.measureLight avgt 5 3.978 ± 0.034 ns/op <del> * RNGBenchmark.measureLightInt avgt 5 4.340 ± 0.135 ns/op <del> * RNGBenchmark.measureLightIntR avgt 5 4.892 ± 0.026 ns/op <del> * RNGBenchmark.measureLightR avgt 5 4.449 ± 0.027 ns/op <del> * RNGBenchmark.measureLongPeriod avgt 5 4.963 ± 0.058 ns/op <del> * RNGBenchmark.measureLongPeriodInt avgt 5 5.276 ± 0.044 ns/op <del> * RNGBenchmark.measureLongPeriodIntR avgt 5 5.947 ± 0.046 ns/op <del> * RNGBenchmark.measureLongPeriodR avgt 5 5.571 ± 0.026 ns/op <del> * RNGBenchmark.measureThrust avgt 5 3.542 ± 0.137 ns/op :? unusual Error result <del> * RNGBenchmark.measureThrustAlt avgt 5 3.541 ± 0.018 ns/op :) best quality/speed/distribution mix <del> * RNGBenchmark.measureThrustAltInt avgt 5 3.746 ± 0.045 ns/op <del> * RNGBenchmark.measureThrustAltIntR avgt 5 4.143 ± 0.019 ns/op <del> * RNGBenchmark.measureThrustAltR avgt 5 3.982 ± 0.184 ns/op <del> * RNGBenchmark.measureThrustInt avgt 5 3.609 ± 0.058 ns/op <del> * RNGBenchmark.measureThrustIntR avgt 5 4.118 ± 0.010 ns/op <del> * RNGBenchmark.measureThrustR avgt 5 3.930 ± 0.031 ns/op <del> * RNGBenchmark.measureVortex avgt 5 3.750 ± 0.018 ns/op <del> * RNGBenchmark.measureVortexDetermine avgt 5 4.595 ± 0.053 ns/op <del> * RNGBenchmark.measureVortexDetermineBare avgt 5 3.627 ± 0.071 ns/op <del> * RNGBenchmark.measureVortexInt avgt 5 4.075 ± 0.039 ns/op <del> * RNGBenchmark.measureVortexIntR avgt 5 4.831 ± 0.047 ns/op <del> * RNGBenchmark.measureVortexR avgt 5 4.298 ± 0.070 ns/op <del> * RNGBenchmark.measureXoRo avgt 5 3.890 ± 0.016 ns/op <del> * RNGBenchmark.measureXoRoInt avgt 5 4.206 ± 0.049 ns/op <del> * RNGBenchmark.measureXoRoIntR avgt 5 4.674 ± 0.069 ns/op <del> * RNGBenchmark.measureXoRoR avgt 5 4.206 ± 0.053 ns/op <add> * Benchmark Mode Cnt Score Error Units <add> * RNGBenchmark.measureAltThrustDetermine avgt 5 2.636 ± 0.006 ns/op <add> * RNGBenchmark.measureBasicRandom32 avgt 5 2.966 ± 0.004 ns/op <add> * RNGBenchmark.measureBasicRandom32Int avgt 5 2.178 ± 0.021 ns/op <add> * RNGBenchmark.measureBasicRandom32IntR avgt 5 2.383 ± 0.027 ns/op <add> * RNGBenchmark.measureBasicRandom32R avgt 5 3.212 ± 0.010 ns/op <add> * RNGBenchmark.measureBasicRandom64 avgt 5 2.549 ± 0.020 ns/op <add> * RNGBenchmark.measureBasicRandom64Int avgt 5 2.660 ± 0.009 ns/op <add> * RNGBenchmark.measureBasicRandom64IntR avgt 5 2.896 ± 0.006 ns/op <add> * RNGBenchmark.measureBasicRandom64R avgt 5 2.822 ± 0.015 ns/op <add> * RNGBenchmark.measureChurro32 avgt 5 6.071 ± 0.052 ns/op <add> * RNGBenchmark.measureChurro32Int avgt 5 3.663 ± 0.003 ns/op <add> * RNGBenchmark.measureChurro32IntR avgt 5 4.460 ± 0.021 ns/op <add> * RNGBenchmark.measureChurro32R avgt 5 8.272 ± 0.056 ns/op <add> * RNGBenchmark.measureDervish avgt 5 3.133 ± 0.038 ns/op <add> * RNGBenchmark.measureDervishInt avgt 5 3.248 ± 0.042 ns/op <add> * RNGBenchmark.measureDervishIntR avgt 5 3.588 ± 0.009 ns/op <add> * RNGBenchmark.measureDervishR avgt 5 3.575 ± 0.117 ns/op <add> * RNGBenchmark.measureDirk avgt 5 3.137 ± 0.006 ns/op <add> * RNGBenchmark.measureDirkDetermine avgt 5 3.016 ± 0.011 ns/op <add> * RNGBenchmark.measureDirkInt avgt 5 3.135 ± 0.017 ns/op <add> * RNGBenchmark.measureDirkIntR avgt 5 3.576 ± 0.013 ns/op <add> * RNGBenchmark.measureDirkR avgt 5 3.559 ± 0.022 ns/op <add> * RNGBenchmark.measureDizzy32 avgt 5 5.429 ± 0.066 ns/op <add> * RNGBenchmark.measureDizzy32Int avgt 5 3.382 ± 0.011 ns/op <add> * RNGBenchmark.measureDizzy32IntNative1 avgt 5 3.479 ± 0.029 ns/op <add> * RNGBenchmark.measureDizzy32IntNative2 avgt 5 3.479 ± 0.009 ns/op <add> * RNGBenchmark.measureDizzy32IntR avgt 5 3.949 ± 0.037 ns/op <add> * RNGBenchmark.measureDizzy32R avgt 5 6.154 ± 0.076 ns/op <add> * RNGBenchmark.measureFlap avgt 5 2.857 ± 0.014 ns/op <add> * RNGBenchmark.measureFlapInt avgt 5 2.380 ± 0.038 ns/op <add> * RNGBenchmark.measureFlapIntR avgt 5 2.703 ± 0.052 ns/op <add> * RNGBenchmark.measureFlapR avgt 5 3.210 ± 0.018 ns/op <add> * RNGBenchmark.measureGWT avgt 5 4.293 ± 0.026 ns/op <add> * RNGBenchmark.measureGWTInt avgt 5 2.918 ± 0.040 ns/op <add> * RNGBenchmark.measureGWTNextInt avgt 5 2.914 ± 0.020 ns/op <add> * RNGBenchmark.measureIsaac avgt 5 5.141 ± 0.012 ns/op <add> * RNGBenchmark.measureIsaac32 avgt 5 8.779 ± 0.069 ns/op <add> * RNGBenchmark.measureIsaac32Int avgt 5 5.242 ± 0.021 ns/op <add> * RNGBenchmark.measureIsaac32IntR avgt 5 5.682 ± 0.018 ns/op <add> * RNGBenchmark.measureIsaac32R avgt 5 9.753 ± 0.066 ns/op <add> * RNGBenchmark.measureIsaacInt avgt 5 5.229 ± 0.037 ns/op <add> * RNGBenchmark.measureIsaacIntR avgt 5 5.590 ± 0.064 ns/op <add> * RNGBenchmark.measureIsaacR avgt 5 5.540 ± 0.190 ns/op <add> * RNGBenchmark.measureJDK avgt 5 17.561 ± 0.054 ns/op <add> * RNGBenchmark.measureJDKInt avgt 5 8.767 ± 0.052 ns/op <add> * RNGBenchmark.measureJab63 avgt 5 2.397 ± 0.011 ns/op <add> * RNGBenchmark.measureJab63Int avgt 5 2.512 ± 0.013 ns/op <add> * RNGBenchmark.measureJab63IntR avgt 5 2.761 ± 0.043 ns/op <add> * RNGBenchmark.measureJab63R avgt 5 2.691 ± 0.030 ns/op <add> * RNGBenchmark.measureLap avgt 5 2.415 ± 0.027 ns/op <add> * RNGBenchmark.measureLapInt avgt 5 2.530 ± 0.024 ns/op <add> * RNGBenchmark.measureLapIntR avgt 5 2.892 ± 0.065 ns/op <add> * RNGBenchmark.measureLapR avgt 5 2.761 ± 0.013 ns/op <add> * RNGBenchmark.measureLathe32 avgt 5 4.296 ± 0.005 ns/op <add> * RNGBenchmark.measureLathe32Int avgt 5 2.915 ± 0.022 ns/op <add> * RNGBenchmark.measureLathe32IntR avgt 5 3.244 ± 0.070 ns/op <add> * RNGBenchmark.measureLathe32R avgt 5 4.873 ± 0.028 ns/op <add> * RNGBenchmark.measureLathe64 avgt 5 2.917 ± 0.028 ns/op <add> * RNGBenchmark.measureLathe64Int avgt 5 3.021 ± 0.036 ns/op <add> * RNGBenchmark.measureLathe64IntR avgt 5 3.432 ± 0.011 ns/op <add> * RNGBenchmark.measureLathe64R avgt 5 3.192 ± 0.008 ns/op <add> * RNGBenchmark.measureLight avgt 5 2.826 ± 0.017 ns/op <add> * RNGBenchmark.measureLight32 avgt 5 4.672 ± 0.038 ns/op <add> * RNGBenchmark.measureLight32Int avgt 5 2.881 ± 0.665 ns/op <add> * RNGBenchmark.measureLight32IntR avgt 5 3.280 ± 0.640 ns/op <add> * RNGBenchmark.measureLight32R avgt 5 5.463 ± 0.008 ns/op <add> * RNGBenchmark.measureLightDetermine avgt 5 2.805 ± 0.007 ns/op <add> * RNGBenchmark.measureLightInt avgt 5 2.830 ± 0.007 ns/op <add> * RNGBenchmark.measureLightIntR avgt 5 3.192 ± 0.032 ns/op <add> * RNGBenchmark.measureLightR avgt 5 3.151 ± 0.027 ns/op <add> * RNGBenchmark.measureLinnorm avgt 5 2.620 ± 0.026 ns/op <add> * RNGBenchmark.measureLinnormDetermine avgt 5 2.770 ± 0.019 ns/op <add> * RNGBenchmark.measureLinnormInt avgt 5 2.665 ± 0.018 ns/op <add> * RNGBenchmark.measureLinnormIntR avgt 5 2.875 ± 0.009 ns/op <add> * RNGBenchmark.measureLinnormR avgt 5 2.989 ± 0.014 ns/op <add> * RNGBenchmark.measureLobster32 avgt 5 4.654 ± 0.178 ns/op <add> * RNGBenchmark.measureLobster32Int avgt 5 3.039 ± 0.026 ns/op <add> * RNGBenchmark.measureLobster32IntR avgt 5 3.346 ± 0.029 ns/op <add> * RNGBenchmark.measureLobster32R avgt 5 5.140 ± 0.025 ns/op <add> * RNGBenchmark.measureLongPeriod avgt 5 3.530 ± 0.011 ns/op <add> * RNGBenchmark.measureLongPeriodInt avgt 5 3.607 ± 0.031 ns/op <add> * RNGBenchmark.measureLongPeriodIntR avgt 5 4.095 ± 0.018 ns/op <add> * RNGBenchmark.measureLongPeriodR avgt 5 3.955 ± 0.038 ns/op <add> * RNGBenchmark.measureMesh avgt 5 3.298 ± 0.022 ns/op <add> * RNGBenchmark.measureMeshInt avgt 5 3.243 ± 0.008 ns/op <add> * RNGBenchmark.measureMeshIntR avgt 5 3.718 ± 0.068 ns/op <add> * RNGBenchmark.measureMeshR avgt 5 3.701 ± 0.010 ns/op <add> * RNGBenchmark.measureMiniMover64 avgt 5 2.398 ± 0.006 ns/op <add> * RNGBenchmark.measureMiniMover64Int avgt 5 2.447 ± 0.010 ns/op <add> * RNGBenchmark.measureMiniMover64IntR avgt 5 2.635 ± 0.017 ns/op <add> * RNGBenchmark.measureMiniMover64R avgt 5 2.634 ± 0.020 ns/op <add> * RNGBenchmark.measureMizuchi avgt 5 2.673 ± 0.019 ns/op <add> * RNGBenchmark.measureMizuchiInt avgt 5 2.704 ± 0.012 ns/op <add> * RNGBenchmark.measureMizuchiIntR avgt 5 2.939 ± 0.010 ns/op <add> * RNGBenchmark.measureMizuchiR avgt 5 3.008 ± 0.042 ns/op <add> * RNGBenchmark.measureMolerat32 avgt 5 5.033 ± 0.040 ns/op <add> * RNGBenchmark.measureMolerat32Int avgt 5 3.050 ± 0.009 ns/op <add> * RNGBenchmark.measureMolerat32IntR avgt 5 3.480 ± 0.012 ns/op <add> * RNGBenchmark.measureMolerat32R avgt 5 5.426 ± 0.010 ns/op <add> * RNGBenchmark.measureMotor avgt 5 3.768 ± 0.023 ns/op <add> * RNGBenchmark.measureMotorInt avgt 5 3.701 ± 0.007 ns/op <add> * RNGBenchmark.measureMotorIntR avgt 5 4.201 ± 0.012 ns/op <add> * RNGBenchmark.measureMotorR avgt 5 4.098 ± 0.006 ns/op <add> * RNGBenchmark.measureMover32 avgt 5 3.822 ± 0.015 ns/op <add> * RNGBenchmark.measureMover32Int avgt 5 2.621 ± 0.013 ns/op <add> * RNGBenchmark.measureMover32IntR avgt 5 2.775 ± 0.032 ns/op <add> * RNGBenchmark.measureMover32R avgt 5 4.209 ± 0.063 ns/op <add> * RNGBenchmark.measureMover64 avgt 5 2.619 ± 0.025 ns/op <add> * RNGBenchmark.measureMover64Int avgt 5 2.636 ± 0.033 ns/op <add> * RNGBenchmark.measureMover64IntR avgt 5 2.772 ± 0.032 ns/op <add> * RNGBenchmark.measureMover64R avgt 5 2.733 ± 0.169 ns/op <add> * RNGBenchmark.measureMoverCounter64 avgt 5 2.463 ± 0.006 ns/op <add> * RNGBenchmark.measureMoverCounter64Int avgt 5 2.466 ± 0.016 ns/op <add> * RNGBenchmark.measureMoverCounter64IntR avgt 5 2.691 ± 0.017 ns/op <add> * RNGBenchmark.measureMoverCounter64R avgt 5 2.687 ± 0.016 ns/op <add> * RNGBenchmark.measureOrbit avgt 5 2.916 ± 0.012 ns/op <add> * RNGBenchmark.measureOrbitA avgt 5 2.914 ± 0.005 ns/op <add> * RNGBenchmark.measureOrbitB avgt 5 3.027 ± 0.010 ns/op <add> * RNGBenchmark.measureOrbitC avgt 5 3.003 ± 0.021 ns/op <add> * RNGBenchmark.measureOrbitD avgt 5 2.914 ± 0.031 ns/op <add> * RNGBenchmark.measureOrbitE avgt 5 3.260 ± 0.027 ns/op <add> * RNGBenchmark.measureOrbitF avgt 5 2.905 ± 0.026 ns/op <add> * RNGBenchmark.measureOrbitG avgt 5 3.027 ± 0.013 ns/op <add> * RNGBenchmark.measureOrbitH avgt 5 2.905 ± 0.026 ns/op <add> * RNGBenchmark.measureOrbitI avgt 5 3.017 ± 0.012 ns/op <add> * RNGBenchmark.measureOrbitInt avgt 5 3.018 ± 0.017 ns/op <add> * RNGBenchmark.measureOrbitIntR avgt 5 3.357 ± 0.009 ns/op <add> * RNGBenchmark.measureOrbitJ avgt 5 2.781 ± 0.009 ns/op <add> * RNGBenchmark.measureOrbitK avgt 5 2.895 ± 0.011 ns/op <add> * RNGBenchmark.measureOrbitL avgt 5 2.753 ± 0.012 ns/op <add> * RNGBenchmark.measureOrbitM avgt 5 3.141 ± 0.011 ns/op <add> * RNGBenchmark.measureOrbitN avgt 5 3.147 ± 0.022 ns/op <add> * RNGBenchmark.measureOrbitO avgt 5 3.008 ± 0.031 ns/op <add> * RNGBenchmark.measureOrbitR avgt 5 3.297 ± 0.019 ns/op <add> * RNGBenchmark.measureOriole32 avgt 5 4.691 ± 0.005 ns/op <add> * RNGBenchmark.measureOriole32Int avgt 5 3.134 ± 0.040 ns/op <add> * RNGBenchmark.measureOriole32IntR avgt 5 3.522 ± 0.017 ns/op <add> * RNGBenchmark.measureOriole32R avgt 5 5.153 ± 0.070 ns/op <add> * RNGBenchmark.measureOtter32 avgt 5 4.958 ± 0.009 ns/op <add> * RNGBenchmark.measureOtter32Int avgt 5 3.121 ± 0.031 ns/op <add> * RNGBenchmark.measureOtter32IntR avgt 5 3.509 ± 0.020 ns/op <add> * RNGBenchmark.measureOtter32R avgt 5 5.633 ± 0.023 ns/op <add> * RNGBenchmark.measureOverdrive64 avgt 5 2.493 ± 0.022 ns/op <add> * RNGBenchmark.measureOverdrive64Int avgt 5 2.558 ± 0.084 ns/op <add> * RNGBenchmark.measureOverdrive64IntR avgt 5 2.735 ± 0.022 ns/op <add> * RNGBenchmark.measureOverdrive64R avgt 5 2.716 ± 0.025 ns/op <add> * RNGBenchmark.measurePaperweight avgt 5 3.370 ± 0.029 ns/op <add> * RNGBenchmark.measurePaperweightInt avgt 5 3.400 ± 0.019 ns/op <add> * RNGBenchmark.measurePaperweightIntR avgt 5 3.879 ± 0.019 ns/op <add> * RNGBenchmark.measurePaperweightR avgt 5 3.796 ± 0.026 ns/op <add> * RNGBenchmark.measureQuixotic avgt 5 2.608 ± 0.020 ns/op <add> * RNGBenchmark.measureQuixoticInt avgt 5 2.660 ± 0.012 ns/op <add> * RNGBenchmark.measureQuixoticIntR avgt 5 2.923 ± 0.012 ns/op <add> * RNGBenchmark.measureQuixoticR avgt 5 2.892 ± 0.023 ns/op <add> * RNGBenchmark.measureSFC64 avgt 5 3.214 ± 0.011 ns/op <add> * RNGBenchmark.measureSFC64Int avgt 5 3.307 ± 0.025 ns/op <add> * RNGBenchmark.measureSFC64IntR avgt 5 3.725 ± 0.023 ns/op <add> * RNGBenchmark.measureSFC64R avgt 5 3.909 ± 0.156 ns/op <add> * RNGBenchmark.measureSeaSlater32 avgt 5 4.992 ± 0.110 ns/op <add> * RNGBenchmark.measureSeaSlater32Int avgt 5 3.063 ± 0.011 ns/op <add> * RNGBenchmark.measureSeaSlater32IntR avgt 5 3.430 ± 0.026 ns/op <add> * RNGBenchmark.measureSeaSlater32R avgt 5 5.585 ± 0.100 ns/op <add> * RNGBenchmark.measureSeaSlater64 avgt 5 3.074 ± 0.039 ns/op <add> * RNGBenchmark.measureSeaSlater64Int avgt 5 3.161 ± 0.009 ns/op <add> * RNGBenchmark.measureSeaSlater64IntR avgt 5 3.544 ± 0.058 ns/op <add> * RNGBenchmark.measureSeaSlater64R avgt 5 3.457 ± 0.075 ns/op <add> * RNGBenchmark.measureSpiral avgt 5 3.471 ± 0.031 ns/op <add> * RNGBenchmark.measureSpiralA avgt 5 3.475 ± 0.025 ns/op <add> * RNGBenchmark.measureSpiralB avgt 5 3.159 ± 0.008 ns/op <add> * RNGBenchmark.measureSpiralC avgt 5 3.290 ± 0.011 ns/op <add> * RNGBenchmark.measureSpiralD avgt 5 3.203 ± 0.073 ns/op <add> * RNGBenchmark.measureSpiralE avgt 5 3.223 ± 0.010 ns/op <add> * RNGBenchmark.measureSpiralF avgt 5 3.001 ± 0.029 ns/op <add> * RNGBenchmark.measureSpiralG avgt 5 3.082 ± 0.062 ns/op <add> * RNGBenchmark.measureSpiralH avgt 5 3.169 ± 0.031 ns/op <add> * RNGBenchmark.measureSpiralI avgt 5 2.669 ± 0.034 ns/op <add> * RNGBenchmark.measureSpiralInt avgt 5 3.513 ± 0.050 ns/op <add> * RNGBenchmark.measureSpiralIntR avgt 5 4.234 ± 0.010 ns/op <add> * RNGBenchmark.measureSpiralR avgt 5 3.991 ± 0.037 ns/op <add> * RNGBenchmark.measureStarfish32 avgt 5 4.449 ± 0.056 ns/op <add> * RNGBenchmark.measureStarfish32Int avgt 5 3.016 ± 0.017 ns/op <add> * RNGBenchmark.measureStarfish32IntR avgt 5 3.208 ± 0.014 ns/op <add> * RNGBenchmark.measureStarfish32NextInt avgt 5 2.997 ± 0.052 ns/op <add> * RNGBenchmark.measureStarfish32R avgt 5 5.013 ± 0.157 ns/op <add> * RNGBenchmark.measureTangle avgt 5 2.572 ± 0.029 ns/op <add> * RNGBenchmark.measureTangleA avgt 5 2.582 ± 0.008 ns/op <add> * RNGBenchmark.measureTangleB avgt 5 2.734 ± 0.004 ns/op <add> * RNGBenchmark.measureTangleC avgt 5 2.762 ± 0.018 ns/op <add> * RNGBenchmark.measureTangleD avgt 5 2.838 ± 0.015 ns/op <add> * RNGBenchmark.measureTangleInt avgt 5 2.651 ± 0.008 ns/op <add> * RNGBenchmark.measureTangleIntR avgt 5 2.978 ± 0.039 ns/op <add> * RNGBenchmark.measureTangleR avgt 5 2.963 ± 0.009 ns/op <add> * RNGBenchmark.measureThrust avgt 5 2.508 ± 0.024 ns/op <add> * RNGBenchmark.measureThrustAlt avgt 5 2.516 ± 0.012 ns/op <add> * RNGBenchmark.measureThrustAlt32 avgt 5 4.363 ± 0.009 ns/op <add> * RNGBenchmark.measureThrustAlt32Int avgt 5 2.792 ± 0.009 ns/op <add> * RNGBenchmark.measureThrustAlt32IntR avgt 5 3.151 ± 0.020 ns/op <add> * RNGBenchmark.measureThrustAlt32R avgt 5 5.111 ± 0.150 ns/op <add> * RNGBenchmark.measureThrustAltInt avgt 5 2.522 ± 0.006 ns/op <add> * RNGBenchmark.measureThrustAltIntR avgt 5 2.811 ± 0.009 ns/op <add> * RNGBenchmark.measureThrustAltR avgt 5 2.823 ± 0.066 ns/op <add> * RNGBenchmark.measureThrustInt avgt 5 2.511 ± 0.010 ns/op <add> * RNGBenchmark.measureThrustIntR avgt 5 2.790 ± 0.038 ns/op <add> * RNGBenchmark.measureThrustR avgt 5 2.791 ± 0.011 ns/op <add> * RNGBenchmark.measureThunder avgt 5 2.653 ± 0.035 ns/op <add> * RNGBenchmark.measureThunderInt avgt 5 2.761 ± 0.022 ns/op <add> * RNGBenchmark.measureThunderIntR avgt 5 3.023 ± 0.015 ns/op <add> * RNGBenchmark.measureThunderR avgt 5 2.984 ± 0.015 ns/op <add> * RNGBenchmark.measureVortex avgt 5 2.928 ± 0.003 ns/op <add> * RNGBenchmark.measureVortexInt avgt 5 3.026 ± 0.028 ns/op <add> * RNGBenchmark.measureVortexIntR avgt 5 3.401 ± 0.027 ns/op <add> * RNGBenchmark.measureVortexR avgt 5 3.342 ± 0.104 ns/op <add> * RNGBenchmark.measureXoRo avgt 5 2.763 ± 0.011 ns/op <add> * RNGBenchmark.measureXoRo32 avgt 5 3.785 ± 0.007 ns/op <add> * RNGBenchmark.measureXoRo32Int avgt 5 2.770 ± 0.030 ns/op <add> * RNGBenchmark.measureXoRo32IntR avgt 5 3.114 ± 0.050 ns/op <add> * RNGBenchmark.measureXoRo32R avgt 5 4.409 ± 0.012 ns/op <add> * RNGBenchmark.measureXoRoInt avgt 5 2.881 ± 0.025 ns/op <add> * RNGBenchmark.measureXoRoIntR avgt 5 3.129 ± 0.026 ns/op <add> * RNGBenchmark.measureXoRoR avgt 5 2.991 ± 0.007 ns/op <add> * RNGBenchmark.measureXoshiroAra32 avgt 5 4.929 ± 0.190 ns/op <add> * RNGBenchmark.measureXoshiroAra32Int avgt 5 3.257 ± 0.024 ns/op <add> * RNGBenchmark.measureXoshiroAra32IntR avgt 5 3.675 ± 0.024 ns/op <add> * RNGBenchmark.measureXoshiroAra32R avgt 5 5.349 ± 0.062 ns/op <add> * RNGBenchmark.measureXoshiroStarPhi32 avgt 5 5.117 ± 0.021 ns/op <add> * RNGBenchmark.measureXoshiroStarPhi32Int avgt 5 3.381 ± 0.009 ns/op <add> * RNGBenchmark.measureXoshiroStarPhi32IntR avgt 5 3.767 ± 0.012 ns/op <add> * RNGBenchmark.measureXoshiroStarPhi32R avgt 5 5.477 ± 0.022 ns/op <add> * RNGBenchmark.measureXoshiroStarStar32 avgt 5 5.257 ± 0.070 ns/op <add> * RNGBenchmark.measureXoshiroStarStar32Int avgt 5 3.466 ± 0.046 ns/op <add> * RNGBenchmark.measureXoshiroStarStar32IntR avgt 5 3.836 ± 0.096 ns/op <add> * RNGBenchmark.measureXoshiroStarStar32R avgt 5 5.747 ± 0.016 ns/op <add> * RNGBenchmark.measureXoshiroXara32 avgt 5 5.080 ± 0.014 ns/op <add> * RNGBenchmark.measureXoshiroXara32Int avgt 5 3.319 ± 0.011 ns/op <add> * RNGBenchmark.measureXoshiroXara32IntR avgt 5 3.748 ± 0.064 ns/op <add> * RNGBenchmark.measureXoshiroXara32R avgt 5 5.512 ± 0.149 ns/op <add> * RNGBenchmark.measureZag32 avgt 5 6.304 ± 0.107 ns/op <add> * RNGBenchmark.measureZag32Int avgt 5 3.366 ± 0.011 ns/op <add> * RNGBenchmark.measureZag32IntR avgt 5 3.875 ± 0.107 ns/op <add> * RNGBenchmark.measureZag32R avgt 5 6.411 ± 0.103 ns/op <add> * RNGBenchmark.measureZig32 avgt 5 5.908 ± 0.084 ns/op <add> * RNGBenchmark.measureZig32Int avgt 5 3.498 ± 0.043 ns/op <add> * RNGBenchmark.measureZig32IntR avgt 5 4.031 ± 0.063 ns/op <add> * RNGBenchmark.measureZig32R avgt 5 6.505 ± 0.056 ns/op <add> * RNGBenchmark.measureZog32 avgt 5 5.206 ± 0.076 ns/op <add> * RNGBenchmark.measureZog32Int avgt 5 3.216 ± 0.018 ns/op <add> * RNGBenchmark.measureZog32IntR avgt 5 3.693 ± 0.035 ns/op <add> * RNGBenchmark.measureZog32R avgt 5 5.770 ± 0.020 ns/op <ide> * </pre> <ide> * <br> <del> * ThrustAltRNG is the fastest so far that passes stringent quality tests (no failures with gjrand on many seeds and few <del> * seeds cause severe failures, none systematically; 32TB PractRand testing completed without failure). Jab63, inlined <del> * in particular, is faster and still tests as having high quality, but neither it nor ThrustAltRNG can produce all <del> * possible 64-bit longs. LightRNG passes PractRand but has more frequent issues with gjrand. XoRo fails PractRand <del> * unless you disregard binary matrix rank tests, as the author recommends; because gjrand can't take a test out of <del> * consideration, XoRo probably fails it fully. ThrustRNG does reasonably well on gjrand but fails on PractRand at only <del> * 32GB. VortexRNG does very well on gjrand and passes PractRand at 32TB, but it's also slower than XoRo with a smaller <del> * period on the same state. <del> * <br> <del> * As for the recently-added GWT-friendly generators Zig32RNG, Zag32RNG, Zog32RNG, and XoRo32RNG, the first three all <del> * perform about equally well on GWT and pass PractRand, while XoRo32RNG performs very well on GWT but fails a few tests <del> * in PractRand fairly early on (There are ways to eliminate the statistical quality issues, but they also slow down the <del> * generator significantly). Even though Zig and Zag are similar, Zog32RNG performs quite a bit better on desktop: <del> * <br> <del> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureXoRo32 avgt 5 5.148 ± 0.352 ns/op <del> * RNGBenchmark.measureXoRo32Int avgt 5 3.825 ± 0.427 ns/op <del> * RNGBenchmark.measureXoRo32IntR avgt 5 4.111 ± 0.396 ns/op <del> * RNGBenchmark.measureXoRo32R avgt 5 6.029 ± 1.172 ns/op <del> * RNGBenchmark.measureZag32 avgt 5 7.638 ± 1.260 ns/op <del> * RNGBenchmark.measureZag32Int avgt 5 4.732 ± 0.851 ns/op <del> * RNGBenchmark.measureZag32IntR avgt 5 5.393 ± 0.919 ns/op <del> * RNGBenchmark.measureZag32R avgt 5 8.506 ± 1.333 ns/op <del> * RNGBenchmark.measureZig32 avgt 5 8.167 ± 1.734 ns/op <del> * RNGBenchmark.measureZig32Int avgt 5 4.843 ± 0.582 ns/op <del> * RNGBenchmark.measureZig32IntR avgt 5 5.573 ± 0.647 ns/op <del> * RNGBenchmark.measureZig32R avgt 5 9.015 ± 1.248 ns/op <del> * RNGBenchmark.measureZog32 avgt 5 7.151 ± 1.485 ns/op <del> * RNGBenchmark.measureZog32Int avgt 5 4.488 ± 0.899 ns/op <del> * RNGBenchmark.measureZog32IntR avgt 5 5.248 ± 0.758 ns/op <del> * RNGBenchmark.measureZog32R avgt 5 7.950 ± 1.415 ns/op <del> * </pre> <del> * <del> * Testing the newly-added variants on XoRo32RNG called Oriole32RNG and Lathe32RNG, Lathe is the faster of the two, and <del> * both beat Zog on speed (Oriole very narrowly, Lathe comfortably) while all three have about the same quality. <del> * Lathe, Oriole, and Zog trounce XoRo32 on quality but are still slower than it. Oriole also has the best period of the <del> * group, but isn't a StatefulRandomness, while Lathe has the same period as XoRo32 and is a StatefulRandomness. <del> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureLathe32 avgt 10 5.692 ± 0.054 ns/op <del> * RNGBenchmark.measureLathe32Int avgt 10 3.971 ± 0.022 ns/op <del> * RNGBenchmark.measureLathe32IntR avgt 10 4.684 ± 0.460 ns/op <del> * RNGBenchmark.measureLathe32R avgt 10 6.456 ± 0.109 ns/op <del> * RNGBenchmark.measureOriole32 avgt 10 6.168 ± 0.029 ns/op <del> * RNGBenchmark.measureOriole32Int avgt 10 4.262 ± 0.020 ns/op <del> * RNGBenchmark.measureOriole32IntR avgt 10 4.816 ± 0.038 ns/op <del> * RNGBenchmark.measureOriole32R avgt 10 6.884 ± 0.101 ns/op <del> * RNGBenchmark.measureXoRo32 avgt 10 5.047 ± 0.026 ns/op <del> * RNGBenchmark.measureXoRo32Int avgt 10 3.717 ± 0.022 ns/op <del> * RNGBenchmark.measureXoRo32IntR avgt 10 4.034 ± 0.029 ns/op <del> * RNGBenchmark.measureXoRo32R avgt 10 5.749 ± 0.024 ns/op <del> * RNGBenchmark.measureZog32 avgt 10 6.839 ± 0.029 ns/op <del> * RNGBenchmark.measureZog32Int avgt 10 4.305 ± 0.026 ns/op <del> * RNGBenchmark.measureZog32IntR avgt 10 4.967 ± 0.028 ns/op <del> * RNGBenchmark.measureZog32R avgt 10 7.586 ± 0.065 ns/op <del> * </pre> <del> * <br> <del> * Testing the top 3 contenders among one-dimensionally equidistributed generators (LightRNG and LinnormRNG pass 32TB on <del> * PractRand but XoRoRNG reliably fails one group of tests and sometimes fails others): <del> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureLight avgt 5 3.763 ± 0.204 ns/op <del> * RNGBenchmark.measureLightInt avgt 5 4.047 ± 0.008 ns/op <del> * RNGBenchmark.measureLinnorm avgt 5 3.442 ± 0.018 ns/op <del> * RNGBenchmark.measureLinnormInt avgt 5 3.668 ± 0.010 ns/op <del> * RNGBenchmark.measureXoRo avgt 5 3.656 ± 0.028 ns/op <del> * RNGBenchmark.measureXoRoInt avgt 5 3.941 ± 0.034 ns/op <del> * ...and one result for the non-equidistributed ThrustAltRNG... <del> * RNGBenchmark.measureThrustAlt avgt 5 3.322 ± 0.053 ns/op <del> * </pre> <del> * Linnorm is the new best generator we have, except that it isn't a SkippingRandomness and its period is "just" 2 to <del> * the 64. Every other need seems to be met by its high speed, easily-stored state, unsurpassed statistical quality, and <del> * ability to produce all long values. ThrustAltRNG may be faster, but since it isn't known how many numbers it is <del> * incapable of producing, it probably shouldn't be used for procedural generation. If you need to target GWT, though, <del> * your needs are suddenly completely different... <add> * The fastest generator depends on your target platform, but on a desktop or laptop using an OpenJDK-based Java <add> * installation, Jab63RNG and MiniMover64RNG are virtually tied for first place. Neither is at all equidistributed; for <add> * generators that are capable of producing all outputs with equal likelihood, LinnormRNG, MizuchiRNG, and QuixoticRNG <add> * are all about the same, with DiverRNG probably a little faster (but it was added after this benchmark was run, so its <add> * results wouldn't be from the same circumstances). DiverRNG and possibly QuixoticRNG are likely to have higher quality <add> * than LinnormRNG and MizuchiRNG, since the last two fail one PractRand test after 16TB while at least DiverRNG does <add> * not have that issue. <ide> * <br> <ide> * GWT-compatible generators need to work with an "int" type that isn't equivalent to Java's "int" and is closer to a <ide> * Java "double" that gets cast to an int when bitwise operations are used on it. This JS int is about 10x-20x faster to <ide> * overflow, and about precision loss if you do exceed those limits severely, since JS numbers are floating-point. So, <ide> * you can't safely multiply by too large of an int (I limit my multipliers to 20 bits), you need to follow up normal <ide> * math with bitwise math to bring any overflowing numbers back to the 32-bit range, and you should avoid longs and math <del> * on them whenever possible. So here's some GWT-safe generators, measured on a desktop JDK: <del> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureDizzy32 avgt 3 7.742 ± 0.144 ns/op // 1D equidistribution <del> * RNGBenchmark.measureDizzy32Int avgt 3 5.094 ± 0.084 ns/op // 2D equidistribution <del> * RNGBenchmark.measureDizzy32IntR avgt 3 5.826 ± 0.113 ns/op // 2D equidistribution <del> * RNGBenchmark.measureDizzy32R avgt 3 8.636 ± 0.079 ns/op // 1D equidistribution <del> * RNGBenchmark.measureLathe32 avgt 3 6.181 ± 0.159 ns/op // no equidistribution <del> * RNGBenchmark.measureLathe32Int avgt 3 4.409 ± 0.024 ns/op // 1D equidistribution <del> * RNGBenchmark.measureLathe32IntR avgt 3 4.791 ± 0.242 ns/op // 1D equidistribution <del> * RNGBenchmark.measureLathe32R avgt 3 7.147 ± 0.013 ns/op // no equidistribution <del> * RNGBenchmark.measureOriole32 avgt 3 6.578 ± 0.058 ns/op // no equidstribution <del> * RNGBenchmark.measureOriole32Int avgt 3 4.640 ± 0.118 ns/op // 1D equidistribution <del> * RNGBenchmark.measureOriole32IntR avgt 3 5.352 ± 0.098 ns/op // 1D equidistribution <del> * RNGBenchmark.measureOriole32R avgt 3 7.729 ± 0.127 ns/op // no equidistribution <del> * RNGBenchmark.measureXoshiroAra32 avgt 3 7.175 ± 0.696 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroAra32Int avgt 3 4.953 ± 0.132 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroAra32IntR avgt 3 5.513 ± 0.227 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroAra32R avgt 3 7.770 ± 0.215 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroStarPhi32 avgt 3 7.294 ± 0.386 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroStarPhi32Int avgt 3 5.032 ± 0.045 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroStarPhi32IntR avgt 3 5.618 ± 0.064 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroStarPhi32R avgt 3 8.017 ± 0.202 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroStarStar32 avgt 3 7.690 ± 0.127 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroStarStar32Int avgt 3 5.210 ± 0.102 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroStarStar32IntR avgt 3 5.856 ± 0.291 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroStarStar32R avgt 3 8.475 ± 0.266 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroXara32 avgt 3 7.309 ± 0.083 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroXara32Int avgt 3 5.027 ± 0.139 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroXara32IntR avgt 3 5.567 ± 0.186 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroXara32R avgt 3 8.075 ± 0.131 ns/op // 2D equidistribution <del> * </pre> <del> * And here's some of the best GWT-safe generators compared against each other, including the new Starfish generator <del> * (these benchmarks were performed while a multi-threaded test was also running, so they are slower): <del> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureLathe32 avgt 3 8.073 ± 0.388 ns/op // no equidistribution <del> * RNGBenchmark.measureLathe32Int avgt 3 5.780 ± 0.976 ns/op // 1D equidistribution <del> * RNGBenchmark.measureLathe32IntR avgt 3 6.358 ± 0.823 ns/op // 1D equidistribution <del> * RNGBenchmark.measureLathe32R avgt 3 9.102 ± 1.079 ns/op // no equidistribution <del> * RNGBenchmark.measureStarfish32 avgt 3 8.285 ± 0.439 ns/op // 1D equidistribution <del> * RNGBenchmark.measureStarfish32Int avgt 3 5.866 ± 0.699 ns/op // 2D equidistribution <del> * RNGBenchmark.measureStarfish32IntR avgt 3 6.448 ± 1.158 ns/op // 2D equidistribution <del> * RNGBenchmark.measureStarfish32R avgt 3 9.297 ± 1.122 ns/op // 1D equidistribution <del> * RNGBenchmark.measureXoshiroAra32 avgt 3 9.048 ± 1.296 ns/op // 2D equidistribution <del> * RNGBenchmark.measureXoshiroAra32Int avgt 3 6.440 ± 0.188 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroAra32IntR avgt 3 7.181 ± 0.497 ns/op // 4D equidistribution <del> * RNGBenchmark.measureXoshiroAra32R avgt 3 9.879 ± 1.205 ns/op // 2D equidistribution <del> * </pre> <del> * And testing (under load, again) Starfish vs. the newer Otter generator; Otter tends to be faster on GWT because <del> * multiplication isn't as fast in browsers, but it is a little slower on desktop. <del> * <pre> <del> * Benchmark Mode Cnt Score Error Units <del> * RNGBenchmark.measureLathe32 avgt 3 6.328 ± 0.568 ns/op <del> * RNGBenchmark.measureLathe32Int avgt 3 4.455 ± 0.165 ns/op <del> * RNGBenchmark.measureLobster32 avgt 3 6.793 ± 0.461 ns/op <del> * RNGBenchmark.measureLobster32Int avgt 3 4.601 ± 0.056 ns/op <del> * RNGBenchmark.measureStarfish32 avgt 3 6.503 ± 0.109 ns/op <del> * RNGBenchmark.measureStarfish32Int avgt 3 4.505 ± 1.135 ns/op <del> * </pre> <add> * on them whenever possible. The GWT-safe generators are in the bulk results above; the ones that are GWT-safe are (an <add> * asterisk marks a generator that doesn't pass many statistical tests): Churro32RNG, Dizzy32RNG, Lathe32RNG, <add> * Lobster32RNG, Molerat32RNG, Mover32RNG, Oriole32RNG, SeaSlater32RNG*, Starfish32RNG, XoRo32RNG*, XoshiroAra32RNG, <add> * XoshiroStarPhi32RNG, XoshiroStarStar32RNG, XoshiroXara32RNG, Zag32RNG, Zig32RNG, and Zog32RNG. GWTRNG is a special <add> * case because it uses Starfish32RNG's algorithm verbatim, but implements IRNG instead of just RandomnessSource and so <add> * has some extra optimizations it can use when producing 32-bit values. Starfish32RNG and all of the Xoshiro-based <add> * generators are probably the best choices for 32-bit generators, with Starfish having a smaller and possibly more <add> * manageable state size, and Xoshiro variants having much longer periods. <add> * <br> <ide> * You can benchmark most of these in GWT for yourself on <ide> * <a href="https://tommyettinger.github.io/SquidLib-Demos/bench/rng/">this SquidLib-Demos page</a>; comparing "runs" <ide> * where higher is better is a good way of estimating how fast a generator is. Each "run" is 10,000 generated numbers.
Java
apache-2.0
11a8aa577c4eed28f5e8bcc22bef4d93d483c390
0
retz/retz,retz/retz,retz/retz,retz/retz
/** * Retz * Copyright (C) 2016-2017 Nautilus Technologies, 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 io.github.retz.web; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import feign.FeignException; import io.github.retz.auth.AuthHeader; import io.github.retz.auth.Authenticator; import io.github.retz.cli.TimestampHelper; import io.github.retz.protocol.*; import io.github.retz.protocol.data.Application; import io.github.retz.protocol.data.Job; import io.github.retz.protocol.exception.UnknownServerResponseException; import io.github.retz.web.feign.Retz; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; public class Client implements AutoCloseable { public static final String VERSION_STRING; private static final ObjectMapper MAPPER = new ObjectMapper(); static final Logger LOG = LoggerFactory.getLogger(Client.class); static { ResourceBundle labels = ResourceBundle.getBundle("retz-client"); VERSION_STRING = labels.getString("version"); MAPPER.registerModule(new Jdk8Module()); } private final Retz retz; private boolean verboseLog = false; private URI uri; private Authenticator authenticator; private SSLSocketFactory socketFactory; private HostnameVerifier hostnameVerifier; private boolean checkCert = true; protected Client(URI uri, Authenticator authenticator) { this(uri, authenticator, true); } protected Client(URI uri, Authenticator authenticator, boolean checkCert) { this.uri = Objects.requireNonNull(uri); this.authenticator = Objects.requireNonNull(authenticator); this.checkCert = checkCert; if (uri.getScheme().equals("https") && !checkCert) { LOG.warn("DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{new WrongTrustManager()}, new java.security.SecureRandom()); socketFactory = sc.getSocketFactory(); hostnameVerifier = new NoOpHostnameVerifier(); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e.toString()); } catch (KeyManagementException e) { throw new AssertionError(e.toString()); } } else { socketFactory = null; hostnameVerifier = null; } this.retz = Retz.connect(uri, authenticator, socketFactory, hostnameVerifier); System.setProperty("http.agent", Client.VERSION_STRING); } public static ClientBuilder newBuilder(URI uri) { return new ClientBuilder(uri); } public void setVerboseLog(boolean b) { verboseLog = b; } @Override public void close() { } public boolean ping() throws IOException { try { return "OK".equals(retz.ping()); } catch (FeignException e) { LOG.debug(e.toString()); return false; } } public Response status() throws IOException { return Retz.tryOrErrorResponse(() -> retz.status()); } public Response list(Job.JobState state, Optional<String> tag) throws IOException { return Retz.tryOrErrorResponse(() -> retz.list(state, tag)); } public Response schedule(Job job) throws IOException { if (job.priority() < -20 || 19 < job.priority()) { throw new IllegalArgumentException("Priority must be [-19, 20]"); } return Retz.tryOrErrorResponse(() -> retz.schedule(Objects.requireNonNull(job))); } public Response getJob(int id) throws IOException { return Retz.tryOrErrorResponse(() -> retz.getJob(id)); } public Response getFile(int id, String file, long offset, long length) throws IOException { return Retz.tryOrErrorResponse( () -> retz.getFile(id, Objects.requireNonNull(file), offset, length)); } public int getBinaryFile(int id, String file, OutputStream out) throws IOException { String date = TimestampHelper.now(); // Encode path forcibly since we return decoded path by list files String encodedFile = file; try { encodedFile = URLEncoder.encode(file, "UTF-8"); } catch (UnsupportedEncodingException e) { } String resource = "/job/" + id + "/download?path=" + encodedFile; AuthHeader header = authenticator.header("GET", "", date, resource); URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode! LOG.info("Fetching {}", url); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); //LOG.info("classname> {}", conn.getClass().getName()); if (uri.getScheme().equals("https") && !checkCert && conn instanceof HttpsURLConnection) { if (verboseLog) { LOG.warn("DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); } HttpsURLConnection sslCon = (HttpsURLConnection) conn; if (socketFactory != null) { sslCon.setSSLSocketFactory(socketFactory); } if (hostnameVerifier != null) { sslCon.setHostnameVerifier(hostnameVerifier); } } conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("Authorization", header.buildHeader()); conn.setRequestProperty("Date", date); conn.setRequestProperty("Content-md5", ""); conn.setDoInput(true); String s2s = authenticator.string2sign("GET", "", date, resource); LOG.debug("Authorization: {} / S2S={}", header.buildHeader(), s2s); if (conn.getResponseCode() != 200) { if (verboseLog) { LOG.warn("HTTP Response:", conn.getResponseMessage()); } if (conn.getResponseCode() < 200) { throw new AssertionError(conn.getResponseMessage()); } else if (conn.getResponseCode() == 404) { throw new FileNotFoundException(url.toString()); } else { String message; try { Response response = MAPPER.readValue(conn.getErrorStream(), Response.class); message = response.status(); LOG.error(message, response); } catch (JsonProcessingException e) { message = e.toString(); LOG.error(message, e); } throw new UnknownServerResponseException(message); } } int size = conn.getContentLength(); if (size < 0) { throw new IOException("Illegal content length:" + size); } else if (size == 0) { // not bytes to save; return 0; } try { return IOUtils.copy(conn.getInputStream(), out); } finally { conn.disconnect(); } } public Response listFiles(int id, String path) throws IOException { return Retz.tryOrErrorResponse( () -> retz.listFiles(id, Objects.requireNonNull(path))); } public Job run(Job job) throws IOException { Response res = schedule(job); if (!(res instanceof ScheduleResponse)) { LOG.error(res.status()); return null; } ScheduleResponse scheduleResponse = (ScheduleResponse) res; LOG.info("Job scheduled: id={}", scheduleResponse.job().id()); return waitPoll(scheduleResponse.job()); } private Job waitPoll(Job job) throws IOException { do { Response res = getJob(job.id()); if (res instanceof GetJobResponse) { GetJobResponse getJobResponse = (GetJobResponse) res; if (getJobResponse.job().isPresent()) { if (getJobResponse.job().get().state() == Job.JobState.FINISHED || getJobResponse.job().get().state() == Job.JobState.KILLED) { return getJobResponse.job().get(); } else { try { Thread.sleep(1024); } catch (InterruptedException e) { } } } else { LOG.error("Job id={} does not exist.", job.id()); return null; } } else { LOG.error(res.status()); return null; } } while (true); } public Response kill(int id) throws IOException { return Retz.tryOrErrorResponse(() -> retz.kill(id)); } public Response getApp(String appid) throws IOException { return Retz.tryOrErrorResponse(() -> retz.getApp(appid)); } public Response load(Application application) throws IOException { return Retz.tryOrErrorResponse(() -> retz.load(Objects.requireNonNull(application))); } public Response listApp() throws IOException { return Retz.tryOrErrorResponse(() -> retz.listApp()); } @Deprecated public Response unload(String appName) throws IOException { return Retz.tryOrErrorResponse(() -> retz.unload(Objects.requireNonNull(appName))); } }
retz-client/src/main/java/io/github/retz/web/Client.java
/** * Retz * Copyright (C) 2016-2017 Nautilus Technologies, 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 io.github.retz.web; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import feign.FeignException; import io.github.retz.auth.AuthHeader; import io.github.retz.auth.Authenticator; import io.github.retz.cli.TimestampHelper; import io.github.retz.protocol.*; import io.github.retz.protocol.data.Application; import io.github.retz.protocol.data.Job; import io.github.retz.protocol.exception.UnknownServerResponseException; import io.github.retz.web.feign.Retz; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Objects; import java.util.Optional; import java.util.ResourceBundle; public class Client implements AutoCloseable { public static final String VERSION_STRING; private static final ObjectMapper MAPPER = new ObjectMapper(); static final Logger LOG = LoggerFactory.getLogger(Client.class); static { ResourceBundle labels = ResourceBundle.getBundle("retz-client"); VERSION_STRING = labels.getString("version"); MAPPER.registerModule(new Jdk8Module()); } private final Retz retz; private boolean verboseLog = false; private URI uri; private Authenticator authenticator; private SSLSocketFactory socketFactory; private HostnameVerifier hostnameVerifier; private boolean checkCert = true; protected Client(URI uri, Authenticator authenticator) { this(uri, authenticator, true); } protected Client(URI uri, Authenticator authenticator, boolean checkCert) { this.uri = Objects.requireNonNull(uri); this.authenticator = Objects.requireNonNull(authenticator); this.checkCert = checkCert; if (uri.getScheme().equals("https") && !checkCert) { LOG.warn("DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{new WrongTrustManager()}, new java.security.SecureRandom()); socketFactory = sc.getSocketFactory(); hostnameVerifier = new NoOpHostnameVerifier(); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e.toString()); } catch (KeyManagementException e) { throw new AssertionError(e.toString()); } } else { socketFactory = null; hostnameVerifier = null; } this.retz = Retz.connect(uri, authenticator, socketFactory, hostnameVerifier); System.setProperty("http.agent", Client.VERSION_STRING); } public static ClientBuilder newBuilder(URI uri) { return new ClientBuilder(uri); } public void setVerboseLog(boolean b) { verboseLog = b; } @Override public void close() { } public boolean ping() throws IOException { try { return "OK".equals(retz.ping()); } catch (FeignException e) { LOG.debug(e.toString()); return false; } } public Response status() throws IOException { return Retz.tryOrErrorResponse(() -> retz.status()); } public Response list(Job.JobState state, Optional<String> tag) throws IOException { return Retz.tryOrErrorResponse(() -> retz.list(state, tag)); } public Response schedule(Job job) throws IOException { if (job.priority() < -20 || 19 < job.priority()) { throw new IllegalArgumentException("Priority must be [-19, 20]"); } return Retz.tryOrErrorResponse(() -> retz.schedule(Objects.requireNonNull(job))); } public Response getJob(int id) throws IOException { return Retz.tryOrErrorResponse(() -> retz.getJob(id)); } public Response getFile(int id, String file, long offset, long length) throws IOException { return Retz.tryOrErrorResponse( () -> retz.getFile(id, Objects.requireNonNull(file), offset, length)); } public int getBinaryFile(int id, String file, OutputStream out) throws IOException { String date = TimestampHelper.now(); String resource = "/job/" + id + "/download?path=" + file; AuthHeader header = authenticator.header("GET", "", date, resource); URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode! LOG.info("Fetching {}", url); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); //LOG.info("classname> {}", conn.getClass().getName()); if (uri.getScheme().equals("https") && !checkCert && conn instanceof HttpsURLConnection) { if (verboseLog) { LOG.warn("DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message."); } HttpsURLConnection sslCon = (HttpsURLConnection) conn; if (socketFactory != null) { sslCon.setSSLSocketFactory(socketFactory); } if (hostnameVerifier != null) { sslCon.setHostnameVerifier(hostnameVerifier); } } conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/octet-stream"); conn.setRequestProperty("Authorization", header.buildHeader()); conn.setRequestProperty("Date", date); conn.setRequestProperty("Content-md5", ""); conn.setDoInput(true); String s2s = authenticator.string2sign("GET", "", date, resource); LOG.debug("Authorization: {} / S2S={}", header.buildHeader(), s2s); if (conn.getResponseCode() != 200) { if (verboseLog) { LOG.warn("HTTP Response:", conn.getResponseMessage()); } if (conn.getResponseCode() < 200) { throw new AssertionError(conn.getResponseMessage()); } else if (conn.getResponseCode() == 404) { throw new FileNotFoundException(url.toString()); } else { String message; try { Response response = MAPPER.readValue(conn.getErrorStream(), Response.class); message = response.status(); LOG.error(message, response); } catch (JsonProcessingException e) { message = e.toString(); LOG.error(message, e); } throw new UnknownServerResponseException(message); } } int size = conn.getContentLength(); if (size < 0) { throw new IOException("Illegal content length:" + size); } else if (size == 0) { // not bytes to save; return 0; } try { return IOUtils.copy(conn.getInputStream(), out); } finally { conn.disconnect(); } } public Response listFiles(int id, String path) throws IOException { return Retz.tryOrErrorResponse( () -> retz.listFiles(id, Objects.requireNonNull(path))); } public Job run(Job job) throws IOException { Response res = schedule(job); if (!(res instanceof ScheduleResponse)) { LOG.error(res.status()); return null; } ScheduleResponse scheduleResponse = (ScheduleResponse) res; LOG.info("Job scheduled: id={}", scheduleResponse.job().id()); return waitPoll(scheduleResponse.job()); } private Job waitPoll(Job job) throws IOException { do { Response res = getJob(job.id()); if (res instanceof GetJobResponse) { GetJobResponse getJobResponse = (GetJobResponse) res; if (getJobResponse.job().isPresent()) { if (getJobResponse.job().get().state() == Job.JobState.FINISHED || getJobResponse.job().get().state() == Job.JobState.KILLED) { return getJobResponse.job().get(); } else { try { Thread.sleep(1024); } catch (InterruptedException e) { } } } else { LOG.error("Job id={} does not exist.", job.id()); return null; } } else { LOG.error(res.status()); return null; } } while (true); } public Response kill(int id) throws IOException { return Retz.tryOrErrorResponse(() -> retz.kill(id)); } public Response getApp(String appid) throws IOException { return Retz.tryOrErrorResponse(() -> retz.getApp(appid)); } public Response load(Application application) throws IOException { return Retz.tryOrErrorResponse(() -> retz.load(Objects.requireNonNull(application))); } public Response listApp() throws IOException { return Retz.tryOrErrorResponse(() -> retz.listApp()); } @Deprecated public Response unload(String appName) throws IOException { return Retz.tryOrErrorResponse(() -> retz.unload(Objects.requireNonNull(appName))); } }
URL-encode get file path forcibly
retz-client/src/main/java/io/github/retz/web/Client.java
URL-encode get file path forcibly
<ide><path>etz-client/src/main/java/io/github/retz/web/Client.java <ide> import java.net.HttpURLConnection; <ide> import java.net.URI; <ide> import java.net.URL; <add>import java.net.URLEncoder; <ide> import java.security.KeyManagementException; <ide> import java.security.NoSuchAlgorithmException; <ide> import java.util.Objects; <ide> <ide> public int getBinaryFile(int id, String file, OutputStream out) throws IOException { <ide> String date = TimestampHelper.now(); <del> String resource = "/job/" + id + "/download?path=" + file; <add> // Encode path forcibly since we return decoded path by list files <add> String encodedFile = file; <add> try { <add> encodedFile = URLEncoder.encode(file, "UTF-8"); <add> } catch (UnsupportedEncodingException e) { <add> } <add> String resource = "/job/" + id + "/download?path=" + encodedFile; <ide> AuthHeader header = authenticator.header("GET", "", date, resource); <ide> URL url = new URL(uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + resource); // TODO url-encode! <ide> LOG.info("Fetching {}", url);
Java
bsd-2-clause
a5d8891fa14b253f3b7c911a19ee0467998975e5
0
mosoft521/jodd,oblac/jodd,mosoft521/jodd,oblac/jodd,mosoft521/jodd,oblac/jodd,mosoft521/jodd,oblac/jodd
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 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 jodd.util; import jodd.test.DisabledOnJava; import jodd.util.fixtures.subclass.IBase; import jodd.util.fixtures.subclass.IExtra; import jodd.util.fixtures.subclass.IOne; import jodd.util.fixtures.subclass.ITwo; import jodd.util.fixtures.subclass.SBase; import jodd.util.fixtures.subclass.SOne; import jodd.util.fixtures.subclass.STwo; import jodd.util.fixtures.testdata.A; import jodd.util.fixtures.testdata.B; import jodd.util.fixtures.testdata.C; import jodd.util.fixtures.testdata.JavaBean; import jodd.util.fixtures.testdata2.D; import jodd.util.fixtures.testdata2.E; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.io.File; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class ClassUtilTest { @Test void testMethod() { TFooBean bean = new TFooBean(); Method m; m = ClassUtil.findMethod(TFooBean.class, "getMore"); assertNotNull(m); m = ClassUtil.findMethod(bean.getClass(), "getMore"); assertNotNull(m); m = ClassUtil.findMethod(bean.getClass(), "getXXX"); assertNull(m); } @Test void testMatchClasses() { TFooBean a = new TFooBean(); TFooBean b = new TFooBean(); TFooBean2 c = new TFooBean2(); assertTrue(TFooBean.class.isInstance(a)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, a.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean.class, b.getClass())); assertTrue(ClassUtil.isTypeOf(a.getClass(), b.getClass())); assertTrue(ClassUtil.isTypeOf(b.getClass(), a.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, c.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, TFooBean.class)); assertFalse(ClassUtil.isTypeOf(TFooBean.class, TFooBean2.class)); assertTrue(ClassUtil.isTypeOf(c.getClass(), TFooBean.class)); assertFalse(ClassUtil.isTypeOf(a.getClass(), TFooBean2.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, Serializable.class)); assertTrue(Serializable.class.isInstance(c)); //noinspection ConstantConditions assertTrue(c instanceof Serializable); assertTrue(ClassUtil.isInstanceOf(c, Serializable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, Comparable.class)); assertFalse(ClassUtil.isTypeOf(TFooBean.class, Comparable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, TFooIndyEx.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, TFooIndyEx.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, TFooIndy.class)); } @Test void testMatchInterfaces() { assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); assertTrue(ClassUtil.isInstanceOf(new HashMap(), Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); } @Test void testAccessibleA() { Method[] ms = ClassUtil.getAccessibleMethods(A.class, null); assertEquals(4 + 11, ms.length); // there are 11 accessible Object methods (9 public + 2 protected) ms = ClassUtil.getAccessibleMethods(A.class); assertEquals(4, ms.length); ms = A.class.getMethods(); assertEquals(1 + 9, ms.length); // there are 9 public Object methods ms = A.class.getDeclaredMethods(); assertEquals(4, ms.length); ms = ClassUtil.getSupportedMethods(A.class, null); assertEquals(4 + 12, ms.length); // there are 12 total Object methods (9 public + 2 protected + 1 private) ms = ClassUtil.getSupportedMethods(A.class); assertEquals(4, ms.length); Field[] fs = ClassUtil.getAccessibleFields(A.class); assertEquals(4, fs.length); fs = A.class.getFields(); assertEquals(1, fs.length); fs = A.class.getDeclaredFields(); assertEquals(4, fs.length); fs = ClassUtil.getSupportedFields(A.class); assertEquals(4, fs.length); } @Test void testAccessibleB() { Method[] ms = ClassUtil.getAccessibleMethods(B.class, null); assertEquals(3 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(B.class); assertEquals(3, ms.length); ms = B.class.getMethods(); assertEquals(1 + 9, ms.length); ms = B.class.getDeclaredMethods(); assertEquals(0, ms.length); ms = ClassUtil.getSupportedMethods(B.class, null); assertEquals(4 + 12, ms.length); ms = ClassUtil.getSupportedMethods(B.class); assertEquals(4, ms.length); Field[] fs = ClassUtil.getAccessibleFields(B.class); assertEquals(3, fs.length); fs = B.class.getFields(); assertEquals(1, fs.length); fs = B.class.getDeclaredFields(); assertEquals(0, fs.length); fs = ClassUtil.getSupportedFields(B.class); assertEquals(4, fs.length); } @Test void testAccessibleC() { Method[] ms = ClassUtil.getAccessibleMethods(C.class, null); assertEquals(5 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(C.class); assertEquals(5, ms.length); ms = C.class.getMethods(); assertEquals(2 + 9, ms.length); ms = C.class.getDeclaredMethods(); assertEquals(5, ms.length); ms = ClassUtil.getSupportedMethods(C.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(C.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(C.class); assertEquals(5, fs.length); fs = C.class.getFields(); assertEquals(3, fs.length); fs = C.class.getDeclaredFields(); assertEquals(5, fs.length); fs = ClassUtil.getSupportedFields(C.class); assertEquals(5, fs.length); } @Test void testAccessibleD() { Method[] ms = ClassUtil.getAccessibleMethods(D.class, null); assertEquals(3 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(D.class); assertEquals(3, ms.length); ms = D.class.getMethods(); assertEquals(2 + 9, ms.length); ms = D.class.getDeclaredMethods(); assertEquals(0, ms.length); ms = ClassUtil.getSupportedMethods(D.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(D.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(D.class); assertEquals(3, fs.length); fs = D.class.getFields(); assertEquals(3, fs.length); fs = D.class.getDeclaredFields(); assertEquals(0, fs.length); fs = ClassUtil.getSupportedFields(D.class); assertEquals(5, fs.length); } @Test void testAccessibleE() { Method[] ms = ClassUtil.getAccessibleMethods(E.class, null); assertEquals(5 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(E.class); assertEquals(5, ms.length); ms = E.class.getMethods(); assertEquals(2 + 9, ms.length); ms = E.class.getDeclaredMethods(); assertEquals(4, ms.length); ms = ClassUtil.getSupportedMethods(E.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(E.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(E.class); assertEquals(5, fs.length); fs = E.class.getFields(); assertEquals(4, fs.length); fs = E.class.getDeclaredFields(); assertEquals(4, fs.length); fs = ClassUtil.getSupportedFields(E.class); assertEquals(5, fs.length); } @Test void testIsSubclassAndInterface() { assertTrue(ClassUtil.isTypeOf(SBase.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, SOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, ITwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, ITwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IExtra.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IExtra.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, STwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, STwo.class)); } @Test void testBeanPropertyNames() { String name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getOne")); assertEquals("one", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setOne")); assertEquals("one", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "isTwo")); assertEquals("two", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setTwo")); assertEquals("two", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getThree")); assertEquals("three", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setThree")); assertEquals("three", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getF")); assertEquals("f", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setF")); assertEquals("f", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getG")); assertEquals("g", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setG")); assertEquals("g", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getURL")); assertEquals("URL", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setURL")); assertEquals("URL", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getBIGsmall")); assertEquals("BIGsmall", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setBIGsmall")); assertEquals("BIGsmall", name); } @Test void testIsSubClassForCommonTypes() { assertTrue(ClassUtil.isTypeOf(Long.class, Long.class)); assertFalse(ClassUtil.isTypeOf(Long.class, long.class)); } /* @Test void testGetCallerClass() { assertFalse(Reflection.getCallerClass(0).equals(ReflectUtil.getCallerClass(0))); assertEquals(Reflection.getCallerClass(1), ReflectUtil.getCallerClass(1)); assertEquals(Reflection.getCallerClass(2), ReflectUtil.getCallerClass(2)); assertEquals(Reflection.getCallerClass(3), ReflectUtil.getCallerClass(3)); assertEquals(ReflectUtilTest.class, ReflectUtil.getCallerClass(1)); } @Test void testGetCallerClass2() throws NoSuchFieldException, IllegalAccessException { Field field = ReflectUtil.class.getDeclaredField("SECURITY_MANAGER"); field.setAccessible(true); Object value = field.get(null); field.set(null, null); assertFalse(Reflection.getCallerClass(0).equals(ReflectUtil.getCallerClass(0))); assertEquals(Reflection.getCallerClass(1), ReflectUtil.getCallerClass(1)); assertEquals(Reflection.getCallerClass(2), ReflectUtil.getCallerClass(2)); assertEquals(Reflection.getCallerClass(3), ReflectUtil.getCallerClass(3)); assertEquals(ReflectUtilTest.class, ReflectUtil.getCallerClass(1)); field.set(null, value); } */ // ---------------------------------------------------------------- field concrete type public static class BaseClass<A, B> { public A f1; public B f2; public String f3; public A[] array1; } public static class ConcreteClass extends BaseClass<String, Integer> { public Long f4; public List<Long> f5; } public static class BaseClass2<X> extends BaseClass<X, Integer> { } public static class ConcreteClass2 extends BaseClass2<String> { } @Test void testGetFieldConcreteType() throws NoSuchFieldException { Field f1 = BaseClass.class.getField("f1"); Field f2 = BaseClass.class.getField("f2"); Field f3 = BaseClass.class.getField("f3"); Field f4 = ConcreteClass.class.getField("f4"); Field f5 = ConcreteClass.class.getField("f5"); Field array1 = BaseClass.class.getField("array1"); Class[] genericSupertypes = ClassUtil.getGenericSupertypes(ConcreteClass.class); assertEquals(String.class, genericSupertypes[0]); assertEquals(Integer.class, genericSupertypes[1]); assertEquals(String.class, ClassUtil.getRawType(f1.getGenericType(), ConcreteClass.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), ConcreteClass.class)); assertEquals(String.class, ClassUtil.getRawType(f3.getGenericType(), ConcreteClass.class)); assertEquals(Long.class, ClassUtil.getRawType(f4.getGenericType(), ConcreteClass.class)); assertEquals(List.class, ClassUtil.getRawType(f5.getGenericType(), ConcreteClass.class)); assertEquals(String[].class, ClassUtil.getRawType(array1.getGenericType(), ConcreteClass.class)); assertEquals(Object.class, ClassUtil.getRawType(f1.getGenericType())); assertNull(ClassUtil.getComponentType(f1.getGenericType(), -1)); assertEquals(Long.class, ClassUtil.getComponentType(f5.getGenericType(), 0)); } @Test void testGetFieldConcreteType2() throws Exception { Field array1 = BaseClass.class.getField("array1"); Field f2 = ConcreteClass2.class.getField("f2"); assertEquals(String[].class, ClassUtil.getRawType(array1.getGenericType(), ConcreteClass2.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), ConcreteClass2.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), BaseClass2.class)); } // ---------------------------------------------------------------- test raw public static class Soo { public List<String> stringList; public String[] strings; public String string; public List<Integer> getIntegerList() {return null;} public Integer[] getIntegers() {return null;} public Integer getInteger() {return null;} public <T> T getTemplate(T foo) {return null;} public Collection<? extends Number> getCollection() {return null;} public Collection<?> getCollection2() {return null;} } @Test void testGetRawAndComponentType() throws NoSuchFieldException { Class<Soo> sooClass = Soo.class; Field stringList = sooClass.getField("stringList"); assertEquals(List.class, ClassUtil.getRawType(stringList.getType())); assertEquals(String.class, ClassUtil.getComponentType(stringList.getGenericType(), 0)); Field strings = sooClass.getField("strings"); assertEquals(String[].class, ClassUtil.getRawType(strings.getType())); assertEquals(String.class, ClassUtil.getComponentType(strings.getGenericType(), -1)); Field string = sooClass.getField("string"); assertEquals(String.class, ClassUtil.getRawType(string.getType())); assertNull(ClassUtil.getComponentType(string.getGenericType(), 0)); Method integerList = ClassUtil.findMethod(sooClass, "getIntegerList"); assertEquals(List.class, ClassUtil.getRawType(integerList.getReturnType())); assertEquals(Integer.class, ClassUtil.getComponentType(integerList.getGenericReturnType(), -1)); Method integers = ClassUtil.findMethod(sooClass, "getIntegers"); assertEquals(Integer[].class, ClassUtil.getRawType(integers.getReturnType())); assertEquals(Integer.class, ClassUtil.getComponentType(integers.getGenericReturnType(), 0)); Method integer = ClassUtil.findMethod(sooClass, "getInteger"); assertEquals(Integer.class, ClassUtil.getRawType(integer.getReturnType())); assertNull(ClassUtil.getComponentType(integer.getGenericReturnType(), -1)); Method template = ClassUtil.findMethod(sooClass, "getTemplate"); assertEquals(Object.class, ClassUtil.getRawType(template.getReturnType())); assertNull(ClassUtil.getComponentType(template.getGenericReturnType(), 0)); Method collection = ClassUtil.findMethod(sooClass, "getCollection"); assertEquals(Collection.class, ClassUtil.getRawType(collection.getReturnType())); assertEquals(Number.class, ClassUtil.getComponentType(collection.getGenericReturnType(), -1)); Method collection2 = ClassUtil.findMethod(sooClass, "getCollection2"); assertEquals(Collection.class, ClassUtil.getRawType(collection2.getReturnType())); assertEquals(Object.class, ClassUtil.getComponentType(collection2.getGenericReturnType(), 0)); } public static class Base2<N extends Number, K> { public N getNumber() {return null;} public K getKiko() {return null;} } public static class Impl1<N extends Number> extends Base2<N, Long> {} public static class Impl2 extends Impl1<Integer> {} public static class Impl3 extends Impl2 {} @Test void testGetRawWithImplClass() throws NoSuchFieldException { Method number = ClassUtil.findMethod(Base2.class, "getNumber"); Method kiko = ClassUtil.findMethod(Base2.class, "getKiko"); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType())); assertEquals(Number.class, ClassUtil.getRawType(number.getGenericReturnType())); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType())); assertEquals(Object.class, ClassUtil.getRawType(kiko.getGenericReturnType())); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl1.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl1.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl1.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl1.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl2.class)); assertEquals(Integer.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl2.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl2.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl2.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl3.class)); assertEquals(Integer.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl3.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl3.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl3.class)); } public static class Base22<K, N extends Number> {} public static class Impl11<N extends Number> extends Base22<Long, N> {} public static class Impl22 extends Impl11<Integer> {} public static class Impl33 extends Impl22 {} @Test void testClassGenerics1() { Class[] componentTypes = ClassUtil.getGenericSupertypes(Base2.class); assertNull(componentTypes); Type[] types = Base2.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl1.class); assertEquals(2, componentTypes.length); assertEquals(Number.class, componentTypes[0]); assertEquals(Long.class, componentTypes[1]); types = Impl1.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl2.class); assertEquals(1, componentTypes.length); assertEquals(Integer.class, componentTypes[0]); types = Impl2.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl3.class); assertNull(componentTypes); } @Test void testClassGenerics2() { Class[] componentTypes = ClassUtil.getGenericSupertypes(Base22.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(Impl11.class); assertEquals(2, componentTypes.length); assertEquals(Long.class, componentTypes[0]); assertEquals(Number.class, componentTypes[1]); componentTypes = ClassUtil.getGenericSupertypes(Impl22.class); assertEquals(1, componentTypes.length); assertEquals(Integer.class, componentTypes[0]); componentTypes = ClassUtil.getGenericSupertypes(Impl33.class); assertNull(componentTypes); } public static interface BaseAna<K, N extends Number> {} public static interface ImplAna<N extends Number> extends BaseAna<Long, N> {} public static interface ImplAna2 extends ImplAna<Integer> {} public static class ImplAna3 implements ImplAna2 {} public static class ImplAna4 extends ImplAna3 {} @Test void testClassGenerics3() { Class[] componentTypes = ClassUtil.getGenericSupertypes(BaseAna.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna2.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna3.class); assertNull(componentTypes); // scan generic interfacase Type[] types = ImplAna3.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(ImplAna2.class, types[0]); assertNull(ClassUtil.getComponentType(types[0], 0)); types = ImplAna2.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(Integer.class, ClassUtil.getComponentType(types[0], 0)); types = ImplAna.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(Long.class, ClassUtil.getComponentType(types[0], 0)); types = BaseAna.class.getGenericInterfaces(); assertEquals(0, types.length); types = ImplAna4.class.getGenericInterfaces(); assertEquals(0, types.length); } // ---------------------------------------------------------------- type2string public static class FieldType<K extends Number, V extends List<String> & Collection<String>> { List fRaw; List<Object> fTypeObject; List<String> fTypeString; List<?> fWildcard; List<? super List<String>> fBoundedWildcard; Map<String, List<Set<Long>>> fTypeNested; Map<K, V> fTypeLiteral; K[] fGenericArray; } @Test void testFieldTypeToString() { Field[] fields = FieldType.class.getDeclaredFields(); Arrays.sort(fields, new Comparator<Field>() { @Override public int compare(Field o1, Field o2) { return o1.getName().compareTo(o2.getName()); } }); String result = ""; for (Field field : fields) { Type type = field.getGenericType(); result += field.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } assertEquals( "fBoundedWildcard - java.util.List<? super java.util.List<java.lang.String>>\n" + "fGenericArray - K[]\n" + "fRaw - java.util.List\n" + "fTypeLiteral - java.util.Map<K extends java.lang.Number>, <V extends java.util.List<java.lang.String> & java.util.Collection<java.lang.String>>\n" + "fTypeNested - java.util.Map<java.lang.String>, <java.util.List<java.util.Set<java.lang.Long>>>\n" + "fTypeObject - java.util.List<java.lang.Object>\n" + "fTypeString - java.util.List<java.lang.String>\n" + "fWildcard - java.util.List<? extends java.lang.Object>\n", result); } public static class MethodReturnType { List mRaw() {return null;} List<String> mTypeString() {return null;} List<?> mWildcard() {return null;} List<? extends Number> mBoundedWildcard() {return null;} <T extends List<String>> List<T> mTypeLiteral() {return null;} } @Test void testMethodTypeToString() { Method[] methods = MethodReturnType.class.getDeclaredMethods(); Arrays.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); String result = ""; for (Method method : methods) { Type type = method.getGenericReturnType(); result += method.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } assertEquals( "mBoundedWildcard - java.util.List<? extends java.lang.Number>\n" + "mRaw - java.util.List\n" + "mTypeLiteral - java.util.List<T extends java.util.List<java.lang.String>>\n" + "mTypeString - java.util.List<java.lang.String>\n" + "mWildcard - java.util.List<? extends java.lang.Object>\n", result); } public static class MethodParameterType<A> { <T extends List<T>> void m(A a, String p1, T p2, List<?> p3, List<T> p4) { } } public static class Mimple extends MethodParameterType<Long>{} @Test void testMethodParameterTypeToString() { String result = ""; Method method = null; for (Method m : MethodParameterType.class.getDeclaredMethods()) { for (Type type : m.getGenericParameterTypes()) { result += m.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } method = m; } assertEquals( "m - A extends java.lang.Object\n" + "m - java.lang.String\n" + "m - T extends java.util.List<T>\n" + "m - java.util.List<? extends java.lang.Object>\n" + "m - java.util.List<T extends java.util.List<T>>\n", result); Type[] types = method.getGenericParameterTypes(); assertEquals(Object.class, ClassUtil.getRawType(types[0], MethodParameterType.class)); assertEquals(String.class, ClassUtil.getRawType(types[1], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[2], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[3], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[4], MethodParameterType.class)); // same methods, using different impl class assertEquals(Long.class, ClassUtil.getRawType(types[0], Mimple.class)); // change! assertEquals(String.class, ClassUtil.getRawType(types[1], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[2], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[3], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[4], Mimple.class)); } public interface SomeGuy {} public interface Cool extends SomeGuy {} public interface Vigilante {} public interface Flying extends Vigilante {} public interface SuperMario extends Flying, Cool {} class User implements SomeGuy {} class SuperUser extends User implements Cool {} class SuperMan extends SuperUser implements Flying {} @Test void testResolveAllInterfaces() { Class[] interfaces = ClassUtil.resolveAllInterfaces(HashMap.class); assertTrue(interfaces.length >= 3); assertTrue(ArraysUtil.contains(interfaces, Map.class)); assertTrue(ArraysUtil.contains(interfaces, Serializable.class)); assertTrue(ArraysUtil.contains(interfaces, Cloneable.class)); interfaces = ClassUtil.resolveAllInterfaces(SuperMan.class); assertEquals(4, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); assertTrue(ArraysUtil.contains(interfaces, Cool.class)); assertTrue(ArraysUtil.contains(interfaces, Flying.class)); assertTrue(ArraysUtil.contains(interfaces, Vigilante.class)); assertTrue(ArraysUtil.indexOf(interfaces, Flying.class) < ArraysUtil.indexOf(interfaces, SomeGuy.class)); interfaces = ClassUtil.resolveAllInterfaces(SuperUser.class); assertEquals(2, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); assertTrue(ArraysUtil.contains(interfaces, Cool.class)); interfaces = ClassUtil.resolveAllInterfaces(User.class); assertEquals(1, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); interfaces = ClassUtil.resolveAllInterfaces(SomeGuy.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Cool.class); assertEquals(1, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Vigilante.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Flying.class); assertEquals(1, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(SuperMario.class); assertEquals(4, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Object.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(int.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(int[].class); assertEquals(2, interfaces.length); // cloneable, serializable interfaces = ClassUtil.resolveAllInterfaces(Integer[].class); assertEquals(2, interfaces.length); } @Test void testResolveAllSuperclsses() { Class[] subclasses = ClassUtil.resolveAllSuperclasses(User.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(SuperUser.class); assertEquals(1, subclasses.length); assertEquals(User.class, subclasses[0]); subclasses = ClassUtil.resolveAllSuperclasses(SuperMan.class); assertEquals(2, subclasses.length); assertEquals(SuperUser.class, subclasses[0]); assertEquals(User.class, subclasses[1]); subclasses = ClassUtil.resolveAllSuperclasses(Cool.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Flying.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(SuperMario.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Object.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(int.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(int[].class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Integer[].class); assertEquals(0, subclasses.length); } @Nested @DisplayName("tests for ClassUtil#isUserDefinedMethod") class IsUserDefinedMethod { @Test void notUserDefinedMethod() throws Exception { final Method method = Object.class.getMethod("hashCode"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(false, actual); } @Test void userDefinedMethod() throws Exception { final Method method = StringBand.class.getMethod("toString"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(true, actual); } @Test void customObjectButMethodFromObject() throws Exception { final Method method = StringBand.class.getMethod("hashCode"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(false, actual); } } @Nested @DisplayName("ClassUtil#getClasses") class GetClasses { @Test void emptyArgument() { final Class[] actual = ClassUtil.getClasses(new Object[0]); // asserts assertNotNull(actual); assertEquals(0, actual.length); } @Test void noNullValueIncluded() { final Class[] actual = ClassUtil.getClasses(new Object(), new Base32(), File.class, 3, 23L, 44.55F, 11.11D); // asserts assertNotNull(actual); assertEquals(7, actual.length); assertEquals(Object.class, actual[0]); assertEquals(Base32.class, actual[1]); assertEquals(Class.class, actual[2]); assertEquals(Integer.class, actual[3]); assertEquals(Long.class, actual[4]); assertEquals(Float.class, actual[5]); assertEquals(Double.class, actual[6]); } @Test void onlyNullValuesIncluded() { final Class[] actual = ClassUtil.getClasses(null, null, null, null); // asserts assertNotNull(actual); assertEquals(4, actual.length); } } @Nested @DisplayName("tests for ClassUtil#isObjectMethod") class IsObjectMethod { @Test void methodFromObject() throws Exception { final Method method = Object.class.getMethod("hashCode"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(true, actual); } @Test void userDefinedMethod() throws Exception { final Method method = StringBand.class.getMethod("toString"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(false, actual); } @Test void customObjectButMethodFromObject() throws Exception { final Method method = StringBand.class.getMethod("hashCode"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(true, actual); } } @Nested @DisplayName("tests for method jarFileOf") class JarFileOf { @Test void checkClassFromExternalJar() { final JarFile actual = ClassUtil.jarFileOf(StringUtils.class); // asserts assertNotNull(actual); assertTrue(actual.getName().contains("commons-lang3")); } @Test void checkWithClassFromThisModule() { final JarFile actual = ClassUtil.jarFileOf(Chalk.class); // asserts assertNull(actual); } @Test @DisabledOnJava(value = 9, description = "rt.jar does not exists in Java 9 anymore") void checkWithClassFromJRE() { final JarFile actual = ClassUtil.jarFileOf(Object.class); // asserts assertNotNull(actual); assertTrue(actual.getName().contains("rt.jar")); } } }
jodd-core/src/test/java/jodd/util/ClassUtilTest.java
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 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 jodd.util; import jodd.util.fixtures.subclass.IBase; import jodd.util.fixtures.subclass.IExtra; import jodd.util.fixtures.subclass.IOne; import jodd.util.fixtures.subclass.ITwo; import jodd.util.fixtures.subclass.SBase; import jodd.util.fixtures.subclass.SOne; import jodd.util.fixtures.subclass.STwo; import jodd.util.fixtures.testdata.A; import jodd.util.fixtures.testdata.B; import jodd.util.fixtures.testdata.C; import jodd.util.fixtures.testdata.JavaBean; import jodd.util.fixtures.testdata2.D; import jodd.util.fixtures.testdata2.E; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.io.File; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class ClassUtilTest { @Test void testMethod() { TFooBean bean = new TFooBean(); Method m; m = ClassUtil.findMethod(TFooBean.class, "getMore"); assertNotNull(m); m = ClassUtil.findMethod(bean.getClass(), "getMore"); assertNotNull(m); m = ClassUtil.findMethod(bean.getClass(), "getXXX"); assertNull(m); } @Test void testMatchClasses() { TFooBean a = new TFooBean(); TFooBean b = new TFooBean(); TFooBean2 c = new TFooBean2(); assertTrue(TFooBean.class.isInstance(a)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, a.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean.class, b.getClass())); assertTrue(ClassUtil.isTypeOf(a.getClass(), b.getClass())); assertTrue(ClassUtil.isTypeOf(b.getClass(), a.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, c.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, TFooBean.class)); assertFalse(ClassUtil.isTypeOf(TFooBean.class, TFooBean2.class)); assertTrue(ClassUtil.isTypeOf(c.getClass(), TFooBean.class)); assertFalse(ClassUtil.isTypeOf(a.getClass(), TFooBean2.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, Serializable.class)); assertTrue(Serializable.class.isInstance(c)); //noinspection ConstantConditions assertTrue(c instanceof Serializable); assertTrue(ClassUtil.isInstanceOf(c, Serializable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, Comparable.class)); assertFalse(ClassUtil.isTypeOf(TFooBean.class, Comparable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, TFooIndyEx.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, TFooIndyEx.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, TFooIndy.class)); } @Test void testMatchInterfaces() { assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); assertTrue(ClassUtil.isInstanceOf(new HashMap(), Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); } @Test void testAccessibleA() { Method[] ms = ClassUtil.getAccessibleMethods(A.class, null); assertEquals(4 + 11, ms.length); // there are 11 accessible Object methods (9 public + 2 protected) ms = ClassUtil.getAccessibleMethods(A.class); assertEquals(4, ms.length); ms = A.class.getMethods(); assertEquals(1 + 9, ms.length); // there are 9 public Object methods ms = A.class.getDeclaredMethods(); assertEquals(4, ms.length); ms = ClassUtil.getSupportedMethods(A.class, null); assertEquals(4 + 12, ms.length); // there are 12 total Object methods (9 public + 2 protected + 1 private) ms = ClassUtil.getSupportedMethods(A.class); assertEquals(4, ms.length); Field[] fs = ClassUtil.getAccessibleFields(A.class); assertEquals(4, fs.length); fs = A.class.getFields(); assertEquals(1, fs.length); fs = A.class.getDeclaredFields(); assertEquals(4, fs.length); fs = ClassUtil.getSupportedFields(A.class); assertEquals(4, fs.length); } @Test void testAccessibleB() { Method[] ms = ClassUtil.getAccessibleMethods(B.class, null); assertEquals(3 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(B.class); assertEquals(3, ms.length); ms = B.class.getMethods(); assertEquals(1 + 9, ms.length); ms = B.class.getDeclaredMethods(); assertEquals(0, ms.length); ms = ClassUtil.getSupportedMethods(B.class, null); assertEquals(4 + 12, ms.length); ms = ClassUtil.getSupportedMethods(B.class); assertEquals(4, ms.length); Field[] fs = ClassUtil.getAccessibleFields(B.class); assertEquals(3, fs.length); fs = B.class.getFields(); assertEquals(1, fs.length); fs = B.class.getDeclaredFields(); assertEquals(0, fs.length); fs = ClassUtil.getSupportedFields(B.class); assertEquals(4, fs.length); } @Test void testAccessibleC() { Method[] ms = ClassUtil.getAccessibleMethods(C.class, null); assertEquals(5 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(C.class); assertEquals(5, ms.length); ms = C.class.getMethods(); assertEquals(2 + 9, ms.length); ms = C.class.getDeclaredMethods(); assertEquals(5, ms.length); ms = ClassUtil.getSupportedMethods(C.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(C.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(C.class); assertEquals(5, fs.length); fs = C.class.getFields(); assertEquals(3, fs.length); fs = C.class.getDeclaredFields(); assertEquals(5, fs.length); fs = ClassUtil.getSupportedFields(C.class); assertEquals(5, fs.length); } @Test void testAccessibleD() { Method[] ms = ClassUtil.getAccessibleMethods(D.class, null); assertEquals(3 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(D.class); assertEquals(3, ms.length); ms = D.class.getMethods(); assertEquals(2 + 9, ms.length); ms = D.class.getDeclaredMethods(); assertEquals(0, ms.length); ms = ClassUtil.getSupportedMethods(D.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(D.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(D.class); assertEquals(3, fs.length); fs = D.class.getFields(); assertEquals(3, fs.length); fs = D.class.getDeclaredFields(); assertEquals(0, fs.length); fs = ClassUtil.getSupportedFields(D.class); assertEquals(5, fs.length); } @Test void testAccessibleE() { Method[] ms = ClassUtil.getAccessibleMethods(E.class, null); assertEquals(5 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(E.class); assertEquals(5, ms.length); ms = E.class.getMethods(); assertEquals(2 + 9, ms.length); ms = E.class.getDeclaredMethods(); assertEquals(4, ms.length); ms = ClassUtil.getSupportedMethods(E.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(E.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(E.class); assertEquals(5, fs.length); fs = E.class.getFields(); assertEquals(4, fs.length); fs = E.class.getDeclaredFields(); assertEquals(4, fs.length); fs = ClassUtil.getSupportedFields(E.class); assertEquals(5, fs.length); } @Test void testIsSubclassAndInterface() { assertTrue(ClassUtil.isTypeOf(SBase.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, SOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, ITwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, ITwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IExtra.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IExtra.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, STwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, STwo.class)); } @Test void testBeanPropertyNames() { String name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getOne")); assertEquals("one", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setOne")); assertEquals("one", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "isTwo")); assertEquals("two", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setTwo")); assertEquals("two", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getThree")); assertEquals("three", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setThree")); assertEquals("three", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getF")); assertEquals("f", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setF")); assertEquals("f", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getG")); assertEquals("g", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setG")); assertEquals("g", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getURL")); assertEquals("URL", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setURL")); assertEquals("URL", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getBIGsmall")); assertEquals("BIGsmall", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setBIGsmall")); assertEquals("BIGsmall", name); } @Test void testIsSubClassForCommonTypes() { assertTrue(ClassUtil.isTypeOf(Long.class, Long.class)); assertFalse(ClassUtil.isTypeOf(Long.class, long.class)); } /* @Test void testGetCallerClass() { assertFalse(Reflection.getCallerClass(0).equals(ReflectUtil.getCallerClass(0))); assertEquals(Reflection.getCallerClass(1), ReflectUtil.getCallerClass(1)); assertEquals(Reflection.getCallerClass(2), ReflectUtil.getCallerClass(2)); assertEquals(Reflection.getCallerClass(3), ReflectUtil.getCallerClass(3)); assertEquals(ReflectUtilTest.class, ReflectUtil.getCallerClass(1)); } @Test void testGetCallerClass2() throws NoSuchFieldException, IllegalAccessException { Field field = ReflectUtil.class.getDeclaredField("SECURITY_MANAGER"); field.setAccessible(true); Object value = field.get(null); field.set(null, null); assertFalse(Reflection.getCallerClass(0).equals(ReflectUtil.getCallerClass(0))); assertEquals(Reflection.getCallerClass(1), ReflectUtil.getCallerClass(1)); assertEquals(Reflection.getCallerClass(2), ReflectUtil.getCallerClass(2)); assertEquals(Reflection.getCallerClass(3), ReflectUtil.getCallerClass(3)); assertEquals(ReflectUtilTest.class, ReflectUtil.getCallerClass(1)); field.set(null, value); } */ // ---------------------------------------------------------------- field concrete type public static class BaseClass<A, B> { public A f1; public B f2; public String f3; public A[] array1; } public static class ConcreteClass extends BaseClass<String, Integer> { public Long f4; public List<Long> f5; } public static class BaseClass2<X> extends BaseClass<X, Integer> { } public static class ConcreteClass2 extends BaseClass2<String> { } @Test void testGetFieldConcreteType() throws NoSuchFieldException { Field f1 = BaseClass.class.getField("f1"); Field f2 = BaseClass.class.getField("f2"); Field f3 = BaseClass.class.getField("f3"); Field f4 = ConcreteClass.class.getField("f4"); Field f5 = ConcreteClass.class.getField("f5"); Field array1 = BaseClass.class.getField("array1"); Class[] genericSupertypes = ClassUtil.getGenericSupertypes(ConcreteClass.class); assertEquals(String.class, genericSupertypes[0]); assertEquals(Integer.class, genericSupertypes[1]); assertEquals(String.class, ClassUtil.getRawType(f1.getGenericType(), ConcreteClass.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), ConcreteClass.class)); assertEquals(String.class, ClassUtil.getRawType(f3.getGenericType(), ConcreteClass.class)); assertEquals(Long.class, ClassUtil.getRawType(f4.getGenericType(), ConcreteClass.class)); assertEquals(List.class, ClassUtil.getRawType(f5.getGenericType(), ConcreteClass.class)); assertEquals(String[].class, ClassUtil.getRawType(array1.getGenericType(), ConcreteClass.class)); assertEquals(Object.class, ClassUtil.getRawType(f1.getGenericType())); assertNull(ClassUtil.getComponentType(f1.getGenericType(), -1)); assertEquals(Long.class, ClassUtil.getComponentType(f5.getGenericType(), 0)); } @Test void testGetFieldConcreteType2() throws Exception { Field array1 = BaseClass.class.getField("array1"); Field f2 = ConcreteClass2.class.getField("f2"); assertEquals(String[].class, ClassUtil.getRawType(array1.getGenericType(), ConcreteClass2.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), ConcreteClass2.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), BaseClass2.class)); } // ---------------------------------------------------------------- test raw public static class Soo { public List<String> stringList; public String[] strings; public String string; public List<Integer> getIntegerList() {return null;} public Integer[] getIntegers() {return null;} public Integer getInteger() {return null;} public <T> T getTemplate(T foo) {return null;} public Collection<? extends Number> getCollection() {return null;} public Collection<?> getCollection2() {return null;} } @Test void testGetRawAndComponentType() throws NoSuchFieldException { Class<Soo> sooClass = Soo.class; Field stringList = sooClass.getField("stringList"); assertEquals(List.class, ClassUtil.getRawType(stringList.getType())); assertEquals(String.class, ClassUtil.getComponentType(stringList.getGenericType(), 0)); Field strings = sooClass.getField("strings"); assertEquals(String[].class, ClassUtil.getRawType(strings.getType())); assertEquals(String.class, ClassUtil.getComponentType(strings.getGenericType(), -1)); Field string = sooClass.getField("string"); assertEquals(String.class, ClassUtil.getRawType(string.getType())); assertNull(ClassUtil.getComponentType(string.getGenericType(), 0)); Method integerList = ClassUtil.findMethod(sooClass, "getIntegerList"); assertEquals(List.class, ClassUtil.getRawType(integerList.getReturnType())); assertEquals(Integer.class, ClassUtil.getComponentType(integerList.getGenericReturnType(), -1)); Method integers = ClassUtil.findMethod(sooClass, "getIntegers"); assertEquals(Integer[].class, ClassUtil.getRawType(integers.getReturnType())); assertEquals(Integer.class, ClassUtil.getComponentType(integers.getGenericReturnType(), 0)); Method integer = ClassUtil.findMethod(sooClass, "getInteger"); assertEquals(Integer.class, ClassUtil.getRawType(integer.getReturnType())); assertNull(ClassUtil.getComponentType(integer.getGenericReturnType(), -1)); Method template = ClassUtil.findMethod(sooClass, "getTemplate"); assertEquals(Object.class, ClassUtil.getRawType(template.getReturnType())); assertNull(ClassUtil.getComponentType(template.getGenericReturnType(), 0)); Method collection = ClassUtil.findMethod(sooClass, "getCollection"); assertEquals(Collection.class, ClassUtil.getRawType(collection.getReturnType())); assertEquals(Number.class, ClassUtil.getComponentType(collection.getGenericReturnType(), -1)); Method collection2 = ClassUtil.findMethod(sooClass, "getCollection2"); assertEquals(Collection.class, ClassUtil.getRawType(collection2.getReturnType())); assertEquals(Object.class, ClassUtil.getComponentType(collection2.getGenericReturnType(), 0)); } public static class Base2<N extends Number, K> { public N getNumber() {return null;} public K getKiko() {return null;} } public static class Impl1<N extends Number> extends Base2<N, Long> {} public static class Impl2 extends Impl1<Integer> {} public static class Impl3 extends Impl2 {} @Test void testGetRawWithImplClass() throws NoSuchFieldException { Method number = ClassUtil.findMethod(Base2.class, "getNumber"); Method kiko = ClassUtil.findMethod(Base2.class, "getKiko"); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType())); assertEquals(Number.class, ClassUtil.getRawType(number.getGenericReturnType())); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType())); assertEquals(Object.class, ClassUtil.getRawType(kiko.getGenericReturnType())); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl1.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl1.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl1.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl1.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl2.class)); assertEquals(Integer.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl2.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl2.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl2.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl3.class)); assertEquals(Integer.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl3.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl3.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl3.class)); } public static class Base22<K, N extends Number> {} public static class Impl11<N extends Number> extends Base22<Long, N> {} public static class Impl22 extends Impl11<Integer> {} public static class Impl33 extends Impl22 {} @Test void testClassGenerics1() { Class[] componentTypes = ClassUtil.getGenericSupertypes(Base2.class); assertNull(componentTypes); Type[] types = Base2.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl1.class); assertEquals(2, componentTypes.length); assertEquals(Number.class, componentTypes[0]); assertEquals(Long.class, componentTypes[1]); types = Impl1.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl2.class); assertEquals(1, componentTypes.length); assertEquals(Integer.class, componentTypes[0]); types = Impl2.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl3.class); assertNull(componentTypes); } @Test void testClassGenerics2() { Class[] componentTypes = ClassUtil.getGenericSupertypes(Base22.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(Impl11.class); assertEquals(2, componentTypes.length); assertEquals(Long.class, componentTypes[0]); assertEquals(Number.class, componentTypes[1]); componentTypes = ClassUtil.getGenericSupertypes(Impl22.class); assertEquals(1, componentTypes.length); assertEquals(Integer.class, componentTypes[0]); componentTypes = ClassUtil.getGenericSupertypes(Impl33.class); assertNull(componentTypes); } public static interface BaseAna<K, N extends Number> {} public static interface ImplAna<N extends Number> extends BaseAna<Long, N> {} public static interface ImplAna2 extends ImplAna<Integer> {} public static class ImplAna3 implements ImplAna2 {} public static class ImplAna4 extends ImplAna3 {} @Test void testClassGenerics3() { Class[] componentTypes = ClassUtil.getGenericSupertypes(BaseAna.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna2.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna3.class); assertNull(componentTypes); // scan generic interfacase Type[] types = ImplAna3.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(ImplAna2.class, types[0]); assertNull(ClassUtil.getComponentType(types[0], 0)); types = ImplAna2.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(Integer.class, ClassUtil.getComponentType(types[0], 0)); types = ImplAna.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(Long.class, ClassUtil.getComponentType(types[0], 0)); types = BaseAna.class.getGenericInterfaces(); assertEquals(0, types.length); types = ImplAna4.class.getGenericInterfaces(); assertEquals(0, types.length); } // ---------------------------------------------------------------- type2string public static class FieldType<K extends Number, V extends List<String> & Collection<String>> { List fRaw; List<Object> fTypeObject; List<String> fTypeString; List<?> fWildcard; List<? super List<String>> fBoundedWildcard; Map<String, List<Set<Long>>> fTypeNested; Map<K, V> fTypeLiteral; K[] fGenericArray; } @Test void testFieldTypeToString() { Field[] fields = FieldType.class.getDeclaredFields(); Arrays.sort(fields, new Comparator<Field>() { @Override public int compare(Field o1, Field o2) { return o1.getName().compareTo(o2.getName()); } }); String result = ""; for (Field field : fields) { Type type = field.getGenericType(); result += field.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } assertEquals( "fBoundedWildcard - java.util.List<? super java.util.List<java.lang.String>>\n" + "fGenericArray - K[]\n" + "fRaw - java.util.List\n" + "fTypeLiteral - java.util.Map<K extends java.lang.Number>, <V extends java.util.List<java.lang.String> & java.util.Collection<java.lang.String>>\n" + "fTypeNested - java.util.Map<java.lang.String>, <java.util.List<java.util.Set<java.lang.Long>>>\n" + "fTypeObject - java.util.List<java.lang.Object>\n" + "fTypeString - java.util.List<java.lang.String>\n" + "fWildcard - java.util.List<? extends java.lang.Object>\n", result); } public static class MethodReturnType { List mRaw() {return null;} List<String> mTypeString() {return null;} List<?> mWildcard() {return null;} List<? extends Number> mBoundedWildcard() {return null;} <T extends List<String>> List<T> mTypeLiteral() {return null;} } @Test void testMethodTypeToString() { Method[] methods = MethodReturnType.class.getDeclaredMethods(); Arrays.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); String result = ""; for (Method method : methods) { Type type = method.getGenericReturnType(); result += method.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } assertEquals( "mBoundedWildcard - java.util.List<? extends java.lang.Number>\n" + "mRaw - java.util.List\n" + "mTypeLiteral - java.util.List<T extends java.util.List<java.lang.String>>\n" + "mTypeString - java.util.List<java.lang.String>\n" + "mWildcard - java.util.List<? extends java.lang.Object>\n", result); } public static class MethodParameterType<A> { <T extends List<T>> void m(A a, String p1, T p2, List<?> p3, List<T> p4) { } } public static class Mimple extends MethodParameterType<Long>{} @Test void testMethodParameterTypeToString() { String result = ""; Method method = null; for (Method m : MethodParameterType.class.getDeclaredMethods()) { for (Type type : m.getGenericParameterTypes()) { result += m.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } method = m; } assertEquals( "m - A extends java.lang.Object\n" + "m - java.lang.String\n" + "m - T extends java.util.List<T>\n" + "m - java.util.List<? extends java.lang.Object>\n" + "m - java.util.List<T extends java.util.List<T>>\n", result); Type[] types = method.getGenericParameterTypes(); assertEquals(Object.class, ClassUtil.getRawType(types[0], MethodParameterType.class)); assertEquals(String.class, ClassUtil.getRawType(types[1], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[2], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[3], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[4], MethodParameterType.class)); // same methods, using different impl class assertEquals(Long.class, ClassUtil.getRawType(types[0], Mimple.class)); // change! assertEquals(String.class, ClassUtil.getRawType(types[1], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[2], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[3], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[4], Mimple.class)); } public interface SomeGuy {} public interface Cool extends SomeGuy {} public interface Vigilante {} public interface Flying extends Vigilante {} public interface SuperMario extends Flying, Cool {} class User implements SomeGuy {} class SuperUser extends User implements Cool {} class SuperMan extends SuperUser implements Flying {} @Test void testResolveAllInterfaces() { Class[] interfaces = ClassUtil.resolveAllInterfaces(HashMap.class); assertTrue(interfaces.length >= 3); assertTrue(ArraysUtil.contains(interfaces, Map.class)); assertTrue(ArraysUtil.contains(interfaces, Serializable.class)); assertTrue(ArraysUtil.contains(interfaces, Cloneable.class)); interfaces = ClassUtil.resolveAllInterfaces(SuperMan.class); assertEquals(4, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); assertTrue(ArraysUtil.contains(interfaces, Cool.class)); assertTrue(ArraysUtil.contains(interfaces, Flying.class)); assertTrue(ArraysUtil.contains(interfaces, Vigilante.class)); assertTrue(ArraysUtil.indexOf(interfaces, Flying.class) < ArraysUtil.indexOf(interfaces, SomeGuy.class)); interfaces = ClassUtil.resolveAllInterfaces(SuperUser.class); assertEquals(2, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); assertTrue(ArraysUtil.contains(interfaces, Cool.class)); interfaces = ClassUtil.resolveAllInterfaces(User.class); assertEquals(1, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); interfaces = ClassUtil.resolveAllInterfaces(SomeGuy.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Cool.class); assertEquals(1, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Vigilante.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Flying.class); assertEquals(1, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(SuperMario.class); assertEquals(4, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Object.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(int.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(int[].class); assertEquals(2, interfaces.length); // cloneable, serializable interfaces = ClassUtil.resolveAllInterfaces(Integer[].class); assertEquals(2, interfaces.length); } @Test void testResolveAllSuperclsses() { Class[] subclasses = ClassUtil.resolveAllSuperclasses(User.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(SuperUser.class); assertEquals(1, subclasses.length); assertEquals(User.class, subclasses[0]); subclasses = ClassUtil.resolveAllSuperclasses(SuperMan.class); assertEquals(2, subclasses.length); assertEquals(SuperUser.class, subclasses[0]); assertEquals(User.class, subclasses[1]); subclasses = ClassUtil.resolveAllSuperclasses(Cool.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Flying.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(SuperMario.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Object.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(int.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(int[].class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Integer[].class); assertEquals(0, subclasses.length); } @Nested @DisplayName("tests for ClassUtil#isUserDefinedMethod") class IsUserDefinedMethod { @Test void notUserDefinedMethod() throws Exception { final Method method = Object.class.getMethod("hashCode"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(false, actual); } @Test void userDefinedMethod() throws Exception { final Method method = StringBand.class.getMethod("toString"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(true, actual); } @Test void customObjectButMethodFromObject() throws Exception { final Method method = StringBand.class.getMethod("hashCode"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(false, actual); } } @Nested @DisplayName("ClassUtil#getClasses") class GetClasses { @Test void emptyArgument() { final Class[] actual = ClassUtil.getClasses(new Object[0]); // asserts assertNotNull(actual); assertEquals(0, actual.length); } @Test void noNullValueIncluded() { final Class[] actual = ClassUtil.getClasses(new Object(), new Base32(), File.class, 3, 23L, 44.55F, 11.11D); // asserts assertNotNull(actual); assertEquals(7, actual.length); assertEquals(Object.class, actual[0]); assertEquals(Base32.class, actual[1]); assertEquals(Class.class, actual[2]); assertEquals(Integer.class, actual[3]); assertEquals(Long.class, actual[4]); assertEquals(Float.class, actual[5]); assertEquals(Double.class, actual[6]); } @Test void onlyNullValuesIncluded() { final Class[] actual = ClassUtil.getClasses(null, null, null, null); // asserts assertNotNull(actual); assertEquals(4, actual.length); } } @Nested @DisplayName("tests for ClassUtil#isObjectMethod") class IsObjectMethod { @Test void methodFromObject() throws Exception { final Method method = Object.class.getMethod("hashCode"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(true, actual); } @Test void userDefinedMethod() throws Exception { final Method method = StringBand.class.getMethod("toString"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(false, actual); } @Test void customObjectButMethodFromObject() throws Exception { final Method method = StringBand.class.getMethod("hashCode"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(true, actual); } } @Nested @DisplayName("tests for method jarFileOf") class JarFileOf { @Test void checkClassFromExternalJar() { final JarFile actual = ClassUtil.jarFileOf(StringUtils.class); // asserts assertNotNull(actual); assertTrue(actual.getName().contains("commons-lang3")); } @Test void checkWithClassFromThisModule() { final JarFile actual = ClassUtil.jarFileOf(Chalk.class); // asserts assertNull(actual); } @Test void checkWithClassFromJRE() { final JarFile actual = ClassUtil.jarFileOf(Object.class); // asserts assertNotNull(actual); assertTrue(actual.getName().contains("rt.jar")); } } }
disabled test on Java 9
jodd-core/src/test/java/jodd/util/ClassUtilTest.java
disabled test on Java 9
<ide><path>odd-core/src/test/java/jodd/util/ClassUtilTest.java <ide> <ide> package jodd.util; <ide> <add>import jodd.test.DisabledOnJava; <ide> import jodd.util.fixtures.subclass.IBase; <ide> import jodd.util.fixtures.subclass.IExtra; <ide> import jodd.util.fixtures.subclass.IOne; <ide> } <ide> <ide> @Test <add> @DisabledOnJava(value = 9, description = "rt.jar does not exists in Java 9 anymore") <ide> void checkWithClassFromJRE() { <ide> final JarFile actual = ClassUtil.jarFileOf(Object.class); <ide>
Java
apache-2.0
6f8b47ff8ff6e6202e9291296f7ff0d7723efacc
0
googleinterns/step143-2020,googleinterns/step143-2020,googleinterns/step143-2020,googleinterns/step143-2020
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import com.google.gson.Gson; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.images.ImagesService; import com.google.appengine.api.images.ImagesServiceFactory; import com.google.appengine.api.images.ServingUrlOptions; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; // import com.google.sps.data.Task; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.SortDirection; import java.util.*; import com.google.appengine.api.datastore.EntityNotFoundException; /** Servlet that returns some example content. TODO: modify this file to handle comments data */ @WebServlet("/edit") public class EditAccountServlet extends HttpServlet { /** Data holder for each individual Profile */ public class Profile { public String name; public long capacity; public String driverEmail; public String driverId; public double rating; public long numratings; public ArrayList<String> usersRated; public ArrayList<Long> myRides; public Profile(String name, long capacity, String driverEmail, String driverId, double rating, long numratings, ArrayList<String> usersRated, ArrayList<Long> myRides) { this.name = name; this.capacity = capacity; this.driverId = driverId; this.driverEmail = driverEmail; this.rating = rating; this.numratings = numratings; this.usersRated = usersRated; this.myRides = myRides; } public String getName() { return name; } public long getCapacity() { return capacity; } } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); UserService userService = UserServiceFactory.getUserService(); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); UserService userService = UserServiceFactory.getUserService(); String profileId; if (request.getParameter("type").equals("1")) { profileId = userService.getCurrentUser().getUserId(); } else { // type is set to ID profileId = request.getParameter("type"); } try{ Key profileEntityKey = KeyFactory.createKey("Profile", profileId); Entity profileEntity = datastore.get(profileEntityKey); List<Profile> profileDetails = new ArrayList<>(); response.setContentType("application/json;"); if (profileEntity.getProperty("name").equals(null)) { Gson gson = new Gson(); String json = gson.toJson(profileDetails); response.getWriter().println(json); } else { String driverEmail = userService.getCurrentUser().getEmail(); double rating = (double) profileEntity.getProperty("rating"); long numratings = (long) profileEntity.getProperty("numratings"); ArrayList<String> usersRated = (ArrayList<String>) profileEntity.getProperty("usersRated"); ArrayList<Long> myRides = (ArrayList<Long>) profileEntity.getProperty("myRides"); Profile temp = new Profile((String) profileEntity.getProperty("name"), (long) profileEntity.getProperty("capacity"), driverEmail, profileId, rating, numratings, usersRated, myRides); profileDetails.add(temp); Gson gson = new Gson(); String json = gson.toJson(profileDetails); response.getWriter().println(json); } } catch (EntityNotFoundException e) { } } // A simple HTTP handler to extract text input from submitted web form and respond that context back to the user. public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String name = request.getParameter("name"); name = name.substring(0,1).toUpperCase() + name.substring(1); long capacity = Long.parseLong(request.getParameter("capacity")); String driverEmail = userService.getCurrentUser().getEmail(); String driverId = userService.getCurrentUser().getUserId(); String uploadUrl = request.getParameter("uploadUrl"); Key profileEntityKey = KeyFactory.createKey("Profile", driverId); Entity profileEntity = datastore.get(profileEntityKey); profileEntity.setProperty("name", name); profileEntity.setProperty("capacity", capacity); datastore.put(profileEntity); response.sendRedirect("/index.html"); } catch (EntityNotFoundException e) { String name = request.getParameter("name"); name = name.substring(0,1).toUpperCase() + name.substring(1); long capacity = Long.parseLong(request.getParameter("capacity")); String driverEmail = userService.getCurrentUser().getEmail(); String driverId = userService.getCurrentUser().getUserId(); String uploadUrl = request.getParameter("uploadUrl"); ArrayList<String> usersRated = new ArrayList<String>(); usersRated.add(""); ArrayList<String> myRides = new ArrayList<String>(); myRides.add(""); Entity entryEntity = new Entity("Profile", driverId); entryEntity.setProperty("name", name); entryEntity.setProperty("capacity", capacity); entryEntity.setProperty("driverId", driverId); entryEntity.setProperty("driverEmail", driverEmail); entryEntity.setProperty("rating", 0.0); entryEntity.setProperty("numratings", 0); entryEntity.setProperty("uploadUrl", uploadUrl); entryEntity.setProperty("usersRated", usersRated); entryEntity.setProperty("myRides", myRides); datastore.put(entryEntity); response.sendRedirect("/index.html"); } } }
rideshare/src/main/java/com/google/sps/servlets/EditAccountServlet.java
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import com.google.gson.Gson; import com.google.appengine.api.blobstore.BlobInfo; import com.google.appengine.api.blobstore.BlobInfoFactory; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.blobstore.BlobstoreService; import com.google.appengine.api.blobstore.BlobstoreServiceFactory; import com.google.appengine.api.images.ImagesService; import com.google.appengine.api.images.ImagesServiceFactory; import com.google.appengine.api.images.ServingUrlOptions; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; // import com.google.sps.data.Task; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.SortDirection; import java.util.*; import com.google.appengine.api.datastore.EntityNotFoundException; /** Servlet that returns some example content. TODO: modify this file to handle comments data */ @WebServlet("/edit") public class EditAccountServlet extends HttpServlet { /** Data holder for each individual Profile */ public class Profile { public String name; public long capacity; public String driverEmail; public String driverId; public double rating; public long numratings; public ArrayList<String> usersRated; public ArrayList<Long> myRides; public Profile(String name, long capacity, String driverEmail, String driverId, double rating, long numratings, ArrayList<String> usersRated, ArrayList<Long> myRides) { this.name = name; this.capacity = capacity; this.driverId = driverId; this.driverEmail = driverEmail; this.rating = rating; this.numratings = numratings; this.usersRated = usersRated; this.myRides = myRides; } public String getName() { return name; } public long getCapacity() { return capacity; } } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); UserService userService = UserServiceFactory.getUserService(); BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); UserService userService = UserServiceFactory.getUserService(); String profileId; if (request.getParameter("type").equals("1")) { profileId = userService.getCurrentUser().getUserId(); } else { // type is set to ID profileId = request.getParameter("type"); } try{ Key profileEntityKey = KeyFactory.createKey("Profile", profileId); Entity profileEntity = datastore.get(profileEntityKey); List<Profile> profileDetails = new ArrayList<>(); response.setContentType("application/json;"); if (profileEntity.getProperty("name").equals(null)) { Gson gson = new Gson(); String json = gson.toJson(profileDetails); response.getWriter().println(json); } else { String driverEmail = userService.getCurrentUser().getEmail(); double rating = (double) profileEntity.getProperty("rating"); long numratings = (long) profileEntity.getProperty("numratings"); ArrayList<String> usersRated = (ArrayList<String>) profileEntity.getProperty("usersRated"); ArrayList<Long> myRides = (ArrayList<Long>) profileEntity.getProperty("myRides"); Profile temp = new Profile((String) profileEntity.getProperty("name"), (long) profileEntity.getProperty("capacity"), driverEmail, profileId, rating, numratings, usersRated, myRides); profileDetails.add(temp); Gson gson = new Gson(); String json = gson.toJson(profileDetails); response.getWriter().println(json); } } catch (EntityNotFoundException e) { } } // A simple HTTP handler to extract text input from submitted web form and respond that context back to the user. public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { try { String name = request.getParameter("name"); name = name.substring(0,1).toUpperCase() + name.substring(1); long capacity = Long.parseLong(request.getParameter("capacity")); String driverEmail = userService.getCurrentUser().getEmail(); String driverId = userService.getCurrentUser().getUserId(); String uploadUrl = request.getParameter("uploadUrl"); Key profileEntityKey = KeyFactory.createKey("Profile", driverId); Entity profileEntity = datastore.get(profileEntityKey); profileEntity.setProperty("name", name); profileEntity.setProperty("capacity", capacity); datastore.put(profileEntity); response.sendRedirect("/index.html"); } catch (EntityNotFoundException e) { String name = request.getParameter("name"); name = name.substring(0,1).toUpperCase() + name.substring(1); long capacity = Long.parseLong(request.getParameter("capacity")); String driverEmail = userService.getCurrentUser().getEmail(); String driverId = userService.getCurrentUser().getUserId(); ArrayList<String> usersRated = new ArrayList<String>(); usersRated.add(""); ArrayList<String> myRides = new ArrayList<String>(); myRides.add(""); Entity entryEntity = new Entity("Profile", driverId); entryEntity.setProperty("name", name); entryEntity.setProperty("capacity", capacity); entryEntity.setProperty("driverId", driverId); entryEntity.setProperty("driverEmail", driverEmail); entryEntity.setProperty("rating", 0.0); entryEntity.setProperty("numratings", 0); entryEntity.setProperty("uploadUrl", uploadUrl); entryEntity.setProperty("usersRated", usersRated); entryEntity.setProperty("myRides", myRides); datastore.put(entryEntity); response.sendRedirect("/index.html"); } } }
Small fix
rideshare/src/main/java/com/google/sps/servlets/EditAccountServlet.java
Small fix
<ide><path>ideshare/src/main/java/com/google/sps/servlets/EditAccountServlet.java <ide> long capacity = Long.parseLong(request.getParameter("capacity")); <ide> String driverEmail = userService.getCurrentUser().getEmail(); <ide> String driverId = userService.getCurrentUser().getUserId(); <add> String uploadUrl = request.getParameter("uploadUrl"); <ide> <ide> ArrayList<String> usersRated = new ArrayList<String>(); <ide> usersRated.add("");
Java
agpl-3.0
504aa8f4dcf50603d067b9a5caa708bb12e4e52d
0
geothomasp/kcmit,UniversityOfHawaiiORS/kc,mukadder/kc,jwillia/kc-old1,geothomasp/kcmit,kuali/kc,kuali/kc,geothomasp/kcmit,iu-uits-es/kc,ColostateResearchServices/kc,jwillia/kc-old1,jwillia/kc-old1,UniversityOfHawaiiORS/kc,mukadder/kc,geothomasp/kcmit,jwillia/kc-old1,mukadder/kc,kuali/kc,ColostateResearchServices/kc,geothomasp/kcmit,iu-uits-es/kc,UniversityOfHawaiiORS/kc,iu-uits-es/kc,ColostateResearchServices/kc
/* * Copyright 2005-2010 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/ecl1.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.kra.timeandmoney.transactions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.kra.award.awardhierarchy.AwardHierarchyService; import org.kuali.kra.award.home.Award; import org.kuali.kra.award.home.AwardAmountInfo; import org.kuali.kra.award.version.service.AwardVersionService; import org.kuali.kra.bo.versioning.VersionHistory; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.rules.ResearchDocumentRuleBase; import org.kuali.kra.service.VersionHistoryService; import org.kuali.kra.timeandmoney.AwardHierarchyNode; import org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument; import org.kuali.kra.timeandmoney.history.TransactionDetail; import org.kuali.kra.timeandmoney.service.ActivePendingTransactionsService; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; /** * The AwardPaymentScheduleRuleImpl */ public class TransactionRuleImpl extends ResearchDocumentRuleBase implements TransactionRule { private static final String SOURCE_AWARD_PROPERTY = "sourceAwardNumber"; private static final String OBLIGATED_AMOUNT_PROPERTY = "obligatedAmount"; private static final String ANTICIPATED_AMOUNT_PROPERTY = "anticipatedAmount"; private static final String DESTINATION_AWARD_PROPERTY = "destinationAwardNumber"; private static final String CURRENT_FUND_EFFECTIVE_DATE = "currentFundEffectiveDate"; private static final String SOURCE_AWARD_ERROR_PARM = "Source Award (Source Award)"; private static final String DESTINATION_AWARD_ERROR_PARM = "Destination Award (Destination Award)"; private static final String TOTALS = "totals"; private static final String TIME_AND_MONEY_TRANSACTION = "timeAndMoneyTransaction"; private static final String NEW_AWARD_AMOUNT_TRANSACTION = "newAwardAmountTransaction"; private static final String TRANSACTION_TYPE_CODE = ".transactionTypeCode"; private ParameterService parameterService; /** * * @see org.kuali.kra.timeandmoney.transactions.TransactionRule#processPendingTransactionBusinessRules( * org.kuali.kra.timeandmoney.transactions.TransactionRuleEvent) */ public boolean processPendingTransactionBusinessRules(TransactionRuleEvent event) { return processCommonValidations(event); } /** * * This method processes new Pending Transaction rules * * @param event * @return */ public boolean processAddPendingTransactionBusinessRules(AddTransactionRuleEvent event) { boolean requiredFieldsComplete = areRequiredFieldsComplete(event.getPendingTransactionItemForValidation()); if (requiredFieldsComplete) { event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); List<Award> awards = processTransactions(event.getTimeAndMoneyDocument()); // need to remove the following, but do it after we processTransactions() since that // method depends on a complete list of pending transactions to determine which awards // are affected by this new transaction. event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getPendingTransactionItemForValidation()); Award award = getLastSourceAwardReferenceInAwards(awards, event.getPendingTransactionItemForValidation().getSourceAwardNumber()); //if source award is "External, the award will be null and we don't need to validate these amounts. boolean validObligatedFunds = true; boolean validAnticipatedFunds = true; boolean validTotalCostLimit = true; if(!(award == null)) { validObligatedFunds = validateSourceObligatedFunds(event.getPendingTransactionItemForValidation(), award); validAnticipatedFunds = validateSourceAnticipatedFunds(event.getPendingTransactionItemForValidation(), award); validTotalCostLimit = validateAwardTotalCostLimit(event.getPendingTransactionItemForValidation(), award); //need to remove the award amount info created from this process transactions call so there won't be a double entry in collection. award.refreshReferenceObject("awardAmountInfos"); } boolean validFunds = false; boolean validDates = false; boolean validSourceAwardDestinationAward = false; validSourceAwardDestinationAward = processCommonValidations(event); if(validSourceAwardDestinationAward){ validFunds = validateAnticipatedGreaterThanObligated (event, awards); validDates = validateObligatedDateIsSet(event, awards); } return requiredFieldsComplete && validSourceAwardDestinationAward && validObligatedFunds && validAnticipatedFunds && validFunds && validDates && validTotalCostLimit ; } else { return false; } } /** * @see org.kuali.kra.timeandmoney.transactions.TransactionRule#processSingleNodeTransactionBusinessRules(org.kuali.kra.timeandmoney.AwardHierarchyNode, org.kuali.kra.award.home.AwardAmountInfo) * Business rules for single node transactions * 1)if direct/F&A view is disabled, then we test that transaction will either move anticipated/obligated money into or our of award. * We cannot have the instance where we are moving in and out of award at same time since the transactions have a source and destination award * 2)if Direct/F&A view is enabled, then there are two possibilities. * a)We cannot move money in and out of award for direct/indirect amounts in same transaction. * b)The exception to this rule is if doing so does not affect the total amount. The net affect of this is moving money from idc to dc or * vice versa. */ public boolean processSingleNodeTransactionBusinessRules (AwardHierarchyNode awardHierarchyNode, AwardAmountInfo aai, TimeAndMoneyDocument doc) { boolean returnValue; if(isDirectIndirectViewEnabled()) { returnValue = processParameterEnabledRules(awardHierarchyNode, aai, doc); } else { returnValue = processParameterDisabledRules(awardHierarchyNode, aai, doc); } return returnValue; } /** * Looks up and returns the ParameterService. * @return the parameter service. */ protected ParameterService getParameterService() { if (this.parameterService == null) { this.parameterService = KraServiceLocator.getService(ParameterService.class); } return this.parameterService; } public boolean isDirectIndirectViewEnabled() { boolean returnValue = false; String directIndirectEnabledValue = getParameterService().getParameterValueAsString(Constants.PARAMETER_MODULE_AWARD, ParameterConstants.DOCUMENT_COMPONENT, "ENABLE_AWD_ANT_OBL_DIRECT_INDIRECT_COST"); if(directIndirectEnabledValue.equals("1")) { returnValue = true; } return returnValue; } private boolean validateAnticipatedGreaterThanObligated (AddTransactionRuleEvent event, List<Award> awards) { boolean valid = true; //add the transaction to the document so we can simulate processing the transaction. event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); for (Award award : awards) { Award activeAward = getAwardVersionService().getWorkingAwardVersion(award.getAwardNumber()); AwardAmountInfo awardAmountInfo = activeAward.getAwardAmountInfos().get(activeAward.getAwardAmountInfos().size() -1); KualiDecimal anticipatedTotal = awardAmountInfo.getAnticipatedTotalAmount(); KualiDecimal obligatedTotal = awardAmountInfo.getAmountObligatedToDate(); for (PendingTransaction pendingTransaction: event.getTimeAndMoneyDocument().getPendingTransactions()) { if (StringUtils.equals(pendingTransaction.getSourceAwardNumber(), awardAmountInfo.getAwardNumber())) { anticipatedTotal = anticipatedTotal.subtract(pendingTransaction.getAnticipatedAmount()); obligatedTotal = obligatedTotal.subtract(pendingTransaction.getObligatedAmount()); } if (StringUtils.equals(pendingTransaction.getDestinationAwardNumber(), award.getAwardNumber())) { anticipatedTotal = anticipatedTotal.add(pendingTransaction.getAnticipatedAmount()); obligatedTotal = obligatedTotal.add(pendingTransaction.getObligatedAmount()); } if (anticipatedTotal.isLessThan(obligatedTotal)) { reportError(OBLIGATED_AMOUNT_PROPERTY, KeyConstants.ERROR_TOTAL_AMOUNT_INVALID, activeAward.getAwardNumber()); valid = false; } } award.refreshReferenceObject("awardAmountInfos"); } //remove the Transaction from the document. event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getTimeAndMoneyDocument().getPendingTransactions().size() - 1); return valid; } private boolean validateObligatedDateIsSet (AddTransactionRuleEvent event, List<Award> awards) { boolean valid = true; //add the transaction to the document so we can simulate processing the transaction. event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); for (Award award : awards) { Award activeAward = getAwardVersionService().getWorkingAwardVersion(award.getAwardNumber()); AwardAmountInfo awardAmountInfo = activeAward.getAwardAmountInfos().get(activeAward.getAwardAmountInfos().size() -1); if (awardAmountInfo.getAmountObligatedToDate().isPositive() && (awardAmountInfo.getCurrentFundEffectiveDate() == null || awardAmountInfo.getObligationExpirationDate() == null)) { reportError(CURRENT_FUND_EFFECTIVE_DATE, KeyConstants.ERROR_DATE_NOT_SET, activeAward.getAwardNumber()); valid = false; } award.refreshReferenceObject("awardAmountInfos"); } //remove the Transaction from the document. event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getTimeAndMoneyDocument().getPendingTransactions().size() - 1); return valid; } private Award findUpdatedRootAward(List<Award> awards, String rootAwardNumber) { Award returnAward = null; for (Award award : awards) { if (award.getAwardNumber() == rootAwardNumber) { returnAward = award; } } if(returnAward == null) { returnAward = getAwardVersionService().getWorkingAwardVersion(rootAwardNumber); // if(returnAward == null){ // returnAward = getActiveAwardVersion(rootAwardNumber); // } } return returnAward; } private List<Award> processTransactions(TimeAndMoneyDocument timeAndMoneyDocument) { Map<String, AwardAmountTransaction> awardAmountTransactionItems = new HashMap<String, AwardAmountTransaction>(); List<Award> awardItems = new ArrayList<Award>(); List<TransactionDetail> transactionDetailItems = new ArrayList<TransactionDetail>(); ActivePendingTransactionsService service = KraServiceLocator.getService(ActivePendingTransactionsService.class); service.processTransactionsForAddRuleProcessing(timeAndMoneyDocument, timeAndMoneyDocument.getAwardAmountTransactions().get(0), awardAmountTransactionItems, awardItems, transactionDetailItems); return awardItems; } private Award getLastSourceAwardReferenceInAwards (List<Award> awards, String sourceAwardNumber) { Award returnAward = null; for (Award award : awards) { if (award.getAwardNumber() == sourceAwardNumber) { returnAward = award; } } if(returnAward == null) { returnAward = getAwardVersionService().getWorkingAwardVersion(sourceAwardNumber); // if(returnAward == null){ // returnAward = getActiveAwardVersion(sourceAwardNumber); // } } return returnAward; } private boolean validateSourceObligatedFunds (PendingTransaction pendingTransaction, Award award) { AwardAmountInfo awardAmountInfo = award.getAwardAmountInfos().get(award.getAwardAmountInfos().size() -1); boolean valid = true; if (awardAmountInfo.getObliDistributableAmount().subtract(pendingTransaction.getObligatedAmount()).isNegative()) { reportError(OBLIGATED_AMOUNT_PROPERTY, KeyConstants.ERROR_OBLIGATED_AMOUNT_INVALID); valid = false; } return valid; } private boolean validateSourceAnticipatedFunds (PendingTransaction pendingTransaction, Award award) { AwardAmountInfo awardAmountInfo = award.getAwardAmountInfos().get(award.getAwardAmountInfos().size() -1); boolean valid = true; if (awardAmountInfo.getAntDistributableAmount().subtract(pendingTransaction.getAnticipatedAmount()).isNegative()) { reportError(ANTICIPATED_AMOUNT_PROPERTY, KeyConstants.ERROR_ANTICIPATED_AMOUNT_INVALID); valid = false; } return valid; } private boolean validateAwardTotalCostLimit(PendingTransaction pendingTransaction, Award award) { AwardAmountInfo awardAmountInfo = award.getAwardAmountInfos().get(award.getAwardAmountInfos().size() -1); KualiDecimal obliDistributableAmount = awardAmountInfo.getObliDistributableAmount().subtract(pendingTransaction.getObligatedAmount()); if (award.getTotalCostBudgetLimit() != null && award.getTotalCostBudgetLimit().isGreaterThan(obliDistributableAmount)) { reportWarning(OBLIGATED_AMOUNT_PROPERTY, KeyConstants.WARNING_TRANSACTION_OBLI_LESS_THAN_BUDGET_LIMIT, new String[]{award.getAwardNumber()}); } return true; } private boolean processCommonValidations(TransactionRuleEvent event) { PendingTransaction pendingTransactionItem = event.getPendingTransactionItemForValidation(); List<PendingTransaction> items = event.getTimeAndMoneyDocument().getPendingTransactions(); return isUnique(items, pendingTransactionItem) && sourceAndDestinationAwardsAreDifferent(pendingTransactionItem) && enforcePositiveAmounts(pendingTransactionItem); } boolean enforcePositiveAmounts(PendingTransaction pendingTransactionItem) { boolean valid = true; if(pendingTransactionItem.getAnticipatedAmount().isNegative() || pendingTransactionItem.getObligatedAmount().isNegative() || pendingTransactionItem.getAnticipatedDirectAmount().isNegative() || pendingTransactionItem.getAnticipatedIndirectAmount().isNegative() || pendingTransactionItem.getObligatedDirectAmount().isNegative() || pendingTransactionItem.getObligatedIndirectAmount().isNegative()) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_TRANSACTION_AMOUNTS_NEGATIVE); valid = false; } return valid; } boolean sourceAndDestinationAwardsAreDifferent(PendingTransaction pendingTransactionItem){ boolean srcAndDestinationAwardsAreDifferent = !StringUtils.equalsIgnoreCase(pendingTransactionItem.getSourceAwardNumber() , pendingTransactionItem.getDestinationAwardNumber()); if(!srcAndDestinationAwardsAreDifferent){ reportError(PENDING_TRANSACTION_ITEMS_LIST_ERROR_KEY, KeyConstants.ERROR_TNM_PENDING_TRANSACTION_SOURCE_AND_DESTINATION_AWARDS_ARE_SAME, SOURCE_AWARD_PROPERTY); } return srcAndDestinationAwardsAreDifferent; } /** * A pending transaction item is unique if no other matching items are in the collection * To know if this is a new add or an edit of an existing pending transaction item, we check * the identifier for nullity. If null, this is an add; otherwise, it's an update * If an update, then we expect to find one match in the collection (itself). If an add, * we expect to find no matches in the collection * @param pendingTransactionItems * @param pendingTransactionItem * @return */ boolean isUnique(List<PendingTransaction> pendingTransactionItems, PendingTransaction pendingTransactionItem) { boolean duplicateFound = false; for(PendingTransaction listItem: pendingTransactionItems) { duplicateFound = pendingTransactionItem != listItem && listItem.equals(pendingTransactionItem); if(duplicateFound) { break; } } if(duplicateFound) { if(!hasDuplicateErrorBeenReported()) { reportError(PENDING_TRANSACTION_ITEMS_LIST_ERROR_KEY, KeyConstants.ERROR_TNM_PENDING_TRANSACTION_ITEM_NOT_UNIQUE, SOURCE_AWARD_PROPERTY); } } return !duplicateFound; } /** * Validate required fields present * @param equipmentItem * @return */ boolean areRequiredFieldsComplete(PendingTransaction pendingTransactionItem) { boolean itemValid = isSourceAwardFieldComplete(pendingTransactionItem); itemValid &= isDestinationAwardFieldComplete(pendingTransactionItem); return itemValid; } protected boolean isSourceAwardFieldComplete(PendingTransaction pendingTransactionItem){ boolean itemValid = pendingTransactionItem.getSourceAwardNumber() != null; if(!itemValid) { reportError(SOURCE_AWARD_PROPERTY, KeyConstants.ERROR_REQUIRED, SOURCE_AWARD_ERROR_PARM); } return itemValid; } protected boolean isDestinationAwardFieldComplete(PendingTransaction pendingTransactionItem){ boolean itemValid = pendingTransactionItem.getDestinationAwardNumber() != null; if(!itemValid) { reportError(DESTINATION_AWARD_PROPERTY, KeyConstants.ERROR_REQUIRED, DESTINATION_AWARD_ERROR_PARM); } return itemValid; } private boolean hasDuplicateErrorBeenReported() { return GlobalVariables.getMessageMap().containsMessageKey(KeyConstants.ERROR_TNM_PENDING_TRANSACTION_ITEM_NOT_UNIQUE); } /* * This method retrieves AwardHierarchyService */ protected AwardHierarchyService getAwardHierarchyService(){ return (AwardHierarchyService) KraServiceLocator.getService(AwardHierarchyService.class); } public AwardVersionService getAwardVersionService() { return KraServiceLocator.getService(AwardVersionService.class); } // public Award getWorkingAwardVersion(String goToAwardNumber) { // Award award = null; // award = getPendingAwardVersion(goToAwardNumber); // if (award == null) { // award = getActiveAwardVersion(goToAwardNumber); // } // return award; // } /** * This method... * @param awardHierarchyNode * @param aai * @return */ public boolean processParameterEnabledRules(AwardHierarchyNode awardHierarchyNode, AwardAmountInfo aai, TimeAndMoneyDocument doc) { boolean valid = true; KualiDecimal obligatedDirectChange = awardHierarchyNode.getObligatedTotalDirect().subtract(aai.getObligatedTotalDirect()); KualiDecimal obligatedIndirectChange = awardHierarchyNode.getObligatedTotalIndirect().subtract(aai.getObligatedTotalIndirect()); KualiDecimal anticipatedDirectChange = awardHierarchyNode.getAnticipatedTotalDirect().subtract(aai.getAnticipatedTotalDirect()); KualiDecimal anticipatedIndirectChange = awardHierarchyNode.getAnticipatedTotalIndirect().subtract(aai.getAnticipatedTotalIndirect()); boolean obligatedTotalChanged = awardHierarchyNode.getObligatedTotalDirect().add(awardHierarchyNode.getObligatedTotalIndirect()).isNonZero(); boolean anticipatedTotalChanged = awardHierarchyNode.getAnticipatedTotalDirect().add(awardHierarchyNode.getAnticipatedTotalIndirect()).isNonZero(); //if totals change and net effect of changes result in reduction of one total with increase of other, we need to report error. if(obligatedTotalChanged || anticipatedTotalChanged) { KualiDecimal obligatedNetEffect = awardHierarchyNode.getObligatedTotalDirect().add(awardHierarchyNode.getObligatedTotalIndirect()); KualiDecimal anticipatedNetEffect = awardHierarchyNode.getAnticipatedTotalDirect().add(awardHierarchyNode.getAnticipatedTotalIndirect()); if((obligatedNetEffect.isNegative() && anticipatedNetEffect.isPositive()) || (obligatedNetEffect.isPositive() && anticipatedNetEffect.isNegative())) { reportError(TOTALS, KeyConstants.ERROR_NET_TOTALS_TRANSACTION); valid = false; } } //if indirect/direct change in transaction is a debit of one and credit of the other, then there cannot be a net change in total. if((((obligatedDirectChange.isPositive() && obligatedIndirectChange.isNegative()) || (obligatedDirectChange.isNegative() && obligatedIndirectChange.isPositive())) && obligatedTotalChanged) || (((anticipatedDirectChange.isPositive() && anticipatedIndirectChange.isNegative()) || (anticipatedDirectChange.isNegative() && anticipatedIndirectChange.isPositive())) && anticipatedTotalChanged)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_NET_TOTALS_TRANSACTION); valid = false; } valid &= validateAwardTotalCostLimit(awardHierarchyNode, aai.getAward()); if (!doc.isInitialSave()) {//this save rule cannot be called on initial save from creation from Award Document. if (doc.getAwardAmountTransactions().size() > 0) { if(doc.getAwardAmountTransactions().get(0).getTransactionTypeCode() == null) { valid = false; reportError(NEW_AWARD_AMOUNT_TRANSACTION+TRANSACTION_TYPE_CODE, KeyConstants.ERROR_TRANSACTION_TYPE_CODE_REQUIRED); } } } KualiDecimal obligatedTotal = new KualiDecimal(0); KualiDecimal anticipatedTotal= new KualiDecimal(0); obligatedTotal = obligatedTotal.add(awardHierarchyNode.getObligatedTotalDirect()); obligatedTotal = obligatedTotal.add(awardHierarchyNode.getObligatedTotalIndirect()); anticipatedTotal = anticipatedTotal.add(awardHierarchyNode.getAnticipatedTotalDirect()); anticipatedTotal = anticipatedTotal.add(awardHierarchyNode.getAnticipatedTotalIndirect()); if (obligatedTotal.isGreaterThan(anticipatedTotal)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_ANTICIPATED_AMOUNT); valid = false; } if (awardHierarchyNode.getAmountObligatedToDate().isLessThan(KualiDecimal.ZERO)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_OBLIGATED_AMOUNT_NEGATIVE); valid = false; } return valid; } /** * This method... * @param awardHierarchyNode * @param aai * @return */ public boolean processParameterDisabledRules(AwardHierarchyNode awardHierarchyNode, AwardAmountInfo aai, TimeAndMoneyDocument doc) { boolean valid = true; KualiDecimal obligatedChange = awardHierarchyNode.getAmountObligatedToDate().subtract(aai.getAmountObligatedToDate()); KualiDecimal anticipatedChange = awardHierarchyNode.getAnticipatedTotalAmount().subtract(aai.getAnticipatedTotalAmount()); if ((obligatedChange.isPositive() && anticipatedChange.isNegative()) || obligatedChange.isNegative() && anticipatedChange.isPositive()) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_NET_TOTALS_TRANSACTION); valid = false; } if (awardHierarchyNode.getAmountObligatedToDate().isGreaterThan(awardHierarchyNode.getAnticipatedTotalAmount())) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_ANTICIPATED_AMOUNT); valid = false; } if (awardHierarchyNode.getAmountObligatedToDate().isLessThan(KualiDecimal.ZERO)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_OBLIGATED_AMOUNT_NEGATIVE); valid = false; } if (awardHierarchyNode.getAnticipatedTotalAmount().isLessThan(KualiDecimal.ZERO)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_ANTICIPATED_AMOUNT_NEGATIVE); valid = false; } valid &= validateAwardTotalCostLimit(awardHierarchyNode, aai.getAward()); if (!doc.isInitialSave()) {//this save rule cannot be called on initial save from creation from Award Document. if (doc.getAwardAmountTransactions().size() > 0) { if(doc.getAwardAmountTransactions().get(0).getTransactionTypeCode() == null) { valid = false; reportError(NEW_AWARD_AMOUNT_TRANSACTION+TRANSACTION_TYPE_CODE, KeyConstants.ERROR_TRANSACTION_TYPE_CODE_REQUIRED); } } } return valid; } protected boolean validateAwardTotalCostLimit(AwardHierarchyNode awardHierarchyNode, Award award) { if (award.getTotalCostBudgetLimit() != null && award.getTotalCostBudgetLimit().isGreaterThan(awardHierarchyNode.getObliDistributableAmount())) { reportWarning(TIME_AND_MONEY_TRANSACTION, KeyConstants.WARNING_TRANSACTION_OBLI_LESS_THAN_BUDGET_LIMIT, new String[]{award.getAwardNumber()}); } return true; } private Map<String, String> getHashMapToFindActiveAward(String goToAwardNumber) { Map<String, String> map = new HashMap<String,String>(); map.put("awardNumber", goToAwardNumber); return map; } private Map<String, String> getHashMap(String goToAwardNumber) { Map<String, String> map = new HashMap<String,String>(); map.put("awardNumber", goToAwardNumber); return map; } }
src/main/java/org/kuali/kra/timeandmoney/transactions/TransactionRuleImpl.java
/* * Copyright 2005-2010 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/ecl1.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.kra.timeandmoney.transactions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.kra.award.awardhierarchy.AwardHierarchyService; import org.kuali.kra.award.home.Award; import org.kuali.kra.award.home.AwardAmountInfo; import org.kuali.kra.award.version.service.AwardVersionService; import org.kuali.kra.bo.versioning.VersionHistory; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KeyConstants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.rules.ResearchDocumentRuleBase; import org.kuali.kra.service.VersionHistoryService; import org.kuali.kra.timeandmoney.AwardHierarchyNode; import org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument; import org.kuali.kra.timeandmoney.history.TransactionDetail; import org.kuali.kra.timeandmoney.service.ActivePendingTransactionsService; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.util.GlobalVariables; /** * The AwardPaymentScheduleRuleImpl */ public class TransactionRuleImpl extends ResearchDocumentRuleBase implements TransactionRule { private static final String SOURCE_AWARD_PROPERTY = "sourceAwardNumber"; private static final String OBLIGATED_AMOUNT_PROPERTY = "obligatedAmount"; private static final String ANTICIPATED_AMOUNT_PROPERTY = "anticipatedAmount"; private static final String DESTINATION_AWARD_PROPERTY = "destinationAwardNumber"; private static final String CURRENT_FUND_EFFECTIVE_DATE = "currentFundEffectiveDate"; private static final String SOURCE_AWARD_ERROR_PARM = "Source Award (Source Award)"; private static final String DESTINATION_AWARD_ERROR_PARM = "Destination Award (Destination Award)"; private static final String TOTALS = "totals"; private static final String TIME_AND_MONEY_TRANSACTION = "timeAndMoneyTransaction"; private static final String NEW_AWARD_AMOUNT_TRANSACTION = "newAwardAmountTransaction"; private static final String TRANSACTION_TYPE_CODE = ".transactionTypeCode"; private ParameterService parameterService; /** * * @see org.kuali.kra.timeandmoney.transactions.TransactionRule#processPendingTransactionBusinessRules( * org.kuali.kra.timeandmoney.transactions.TransactionRuleEvent) */ public boolean processPendingTransactionBusinessRules(TransactionRuleEvent event) { return processCommonValidations(event); } /** * * This method processes new Pending Transaction rules * * @param event * @return */ public boolean processAddPendingTransactionBusinessRules(AddTransactionRuleEvent event) { boolean requiredFieldsComplete = areRequiredFieldsComplete(event.getPendingTransactionItemForValidation()); if (requiredFieldsComplete) { event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getPendingTransactionItemForValidation()); List<Award> awards = processTransactions(event.getTimeAndMoneyDocument()); Award award = getLastSourceAwardReferenceInAwards(awards, event.getPendingTransactionItemForValidation().getSourceAwardNumber()); //if source award is "External, the award will be null and we don't need to validate these amounts. boolean validObligatedFunds = true; boolean validAnticipatedFunds = true; boolean validTotalCostLimit = true; if(!(award == null)) { validObligatedFunds = validateSourceObligatedFunds(event.getPendingTransactionItemForValidation(), award); validAnticipatedFunds = validateSourceAnticipatedFunds(event.getPendingTransactionItemForValidation(), award); validTotalCostLimit = validateAwardTotalCostLimit(event.getPendingTransactionItemForValidation(), award); //need to remove the award amount info created from this process transactions call so there won't be a double entry in collection. award.refreshReferenceObject("awardAmountInfos"); } boolean validFunds = false; boolean validDates = false; boolean validSourceAwardDestinationAward = false; validSourceAwardDestinationAward = processCommonValidations(event); if(validSourceAwardDestinationAward){ validFunds = validateAnticipatedGreaterThanObligated (event, awards); validDates = validateObligatedDateIsSet(event, awards); } return requiredFieldsComplete && validSourceAwardDestinationAward && validObligatedFunds && validAnticipatedFunds && validFunds && validDates && validTotalCostLimit ; } else { return false; } } /** * @see org.kuali.kra.timeandmoney.transactions.TransactionRule#processSingleNodeTransactionBusinessRules(org.kuali.kra.timeandmoney.AwardHierarchyNode, org.kuali.kra.award.home.AwardAmountInfo) * Business rules for single node transactions * 1)if direct/F&A view is disabled, then we test that transaction will either move anticipated/obligated money into or our of award. * We cannot have the instance where we are moving in and out of award at same time since the transactions have a source and destination award * 2)if Direct/F&A view is enabled, then there are two possibilities. * a)We cannot move money in and out of award for direct/indirect amounts in same transaction. * b)The exception to this rule is if doing so does not affect the total amount. The net affect of this is moving money from idc to dc or * vice versa. */ public boolean processSingleNodeTransactionBusinessRules (AwardHierarchyNode awardHierarchyNode, AwardAmountInfo aai, TimeAndMoneyDocument doc) { boolean returnValue; if(isDirectIndirectViewEnabled()) { returnValue = processParameterEnabledRules(awardHierarchyNode, aai, doc); } else { returnValue = processParameterDisabledRules(awardHierarchyNode, aai, doc); } return returnValue; } /** * Looks up and returns the ParameterService. * @return the parameter service. */ protected ParameterService getParameterService() { if (this.parameterService == null) { this.parameterService = KraServiceLocator.getService(ParameterService.class); } return this.parameterService; } public boolean isDirectIndirectViewEnabled() { boolean returnValue = false; String directIndirectEnabledValue = getParameterService().getParameterValueAsString(Constants.PARAMETER_MODULE_AWARD, ParameterConstants.DOCUMENT_COMPONENT, "ENABLE_AWD_ANT_OBL_DIRECT_INDIRECT_COST"); if(directIndirectEnabledValue.equals("1")) { returnValue = true; } return returnValue; } private boolean validateAnticipatedGreaterThanObligated (AddTransactionRuleEvent event, List<Award> awards) { boolean valid = true; //add the transaction to the document so we can simulate processing the transaction. event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); for (Award award : awards) { Award activeAward = getAwardVersionService().getWorkingAwardVersion(award.getAwardNumber()); AwardAmountInfo awardAmountInfo = activeAward.getAwardAmountInfos().get(activeAward.getAwardAmountInfos().size() -1); KualiDecimal anticipatedTotal = awardAmountInfo.getAnticipatedTotalAmount(); KualiDecimal obligatedTotal = awardAmountInfo.getAmountObligatedToDate(); for (PendingTransaction pendingTransaction: event.getTimeAndMoneyDocument().getPendingTransactions()) { if (StringUtils.equals(pendingTransaction.getSourceAwardNumber(), awardAmountInfo.getAwardNumber())) { anticipatedTotal = anticipatedTotal.subtract(pendingTransaction.getAnticipatedAmount()); obligatedTotal = obligatedTotal.subtract(pendingTransaction.getObligatedAmount()); } if (StringUtils.equals(pendingTransaction.getDestinationAwardNumber(), award.getAwardNumber())) { anticipatedTotal = anticipatedTotal.add(pendingTransaction.getAnticipatedAmount()); obligatedTotal = obligatedTotal.add(pendingTransaction.getObligatedAmount()); } if (anticipatedTotal.isLessThan(obligatedTotal)) { reportError(OBLIGATED_AMOUNT_PROPERTY, KeyConstants.ERROR_TOTAL_AMOUNT_INVALID, activeAward.getAwardNumber()); valid = false; } } award.refreshReferenceObject("awardAmountInfos"); } //remove the Transaction from the document. event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getTimeAndMoneyDocument().getPendingTransactions().size() - 1); return valid; } private boolean validateObligatedDateIsSet (AddTransactionRuleEvent event, List<Award> awards) { boolean valid = true; //add the transaction to the document so we can simulate processing the transaction. event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); for (Award award : awards) { Award activeAward = getAwardVersionService().getWorkingAwardVersion(award.getAwardNumber()); AwardAmountInfo awardAmountInfo = activeAward.getAwardAmountInfos().get(activeAward.getAwardAmountInfos().size() -1); if (awardAmountInfo.getAmountObligatedToDate().isPositive() && (awardAmountInfo.getCurrentFundEffectiveDate() == null || awardAmountInfo.getObligationExpirationDate() == null)) { reportError(CURRENT_FUND_EFFECTIVE_DATE, KeyConstants.ERROR_DATE_NOT_SET, activeAward.getAwardNumber()); valid = false; } award.refreshReferenceObject("awardAmountInfos"); } //remove the Transaction from the document. event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getTimeAndMoneyDocument().getPendingTransactions().size() - 1); return valid; } private Award findUpdatedRootAward(List<Award> awards, String rootAwardNumber) { Award returnAward = null; for (Award award : awards) { if (award.getAwardNumber() == rootAwardNumber) { returnAward = award; } } if(returnAward == null) { returnAward = getAwardVersionService().getWorkingAwardVersion(rootAwardNumber); // if(returnAward == null){ // returnAward = getActiveAwardVersion(rootAwardNumber); // } } return returnAward; } private List<Award> processTransactions(TimeAndMoneyDocument timeAndMoneyDocument) { Map<String, AwardAmountTransaction> awardAmountTransactionItems = new HashMap<String, AwardAmountTransaction>(); List<Award> awardItems = new ArrayList<Award>(); List<TransactionDetail> transactionDetailItems = new ArrayList<TransactionDetail>(); ActivePendingTransactionsService service = KraServiceLocator.getService(ActivePendingTransactionsService.class); service.processTransactionsForAddRuleProcessing(timeAndMoneyDocument, timeAndMoneyDocument.getAwardAmountTransactions().get(0), awardAmountTransactionItems, awardItems, transactionDetailItems); return awardItems; } private Award getLastSourceAwardReferenceInAwards (List<Award> awards, String sourceAwardNumber) { Award returnAward = null; for (Award award : awards) { if (award.getAwardNumber() == sourceAwardNumber) { returnAward = award; } } if(returnAward == null) { returnAward = getAwardVersionService().getWorkingAwardVersion(sourceAwardNumber); // if(returnAward == null){ // returnAward = getActiveAwardVersion(sourceAwardNumber); // } } return returnAward; } private boolean validateSourceObligatedFunds (PendingTransaction pendingTransaction, Award award) { AwardAmountInfo awardAmountInfo = award.getAwardAmountInfos().get(award.getAwardAmountInfos().size() -1); boolean valid = true; if (awardAmountInfo.getObliDistributableAmount().subtract(pendingTransaction.getObligatedAmount()).isNegative()) { reportError(OBLIGATED_AMOUNT_PROPERTY, KeyConstants.ERROR_OBLIGATED_AMOUNT_INVALID); valid = false; } return valid; } private boolean validateSourceAnticipatedFunds (PendingTransaction pendingTransaction, Award award) { AwardAmountInfo awardAmountInfo = award.getAwardAmountInfos().get(award.getAwardAmountInfos().size() -1); boolean valid = true; if (awardAmountInfo.getAntDistributableAmount().subtract(pendingTransaction.getAnticipatedAmount()).isNegative()) { reportError(ANTICIPATED_AMOUNT_PROPERTY, KeyConstants.ERROR_ANTICIPATED_AMOUNT_INVALID); valid = false; } return valid; } private boolean validateAwardTotalCostLimit(PendingTransaction pendingTransaction, Award award) { AwardAmountInfo awardAmountInfo = award.getAwardAmountInfos().get(award.getAwardAmountInfos().size() -1); KualiDecimal obliDistributableAmount = awardAmountInfo.getObliDistributableAmount().subtract(pendingTransaction.getObligatedAmount()); if (award.getTotalCostBudgetLimit() != null && award.getTotalCostBudgetLimit().isGreaterThan(obliDistributableAmount)) { reportWarning(OBLIGATED_AMOUNT_PROPERTY, KeyConstants.WARNING_TRANSACTION_OBLI_LESS_THAN_BUDGET_LIMIT, new String[]{award.getAwardNumber()}); } return true; } private boolean processCommonValidations(TransactionRuleEvent event) { PendingTransaction pendingTransactionItem = event.getPendingTransactionItemForValidation(); List<PendingTransaction> items = event.getTimeAndMoneyDocument().getPendingTransactions(); return isUnique(items, pendingTransactionItem) && sourceAndDestinationAwardsAreDifferent(pendingTransactionItem) && enforcePositiveAmounts(pendingTransactionItem); } boolean enforcePositiveAmounts(PendingTransaction pendingTransactionItem) { boolean valid = true; if(pendingTransactionItem.getAnticipatedAmount().isNegative() || pendingTransactionItem.getObligatedAmount().isNegative() || pendingTransactionItem.getAnticipatedDirectAmount().isNegative() || pendingTransactionItem.getAnticipatedIndirectAmount().isNegative() || pendingTransactionItem.getObligatedDirectAmount().isNegative() || pendingTransactionItem.getObligatedIndirectAmount().isNegative()) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_TRANSACTION_AMOUNTS_NEGATIVE); valid = false; } return valid; } boolean sourceAndDestinationAwardsAreDifferent(PendingTransaction pendingTransactionItem){ boolean srcAndDestinationAwardsAreDifferent = !StringUtils.equalsIgnoreCase(pendingTransactionItem.getSourceAwardNumber() , pendingTransactionItem.getDestinationAwardNumber()); if(!srcAndDestinationAwardsAreDifferent){ reportError(PENDING_TRANSACTION_ITEMS_LIST_ERROR_KEY, KeyConstants.ERROR_TNM_PENDING_TRANSACTION_SOURCE_AND_DESTINATION_AWARDS_ARE_SAME, SOURCE_AWARD_PROPERTY); } return srcAndDestinationAwardsAreDifferent; } /** * A pending transaction item is unique if no other matching items are in the collection * To know if this is a new add or an edit of an existing pending transaction item, we check * the identifier for nullity. If null, this is an add; otherwise, it's an update * If an update, then we expect to find one match in the collection (itself). If an add, * we expect to find no matches in the collection * @param pendingTransactionItems * @param pendingTransactionItem * @return */ boolean isUnique(List<PendingTransaction> pendingTransactionItems, PendingTransaction pendingTransactionItem) { boolean duplicateFound = false; for(PendingTransaction listItem: pendingTransactionItems) { duplicateFound = pendingTransactionItem != listItem && listItem.equals(pendingTransactionItem); if(duplicateFound) { break; } } if(duplicateFound) { if(!hasDuplicateErrorBeenReported()) { reportError(PENDING_TRANSACTION_ITEMS_LIST_ERROR_KEY, KeyConstants.ERROR_TNM_PENDING_TRANSACTION_ITEM_NOT_UNIQUE, SOURCE_AWARD_PROPERTY); } } return !duplicateFound; } /** * Validate required fields present * @param equipmentItem * @return */ boolean areRequiredFieldsComplete(PendingTransaction pendingTransactionItem) { boolean itemValid = isSourceAwardFieldComplete(pendingTransactionItem); itemValid &= isDestinationAwardFieldComplete(pendingTransactionItem); return itemValid; } protected boolean isSourceAwardFieldComplete(PendingTransaction pendingTransactionItem){ boolean itemValid = pendingTransactionItem.getSourceAwardNumber() != null; if(!itemValid) { reportError(SOURCE_AWARD_PROPERTY, KeyConstants.ERROR_REQUIRED, SOURCE_AWARD_ERROR_PARM); } return itemValid; } protected boolean isDestinationAwardFieldComplete(PendingTransaction pendingTransactionItem){ boolean itemValid = pendingTransactionItem.getDestinationAwardNumber() != null; if(!itemValid) { reportError(DESTINATION_AWARD_PROPERTY, KeyConstants.ERROR_REQUIRED, DESTINATION_AWARD_ERROR_PARM); } return itemValid; } private boolean hasDuplicateErrorBeenReported() { return GlobalVariables.getMessageMap().containsMessageKey(KeyConstants.ERROR_TNM_PENDING_TRANSACTION_ITEM_NOT_UNIQUE); } /* * This method retrieves AwardHierarchyService */ protected AwardHierarchyService getAwardHierarchyService(){ return (AwardHierarchyService) KraServiceLocator.getService(AwardHierarchyService.class); } public AwardVersionService getAwardVersionService() { return KraServiceLocator.getService(AwardVersionService.class); } // public Award getWorkingAwardVersion(String goToAwardNumber) { // Award award = null; // award = getPendingAwardVersion(goToAwardNumber); // if (award == null) { // award = getActiveAwardVersion(goToAwardNumber); // } // return award; // } /** * This method... * @param awardHierarchyNode * @param aai * @return */ public boolean processParameterEnabledRules(AwardHierarchyNode awardHierarchyNode, AwardAmountInfo aai, TimeAndMoneyDocument doc) { boolean valid = true; KualiDecimal obligatedDirectChange = awardHierarchyNode.getObligatedTotalDirect().subtract(aai.getObligatedTotalDirect()); KualiDecimal obligatedIndirectChange = awardHierarchyNode.getObligatedTotalIndirect().subtract(aai.getObligatedTotalIndirect()); KualiDecimal anticipatedDirectChange = awardHierarchyNode.getAnticipatedTotalDirect().subtract(aai.getAnticipatedTotalDirect()); KualiDecimal anticipatedIndirectChange = awardHierarchyNode.getAnticipatedTotalIndirect().subtract(aai.getAnticipatedTotalIndirect()); boolean obligatedTotalChanged = awardHierarchyNode.getObligatedTotalDirect().add(awardHierarchyNode.getObligatedTotalIndirect()).isNonZero(); boolean anticipatedTotalChanged = awardHierarchyNode.getAnticipatedTotalDirect().add(awardHierarchyNode.getAnticipatedTotalIndirect()).isNonZero(); //if totals change and net effect of changes result in reduction of one total with increase of other, we need to report error. if(obligatedTotalChanged || anticipatedTotalChanged) { KualiDecimal obligatedNetEffect = awardHierarchyNode.getObligatedTotalDirect().add(awardHierarchyNode.getObligatedTotalIndirect()); KualiDecimal anticipatedNetEffect = awardHierarchyNode.getAnticipatedTotalDirect().add(awardHierarchyNode.getAnticipatedTotalIndirect()); if((obligatedNetEffect.isNegative() && anticipatedNetEffect.isPositive()) || (obligatedNetEffect.isPositive() && anticipatedNetEffect.isNegative())) { reportError(TOTALS, KeyConstants.ERROR_NET_TOTALS_TRANSACTION); valid = false; } } //if indirect/direct change in transaction is a debit of one and credit of the other, then there cannot be a net change in total. if((((obligatedDirectChange.isPositive() && obligatedIndirectChange.isNegative()) || (obligatedDirectChange.isNegative() && obligatedIndirectChange.isPositive())) && obligatedTotalChanged) || (((anticipatedDirectChange.isPositive() && anticipatedIndirectChange.isNegative()) || (anticipatedDirectChange.isNegative() && anticipatedIndirectChange.isPositive())) && anticipatedTotalChanged)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_NET_TOTALS_TRANSACTION); valid = false; } valid &= validateAwardTotalCostLimit(awardHierarchyNode, aai.getAward()); if (!doc.isInitialSave()) {//this save rule cannot be called on initial save from creation from Award Document. if (doc.getAwardAmountTransactions().size() > 0) { if(doc.getAwardAmountTransactions().get(0).getTransactionTypeCode() == null) { valid = false; reportError(NEW_AWARD_AMOUNT_TRANSACTION+TRANSACTION_TYPE_CODE, KeyConstants.ERROR_TRANSACTION_TYPE_CODE_REQUIRED); } } } KualiDecimal obligatedTotal = new KualiDecimal(0); KualiDecimal anticipatedTotal= new KualiDecimal(0); obligatedTotal = obligatedTotal.add(awardHierarchyNode.getObligatedTotalDirect()); obligatedTotal = obligatedTotal.add(awardHierarchyNode.getObligatedTotalIndirect()); anticipatedTotal = anticipatedTotal.add(awardHierarchyNode.getAnticipatedTotalDirect()); anticipatedTotal = anticipatedTotal.add(awardHierarchyNode.getAnticipatedTotalIndirect()); if (obligatedTotal.isGreaterThan(anticipatedTotal)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_ANTICIPATED_AMOUNT); valid = false; } if (awardHierarchyNode.getAmountObligatedToDate().isLessThan(KualiDecimal.ZERO)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_OBLIGATED_AMOUNT_NEGATIVE); valid = false; } return valid; } /** * This method... * @param awardHierarchyNode * @param aai * @return */ public boolean processParameterDisabledRules(AwardHierarchyNode awardHierarchyNode, AwardAmountInfo aai, TimeAndMoneyDocument doc) { boolean valid = true; KualiDecimal obligatedChange = awardHierarchyNode.getAmountObligatedToDate().subtract(aai.getAmountObligatedToDate()); KualiDecimal anticipatedChange = awardHierarchyNode.getAnticipatedTotalAmount().subtract(aai.getAnticipatedTotalAmount()); if ((obligatedChange.isPositive() && anticipatedChange.isNegative()) || obligatedChange.isNegative() && anticipatedChange.isPositive()) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_NET_TOTALS_TRANSACTION); valid = false; } if (awardHierarchyNode.getAmountObligatedToDate().isGreaterThan(awardHierarchyNode.getAnticipatedTotalAmount())) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_ANTICIPATED_AMOUNT); valid = false; } if (awardHierarchyNode.getAmountObligatedToDate().isLessThan(KualiDecimal.ZERO)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_OBLIGATED_AMOUNT_NEGATIVE); valid = false; } if (awardHierarchyNode.getAnticipatedTotalAmount().isLessThan(KualiDecimal.ZERO)) { reportError(TIME_AND_MONEY_TRANSACTION, KeyConstants.ERROR_ANTICIPATED_AMOUNT_NEGATIVE); valid = false; } valid &= validateAwardTotalCostLimit(awardHierarchyNode, aai.getAward()); if (!doc.isInitialSave()) {//this save rule cannot be called on initial save from creation from Award Document. if (doc.getAwardAmountTransactions().size() > 0) { if(doc.getAwardAmountTransactions().get(0).getTransactionTypeCode() == null) { valid = false; reportError(NEW_AWARD_AMOUNT_TRANSACTION+TRANSACTION_TYPE_CODE, KeyConstants.ERROR_TRANSACTION_TYPE_CODE_REQUIRED); } } } return valid; } protected boolean validateAwardTotalCostLimit(AwardHierarchyNode awardHierarchyNode, Award award) { if (award.getTotalCostBudgetLimit() != null && award.getTotalCostBudgetLimit().isGreaterThan(awardHierarchyNode.getObliDistributableAmount())) { reportWarning(TIME_AND_MONEY_TRANSACTION, KeyConstants.WARNING_TRANSACTION_OBLI_LESS_THAN_BUDGET_LIMIT, new String[]{award.getAwardNumber()}); } return true; } private Map<String, String> getHashMapToFindActiveAward(String goToAwardNumber) { Map<String, String> map = new HashMap<String,String>(); map.put("awardNumber", goToAwardNumber); return map; } private Map<String, String> getHashMap(String goToAwardNumber) { Map<String, String> map = new HashMap<String,String>(); map.put("awardNumber", goToAwardNumber); return map; } }
KRACOEUS-6161: Make sure initial transaction is processed the same as the rest...
src/main/java/org/kuali/kra/timeandmoney/transactions/TransactionRuleImpl.java
KRACOEUS-6161: Make sure initial transaction is processed the same as the rest...
<ide><path>rc/main/java/org/kuali/kra/timeandmoney/transactions/TransactionRuleImpl.java <ide> boolean requiredFieldsComplete = areRequiredFieldsComplete(event.getPendingTransactionItemForValidation()); <ide> if (requiredFieldsComplete) { <ide> event.getTimeAndMoneyDocument().add(event.getPendingTransactionItemForValidation()); <add> List<Award> awards = processTransactions(event.getTimeAndMoneyDocument()); <add> // need to remove the following, but do it after we processTransactions() since that <add> // method depends on a complete list of pending transactions to determine which awards <add> // are affected by this new transaction. <ide> event.getTimeAndMoneyDocument().getPendingTransactions().remove(event.getPendingTransactionItemForValidation()); <del> List<Award> awards = processTransactions(event.getTimeAndMoneyDocument()); <ide> Award award = getLastSourceAwardReferenceInAwards(awards, event.getPendingTransactionItemForValidation().getSourceAwardNumber()); <ide> //if source award is "External, the award will be null and we don't need to validate these amounts. <ide> boolean validObligatedFunds = true;
JavaScript
bsd-3-clause
4ceabbfd8b36f30323d73083fc59bee7b04e5a52
0
splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb,splashblot/deep-insights.js,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,splashblot/deep-insights.js,splashblot/dronedb
var AutoStyler = require('./auto-styler'); var _ = require('underscore'); var HistogramAutoStyler = AutoStyler.extend({ getStyle: function () { var preserveWidth = true; var startingStyle = this.layer.get && (this.layer.get('cartocss') || this.layer.get('meta').cartocss); if (startingStyle) { var originalWidth = startingStyle.match(/marker-width:.*;/g); if (originalWidth) { if (originalWidth.length > 1) { preserveWidth = false; } else { originalWidth = originalWidth[0].replace('marker-width:', '').replace(';', ''); } } } var style = ''; var colors = ['YlGnBu', 'Greens', 'Reds', 'Blues']; var color = colors[Math.floor(Math.random() * colors.length)]; var stylesByGeometry = this.STYLE_TEMPLATE; var geometryType = this.layer.getGeometryType(); if (geometryType) { style = this._getHistGeometry(geometryType) .replace('{{layername}}', '#layer{'); } else { for (var symbol in stylesByGeometry) { style += this._getHistGeometry(symbol) .replace('{{layername}}', this._getLayerHeader(symbol)); } } if (preserveWidth) { style = style.replace('{{markerWidth}}', originalWidth); } return style.replace(/{{column}}/g, this.dataviewModel.get('column')) .replace(/{{bins}}/g, this.dataviewModel.get('bins')) .replace(/{{color}}/g, color) .replace(/{{min}}/g, 1) .replace(/{{max}}/g, 20) .replace(/{{ramp}}/g, '') .replace(/{{defaultColor}}/g, '#000'); }, _getHistGeometry: function (geometryType) { var style = this.STYLE_TEMPLATE[geometryType]; var shape = this.dataviewModel.getDistributionType(); if (geometryType === 'polygon') { if (shape === 'F') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset3, {{bins}})), quantiles'); } else if (shape === 'L' || shape === 'J') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset2, {{bins}}), headtails)'); } else if (shape === 'A') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Geyser, {{bins}})), quantiles'); } else if (shape === 'C' || shape === 'U') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Emrld1, {{bins}}), jenks)'); } else { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], colorbrewer({{color}}, {{bins}}))'); } } else if (geometryType === 'marker') { if (shape === 'F') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(RedOr1, {{bins}})), quantiles'); } else if (shape === 'L' || shape === 'J') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset2, {{bins}}), headtails)'); } else if (shape === 'A') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Geyser, {{bins}})), quantiles)'); } else if (shape === 'C' || shape === 'U') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(BluYl1, {{bins}}), jenks)'); } else { style = style.replace('{{markerWidth}}', 'ramp([{{column}}], {{min}}, {{max}}, {{bins}})'); } } else { style = style.replace('{{markerWidth}}', 'ramp([{{column}}], {{min}}, {{max}}, {{bins}})'); } return style; } }); module.exports = HistogramAutoStyler;
src/widgets/auto-style/histogram.js
var AutoStyler = require('./auto-styler'); var HistogramAutoStyler = AutoStyler.extend({ getStyle: function () { var style = ''; var colors = ['YlGnBu', 'Greens', 'Reds', 'Blues']; var color = colors[Math.floor(Math.random() * colors.length)]; var stylesByGeometry = this.STYLE_TEMPLATE; var geometryType = this.layer.getGeometryType(); if (geometryType) { style = this._getHistGeometry(geometryType) .replace('{{layername}}', '#layer{'); } else { for (var symbol in stylesByGeometry) { style += this._getHistGeometry(symbol) .replace('{{layername}}', this._getLayerHeader(symbol)); } } return style.replace(/{{column}}/g, this.dataviewModel.get('column')) .replace(/{{bins}}/g, this.dataviewModel.get('bins')) .replace(/{{color}}/g, color) .replace(/{{min}}/g, 1) .replace(/{{max}}/g, 20) .replace(/{{ramp}}/g, '') .replace(/{{defaultColor}}/g, '#000'); }, _getHistGeometry: function (geometryType) { var style = this.STYLE_TEMPLATE[geometryType]; var shape = this.dataviewModel.getDistributionType(); if (geometryType === 'polygon') { if (shape === 'F') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset3, {{bins}})), quantiles'); } else if (shape === 'L' || shape === 'J') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset2, {{bins}}), headtails)'); } else if (shape === 'A') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Geyser, {{bins}})), quantiles'); } else if (shape === 'C' || shape === 'U') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Emrld1, {{bins}}), jenks)'); } else { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], colorbrewer({{color}}, {{bins}}))'); } } else if (geometryType === 'marker') { if (shape === 'F') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(RedOr1, {{bins}})), quantiles') .replace('{{markerWidth}}', '7'); } else if (shape === 'L' || shape === 'J') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset2, {{bins}}), headtails)') .replace('{{markerWidth}}', '7'); } else if (shape === 'A') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Geyser, {{bins}})), quantiles') .replace('{{markerWidth}}', '7'); } else if (shape === 'C' || shape === 'U') { style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(BluYl1, {{bins}}), jenks)') .replace('{{markerWidth}}', '7'); } else { style = style.replace('{{markerWidth}}', 'ramp([{{column}}], {{min}}, {{max}}, {{bins}})'); } } else { style = style.replace('{{markerWidth}}', 'ramp([{{column}}], {{min}}, {{max}}, {{bins}})'); } return style; } }); module.exports = HistogramAutoStyler;
preserves marker width for histogram autostyling, too
src/widgets/auto-style/histogram.js
preserves marker width for histogram autostyling, too
<ide><path>rc/widgets/auto-style/histogram.js <ide> var AutoStyler = require('./auto-styler'); <add>var _ = require('underscore'); <ide> var HistogramAutoStyler = AutoStyler.extend({ <ide> getStyle: function () { <add> var preserveWidth = true; <add> var startingStyle = this.layer.get && (this.layer.get('cartocss') || this.layer.get('meta').cartocss); <add> if (startingStyle) { <add> var originalWidth = startingStyle.match(/marker-width:.*;/g); <add> if (originalWidth) { <add> if (originalWidth.length > 1) { <add> preserveWidth = false; <add> } else { <add> originalWidth = originalWidth[0].replace('marker-width:', '').replace(';', ''); <add> } <add> } <add> } <ide> var style = ''; <ide> var colors = ['YlGnBu', 'Greens', 'Reds', 'Blues']; <ide> var color = colors[Math.floor(Math.random() * colors.length)]; <ide> style += this._getHistGeometry(symbol) <ide> .replace('{{layername}}', this._getLayerHeader(symbol)); <ide> } <add> } <add> if (preserveWidth) { <add> style = style.replace('{{markerWidth}}', originalWidth); <ide> } <ide> return style.replace(/{{column}}/g, this.dataviewModel.get('column')) <ide> .replace(/{{bins}}/g, this.dataviewModel.get('bins')) <ide> } <ide> } else if (geometryType === 'marker') { <ide> if (shape === 'F') { <del> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(RedOr1, {{bins}})), quantiles') <del> .replace('{{markerWidth}}', '7'); <add> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(RedOr1, {{bins}})), quantiles'); <ide> } else if (shape === 'L' || shape === 'J') { <del> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset2, {{bins}}), headtails)') <del> .replace('{{markerWidth}}', '7'); <add> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Sunset2, {{bins}}), headtails)'); <ide> } else if (shape === 'A') { <del> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Geyser, {{bins}})), quantiles') <del> .replace('{{markerWidth}}', '7'); <add> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(Geyser, {{bins}})), quantiles)'); <ide> } else if (shape === 'C' || shape === 'U') { <del> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(BluYl1, {{bins}}), jenks)') <del> .replace('{{markerWidth}}', '7'); <add> style = style.replace('{{defaultColor}}', 'ramp([{{column}}], cartocolor(BluYl1, {{bins}}), jenks)'); <ide> } else { <ide> style = style.replace('{{markerWidth}}', 'ramp([{{column}}], {{min}}, {{max}}, {{bins}})'); <ide> }
Java
apache-2.0
997b990dd06799f52ebdb3cdc498e533d9850f99
0
anzhdanov/seeding-realistic-concurrency-bugs,mureinik/commons-lang,rikles/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,mureinik/commons-lang,mureinik/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang,rikles/commons-lang
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.commons.lang; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * <p><code>ArrayUtils</code> contains utility methods for working for * arrays.</p> * * @author Stephen Colebourne * @author Moritz Petersen * @author <a href="mailto:[email protected]">Fredrik Westermarck</a> * @author Nikolay Metchev * @since 2.0 * @version $Id: ArrayUtils.java,v 1.10 2003/03/23 17:57:42 scolebourne Exp $ */ public class ArrayUtils { /** An empty immutable object array */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** An empty immutable class array */ public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; /** An empty immutable string array */ public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** An empty immutable long array */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** An empty immutable int array */ public static final int[] EMPTY_INT_ARRAY = new int[0]; /** An empty immutable short array */ public static final short[] EMPTY_SHORT_ARRAY = new short[0]; /** An empty immutable byte array */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** An empty immutable double array */ public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; /** An empty immutable float array */ public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; /** An empty immutable boolean array */ public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * <p>ArrayUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as <code>ArrayUtils.clone(new int[] {2})</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean instance * to operate.</p> */ public ArrayUtils() { } // Basic methods handling multi-dimensional arrays //----------------------------------------------------------------------- /** * <p>Outputs an array as a String, treating <code>null</code> as an empty array.</p> * * <p>Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.</p> * * <p>The format is that of Java source code, for example {a,b}.</p> * * @param array the array to get a toString for, may be <code>null</code> * @return a String representation of the array, '{}' if <code>null</code> passed in */ public static String toString(Object array) { return toString(array, "{}"); } /** * <p>Outputs an array as a String handling <code>null</code>s.</p> * * <p>Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.</p> * * <p>The format is that of Java source code, for example {a,b}.</p> * * @param array the array to get a toString for, may be <code>null</code> * @param stringIfNull the String to return if the array is <code>null</code> * @return a String representation of the array */ public static String toString(Object array, String stringIfNull) { if (array == null) { return stringIfNull; } return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); } /** * <p>Get a hashCode for an array handling multi-dimensional arrays correctly.</p> * * <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p> * * @param array the array to get a hashCode for, may be <code>null</code> * @return a hashCode for the array */ public static int hashCode(Object array) { return new HashCodeBuilder().append(array).toHashCode(); } /** * <p>Compares two arrays, using equals(), handling multi-dimensional arrays * correctly.</p> * * <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p> * * @param array1 the array to get a hashCode for, may be <code>null</code> * @param array2 the array to get a hashCode for, may be <code>null</code> * @return <code>true</code> if the arrays are equal */ public static boolean isEquals(Object array1, Object array2) { return new EqualsBuilder().append(array1, array2).isEquals(); } //----------------------------------------------------------------------- /** * <p>Converts the given array into a {@link Map}. Each element of the array * must be either a {@link Map.Entry} or an Array, containing at least two * elements, where the first element is used as key and the second as * value.</p> * * <p>This method can be used to initialize:</p> * <pre> * // Create a Map mapping colors. * Map colorMap = MapUtils.toMap(new String[][] {{ * {"RED", "#FF0000"}, * {"GREEN", "#00FF00"}, * {"BLUE", "#0000FF"}}); * </pre> * * @param array an array whose elements are either a {@link Map.Entry} or * an Array containing at least two elements * @return a <code>Map</code> that was created from the array * @throws IllegalArgumentException if the array is <code>null</code> * @throws IllegalArgumentException if one element of this Array is * itself an Array containing less then two elements * @throws IllegalArgumentException if the array contains elements other * than {@link Map.Entry} and an Array */ public static Map toMap(Object[] array) { if (array == null) { throw new IllegalArgumentException("The array must not be null"); } Map map = new HashMap((int) (array.length * 1.5)); for (int i = 0; i < array.length; i++) { Object object = array[i]; if (object instanceof Map.Entry) { Map.Entry entry = (Map.Entry) object; map.put(entry.getKey(), entry.getValue()); } else if (object instanceof Object[]) { Object[] entry = (Object[]) object; if (entry.length < 2) { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', has a length less than 2"); } map.put(entry[0], entry[1]); } else { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', is neither of type Map.Entry nor an Array"); } } return map; } // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(long[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(int[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(short[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(byte[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1.0,2.0}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(double[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1.0,2.0}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(float[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {true,false}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(boolean[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } //----------------------------------------------------------------------- /** * <p>Shallow clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>The objecs in the array are not cloned, thus there is no special * handling for multi-dimensional arrays.</p> * * @param array the array to shallow clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static Object[] clone(Object[] array) { if (array == null) { return null; } return (Object[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static long[] clone(long[] array) { if (array == null) { return null; } return (long[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static int[] clone(int[] array) { if (array == null) { return null; } return (int[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static short[] clone(short[] array) { if (array == null) { return null; } return (short[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static char[] clone(char[] array) { if (array == null) { return null; } return (char[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static byte[] clone(byte[] array) { if (array == null) { return null; } return (byte[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static double[] clone(double[] array) { if (array == null) { return null; } return (double[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static float[] clone(float[] array) { if (array == null) { return null; } return (float[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static boolean[] clone(boolean[] array) { if (array == null) { return null; } return (boolean[]) array.clone(); } //----------------------------------------------------------------------- /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>. * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(Object[] array1, Object[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(long[] array1, long[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(int[] array1, int[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(short[] array1, short[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(char[] array1, char[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(byte[] array1, byte[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(double[] array1, double[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored</p>. * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(float[] array1, float[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(boolean[] array1, boolean[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same type taking into account * multi-dimensional arrays.</p> * * <p>Primitive arrays may be compared using this method too.</p> * * @param array1 the first array, must not be <code>null</code> * @param array2 the second array, must not be <code>null</code> * @return <code>true</code> if type of arrays matches * @throws IllegalArgumentException if either array is <code>null</code> */ public static boolean isSameType(Object array1, Object array2) { if (array1 == null || array2 == null) { throw new IllegalArgumentException("The array must not be null"); } return array1.getClass().getName().equals(array2.getClass().getName()); } //----------------------------------------------------------------------- /** * Reverses the order of the given array. * <p> * There is no special handling for multi-dimensional arrays. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(Object[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(long[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; long tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(int[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; int tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * There is no special handling for multi-dimensional arrays. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(short[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; short tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(char[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; char tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(byte[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; byte tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(double[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; double tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(float[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; float tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(boolean[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; boolean tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } //----------------------------------------------------------------------- /** * Find the index of the given object in the array. * <p> * The method returns -1 if a <code>null</code> array is passed in. * * @param array the array to search through for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @return the index of the object within the array, or -1 if not found */ public static int indexOf(Object[] array, Object objectToFind) { return indexOf(array, objectToFind, 0); } /** * Find the index of the given object in the array starting at the given index. * <p> * The method returns -1 if a <code>null</code> array is passed in. * <p> * A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1. * * @param array the array to search through for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @param startIndex the index to start searching at * @return the index of the object within the array starting at the * given index, or -1 if not found */ public static int indexOf(Object[] array, Object objectToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } if (objectToFind == null) { for (int i = startIndex; i < array.length; i++) { if (array[i] == null) { return i; } } } else { for (int i = startIndex; i < array.length; i++) { if (objectToFind.equals(array[i])) { return i; } } } return -1; } /** * Find the last index of the given object within the array. * <p> * The method returns -1 if a <code>null</code> array is passed in. * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @return the last index of the object to find, or -1 if not found */ public static int lastIndexOf(Object[] array, Object objectToFind) { if (array == null) { return -1; } return lastIndexOf(array, objectToFind, array.length - 1); } /** * Find the last index of the given object in the array starting at the given index. * <p> * The method returns -1 if a <code>null</code> array is passed in. * <p> * A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array. * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @param startIndex the start index to travers backwards from * @return the last index of the object within the array starting at the given index, * or -1 if not found */ public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } if (objectToFind == null) { for (int i = startIndex; i >= 0; i--) { if (array[i] == null) { return i; } } } else { for (int i = startIndex; i >= 0; i--) { if (objectToFind.equals(array[i])) { return i; } } } return -1; } /** * Checks if the object is in the given array. * <p> * The method returns <code>false</code> if a <code>null</code> array is passed in. * * @param array the array to search through * @param objectToFind the object to find * @return <code>true</code> if the array contains the object */ public static boolean contains(Object[] array, Object objectToFind) { return (indexOf(array, objectToFind) != -1); } }
src/java/org/apache/commons/lang/ArrayUtils.java
/* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2002-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.commons.lang; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * <p><code>ArrayUtils</code> contains utility methods for working for * arrays.</p> * * @author Stephen Colebourne * @author Moritz Petersen * @author <a href="mailto:[email protected]">Fredrik Westermarck</a> * @author Nikolay Metchev * @since 2.0 * @version $Id: ArrayUtils.java,v 1.9 2003/03/23 04:58:47 bayard Exp $ */ public class ArrayUtils { /** An empty immutable object array */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** An empty immutable class array */ public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; /** An empty immutable string array */ public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** An empty immutable long array */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** An empty immutable int array */ public static final int[] EMPTY_INT_ARRAY = new int[0]; /** An empty immutable short array */ public static final short[] EMPTY_SHORT_ARRAY = new short[0]; /** An empty immutable byte array */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** An empty immutable double array */ public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; /** An empty immutable float array */ public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; /** An empty immutable boolean array */ public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * <p>ArrayUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as <code>ArrayUtils.clone(new int[] {2})</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean instance * to operate.</p> */ public ArrayUtils() { } // Basic methods handling multi-dimensional arrays //----------------------------------------------------------------------- /** * <p>Outputs an array as a String, treating <code>null</code> as an empty array.</p> * * <p>Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.</p> * * <p>The format is that of Java source code, for example {a,b}.</p> * * @param array the array to get a toString for, may be <code>null</code> * @return a String representation of the array, '{}' if <code>null</code> passed in */ public static String toString(Object array) { return toString(array, "{}"); } /** * <p>Outputs an array as a String handling <code>null</code>s.</p> * * <p>Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.</p> * * <p>The format is that of Java source code, for example {a,b}.</p> * * @param array the array to get a toString for, may be <code>null</code> * @param stringIfNull the String to return if the array is <code>null</code> * @return a String representation of the array */ public static String toString(Object array, String stringIfNull) { if (array == null) { return stringIfNull; } return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); } /** * <p>Get a hashCode for an array handling multi-dimensional arrays correctly.</p> * * <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p> * * @param array the array to get a hashCode for, may be <code>null</code> * @return a hashCode for the array */ public static int hashCode(Object array) { return new HashCodeBuilder().append(array).toHashCode(); } /** * <p>Compares two arrays, using equals(), handling multi-dimensional arrays * correctly.</p> * * <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p> * * @param array1 the array to get a hashCode for, may be <code>null</code> * @param array2 the array to get a hashCode for, may be <code>null</code> * @return <code>true</code> if the arrays are equal */ public static boolean isEquals(Object array1, Object array2) { return new EqualsBuilder().append(array1, array2).isEquals(); } //----------------------------------------------------------------------- /** * <p>Converts the given array into a {@link Map}. Each element of the array * must be either a {@link Map.Entry} or an Array, containing at least two * elements, where the first element is used as key and the second as * value.</p> * * <p>This method can be used to initialize:</p> * <pre> * // Create a Map mapping colors. * Map colorMap = MapUtils.toMap(new String[][] {{ * {"RED", "#FF0000"}, * {"GREEN", "#00FF00"}, * {"BLUE", "#0000FF"}}); * </pre> * * @param array an array whose elements are either a {@link Map.Entry} or * an Array containing at least two elements * @return a <code>Map</code> that was created from the array * @throws IllegalArgumentException if the array is <code>null</code> * @throws IllegalArgumentException if one element of this Array is * itself an Array containing less then two elements * @throws IllegalArgumentException if the array contains elements other * than {@link Map.Entry} and an Array */ public static Map toMap(Object[] array) { if (array == null) { throw new IllegalArgumentException("The array must not be null"); } Map map = new HashMap((int) (array.length * 1.5)); for (int i = 0; i < array.length; i++) { Object object = array[i]; if (object instanceof Map.Entry) { Map.Entry entry = (Map.Entry) object; map.put(entry.getKey(), entry.getValue()); } else if (object instanceof Object[]) { Object[] entry = (Object[]) object; if (entry.length < 2) { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', has a length less than 2"); } map.put(entry[0], entry[1]); } else { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', is neither of type Map.Entry nor an Array"); } } return map; } // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(long[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(int[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(short[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1,2}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(byte[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1.0,2.0}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(double[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {1.0,2.0}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(float[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } // // /** // * <p>Output the array as a String.</p> // * // * <p>Multi-dimensional arrays are handled by the Object[] method.</p> // * // * <p>The format is that of Java source code, for example {true,false}.</p> // * // * @param array the array to get a toString for, must not be <code>null</code> // * @return a String representation of the array // * @throws IllegalArgumentException if the array is <code>null</code> // */ // public static String toString(boolean[] array) { // return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); // } //----------------------------------------------------------------------- /** * <p>Shallow clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>The objecs in the array are not cloned, thus there is no special * handling for multi-dimensional arrays.</p> * * @param array the array to shallow clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static Object[] clone(Object[] array) { if (array == null) { return null; } return (Object[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static long[] clone(long[] array) { if (array == null) { return null; } return (long[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static int[] clone(int[] array) { if (array == null) { return null; } return (int[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static short[] clone(short[] array) { if (array == null) { return null; } return (short[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static char[] clone(char[] array) { if (array == null) { return null; } return (char[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static byte[] clone(byte[] array) { if (array == null) { return null; } return (byte[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static double[] clone(double[] array) { if (array == null) { return null; } return (double[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static float[] clone(float[] array) { if (array == null) { return null; } return (float[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, or <code>null</code> if <code>null</code> * passed in */ public static boolean[] clone(boolean[] array) { if (array == null) { return null; } return (boolean[]) array.clone(); } //----------------------------------------------------------------------- /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>. * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(Object[] array1, Object[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(long[] array1, long[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(int[] array1, int[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(short[] array1, short[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(char[] array1, char[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(byte[] array1, byte[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(double[] array1, double[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored</p>. * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(float[] array1, float[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(boolean[] array1, boolean[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same type taking into account * multi-dimensional arrays.</p> * * <p>Primitive arrays may be compared using this method too.</p> * * @param array1 the first array, must not be <code>null</code> * @param array2 the second array, must not be <code>null</code> * @return <code>true</code> if type of arrays matches * @throws IllegalArgumentException if either array is <code>null</code> */ public static boolean isSameType(Object array1, Object array2) { if (array1 == null || array2 == null) { throw new IllegalArgumentException("The array must not be null"); } return array1.getClass().getName().equals(array2.getClass().getName()); } //----------------------------------------------------------------------- /** * Reverses the order of the given array. * <p> * There is no special handling for multi-dimensional arrays. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(Object[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(long[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; long tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(int[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; int tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * There is no special handling for multi-dimensional arrays. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(short[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; short tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(char[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; char tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(byte[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; byte tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(double[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; double tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(float[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; float tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** * Reverses the order of the given array. * <p> * The method does nothing if <code>null</code> is passed in. * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(boolean[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; boolean tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } //----------------------------------------------------------------------- /** * Find the index of the given object in the array. * <p> * The method returns -1 if a <code>null</code> array is passed in. * * @param array the array to search through for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @return the index of the object within the array, or -1 if not found */ public static int indexOf(Object[] array, Object objectToFind) { return indexOf(array, objectToFind, 0); } /** * Find the index of the given object in the array starting at the given index. * <p> * The method returns -1 if a <code>null</code> array is passed in. * <p> * A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1. * * @param array the array to search through for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @param startIndex the index to start searching at * @return the index of the object within the array starting at the * given index, or -1 if not found */ public static int indexOf(Object[] array, Object objectToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } if (objectToFind == null) { for (int i = startIndex; i < array.length; i++) { if (array[i] == null) { return i; } } } else { for (int i = startIndex; i < array.length; i++) { if (objectToFind.equals(array[i])) { return i; } } } return -1; } /** * Find the last index of the given object within the array. * <p> * The method returns -1 if a <code>null</code> array is passed in. * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @return the last index of the object to find, or -1 if not found */ public static int lastIndexOf(Object[] array, Object objectToFind) { if (array == null) { return -1; } return lastIndexOf(array, objectToFind, array.length - 1); } /** * Find the last index of the given object in the array starting at the given index. * <p> * The method returns -1 if a <code>null</code> array is passed in. * <p> * A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array. * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @param startIndex the start index to travers backwards from * @return the last index of the object within the array starting at the given index, * or -1 if not found */ public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } if (objectToFind == null) { for (int i = startIndex; i >= 0; i--) { if (array[i] == null) { return i; } } } else { for (int i = startIndex; i >= 0; i--) { if (objectToFind.equals(array[i])) { return i; } } } return -1; } /** * Checks if the object is in the given array. * <p> * The method returns <code>false</code> if a <code>null</code> array is passed in. * * @param array the array to search through * @param objectToFind the object to find * @return <code>true</code> if the array contains the object */ public static boolean contains(Object[] array, Object objectToFind) { return (indexOf(array, objectToFind) != -1); } /** * <p>Reverses an array.</p> * * <p>TAKEN FROM CollectionsUtils.</p> * * @param array the array to reverse */ public static void reverseArray(Object[] array) { int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } }
Remove reverseArray as reverse already exists! git-svn-id: d201ecbade8cc7da50e7bffa1d709f7a0d92be7d@137269 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/lang/ArrayUtils.java
Remove reverseArray as reverse already exists!
<ide><path>rc/java/org/apache/commons/lang/ArrayUtils.java <ide> * @author <a href="mailto:[email protected]">Fredrik Westermarck</a> <ide> * @author Nikolay Metchev <ide> * @since 2.0 <del> * @version $Id: ArrayUtils.java,v 1.9 2003/03/23 04:58:47 bayard Exp $ <add> * @version $Id: ArrayUtils.java,v 1.10 2003/03/23 17:57:42 scolebourne Exp $ <ide> */ <ide> public class ArrayUtils { <ide> <ide> return (indexOf(array, objectToFind) != -1); <ide> } <ide> <del> /** <del> * <p>Reverses an array.</p> <del> * <del> * <p>TAKEN FROM CollectionsUtils.</p> <del> * <del> * @param array the array to reverse <del> */ <del> public static void reverseArray(Object[] array) { <del> int i = 0; <del> int j = array.length - 1; <del> Object tmp; <del> <del> while (j > i) { <del> tmp = array[j]; <del> array[j] = array[i]; <del> array[i] = tmp; <del> j--; <del> i++; <del> } <del> } <del> <ide> }
Java
apache-2.0
82a54ada7f6b2446207efd8c39159e972856e30f
0
baomidou/mybatis-plus,baomidou/mybatis-plus
/* * Copyright (c) 2011-2020, baomidou ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.generator.config.querys; import java.sql.ResultSet; import java.sql.SQLException; /** * MySql 表数据查询 * * @author steven ma * @since 2020-08-20 */ public class FirebirdQuery extends AbstractDbQuery { @Override public String tablesSql() { return "select trim(rdb$relation_name) as rdb$relation_name " + "from rdb$relations " + "where rdb$view_blr is null " + "and (rdb$system_flag is null or rdb$system_flag = 0)"; } @Override public String tableFieldsSql() { return "select trim(f.rdb$relation_name) AS rdb$relation_name, " + "trim(f.rdb$field_name) AS FIELD, t.rdb$type_name AS TYPE, '' AS PK " + "from rdb$relation_fields f " + "join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name " + "JOIN rdb$fields fs ON f.rdb$field_source = fs.rdb$field_name " + "JOIN rdb$types t ON fs.rdb$field_type = t.rdb$type " + "and r.rdb$view_blr is NULL " + "AND t.rdb$field_name = 'RDB$FIELD_TYPE' " + "and (r.rdb$system_flag is null or r.rdb$system_flag = 0) " + "AND f.rdb$relation_name = '%s' " + "order by 1, f.rdb$field_position"; } @Override public String tableName() { return "rdb$relation_name"; } @Override public String tableComment() { return ""; } @Override public String fieldName() { return "FIELD"; } @Override public String fieldType() { return "TYPE"; } @Override public String fieldComment() { return ""; } @Override public String fieldKey() { return "PK"; } }
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/FirebirdQuery.java
/* * Copyright (c) 2011-2020, baomidou ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * https://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.generator.config.querys; import java.sql.ResultSet; import java.sql.SQLException; /** * MySql 表数据查询 * * @author steven ma * @since 2020-08-20 */ public class FirebirdQuery extends AbstractDbQuery { @Override public String tablesSql() { return "select rdb$relation_name as NAME " + "from rdb$relations " + "where rdb$view_blr is null " + "and (rdb$system_flag is null or rdb$system_flag = 0)"; } @Override public String tableFieldsSql() { return "select f.rdb$relation_name AS NAME, f.rdb$field_name AS FIELD, t.rdb$type_name AS TYPE " + "from rdb$relation_fields f " + "join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name " + "JOIN rdb$fields fs ON f.rdb$field_source = fs.rdb$field_name " + "JOIN rdb$types t ON fs.rdb$field_type = t.rdb$type " + "and r.rdb$view_blr is NULL " + "AND t.rdb$field_name = 'RDB$FIELD_TYPE' " + "and (r.rdb$system_flag is null or r.rdb$system_flag = 0) " + "AND f.rdb$relation_name = `%s` " + "order by 1, f.rdb$field_position"; } @Override public String tableName() { return "NAME"; } @Override public String tableComment() { return "COMMENT"; } @Override public String fieldName() { return "FIELD"; } @Override public String fieldType() { return "TYPE"; } @Override public String fieldComment() { return "COMMENT"; } @Override public String fieldKey() { return "KEY"; } }
fix bug
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/FirebirdQuery.java
fix bug
<ide><path>ybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/FirebirdQuery.java <ide> <ide> @Override <ide> public String tablesSql() { <del> return "select rdb$relation_name as NAME " + <add> return "select trim(rdb$relation_name) as rdb$relation_name " + <ide> "from rdb$relations " + <ide> "where rdb$view_blr is null " + <ide> "and (rdb$system_flag is null or rdb$system_flag = 0)"; <ide> <ide> @Override <ide> public String tableFieldsSql() { <del> return "select f.rdb$relation_name AS NAME, f.rdb$field_name AS FIELD, t.rdb$type_name AS TYPE " + <add> return "select trim(f.rdb$relation_name) AS rdb$relation_name, " + <add> "trim(f.rdb$field_name) AS FIELD, t.rdb$type_name AS TYPE, '' AS PK " + <ide> "from rdb$relation_fields f " + <ide> "join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name " + <ide> "JOIN rdb$fields fs ON f.rdb$field_source = fs.rdb$field_name " + <ide> "and r.rdb$view_blr is NULL " + <ide> "AND t.rdb$field_name = 'RDB$FIELD_TYPE' " + <ide> "and (r.rdb$system_flag is null or r.rdb$system_flag = 0) " + <del> "AND f.rdb$relation_name = `%s` " + <add> "AND f.rdb$relation_name = '%s' " + <ide> "order by 1, f.rdb$field_position"; <ide> } <ide> <ide> <ide> @Override <ide> public String tableName() { <del> return "NAME"; <add> return "rdb$relation_name"; <ide> } <ide> <ide> <ide> @Override <ide> public String tableComment() { <del> return "COMMENT"; <add> return ""; <ide> } <ide> <ide> <ide> <ide> @Override <ide> public String fieldComment() { <del> return "COMMENT"; <add> return ""; <ide> } <ide> <ide> <ide> @Override <ide> public String fieldKey() { <del> return "KEY"; <add> return "PK"; <ide> } <ide> <ide> }
Java
apache-2.0
57cb1ef782fcf89a84c826339076bd2d37e64878
0
rodriguezdevera/sakai,zqian/sakai,willkara/sakai,frasese/sakai,hackbuteer59/sakai,OpenCollabZA/sakai,udayg/sakai,kingmook/sakai,conder/sakai,ouit0408/sakai,liubo404/sakai,colczr/sakai,tl-its-umich-edu/sakai,kingmook/sakai,whumph/sakai,clhedrick/sakai,udayg/sakai,OpenCollabZA/sakai,introp-software/sakai,colczr/sakai,puramshetty/sakai,ktakacs/sakai,rodriguezdevera/sakai,pushyamig/sakai,tl-its-umich-edu/sakai,introp-software/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,joserabal/sakai,ouit0408/sakai,buckett/sakai-gitflow,OpenCollabZA/sakai,Fudan-University/sakai,rodriguezdevera/sakai,conder/sakai,kingmook/sakai,ouit0408/sakai,clhedrick/sakai,pushyamig/sakai,frasese/sakai,rodriguezdevera/sakai,wfuedu/sakai,willkara/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,buckett/sakai-gitflow,Fudan-University/sakai,hackbuteer59/sakai,surya-janani/sakai,wfuedu/sakai,bkirschn/sakai,puramshetty/sakai,pushyamig/sakai,rodriguezdevera/sakai,noondaysun/sakai,wfuedu/sakai,kwedoff1/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,colczr/sakai,bkirschn/sakai,wfuedu/sakai,liubo404/sakai,hackbuteer59/sakai,ktakacs/sakai,bzhouduke123/sakai,joserabal/sakai,surya-janani/sakai,rodriguezdevera/sakai,introp-software/sakai,clhedrick/sakai,kwedoff1/sakai,buckett/sakai-gitflow,zqian/sakai,hackbuteer59/sakai,conder/sakai,udayg/sakai,Fudan-University/sakai,lorenamgUMU/sakai,willkara/sakai,colczr/sakai,frasese/sakai,whumph/sakai,OpenCollabZA/sakai,colczr/sakai,lorenamgUMU/sakai,kingmook/sakai,hackbuteer59/sakai,ouit0408/sakai,bzhouduke123/sakai,liubo404/sakai,conder/sakai,ouit0408/sakai,conder/sakai,tl-its-umich-edu/sakai,liubo404/sakai,wfuedu/sakai,puramshetty/sakai,noondaysun/sakai,surya-janani/sakai,lorenamgUMU/sakai,willkara/sakai,frasese/sakai,pushyamig/sakai,bkirschn/sakai,conder/sakai,introp-software/sakai,wfuedu/sakai,ouit0408/sakai,bzhouduke123/sakai,noondaysun/sakai,lorenamgUMU/sakai,conder/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,liubo404/sakai,whumph/sakai,bkirschn/sakai,lorenamgUMU/sakai,kwedoff1/sakai,frasese/sakai,puramshetty/sakai,ktakacs/sakai,surya-janani/sakai,whumph/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,bkirschn/sakai,bzhouduke123/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,ktakacs/sakai,lorenamgUMU/sakai,pushyamig/sakai,surya-janani/sakai,buckett/sakai-gitflow,zqian/sakai,Fudan-University/sakai,clhedrick/sakai,OpenCollabZA/sakai,colczr/sakai,clhedrick/sakai,kwedoff1/sakai,introp-software/sakai,udayg/sakai,udayg/sakai,pushyamig/sakai,duke-compsci290-spring2016/sakai,udayg/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,pushyamig/sakai,frasese/sakai,willkara/sakai,bzhouduke123/sakai,udayg/sakai,ouit0408/sakai,joserabal/sakai,joserabal/sakai,hackbuteer59/sakai,kwedoff1/sakai,liubo404/sakai,liubo404/sakai,ktakacs/sakai,ktakacs/sakai,zqian/sakai,puramshetty/sakai,Fudan-University/sakai,zqian/sakai,kingmook/sakai,clhedrick/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,ktakacs/sakai,kingmook/sakai,puramshetty/sakai,whumph/sakai,bkirschn/sakai,ouit0408/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,joserabal/sakai,willkara/sakai,whumph/sakai,whumph/sakai,udayg/sakai,hackbuteer59/sakai,conder/sakai,willkara/sakai,zqian/sakai,frasese/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,bkirschn/sakai,surya-janani/sakai,hackbuteer59/sakai,kwedoff1/sakai,joserabal/sakai,joserabal/sakai,noondaysun/sakai,wfuedu/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,willkara/sakai,frasese/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,kingmook/sakai,kwedoff1/sakai,wfuedu/sakai,kingmook/sakai,bkirschn/sakai,bzhouduke123/sakai,whumph/sakai,Fudan-University/sakai,colczr/sakai,surya-janani/sakai,noondaysun/sakai,introp-software/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,joserabal/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,zqian/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,puramshetty/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,noondaysun/sakai,liubo404/sakai,introp-software/sakai,kwedoff1/sakai,zqian/sakai
/******************************************************************************* * Copyright (c) 2006, 2007, 2008, 2009 The Sakai 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.osedu.org/licenses/ECL-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.sakaiproject.tool.gradebook.ui; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.event.ActionEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord; import org.sakaiproject.service.gradebook.shared.StaleObjectModificationException; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.gradebook.AbstractGradeRecord; import org.sakaiproject.tool.gradebook.Assignment; import org.sakaiproject.tool.gradebook.AssignmentGradeRecord; import org.sakaiproject.tool.gradebook.Category; import org.sakaiproject.tool.gradebook.CourseGrade; import org.sakaiproject.tool.gradebook.CourseGradeRecord; import org.sakaiproject.tool.gradebook.GradableObject; import org.sakaiproject.tool.gradebook.jsf.FacesUtil; /** * Provides data for the instructor's view of a student's grades in the gradebook. */ public class InstructorViewBean extends ViewByStudentBean implements Serializable { private static Log logger = LogFactory.getLog(InstructorViewBean.class); private EnrollmentRecord previousStudent; private EnrollmentRecord nextStudent; private EnrollmentRecord currentStudent; private String studentEmailAddress; private String studentSections; private List orderedEnrollmentList; // parameters passed to the page private String returnToPage; private String assignmentId; // for returning to specific gradebook item private static final String ROSTER_PAGE = "roster"; private static final String ASSIGN_DETAILS_PAGE = "assignmentDetails"; /** * @see org.sakaiproject.tool.gradebook.ui.InitializableBean#init() */ public void init() { previousStudent = null; nextStudent = null; studentSections = null; String sortByCol = getSortColumn(); boolean sortAsc = isSortAscending(); setIsInstructorView(true); if (getStudentUid() != null) { super.init(); studentEmailAddress = getUserDirectoryService().getUserEmailAddress(getStudentUid()); studentSections = getStudentSectionsForDisplay(); // set up the "next" and "previous" student navigation // TODO preserve filter/sort status from originating page if (orderedEnrollmentList == null) { orderedEnrollmentList = new ArrayList(); if (returnToPage.equals(ROSTER_PAGE)) { super.setSelectedSectionFilterValue(getPreferencesBean().getRosterTableSectionFilter()); maxDisplayedScoreRows = 0; orderedEnrollmentList = getOrderedEnrolleesFromRosterPage(); } else if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) { super.setSelectedSectionFilterValue(getPreferencesBean().getAssignmentDetailsTableSectionFilter()); maxDisplayedScoreRows = 0; orderedEnrollmentList = getOrderedEnrolleesFromAssignDetailsPage(); } } if (orderedEnrollmentList != null && orderedEnrollmentList.size() > 1) { int index = 0; while (index < orderedEnrollmentList.size()) { EnrollmentRecord enrollee = (EnrollmentRecord)orderedEnrollmentList.get(index); if (enrollee.getUser().getUserUid().equals(getStudentUid())) { currentStudent = enrollee; if (index-1 >= 0) { previousStudent = (EnrollmentRecord) orderedEnrollmentList.get(index-1); } if (index+1 < orderedEnrollmentList.size()) { nextStudent = (EnrollmentRecord) orderedEnrollmentList.get(index+1); } break; } index++; } } setSortColumn(sortByCol); setSortAscending(sortAsc); } } // Navigation public EnrollmentRecord getPreviousStudent() { return previousStudent; } public EnrollmentRecord getNextStudent() { return nextStudent; } public boolean isFirst() { return previousStudent == null; } public boolean isLast() { return nextStudent == null; } public EnrollmentRecord getCurrentStudent() { return currentStudent; } /** * @return text for "Return to" button */ public String getReturnToPageButtonName() { String pageTitle; if (ASSIGN_DETAILS_PAGE.equals(returnToPage)) pageTitle = getLocalizedString("assignment_details_page_title"); else pageTitle = getLocalizedString("roster_page_title"); return getLocalizedString("inst_view_return_to", new String[] {pageTitle}); } /** * * @return page title of originating page */ public String getReturnToPageName() { if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) return getLocalizedString("assignment_details_page_title"); else return getLocalizedString("roster_page_title"); } /** * * @return comma-separated string of user's section/group memberships */ public String getStudentSections() { return studentSections; } /** * @return studentEmailAddress */ public String getStudentEmailAddress() { return studentEmailAddress; } /** * Action listener to view a different student */ public void processStudentUidChange(ActionEvent event) { Map params = FacesUtil.getEventParameterMap(event); if (logger.isDebugEnabled()) logger.debug("processStudentUidChange params=" + params + ", current studentUid=" + getStudentUid()); // run the updates before changing the student id processUpdateScoresForPreNextStudent(); String idParam = (String)params.get("studentUid"); if (idParam != null) { setStudentUid(idParam); } } public void processUpdateScoresForPreNextStudent() { try { saveScoresWithoutConfirmation(); } catch (StaleObjectModificationException e) { FacesUtil.addErrorMessage(getLocalizedString("assignment_details_locking_failure")); } } /** * Save the input scores for the user * @throws StaleObjectModificationException */ public void saveScoresWithoutConfirmation() throws StaleObjectModificationException { if (logger.isInfoEnabled()) logger.info("saveScores for " + getStudentUid()); // first, determine which scores were updated List updatedGradeRecords = new ArrayList(); if (getGradebookItems() != null) { Iterator itemIter = getGradebookItems().iterator(); while (itemIter.hasNext()) { Object item = itemIter.next(); if (item instanceof AssignmentGradeRow) { AssignmentGradeRow gradeRow = (AssignmentGradeRow) item; AssignmentGradeRecord gradeRecord = gradeRow.getGradeRecord(); if (gradeRecord == null && (gradeRow.getScore() != null || gradeRow.getLetterScore() != null)) { // this is a new grade gradeRecord = new AssignmentGradeRecord(gradeRow.getAssociatedAssignment(), getStudentUid(), null); } if (gradeRecord != null) { if (getGradeEntryByPoints()) { Double originalScore = null; originalScore = gradeRecord.getPointsEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPointsEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if(getGradeEntryByPercent()) { Double originalScore = null; originalScore = gradeRecord.getPercentEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPercentEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if (getGradeEntryByLetter()) { String originalScore = gradeRecord.getLetterEarned(); String newScore = gradeRow.getLetterScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setLetterEarned(newScore); updatedGradeRecords.add(gradeRecord); } } } } } } Set excessiveScores = getGradebookManager().updateStudentGradeRecords(updatedGradeRecords, getGradebook().getGrade_type(), getStudentUid()); if(updatedGradeRecords.size() > 0){ getGradebookBean().getEventTrackingService().postEvent("gradebook.updateItemScores","/gradebook/"+getGradebookId()+"/"+updatedGradeRecords.size()+"/"+getAuthzLevel()); } } /** * Action listener to update scores. */ public void processUpdateScores() { try { saveScores(); } catch (StaleObjectModificationException e) { FacesUtil.addErrorMessage(getLocalizedString("assignment_details_locking_failure")); } } /** * Save the input scores for the user * @throws StaleObjectModificationException */ public void saveScores() throws StaleObjectModificationException { if (logger.isInfoEnabled()) logger.info("saveScores for " + getStudentUid()); // first, determine which scores were updated List updatedGradeRecords = new ArrayList(); if (getGradebookItems() != null) { Iterator itemIter = getGradebookItems().iterator(); while (itemIter.hasNext()) { Object item = itemIter.next(); if (item instanceof AssignmentGradeRow) { AssignmentGradeRow gradeRow = (AssignmentGradeRow) item; AssignmentGradeRecord gradeRecord = gradeRow.getGradeRecord(); if (gradeRecord == null && (gradeRow.getScore() != null || gradeRow.getLetterScore() != null)) { // this is a new grade gradeRecord = new AssignmentGradeRecord(gradeRow.getAssociatedAssignment(), getStudentUid(), null); } if (gradeRecord != null) { if (getGradeEntryByPoints()) { Double originalScore = null; originalScore = gradeRecord.getPointsEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPointsEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if(getGradeEntryByPercent()) { Double originalScore = null; originalScore = gradeRecord.getPercentEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPercentEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if (getGradeEntryByLetter()) { String originalScore = gradeRecord.getLetterEarned(); String newScore = gradeRow.getLetterScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setLetterEarned(newScore); updatedGradeRecords.add(gradeRecord); } } } } } } Set excessiveScores = getGradebookManager().updateStudentGradeRecords(updatedGradeRecords, getGradebook().getGrade_type(), getStudentUid()); if(updatedGradeRecords.size() > 0){ getGradebookBean().getEventTrackingService().postEvent("gradebook.updateItemScores","/gradebook/"+getGradebookId()+"/"+updatedGradeRecords.size()+"/"+getAuthzLevel()); String messageKey = (excessiveScores.size() > 0) ? "inst_view_scores_saved_excessive" : "inst_view_scores_saved"; // Let the user know. FacesUtil.addMessage(getLocalizedString(messageKey)); } } private String getColumnHeader(GradableObject gradableObject) { if (gradableObject.isCourseGrade()) { return getLocalizedString("roster_course_grade_column_name"); } else { return ((Assignment)gradableObject).getName(); } } /** * If we came to the instructor view from the roster page, we need to * set the previous and next student info according to the order and filter * on the roster page * @return */ private List getOrderedEnrolleesFromRosterPage() { // it may be sorted by name, id, cumulative score, or any of the individual // assignments setSortColumn(getPreferencesBean().getRosterTableSortColumn()); setSortAscending(getPreferencesBean().isRosterTableSortAscending()); Map enrollmentMap = getOrderedEnrollmentMapForAllItems(); List workingEnrollments = new ArrayList(enrollmentMap.keySet()); if (isEnrollmentSort()) { return workingEnrollments; } Map studentIdItemIdFunctionMap = new HashMap(); Map studentIdEnrRecMap = new HashMap(); for (Iterator enrIter = workingEnrollments.iterator(); enrIter.hasNext();) { EnrollmentRecord enr = (EnrollmentRecord) enrIter.next(); if (enr != null) { String studentId = enr.getUser().getUserUid(); Map itemFunctionMap = (Map)enrollmentMap.get(enr); studentIdItemIdFunctionMap.put(studentId, itemFunctionMap); studentIdEnrRecMap.put(studentId, enr); } } List rosterGradeRecords = getGradebookManager().getAllAssignmentGradeRecords(getGradebookId(), studentIdItemIdFunctionMap.keySet()); Map gradeRecordMap = new HashMap(); if (!isUserAbleToGradeAll() && isUserHasGraderPermissions()) { getGradebookManager().addToGradeRecordMap(gradeRecordMap, rosterGradeRecords, studentIdItemIdFunctionMap); // we need to re-sort these records b/c some may actually be null based upon permissions. // retrieve updated grade recs from gradeRecordMap List updatedGradeRecs = new ArrayList(); for (Iterator iter = gradeRecordMap.keySet().iterator(); iter.hasNext();) { String studentId = (String)iter.next(); Map itemIdGradeRecMap = (Map)gradeRecordMap.get(studentId); if (!itemIdGradeRecMap.isEmpty()) { updatedGradeRecs.addAll(itemIdGradeRecMap.values()); } } Collections.sort(updatedGradeRecs, AssignmentGradeRecord.calcComparator); rosterGradeRecords = updatedGradeRecs; } else { getGradebookManager().addToGradeRecordMap(gradeRecordMap, rosterGradeRecords); } if (logger.isDebugEnabled()) logger.debug("init - gradeRecordMap.keySet().size() = " + gradeRecordMap.keySet().size()); List assignments = null; String selectedCategoryUid = getSelectedCategoryUid(); CourseGrade courseGrade = getGradebookManager().getCourseGrade(getGradebookId()); if(selectedCategoryUid == null) { assignments = getGradebookManager().getAssignments(getGradebookId()); } else { assignments = getGradebookManager().getAssignmentsForCategory(new Long(getSelectedSectionFilterValue().longValue())); } List courseGradeRecords = getGradebookManager().getPointsEarnedCourseGradeRecords(courseGrade, studentIdItemIdFunctionMap.keySet(), assignments, gradeRecordMap); Collections.sort(courseGradeRecords, CourseGradeRecord.calcComparator); getGradebookManager().addToGradeRecordMap(gradeRecordMap, courseGradeRecords); rosterGradeRecords.addAll(courseGradeRecords); //do category results Map categoryResultMap = new HashMap(); List categories = getGradebookManager().getCategories(getGradebookId()); getGradebookManager().addToCategoryResultMap(categoryResultMap, categories, gradeRecordMap, studentIdEnrRecMap); if (logger.isDebugEnabled()) logger.debug("init - categoryResultMap.keySet().size() = " + categoryResultMap.keySet().size()); // Need to sort and page based on a scores column. String sortColumn = getSortColumn(); List scoreSortedEnrollments = new ArrayList(); for(Iterator iter = rosterGradeRecords.iterator(); iter.hasNext();) { AbstractGradeRecord agr = (AbstractGradeRecord)iter.next(); if(getColumnHeader(agr.getGradableObject()).equals(sortColumn)) { scoreSortedEnrollments.add(studentIdEnrRecMap.get(agr.getStudentId())); } } // Put enrollments with no scores at the beginning of the final list. workingEnrollments.removeAll(scoreSortedEnrollments); // Add all sorted enrollments with scores into the final list workingEnrollments.addAll(scoreSortedEnrollments); workingEnrollments = finalizeSortingAndPaging(workingEnrollments); return workingEnrollments; } /** * If we came to the instructor view from the assign details page, we need to * set the previous and next student info according to the order and filter * on the assign details page * @return */ private List getOrderedEnrolleesFromAssignDetailsPage() { setSortColumn(getPreferencesBean().getAssignmentDetailsTableSortColumn()); setSortAscending(getPreferencesBean().isAssignmentDetailsTableSortAscending()); List assignGradeRecords = new ArrayList(); List enrollments = new ArrayList(); Long assignmentIdAsLong = getAssignmentIdAsLong(); if (assignmentIdAsLong != null) { Assignment prevAssignment = getGradebookManager().getAssignment(assignmentIdAsLong); Category category = prevAssignment.getCategory(); Long catId = null; if (category != null) catId = category.getId(); Map enrollmentMap = getOrderedStudentIdEnrollmentMapForItem(catId); if (isEnrollmentSort()) { return new ArrayList(enrollmentMap.values()); } List studentUids = new ArrayList(enrollmentMap.keySet()); if (getGradeEntryByPoints()) assignGradeRecords = getGradebookManager().getAssignmentGradeRecords(prevAssignment, studentUids); else if (getGradeEntryByPercent() || getGradeEntryByLetter()) assignGradeRecords = getGradebookManager().getAssignmentGradeRecordsConverted(prevAssignment, studentUids); // Need to sort and page based on a scores column. List scoreSortedStudentUids = new ArrayList(); for(Iterator iter = assignGradeRecords.iterator(); iter.hasNext();) { AbstractGradeRecord agr = (AbstractGradeRecord)iter.next(); scoreSortedStudentUids.add(agr.getStudentId()); } // Put enrollments with no scores at the beginning of the final list. studentUids.removeAll(scoreSortedStudentUids); // Add all sorted enrollments with scores into the final list studentUids.addAll(scoreSortedStudentUids); studentUids = finalizeSortingAndPaging(studentUids); if (studentUids != null) { Iterator studentIter = studentUids.iterator(); while (studentIter.hasNext()) { String studentId = (String) studentIter.next(); EnrollmentRecord enrollee = (EnrollmentRecord)enrollmentMap.get(studentId); if (enrollee != null) enrollments.add(enrollee); } } } return enrollments; } /** * * @return String representation of the student's sections/groups */ private String getStudentSectionsForDisplay() { StringBuilder sectionList = new StringBuilder(); List studentMemberships = getGradebookBean().getAuthzService().getStudentSectionMembershipNames(getGradebookUid(), getStudentUid()); if (studentMemberships != null && !studentMemberships.isEmpty()) { Collections.sort(studentMemberships); for (int i=0; i < studentMemberships.size(); i++) { String sectionName = (String)studentMemberships.get(i); if (i == (studentMemberships.size()-1)) sectionList.append(sectionName); else sectionList.append(getLocalizedString("inst_view_sections_list", new String[] {sectionName}) + " "); } } return sectionList.toString(); } /** * View maintenance methods. */ public String getReturnToPage() { if (returnToPage == null) returnToPage = ROSTER_PAGE; return returnToPage; } public void setReturnToPage(String returnToPage) { this.returnToPage = returnToPage; } public String getAssignmentId() { return assignmentId; } public void setAssignmentId(String assignmentId) { this.assignmentId = assignmentId; } private Long getAssignmentIdAsLong() { Long id = null; if (assignmentId == null) return id; try { id = new Long(assignmentId); } catch (Exception e) { } return id; } /** * Go to assignment details page. Need to override here * because on other pages, may need to return to where * called from while here we want to go directly to * assignment details. */ public String navigateToAssignmentDetails() { setNav(null, null, null, "false", null); return "assignmentDetails"; } /** * Go to either Roster or Assignment Details page. */ public String processCancel() { if (new Boolean((String) SessionManager.getCurrentToolSession().getAttribute("middle")).booleanValue()) { AssignmentDetailsBean assignmentDetailsBean = (AssignmentDetailsBean)FacesUtil.resolveVariable("assignmentDetailsBean"); assignmentDetailsBean.setAssignmentId(new Long(assignmentId)); return navigateToAssignmentDetails(); } else { return getBreadcrumbPage(); } } }
gradebook/app/ui/src/java/org/sakaiproject/tool/gradebook/ui/InstructorViewBean.java
/******************************************************************************* * Copyright (c) 2006, 2007, 2008, 2009 The Sakai 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.osedu.org/licenses/ECL-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.sakaiproject.tool.gradebook.ui; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.event.ActionEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord; import org.sakaiproject.service.gradebook.shared.StaleObjectModificationException; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.gradebook.AbstractGradeRecord; import org.sakaiproject.tool.gradebook.Assignment; import org.sakaiproject.tool.gradebook.AssignmentGradeRecord; import org.sakaiproject.tool.gradebook.Category; import org.sakaiproject.tool.gradebook.CourseGrade; import org.sakaiproject.tool.gradebook.CourseGradeRecord; import org.sakaiproject.tool.gradebook.GradableObject; import org.sakaiproject.tool.gradebook.jsf.FacesUtil; /** * Provides data for the instructor's view of a student's grades in the gradebook. */ public class InstructorViewBean extends ViewByStudentBean implements Serializable { private static Log logger = LogFactory.getLog(InstructorViewBean.class); private EnrollmentRecord previousStudent; private EnrollmentRecord nextStudent; private EnrollmentRecord currentStudent; private String studentEmailAddress; private String studentSections; private List orderedEnrollmentList; // parameters passed to the page private String returnToPage; private String assignmentId; // for returning to specific gradebook item private static final String ROSTER_PAGE = "roster"; private static final String ASSIGN_DETAILS_PAGE = "assignmentDetails"; /** * @see org.sakaiproject.tool.gradebook.ui.InitializableBean#init() */ public void init() { previousStudent = null; nextStudent = null; studentSections = null; String sortByCol = getSortColumn(); boolean sortAsc = isSortAscending(); setIsInstructorView(true); if (getStudentUid() != null) { super.init(); studentEmailAddress = getUserDirectoryService().getUserEmailAddress(getStudentUid()); studentSections = getStudentSectionsForDisplay(); // set up the "next" and "previous" student navigation // TODO preserve filter/sort status from originating page if (orderedEnrollmentList == null) { orderedEnrollmentList = new ArrayList(); if (returnToPage.equals(ROSTER_PAGE)) { super.setSelectedSectionFilterValue(getPreferencesBean().getRosterTableSectionFilter()); maxDisplayedScoreRows = 0; orderedEnrollmentList = getOrderedEnrolleesFromRosterPage(); } else if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) { super.setSelectedSectionFilterValue(getPreferencesBean().getAssignmentDetailsTableSectionFilter()); orderedEnrollmentList = getOrderedEnrolleesFromAssignDetailsPage(); } } if (orderedEnrollmentList != null && orderedEnrollmentList.size() > 1) { int index = 0; while (index < orderedEnrollmentList.size()) { EnrollmentRecord enrollee = (EnrollmentRecord)orderedEnrollmentList.get(index); if (enrollee.getUser().getUserUid().equals(getStudentUid())) { currentStudent = enrollee; if (index-1 >= 0) { previousStudent = (EnrollmentRecord) orderedEnrollmentList.get(index-1); } if (index+1 < orderedEnrollmentList.size()) { nextStudent = (EnrollmentRecord) orderedEnrollmentList.get(index+1); } break; } index++; } } setSortColumn(sortByCol); setSortAscending(sortAsc); } } // Navigation public EnrollmentRecord getPreviousStudent() { return previousStudent; } public EnrollmentRecord getNextStudent() { return nextStudent; } public boolean isFirst() { return previousStudent == null; } public boolean isLast() { return nextStudent == null; } public EnrollmentRecord getCurrentStudent() { return currentStudent; } /** * @return text for "Return to" button */ public String getReturnToPageButtonName() { String pageTitle; if (ASSIGN_DETAILS_PAGE.equals(returnToPage)) pageTitle = getLocalizedString("assignment_details_page_title"); else pageTitle = getLocalizedString("roster_page_title"); return getLocalizedString("inst_view_return_to", new String[] {pageTitle}); } /** * * @return page title of originating page */ public String getReturnToPageName() { if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) return getLocalizedString("assignment_details_page_title"); else return getLocalizedString("roster_page_title"); } /** * * @return comma-separated string of user's section/group memberships */ public String getStudentSections() { return studentSections; } /** * @return studentEmailAddress */ public String getStudentEmailAddress() { return studentEmailAddress; } /** * Action listener to view a different student */ public void processStudentUidChange(ActionEvent event) { Map params = FacesUtil.getEventParameterMap(event); if (logger.isDebugEnabled()) logger.debug("processStudentUidChange params=" + params + ", current studentUid=" + getStudentUid()); // run the updates before changing the student id processUpdateScoresForPreNextStudent(); String idParam = (String)params.get("studentUid"); if (idParam != null) { setStudentUid(idParam); } } public void processUpdateScoresForPreNextStudent() { try { saveScoresWithoutConfirmation(); } catch (StaleObjectModificationException e) { FacesUtil.addErrorMessage(getLocalizedString("assignment_details_locking_failure")); } } /** * Save the input scores for the user * @throws StaleObjectModificationException */ public void saveScoresWithoutConfirmation() throws StaleObjectModificationException { if (logger.isInfoEnabled()) logger.info("saveScores for " + getStudentUid()); // first, determine which scores were updated List updatedGradeRecords = new ArrayList(); if (getGradebookItems() != null) { Iterator itemIter = getGradebookItems().iterator(); while (itemIter.hasNext()) { Object item = itemIter.next(); if (item instanceof AssignmentGradeRow) { AssignmentGradeRow gradeRow = (AssignmentGradeRow) item; AssignmentGradeRecord gradeRecord = gradeRow.getGradeRecord(); if (gradeRecord == null && (gradeRow.getScore() != null || gradeRow.getLetterScore() != null)) { // this is a new grade gradeRecord = new AssignmentGradeRecord(gradeRow.getAssociatedAssignment(), getStudentUid(), null); } if (gradeRecord != null) { if (getGradeEntryByPoints()) { Double originalScore = null; originalScore = gradeRecord.getPointsEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPointsEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if(getGradeEntryByPercent()) { Double originalScore = null; originalScore = gradeRecord.getPercentEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPercentEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if (getGradeEntryByLetter()) { String originalScore = gradeRecord.getLetterEarned(); String newScore = gradeRow.getLetterScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setLetterEarned(newScore); updatedGradeRecords.add(gradeRecord); } } } } } } Set excessiveScores = getGradebookManager().updateStudentGradeRecords(updatedGradeRecords, getGradebook().getGrade_type(), getStudentUid()); if(updatedGradeRecords.size() > 0){ getGradebookBean().getEventTrackingService().postEvent("gradebook.updateItemScores","/gradebook/"+getGradebookId()+"/"+updatedGradeRecords.size()+"/"+getAuthzLevel()); } } /** * Action listener to update scores. */ public void processUpdateScores() { try { saveScores(); } catch (StaleObjectModificationException e) { FacesUtil.addErrorMessage(getLocalizedString("assignment_details_locking_failure")); } } /** * Save the input scores for the user * @throws StaleObjectModificationException */ public void saveScores() throws StaleObjectModificationException { if (logger.isInfoEnabled()) logger.info("saveScores for " + getStudentUid()); // first, determine which scores were updated List updatedGradeRecords = new ArrayList(); if (getGradebookItems() != null) { Iterator itemIter = getGradebookItems().iterator(); while (itemIter.hasNext()) { Object item = itemIter.next(); if (item instanceof AssignmentGradeRow) { AssignmentGradeRow gradeRow = (AssignmentGradeRow) item; AssignmentGradeRecord gradeRecord = gradeRow.getGradeRecord(); if (gradeRecord == null && (gradeRow.getScore() != null || gradeRow.getLetterScore() != null)) { // this is a new grade gradeRecord = new AssignmentGradeRecord(gradeRow.getAssociatedAssignment(), getStudentUid(), null); } if (gradeRecord != null) { if (getGradeEntryByPoints()) { Double originalScore = null; originalScore = gradeRecord.getPointsEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPointsEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if(getGradeEntryByPercent()) { Double originalScore = null; originalScore = gradeRecord.getPercentEarned(); if (originalScore != null) { // truncate to two decimals for more accurate comparison originalScore = new Double(FacesUtil.getRoundDown(originalScore.doubleValue(), 2)); } Double newScore = gradeRow.getScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setPercentEarned(newScore); updatedGradeRecords.add(gradeRecord); } } else if (getGradeEntryByLetter()) { String originalScore = gradeRecord.getLetterEarned(); String newScore = gradeRow.getLetterScore(); if ( (originalScore != null && !originalScore.equals(newScore)) || (originalScore == null && newScore != null) ) { gradeRecord.setLetterEarned(newScore); updatedGradeRecords.add(gradeRecord); } } } } } } Set excessiveScores = getGradebookManager().updateStudentGradeRecords(updatedGradeRecords, getGradebook().getGrade_type(), getStudentUid()); if(updatedGradeRecords.size() > 0){ getGradebookBean().getEventTrackingService().postEvent("gradebook.updateItemScores","/gradebook/"+getGradebookId()+"/"+updatedGradeRecords.size()+"/"+getAuthzLevel()); String messageKey = (excessiveScores.size() > 0) ? "inst_view_scores_saved_excessive" : "inst_view_scores_saved"; // Let the user know. FacesUtil.addMessage(getLocalizedString(messageKey)); } } private String getColumnHeader(GradableObject gradableObject) { if (gradableObject.isCourseGrade()) { return getLocalizedString("roster_course_grade_column_name"); } else { return ((Assignment)gradableObject).getName(); } } /** * If we came to the instructor view from the roster page, we need to * set the previous and next student info according to the order and filter * on the roster page * @return */ private List getOrderedEnrolleesFromRosterPage() { // it may be sorted by name, id, cumulative score, or any of the individual // assignments setSortColumn(getPreferencesBean().getRosterTableSortColumn()); setSortAscending(getPreferencesBean().isRosterTableSortAscending()); Map enrollmentMap = getOrderedEnrollmentMapForAllItems(); List workingEnrollments = new ArrayList(enrollmentMap.keySet()); if (isEnrollmentSort()) { return workingEnrollments; } Map studentIdItemIdFunctionMap = new HashMap(); Map studentIdEnrRecMap = new HashMap(); for (Iterator enrIter = workingEnrollments.iterator(); enrIter.hasNext();) { EnrollmentRecord enr = (EnrollmentRecord) enrIter.next(); if (enr != null) { String studentId = enr.getUser().getUserUid(); Map itemFunctionMap = (Map)enrollmentMap.get(enr); studentIdItemIdFunctionMap.put(studentId, itemFunctionMap); studentIdEnrRecMap.put(studentId, enr); } } List rosterGradeRecords = getGradebookManager().getAllAssignmentGradeRecords(getGradebookId(), studentIdItemIdFunctionMap.keySet()); Map gradeRecordMap = new HashMap(); if (!isUserAbleToGradeAll() && isUserHasGraderPermissions()) { getGradebookManager().addToGradeRecordMap(gradeRecordMap, rosterGradeRecords, studentIdItemIdFunctionMap); // we need to re-sort these records b/c some may actually be null based upon permissions. // retrieve updated grade recs from gradeRecordMap List updatedGradeRecs = new ArrayList(); for (Iterator iter = gradeRecordMap.keySet().iterator(); iter.hasNext();) { String studentId = (String)iter.next(); Map itemIdGradeRecMap = (Map)gradeRecordMap.get(studentId); if (!itemIdGradeRecMap.isEmpty()) { updatedGradeRecs.addAll(itemIdGradeRecMap.values()); } } Collections.sort(updatedGradeRecs, AssignmentGradeRecord.calcComparator); rosterGradeRecords = updatedGradeRecs; } else { getGradebookManager().addToGradeRecordMap(gradeRecordMap, rosterGradeRecords); } if (logger.isDebugEnabled()) logger.debug("init - gradeRecordMap.keySet().size() = " + gradeRecordMap.keySet().size()); List assignments = null; String selectedCategoryUid = getSelectedCategoryUid(); CourseGrade courseGrade = getGradebookManager().getCourseGrade(getGradebookId()); if(selectedCategoryUid == null) { assignments = getGradebookManager().getAssignments(getGradebookId()); } else { assignments = getGradebookManager().getAssignmentsForCategory(new Long(getSelectedSectionFilterValue().longValue())); } List courseGradeRecords = getGradebookManager().getPointsEarnedCourseGradeRecords(courseGrade, studentIdItemIdFunctionMap.keySet(), assignments, gradeRecordMap); Collections.sort(courseGradeRecords, CourseGradeRecord.calcComparator); getGradebookManager().addToGradeRecordMap(gradeRecordMap, courseGradeRecords); rosterGradeRecords.addAll(courseGradeRecords); //do category results Map categoryResultMap = new HashMap(); List categories = getGradebookManager().getCategories(getGradebookId()); getGradebookManager().addToCategoryResultMap(categoryResultMap, categories, gradeRecordMap, studentIdEnrRecMap); if (logger.isDebugEnabled()) logger.debug("init - categoryResultMap.keySet().size() = " + categoryResultMap.keySet().size()); // Need to sort and page based on a scores column. String sortColumn = getSortColumn(); List scoreSortedEnrollments = new ArrayList(); for(Iterator iter = rosterGradeRecords.iterator(); iter.hasNext();) { AbstractGradeRecord agr = (AbstractGradeRecord)iter.next(); if(getColumnHeader(agr.getGradableObject()).equals(sortColumn)) { scoreSortedEnrollments.add(studentIdEnrRecMap.get(agr.getStudentId())); } } // Put enrollments with no scores at the beginning of the final list. workingEnrollments.removeAll(scoreSortedEnrollments); // Add all sorted enrollments with scores into the final list workingEnrollments.addAll(scoreSortedEnrollments); workingEnrollments = finalizeSortingAndPaging(workingEnrollments); return workingEnrollments; } /** * If we came to the instructor view from the assign details page, we need to * set the previous and next student info according to the order and filter * on the assign details page * @return */ private List getOrderedEnrolleesFromAssignDetailsPage() { setSortColumn(getPreferencesBean().getAssignmentDetailsTableSortColumn()); setSortAscending(getPreferencesBean().isAssignmentDetailsTableSortAscending()); List assignGradeRecords = new ArrayList(); List enrollments = new ArrayList(); Long assignmentIdAsLong = getAssignmentIdAsLong(); if (assignmentIdAsLong != null) { Assignment prevAssignment = getGradebookManager().getAssignment(assignmentIdAsLong); Category category = prevAssignment.getCategory(); Long catId = null; if (category != null) catId = category.getId(); Map enrollmentMap = getOrderedStudentIdEnrollmentMapForItem(catId); if (isEnrollmentSort()) { return new ArrayList(enrollmentMap.values()); } List studentUids = new ArrayList(enrollmentMap.keySet()); if (getGradeEntryByPoints()) assignGradeRecords = getGradebookManager().getAssignmentGradeRecords(prevAssignment, studentUids); else if (getGradeEntryByPercent() || getGradeEntryByLetter()) assignGradeRecords = getGradebookManager().getAssignmentGradeRecordsConverted(prevAssignment, studentUids); // Need to sort and page based on a scores column. List scoreSortedStudentUids = new ArrayList(); for(Iterator iter = assignGradeRecords.iterator(); iter.hasNext();) { AbstractGradeRecord agr = (AbstractGradeRecord)iter.next(); scoreSortedStudentUids.add(agr.getStudentId()); } // Put enrollments with no scores at the beginning of the final list. studentUids.removeAll(scoreSortedStudentUids); // Add all sorted enrollments with scores into the final list studentUids.addAll(scoreSortedStudentUids); studentUids = finalizeSortingAndPaging(studentUids); if (studentUids != null) { Iterator studentIter = studentUids.iterator(); while (studentIter.hasNext()) { String studentId = (String) studentIter.next(); EnrollmentRecord enrollee = (EnrollmentRecord)enrollmentMap.get(studentId); if (enrollee != null) enrollments.add(enrollee); } } } return enrollments; } /** * * @return String representation of the student's sections/groups */ private String getStudentSectionsForDisplay() { StringBuilder sectionList = new StringBuilder(); List studentMemberships = getGradebookBean().getAuthzService().getStudentSectionMembershipNames(getGradebookUid(), getStudentUid()); if (studentMemberships != null && !studentMemberships.isEmpty()) { Collections.sort(studentMemberships); for (int i=0; i < studentMemberships.size(); i++) { String sectionName = (String)studentMemberships.get(i); if (i == (studentMemberships.size()-1)) sectionList.append(sectionName); else sectionList.append(getLocalizedString("inst_view_sections_list", new String[] {sectionName}) + " "); } } return sectionList.toString(); } /** * View maintenance methods. */ public String getReturnToPage() { if (returnToPage == null) returnToPage = ROSTER_PAGE; return returnToPage; } public void setReturnToPage(String returnToPage) { this.returnToPage = returnToPage; } public String getAssignmentId() { return assignmentId; } public void setAssignmentId(String assignmentId) { this.assignmentId = assignmentId; } private Long getAssignmentIdAsLong() { Long id = null; if (assignmentId == null) return id; try { id = new Long(assignmentId); } catch (Exception e) { } return id; } /** * Go to assignment details page. Need to override here * because on other pages, may need to return to where * called from while here we want to go directly to * assignment details. */ public String navigateToAssignmentDetails() { setNav(null, null, null, "false", null); return "assignmentDetails"; } /** * Go to either Roster or Assignment Details page. */ public String processCancel() { if (new Boolean((String) SessionManager.getCurrentToolSession().getAttribute("middle")).booleanValue()) { AssignmentDetailsBean assignmentDetailsBean = (AssignmentDetailsBean)FacesUtil.resolveVariable("assignmentDetailsBean"); assignmentDetailsBean.setAssignmentId(new Long(assignmentId)); return navigateToAssignmentDetails(); } else { return getBreadcrumbPage(); } } }
SAK-13540 / ONC-382 - GB / "Next Student" button grays out git-svn-id: 544c358cc09106d3ca69bf3799573b8ef390fbe0@63472 66ffb92e-73f9-0310-93c1-f5514f145a0a
gradebook/app/ui/src/java/org/sakaiproject/tool/gradebook/ui/InstructorViewBean.java
SAK-13540 / ONC-382 - GB / "Next Student" button grays out
<ide><path>radebook/app/ui/src/java/org/sakaiproject/tool/gradebook/ui/InstructorViewBean.java <ide> orderedEnrollmentList = getOrderedEnrolleesFromRosterPage(); <ide> } else if (returnToPage.equals(ASSIGN_DETAILS_PAGE)) { <ide> super.setSelectedSectionFilterValue(getPreferencesBean().getAssignmentDetailsTableSectionFilter()); <add> maxDisplayedScoreRows = 0; <ide> orderedEnrollmentList = getOrderedEnrolleesFromAssignDetailsPage(); <ide> } <ide> }
Java
apache-2.0
d03ea248d5523ad4475fce3471ff3155febbbf1c
0
bassages/home-server,bassages/home-server,bassages/homecontrol,bassages/homecontrol
package nl.homeserver.energie.mindergasnl; import static java.time.format.DateTimeFormatter.ofPattern; import static nl.homeserver.DatePeriod.aPeriodWithToDate; import static org.apache.commons.collections4.CollectionUtils.isEmpty; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.inject.Provider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import lombok.AllArgsConstructor; import nl.homeserver.DatePeriod; import nl.homeserver.energie.meterstand.MeterstandOpDag; import nl.homeserver.energie.meterstand.MeterstandService; import org.springframework.transaction.annotation.Transactional; @Service @AllArgsConstructor public class MindergasnlService { private static final Logger LOGGER = LoggerFactory.getLogger(MindergasnlService.class); private static final String METER_READING_UPLOAD_URL = "http://www.mindergas.nl/api/gas_meter_readings"; private static final String THREE_AM = "0 0 3 * * *"; static final String HEADER_NAME_CONTENT_TYPE = "content-type"; static final String HEADER_NAME_AUTH_TOKEN = "AUTH-TOKEN"; private final MindergasnlSettingsRepository mindergasnlSettingsRepository; private final MeterstandService meterstandService; private final Provider<HttpClientBuilder> httpClientBuilder; private final Clock clock; @Transactional(readOnly = true) Optional<MindergasnlSettings> findOne() { return mindergasnlSettingsRepository.findOneByIdIsNotNull(); } @Transactional MindergasnlSettings save(final MindergasnlSettings mindergasnlSettings) { final Optional<MindergasnlSettings> optionalExistingMindergasnlSettings = mindergasnlSettingsRepository.findOneByIdIsNotNull(); if (optionalExistingMindergasnlSettings.isPresent()) { final MindergasnlSettings existingMindergasnlSettings = optionalExistingMindergasnlSettings.get(); existingMindergasnlSettings.setAutomatischUploaden(mindergasnlSettings.isAutomatischUploaden()); existingMindergasnlSettings.setAuthenticatietoken(mindergasnlSettings.getAuthenticatietoken()); return mindergasnlSettingsRepository.save(existingMindergasnlSettings); } else { return mindergasnlSettingsRepository.save(mindergasnlSettings); } } @Scheduled(cron = THREE_AM) public void uploadMeterstandWhenEnabled() { findOne().filter(MindergasnlSettings::isAutomatischUploaden) .ifPresent(this::uploadMeterstand); } private void uploadMeterstand(final MindergasnlSettings settings) { final LocalDate today = LocalDate.now(clock); final LocalDate yesterday = today.minusDays(1); final DatePeriod period = aPeriodWithToDate(yesterday, today); final List<MeterstandOpDag> yesterdaysLastMeterReading = meterstandService.getPerDag(period); if (isEmpty(yesterdaysLastMeterReading)) { LOGGER.warn("Failed to upload to mindergas.nl because no meter reading could be found for date {}", yesterday); return; } final BigDecimal gasReading = yesterdaysLastMeterReading.get(0).getMeterstand().getGas(); try (final CloseableHttpClient httpClient = httpClientBuilder.get().build()){ final HttpPost request = createRequest(yesterday, gasReading, settings.getAuthenticatietoken()); final CloseableHttpResponse response = httpClient.execute(request); logErrorWhenNoSuccess(response); } catch (final Exception ex) { LOGGER.error("Failed to upload to mindergas.nl", ex); } } private HttpPost createRequest(final LocalDate day, final BigDecimal gasReading, final String authenticationToken) throws UnsupportedEncodingException { final HttpPost request = new HttpPost(METER_READING_UPLOAD_URL); final String message = """ { "date": "%s", "reading": %s } """.formatted(day.format(ofPattern("yyyy-MM-dd")), gasReading.toString()); LOGGER.info("Upload to mindergas.nl: {}", message); request.addHeader(HEADER_NAME_CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); request.addHeader(HEADER_NAME_AUTH_TOKEN, authenticationToken); final StringEntity params = new StringEntity(message); request.setEntity(params); return request; } private void logErrorWhenNoSuccess(final CloseableHttpResponse response) { final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 201) { LOGGER.error("Failed to upload to mindergas.nl. HTTP status code: {}", statusCode); } } }
src/main/java/nl/homeserver/energie/mindergasnl/MindergasnlService.java
package nl.homeserver.energie.mindergasnl; import static java.time.format.DateTimeFormatter.ofPattern; import static nl.homeserver.DatePeriod.aPeriodWithToDate; import static org.apache.commons.collections4.CollectionUtils.isEmpty; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.time.Clock; import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.inject.Provider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import lombok.AllArgsConstructor; import nl.homeserver.DatePeriod; import nl.homeserver.energie.meterstand.MeterstandOpDag; import nl.homeserver.energie.meterstand.MeterstandService; import org.springframework.transaction.annotation.Transactional; @Service @AllArgsConstructor public class MindergasnlService { private static final Logger LOGGER = LoggerFactory.getLogger(MindergasnlService.class); private static final String METERSTAND_UPLOAD_ENDPOINT_URL = "http://www.mindergas.nl/api/gas_meter_readings"; private static final String THREE_AM = "0 0 3 * * *"; static final String HEADER_NAME_CONTENT_TYPE = "content-type"; static final String HEADER_NAME_AUTH_TOKEN = "AUTH-TOKEN"; private final MindergasnlSettingsRepository mindergasnlSettingsRepository; private final MeterstandService meterstandService; private final Provider<HttpClientBuilder> httpClientBuilder; private final Clock clock; @Transactional(readOnly = true) Optional<MindergasnlSettings> findOne() { return mindergasnlSettingsRepository.findOneByIdIsNotNull(); } @Transactional MindergasnlSettings save(final MindergasnlSettings mindergasnlSettings) { final Optional<MindergasnlSettings> optionalExistingMindergasnlSettings = mindergasnlSettingsRepository.findOneByIdIsNotNull(); if (optionalExistingMindergasnlSettings.isPresent()) { final MindergasnlSettings existingMindergasnlSettings = optionalExistingMindergasnlSettings.get(); existingMindergasnlSettings.setAutomatischUploaden(mindergasnlSettings.isAutomatischUploaden()); existingMindergasnlSettings.setAuthenticatietoken(mindergasnlSettings.getAuthenticatietoken()); return mindergasnlSettingsRepository.save(existingMindergasnlSettings); } else { return mindergasnlSettingsRepository.save(mindergasnlSettings); } } @Scheduled(cron = THREE_AM) public void uploadMeterstandWhenEnabled() { findOne().filter(MindergasnlSettings::isAutomatischUploaden) .ifPresent(this::uploadMeterstand); } private void uploadMeterstand(final MindergasnlSettings settings) { final LocalDate today = LocalDate.now(clock); final LocalDate yesterday = today.minusDays(1); final DatePeriod period = aPeriodWithToDate(yesterday, today); final List<MeterstandOpDag> yesterdaysLastMeterReading = meterstandService.getPerDag(period); if (isEmpty(yesterdaysLastMeterReading)) { LOGGER.warn("Failed to upload to mindergas.nl because no meter reading could be found for date {}", yesterday); return; } final BigDecimal gasReading = yesterdaysLastMeterReading.get(0).getMeterstand().getGas(); try (final CloseableHttpClient httpClient = httpClientBuilder.get().build()){ final HttpPost request = createRequest(yesterday, gasReading, settings.getAuthenticatietoken()); final CloseableHttpResponse response = httpClient.execute(request); logErrorWhenNoSuccess(response); } catch (final Exception ex) { LOGGER.error("Failed to upload to mindergas.nl", ex); } } private HttpPost createRequest(final LocalDate day, final BigDecimal gasReading, final String authenticationToken) throws UnsupportedEncodingException { final HttpPost request = new HttpPost(METERSTAND_UPLOAD_ENDPOINT_URL); final String message = """ { "date": "%s", "reading": %s } """.formatted(day.format(ofPattern("yyyy-MM-dd")), gasReading.toString()); LOGGER.info("Upload to mindergas.nl: {}", message); request.addHeader(HEADER_NAME_CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); request.addHeader(HEADER_NAME_AUTH_TOKEN, authenticationToken); final StringEntity params = new StringEntity(message); request.setEntity(params); return request; } private void logErrorWhenNoSuccess(final CloseableHttpResponse response) { final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 201) { LOGGER.error("Failed to upload to mindergas.nl. HTTP status code: {}", statusCode); } } }
Translate to english
src/main/java/nl/homeserver/energie/mindergasnl/MindergasnlService.java
Translate to english
<ide><path>rc/main/java/nl/homeserver/energie/mindergasnl/MindergasnlService.java <ide> <ide> private static final Logger LOGGER = LoggerFactory.getLogger(MindergasnlService.class); <ide> <del> private static final String METERSTAND_UPLOAD_ENDPOINT_URL = "http://www.mindergas.nl/api/gas_meter_readings"; <add> private static final String METER_READING_UPLOAD_URL = "http://www.mindergas.nl/api/gas_meter_readings"; <ide> private static final String THREE_AM = "0 0 3 * * *"; <ide> <ide> static final String HEADER_NAME_CONTENT_TYPE = "content-type"; <ide> private HttpPost createRequest(final LocalDate day, <ide> final BigDecimal gasReading, <ide> final String authenticationToken) throws UnsupportedEncodingException { <del> final HttpPost request = new HttpPost(METERSTAND_UPLOAD_ENDPOINT_URL); <add> final HttpPost request = new HttpPost(METER_READING_UPLOAD_URL); <ide> <ide> final String message = """ <ide> { "date": "%s", "reading": %s }
Java
bsd-3-clause
error: pathspec 'src/com/coderedrobotics/tiberius/libs/ImageObject.java' did not match any file(s) known to git
a7f866c43c6862e3505ed3c570bc3f06b6a162c0
1
CodeRed2771/Tiberius2014
package com.coderedrobotics.tiberius.libs; import com.coderedrobotics.tiberius.libs.Debug; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.camera.AxisCameraException; import edu.wpi.first.wpilibj.image.BinaryImage; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.NIVisionException; import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; import java.util.Vector; public class ImageObject implements Runnable { private AxisCamera camera; // CriteriaCollection cc; private Thread thread; // Filter filter; private boolean gettingImage = false; private boolean imageReady = false; // private double distance; // private double angleX; // private double angleY; // private double gyroReading; // private boolean threePoint; private int areaThreshold = 25; private int brightnessThreshold = 160; public ImageObject(AxisCamera camera) { } ImageObject() { thread = new Thread(this); try { camera = AxisCamera.getInstance(); } catch (Exception ex) { Debug.println("CAMERA - FAILED TO INITIALIZE", Debug.WARNING); } //myCamera.writeResolution(AxisCamera.ResolutionT.k320x240); thread.start(); } public void run() { while (true) { if (gettingImage) { Debug.println("getting image", Debug.STANDARD); long startTime = System.currentTimeMillis(); GetImage(); Debug.println("Image Acquisition Time: " + (startTime - System.currentTimeMillis()), Debug.EXTENDED); if (ParticleCount() > 0) { // PrintParticles(); double offset = GetOffsetPercentX(); gettingImage = false; imageReady = true; } } GetImage(); try { Thread.sleep(50); } catch (InterruptedException ex) { } } } public double[] GetImage() { if (camera != null && DriverStation.getInstance().isEnabled()) { ColorImage image = null; //startTime = System.currentTimeMillis(); try { image = camera.getImage(); } catch (AxisCameraException ex) { } catch (NIVisionException ex) { } ParticleAnalysisReport[] particles; try { BinaryImage thresholdImage = image.thresholdRGB( brightnessThreshold, 255, brightnessThreshold, 255, brightnessThreshold, 255); // keep only bright objects particles = thresholdImage.getOrderedParticleAnalysisReports(); // get list of "particles" (image objects found) Debug.println("Number of particles: " + new Integer(particles.length), Debug.STANDARD/*change to ex*/); //endTime = System.currentTimeMillis();106 //imageAcquisitionMS = endTime - startTime; //System.out.println("Image Acquisition Time: " + imageAcquisitionMS); //System.out.println("particles found: " + particles.length); // Sort the particles so the one highest in the image is first if (particles.length > 0) { Vector bigParticles = new Vector(particles.length); for (int i = 0; i < particles.length; ++i) { if (particles[i].particleArea > areaThreshold) { bigParticles.addElement(particles[i]); Debug.println("Accepted" + i, Debug.STANDARD/*change to ex*/); } else { Debug.println("Rejected" + i, Debug.STANDARD/*change to ex*/); } } bigParticles.trimToSize(); double rot = 0; //double ratio = 600; for (int i = 0; i < bigParticles.size(); i++) { ParticleAnalysisReport p = (ParticleAnalysisReport) bigParticles.elementAt(i); if ((2.2 < ((double) p.boundingRectWidth) / ((double) p.boundingRectHeight)) && (((double) p.boundingRectWidth) / ((double) p.boundingRectHeight) < 3.0) && false) { double midpoint = p.boundingRectLeft + (p.boundingRectWidth / 2); rot = ((double) (midpoint - (p.imageWidth / 2))) / ((double) p.imageWidth / 2); rot = rot * 20; } else if ((1.4 < ((double) p.boundingRectWidth) / ((double) p.boundingRectHeight)) && (((double) p.boundingRectWidth) / ((double) p.boundingRectHeight) < 2.2) && !false) { double midpoint = p.boundingRectLeft + (p.boundingRectWidth / 2); rot = ((double) (midpoint - (p.imageWidth / 2))) / ((double) p.imageWidth / 2); rot = rot * -20d; } } } thresholdImage.free(); image.free(); } catch (NIVisionException ex) { } } return null; } public void requestImage(double gyroAngle) { gyroReading = gyroAngle; imageReady = false; gettingImage = true; } public void cancelRequest() { gettingImage = false; } public double getAngleX() { imageReady = false; return angleX; } public double getDistance() { imageReady = false; return distance; } public double getDistanceRawData() { return (getDistance() * 12); } public boolean isReady() { return imageReady; } private double GetDistance() { double DISTANCE_FUDGE_FACTOR = -1; double dst = 0; if (GetMaxHeight() != 0) { // le original fancy formula dst = (((326.04 - (1.6 * GetMaxHeight())) / 12) + DISTANCE_FUDGE_FACTOR); //calculating inches, returning feet - Fudge factor is a manual refinement } return dst; } public int GetHeight() { return GetHeight(0); } public int GetHeight(int idx) { if (idx < 0) { return 0; } else { return particles[idx].boundingRectHeight; } } public int GetMaxHeight() { int maxHeight = 0; if (particles.length > 0) { for (int i = 0; i < particles.length; i++) { if (particles[i].boundingRectHeight > maxHeight) { maxHeight = particles[i].boundingRectHeight; } } } return maxHeight; } public int GetWidth() { return GetWidth(0); } public int GetWidth(int idx) { if (idx < 0) { return 0; } else { return particles[idx].boundingRectWidth; } } public double GetXPos() { return GetXPos(0); } public double GetXPos(int idx) { if (idx < 0) { return 0; } else { return particles[idx].boundingRectLeft; } } public int ParticleCount() { return particles.length; } public int GetParticleMidPointX() { return GetParticleMidPointX(0); } public int GetParticleMidPointX(int idx) { if (idx < 0) { return 0; } else { return particles[idx].boundingRectLeft + (particles[idx].boundingRectWidth / 2); } } public int GetParticleMidPointY() { return GetParticleMidPointY(0); } public int GetParticleMidPointY(int idx) { if (idx < 0) { return 0; } else { return particles[idx].boundingRectTop + (particles[idx].boundingRectHeight / 2); } } public int GetImageWidth() { return GetImageWidth(0); } public int GetImageWidth(int idx) { if (idx < 0) { return 0; } else { return particles[idx].imageWidth; } } public int GetParticleOffsetX() { return GetParticleOffsetX(0); } public int GetParticleOffsetX(int idx) { return GetParticleMidPointX(idx) - (particles[idx].imageWidth / 2); } public double GetOffsetPercentX() { return GetOffsetPercentX(0); } public double GetOffsetPercentX(int idx) { return ((double) GetParticleOffsetX(idx)) / ((double) GetImageWidth(idx) / 2); } public void PrintParticles() { if (ParticleCount() > 0) { for (int i = 0; i < ParticleCount(); i++) { System.out.println("Particular: " + i); System.out.println("X: " + particles[i].boundingRectLeft); System.out.println("Y: " + particles[i].boundingRectTop); System.out.println("H: " + particles[i].boundingRectHeight); System.out.println("AREA: " + particles[i].particleArea); System.out.println("MAX PART HEIGHT: " + GetMaxHeight()); } } } public void setThreePoint(boolean threePoint) { this.threePoint = threePoint; } private class Filter { double val = 0; double weight = 0; public void filter(double input) { val = ((val * weight) + input) / (weight + 1); weight += 1; } public double get() { return val; } } }
src/com/coderedrobotics/tiberius/libs/ImageObject.java
added image object
src/com/coderedrobotics/tiberius/libs/ImageObject.java
added image object
<ide><path>rc/com/coderedrobotics/tiberius/libs/ImageObject.java <add>package com.coderedrobotics.tiberius.libs; <add> <add>import com.coderedrobotics.tiberius.libs.Debug; <add>import edu.wpi.first.wpilibj.DriverStation; <add>import edu.wpi.first.wpilibj.camera.AxisCamera; <add>import edu.wpi.first.wpilibj.camera.AxisCameraException; <add>import edu.wpi.first.wpilibj.image.BinaryImage; <add>import edu.wpi.first.wpilibj.image.ColorImage; <add>import edu.wpi.first.wpilibj.image.NIVisionException; <add>import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; <add>import java.util.Vector; <add> <add>public class ImageObject implements Runnable { <add> <add> private AxisCamera camera; <add>// CriteriaCollection cc; <add> private Thread thread; <add>// Filter filter; <add> private boolean gettingImage = false; <add> private boolean imageReady = false; <add>// private double distance; <add>// private double angleX; <add>// private double angleY; <add>// private double gyroReading; <add>// private boolean threePoint; <add> private int areaThreshold = 25; <add> private int brightnessThreshold = 160; <add> <add> public ImageObject(AxisCamera camera) { <add> } <add> <add> ImageObject() { <add> thread = new Thread(this); <add> try { <add> camera = AxisCamera.getInstance(); <add> } catch (Exception ex) { <add> Debug.println("CAMERA - FAILED TO INITIALIZE", Debug.WARNING); <add> } <add> <add> //myCamera.writeResolution(AxisCamera.ResolutionT.k320x240); <add> thread.start(); <add> } <add> <add> public void run() { <add> while (true) { <add> <add> if (gettingImage) { <add> Debug.println("getting image", Debug.STANDARD); <add> <add> long startTime = System.currentTimeMillis(); <add> GetImage(); <add> Debug.println("Image Acquisition Time: " <add> + (startTime - System.currentTimeMillis()), <add> Debug.EXTENDED); <add> <add> if (ParticleCount() > 0) { <add> <add> // PrintParticles(); <add> double offset = GetOffsetPercentX(); <add> <add> gettingImage = false; <add> imageReady = true; <add> } <add> } <add> GetImage(); <add> try { <add> Thread.sleep(50); <add> } catch (InterruptedException ex) { <add> } <add> } <add> } <add> <add> public double[] GetImage() { <add> <add> if (camera != null && DriverStation.getInstance().isEnabled()) { <add> <add> ColorImage image = null; <add> <add> //startTime = System.currentTimeMillis(); <add> try { <add> image = camera.getImage(); <add> } catch (AxisCameraException ex) { <add> } catch (NIVisionException ex) { <add> } <add> <add> ParticleAnalysisReport[] particles; <add> <add> try { <add> BinaryImage thresholdImage <add> = image.thresholdRGB( <add> brightnessThreshold, 255, <add> brightnessThreshold, 255, <add> brightnessThreshold, 255); // keep only bright objects <add> particles = thresholdImage.getOrderedParticleAnalysisReports(); // get list of "particles" (image objects found) <add> <add> Debug.println("Number of particles: " + new Integer(particles.length), Debug.STANDARD/*change to ex*/); <add>//endTime = System.currentTimeMillis();106 <add> <add> //imageAcquisitionMS = endTime - startTime; <add> //System.out.println("Image Acquisition Time: " + imageAcquisitionMS); <add> //System.out.println("particles found: " + particles.length); <add> // Sort the particles so the one highest in the image is first <add> if (particles.length > 0) { <add> Vector bigParticles = new Vector(particles.length); <add> for (int i = 0; i < particles.length; ++i) { <add> if (particles[i].particleArea > areaThreshold) { <add> bigParticles.addElement(particles[i]); <add> Debug.println("Accepted" + i, Debug.STANDARD/*change to ex*/); <add> } else { <add> Debug.println("Rejected" + i, Debug.STANDARD/*change to ex*/); <add> } <add> } <add> bigParticles.trimToSize(); <add> double rot = 0; <add> //double ratio = 600; <add> for (int i = 0; i < bigParticles.size(); i++) { <add> ParticleAnalysisReport p = (ParticleAnalysisReport) bigParticles.elementAt(i); <add> if ((2.2 < ((double) p.boundingRectWidth) / ((double) p.boundingRectHeight)) <add> && (((double) p.boundingRectWidth) / ((double) p.boundingRectHeight) < 3.0) <add> && false) { <add> double midpoint = p.boundingRectLeft + (p.boundingRectWidth / 2); <add> rot = ((double) (midpoint - (p.imageWidth / 2))) / ((double) p.imageWidth / 2); <add> rot = rot * 20; <add> } else if ((1.4 < ((double) p.boundingRectWidth) / ((double) p.boundingRectHeight)) <add> && (((double) p.boundingRectWidth) / ((double) p.boundingRectHeight) < 2.2) <add> && !false) { <add> double midpoint = p.boundingRectLeft + (p.boundingRectWidth / 2); <add> rot = ((double) (midpoint - (p.imageWidth / 2))) / ((double) p.imageWidth / 2); <add> rot = rot * -20d; <add> } <add> } <add> } <add> <add> thresholdImage.free(); <add> image.free(); <add> } catch (NIVisionException ex) { <add> } <add> } <add> return null; <add> } <add> <add> public void requestImage(double gyroAngle) { <add> gyroReading = gyroAngle; <add> imageReady = false; <add> gettingImage = true; <add> } <add> <add> public void cancelRequest() { <add> gettingImage = false; <add> } <add> <add> public double getAngleX() { <add> imageReady = false; <add> return angleX; <add> } <add> <add> public double getDistance() { <add> imageReady = false; <add> return distance; <add> } <add> <add> public double getDistanceRawData() { <add> return (getDistance() * 12); <add> } <add> <add> public boolean isReady() { <add> return imageReady; <add> } <add> <add> private double GetDistance() { <add> double DISTANCE_FUDGE_FACTOR = -1; <add> <add> double dst = 0; <add> if (GetMaxHeight() != 0) { <add> // le original fancy formula <add> dst = (((326.04 - (1.6 * GetMaxHeight())) / 12) + DISTANCE_FUDGE_FACTOR); //calculating inches, returning feet - Fudge factor is a manual refinement <add> } <add> return dst; <add> } <add> <add> public int GetHeight() { <add> return GetHeight(0); <add> } <add> <add> public int GetHeight(int idx) { <add> if (idx < 0) { <add> return 0; <add> } else { <add> return particles[idx].boundingRectHeight; <add> } <add> } <add> <add> public int GetMaxHeight() { <add> int maxHeight = 0; <add> if (particles.length > 0) { <add> for (int i = 0; i < particles.length; i++) { <add> if (particles[i].boundingRectHeight > maxHeight) { <add> maxHeight = particles[i].boundingRectHeight; <add> } <add> } <add> } <add> return maxHeight; <add> } <add> <add> public int GetWidth() { <add> return GetWidth(0); <add> } <add> <add> public int GetWidth(int idx) { <add> if (idx < 0) { <add> return 0; <add> } else { <add> return particles[idx].boundingRectWidth; <add> } <add> } <add> <add> public double GetXPos() { <add> return GetXPos(0); <add> } <add> <add> public double GetXPos(int idx) { <add> if (idx < 0) { <add> return 0; <add> } else { <add> return particles[idx].boundingRectLeft; <add> } <add> } <add> <add> public int ParticleCount() { <add> return particles.length; <add> } <add> <add> public int GetParticleMidPointX() { <add> return GetParticleMidPointX(0); <add> } <add> <add> public int GetParticleMidPointX(int idx) { <add> if (idx < 0) { <add> return 0; <add> } else { <add> return particles[idx].boundingRectLeft + (particles[idx].boundingRectWidth / 2); <add> } <add> } <add> <add> public int GetParticleMidPointY() { <add> return GetParticleMidPointY(0); <add> } <add> <add> public int GetParticleMidPointY(int idx) { <add> if (idx < 0) { <add> return 0; <add> } else { <add> return particles[idx].boundingRectTop + (particles[idx].boundingRectHeight / 2); <add> } <add> } <add> <add> public int GetImageWidth() { <add> return GetImageWidth(0); <add> } <add> <add> public int GetImageWidth(int idx) { <add> if (idx < 0) { <add> return 0; <add> } else { <add> return particles[idx].imageWidth; <add> } <add> } <add> <add> public int GetParticleOffsetX() { <add> return GetParticleOffsetX(0); <add> } <add> <add> public int GetParticleOffsetX(int idx) { <add> return GetParticleMidPointX(idx) - (particles[idx].imageWidth / 2); <add> } <add> <add> public double GetOffsetPercentX() { <add> return GetOffsetPercentX(0); <add> } <add> <add> public double GetOffsetPercentX(int idx) { <add> return ((double) GetParticleOffsetX(idx)) / ((double) GetImageWidth(idx) / 2); <add> } <add> <add> public void PrintParticles() { <add> if (ParticleCount() > 0) { <add> for (int i = 0; i < ParticleCount(); i++) { <add> System.out.println("Particular: " + i); <add> System.out.println("X: " + particles[i].boundingRectLeft); <add> System.out.println("Y: " + particles[i].boundingRectTop); <add> System.out.println("H: " + particles[i].boundingRectHeight); <add> System.out.println("AREA: " + particles[i].particleArea); <add> System.out.println("MAX PART HEIGHT: " + GetMaxHeight()); <add> } <add> } <add> } <add> <add> public void setThreePoint(boolean threePoint) { <add> this.threePoint = threePoint; <add> } <add> <add> private class Filter { <add> <add> double val = 0; <add> double weight = 0; <add> <add> public void filter(double input) { <add> val = ((val * weight) + input) / (weight + 1); <add> weight += 1; <add> } <add> <add> public double get() { <add> return val; <add> } <add> } <add>}
Java
apache-2.0
42e07d035549b6a2eee07ad9e52052a4c3a291dd
0
indus1/k-9,cketti/k-9,G00fY2/k-9_material_design,CodingRmy/k-9,cketti/k-9,vasyl-khomko/k-9,jberkel/k-9,gilbertw1/k-9,gilbertw1/k-9,cketti/k-9,roscrazy/k-9,indus1/k-9,vatsalsura/k-9,ndew623/k-9,vt0r/k-9,ndew623/k-9,dgger/k-9,CodingRmy/k-9,jberkel/k-9,dgger/k-9,rishabhbitsg/k-9,philipwhiuk/q-mail,roscrazy/k-9,mawiegand/k-9,GuillaumeSmaha/k-9,vatsalsura/k-9,mawiegand/k-9,philipwhiuk/q-mail,mawiegand/k-9,jca02266/k-9,philipwhiuk/k-9,gilbertw1/k-9,rishabhbitsg/k-9,philipwhiuk/k-9,GuillaumeSmaha/k-9,k9mail/k-9,cketti/k-9,GuillaumeSmaha/k-9,philipwhiuk/q-mail,ndew623/k-9,sedrubal/k-9,vt0r/k-9,vasyl-khomko/k-9,vasyl-khomko/k-9,sedrubal/k-9,dgger/k-9,G00fY2/k-9_material_design,jca02266/k-9,k9mail/k-9,k9mail/k-9,jca02266/k-9
package com.fsck.k9.mail.store.imap; import java.io.IOException; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import android.content.Context; import android.os.PowerManager; import android.util.Log; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.K9MailLib; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.power.TracingPowerManager; import com.fsck.k9.mail.power.TracingPowerManager.TracingWakeLock; import com.fsck.k9.mail.store.RemoteStore; import static com.fsck.k9.mail.K9MailLib.LOG_TAG; import static com.fsck.k9.mail.K9MailLib.PUSH_WAKE_LOCK_TIMEOUT; import static com.fsck.k9.mail.store.imap.ImapResponseParser.equalsIgnoreCase; class ImapFolderPusher extends ImapFolder { private static final int IDLE_READ_TIMEOUT_INCREMENT = 5 * 60 * 1000; private static final int IDLE_FAILURE_COUNT_LIMIT = 10; private static final int MAX_DELAY_TIME = 5 * 60 * 1000; // 5 minutes private static final int NORMAL_DELAY_TIME = 5000; private final PushReceiver pushReceiver; private final AtomicBoolean stop = new AtomicBoolean(false); private final AtomicBoolean idling = new AtomicBoolean(false); private final Object threadLock = new Object(); private final IdleStopper idleStopper = new IdleStopper(); private final TracingWakeLock wakeLock; private List<ImapResponse> storedUntaggedResponses = new ArrayList<ImapResponse>(); private Thread listeningThread; public ImapFolderPusher(ImapStore store, String name, PushReceiver pushReceiver) { super(store, name); this.pushReceiver = pushReceiver; Context context = pushReceiver.getContext(); TracingPowerManager powerManager = TracingPowerManager.getPowerManager(context); String tag = "ImapFolderPusher " + store.getStoreConfig().toString() + ":" + getName(); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag); wakeLock.setReferenceCounted(false); } public void start() { synchronized (threadLock) { listeningThread = new Thread(new PushRunnable()); listeningThread.start(); } } public void refresh() throws IOException, MessagingException { if (idling.get()) { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); idleStopper.stopIdle(); } } public void stop() { stop.set(true); interruptListeningThread(); ImapConnection conn = connection; if (conn != null) { if (K9MailLib.isDebug()) { Log.v(LOG_TAG, "Closing connection to stop pushing for " + getLogId()); } conn.close(); } else { Log.w(LOG_TAG, "Attempt to interrupt null connection to stop pushing on folderPusher for " + getLogId()); } } private void interruptListeningThread() { synchronized (threadLock) { if (listeningThread != null) { listeningThread.interrupt(); } } } @Override protected void handleUntaggedResponse(ImapResponse response) { if (response.getTag() == null && response.size() > 1) { Object responseType = response.get(1); if (equalsIgnoreCase(responseType, "FETCH") || equalsIgnoreCase(responseType, "EXPUNGE") || equalsIgnoreCase(responseType, "EXISTS")) { if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Storing response " + response + " for later processing"); } storedUntaggedResponses.add(response); } handlePossibleUidNext(response); } } private void superHandleUntaggedResponse(ImapResponse response) { super.handleUntaggedResponse(response); } private class PushRunnable implements Runnable, UntaggedHandler { private int delayTime = NORMAL_DELAY_TIME; private int idleFailureCount = 0; private boolean needsPoll = false; @Override public void run() { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Pusher starting for " + getLogId()); } long lastUidNext = -1L; while (!stop.get()) { try { long oldUidNext = getOldUidNext(); /* * This makes sure 'oldUidNext' is never smaller than 'UIDNEXT' from * the last loop iteration. This way we avoid looping endlessly causing * the battery to drain. * * See issue 4907 */ if (oldUidNext < lastUidNext) { oldUidNext = lastUidNext; } ImapConnection oldConnection = connection; internalOpen(OPEN_MODE_RO); ImapConnection conn = connection; checkConnectionNotNull(conn); checkConnectionIdleCapable(conn); if (stop.get()) { break; } boolean pushPollOnConnect = store.getStoreConfig().isPushPollOnConnect(); boolean openedNewConnection = conn != oldConnection; if (pushPollOnConnect && (openedNewConnection || needsPoll)) { needsPoll = false; syncFolderOnConnect(); } if (stop.get()) { break; } long newUidNext = getNewUidNext(); lastUidNext = newUidNext; long startUid = getStartUid(oldUidNext, newUidNext); if (newUidNext > startUid) { notifyMessagesArrived(startUid, newUidNext); } else { processStoredUntaggedResponses(); if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "About to IDLE for " + getLogId()); } prepareForIdle(); setReadTimeoutForIdle(conn); sendIdle(conn); returnFromIdle(); } } catch (Exception e) { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); storedUntaggedResponses.clear(); idling.set(false); pushReceiver.setPushActive(getName(), false); try { close(); } catch (Exception me) { Log.e(LOG_TAG, "Got exception while closing for exception for " + getLogId(), me); } if (stop.get()) { Log.i(LOG_TAG, "Got exception while idling, but stop is set for " + getLogId()); } else { pushReceiver.pushError("Push error for " + getName(), e); Log.e(LOG_TAG, "Got exception while idling for " + getLogId(), e); pushReceiver.sleep(wakeLock, delayTime); delayTime *= 2; if (delayTime > MAX_DELAY_TIME) { delayTime = MAX_DELAY_TIME; } if (++idleFailureCount > IDLE_FAILURE_COUNT_LIMIT) { Log.e(LOG_TAG, "Disabling pusher for " + getLogId() + " after " + idleFailureCount + " consecutive errors"); pushReceiver.pushError("Push disabled for " + getName() + " after " + idleFailureCount + " consecutive errors", e); stop.set(true); } } } } pushReceiver.setPushActive(getName(), false); try { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Pusher for " + getLogId() + " is exiting"); } close(); } catch (Exception me) { Log.e(LOG_TAG, "Got exception while closing for " + getLogId(), me); } finally { wakeLock.release(); } } private long getNewUidNext() throws MessagingException { long newUidNext = uidNext; if (newUidNext != -1L) { return newUidNext; } if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "uidNext is -1, using search to find highest UID"); } long highestUid = getHighestUid(); if (highestUid == -1L) { return -1L; } newUidNext = highestUid + 1; if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "highest UID = " + highestUid + ", set newUidNext to " + newUidNext); } return newUidNext; } private long getStartUid(long oldUidNext, long newUidNext) { long startUid = oldUidNext; int displayCount = store.getStoreConfig().getDisplayCount(); if (startUid < newUidNext - displayCount) { startUid = newUidNext - displayCount; } if (startUid < 1) { startUid = 1; } return startUid; } private void prepareForIdle() { pushReceiver.setPushActive(getName(), true); idling.set(true); } private void sendIdle(ImapConnection conn) throws MessagingException, IOException { String tag = conn.sendCommand(Commands.IDLE, false); List<ImapResponse> responses; try { try { responses = conn.readStatusResponse(tag, Commands.IDLE, this); } finally { idleStopper.stopAcceptingDoneContinuation(); } } catch (IOException e) { close(); throw e; } handleUntaggedResponses(responses); } private void returnFromIdle() { idling.set(false); delayTime = NORMAL_DELAY_TIME; idleFailureCount = 0; } private void checkConnectionNotNull(ImapConnection conn) throws MessagingException { if (conn == null) { String message = "Could not establish connection for IDLE"; pushReceiver.pushError(message, null); throw new MessagingException(message); } } private void checkConnectionIdleCapable(ImapConnection conn) throws MessagingException { if (!conn.isIdleCapable()) { stop.set(true); String message = "IMAP server is not IDLE capable: " + conn.toString(); pushReceiver.pushError(message, null); throw new MessagingException(message); } } private void setReadTimeoutForIdle(ImapConnection conn) throws SocketException { int idleRefreshTimeout = store.getStoreConfig().getIdleRefreshMinutes() * 60 * 1000; conn.setReadTimeout(idleRefreshTimeout + IDLE_READ_TIMEOUT_INCREMENT); } @Override public void handleAsyncUntaggedResponse(ImapResponse response) { if (K9MailLib.isDebug()) { Log.v(LOG_TAG, "Got async response: " + response); } if (stop.get()) { if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got async untagged response: " + response + ", but stop is set for " + getLogId()); } idleStopper.stopIdle(); } else { if (response.getTag() == null) { if (response.size() > 1) { Object responseType = response.get(1); if (equalsIgnoreCase(responseType, "EXISTS") || equalsIgnoreCase(responseType, "EXPUNGE") || equalsIgnoreCase(responseType, "FETCH")) { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got useful async untagged response: " + response + " for " + getLogId()); } idleStopper.stopIdle(); } } else if (response.isContinuationRequested()) { if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Idling " + getLogId()); } idleStopper.startAcceptingDoneContinuation(connection); wakeLock.release(); } } } } private void processStoredUntaggedResponses() throws MessagingException { List<ImapResponse> untaggedResponses; while (!storedUntaggedResponses.isEmpty()) { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Processing " + storedUntaggedResponses.size() + " untagged responses from previous commands for " + getLogId()); } untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses); storedUntaggedResponses.clear(); processUntaggedResponses(untaggedResponses); } } private void processUntaggedResponses(List<ImapResponse> responses) throws MessagingException { boolean skipSync = false; int oldMessageCount = messageCount; if (oldMessageCount == -1) { skipSync = true; } List<Long> flagSyncMsgSeqs = new ArrayList<Long>(); List<String> removeMsgUids = new LinkedList<String>(); for (ImapResponse response : responses) { oldMessageCount += processUntaggedResponse(oldMessageCount, response, flagSyncMsgSeqs, removeMsgUids); } if (!skipSync) { if (oldMessageCount < 0) { oldMessageCount = 0; } if (messageCount > oldMessageCount) { syncMessages(messageCount); } } if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "UIDs for messages needing flag sync are " + flagSyncMsgSeqs + " for " + getLogId()); } if (!flagSyncMsgSeqs.isEmpty()) { syncMessages(flagSyncMsgSeqs); } if (!removeMsgUids.isEmpty()) { removeMessages(removeMsgUids); } } private int processUntaggedResponse(long oldMessageCount, ImapResponse response, List<Long> flagSyncMsgSeqs, List<String> removeMsgUids) { superHandleUntaggedResponse(response); int messageCountDelta = 0; if (response.getTag() == null && response.size() > 1) { try { Object responseType = response.get(1); if (equalsIgnoreCase(responseType, "FETCH")) { Log.i(LOG_TAG, "Got FETCH " + response); long msgSeq = response.getLong(0); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got untagged FETCH for msgseq " + msgSeq + " for " + getLogId()); } if (!flagSyncMsgSeqs.contains(msgSeq)) { flagSyncMsgSeqs.add(msgSeq); } } if (equalsIgnoreCase(responseType, "EXPUNGE")) { long msgSeq = response.getLong(0); if (msgSeq <= oldMessageCount) { messageCountDelta = -1; } if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got untagged EXPUNGE for msgseq " + msgSeq + " for " + getLogId()); } List<Long> newSeqs = new ArrayList<Long>(); Iterator<Long> flagIter = flagSyncMsgSeqs.iterator(); while (flagIter.hasNext()) { long flagMsg = flagIter.next(); if (flagMsg >= msgSeq) { flagIter.remove(); if (flagMsg > msgSeq) { newSeqs.add(flagMsg); } } } flagSyncMsgSeqs.addAll(newSeqs); List<Long> msgSeqs = new ArrayList<Long>(msgSeqUidMap.keySet()); Collections.sort(msgSeqs); // Have to do comparisons in order because of msgSeq reductions for (long msgSeqNum : msgSeqs) { if (K9MailLib.isDebug()) { Log.v(LOG_TAG, "Comparing EXPUNGEd msgSeq " + msgSeq + " to " + msgSeqNum); } if (msgSeqNum == msgSeq) { String uid = msgSeqUidMap.get(msgSeqNum); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Scheduling removal of UID " + uid + " because msgSeq " + msgSeqNum + " was expunged"); } removeMsgUids.add(uid); msgSeqUidMap.remove(msgSeqNum); } else if (msgSeqNum > msgSeq) { String uid = msgSeqUidMap.get(msgSeqNum); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Reducing msgSeq for UID " + uid + " from " + msgSeqNum + " to " + (msgSeqNum - 1)); } msgSeqUidMap.remove(msgSeqNum); msgSeqUidMap.put(msgSeqNum - 1, uid); } } } } catch (Exception e) { Log.e(LOG_TAG, "Could not handle untagged FETCH for " + getLogId(), e); } } return messageCountDelta; } private void syncMessages(int end) throws MessagingException { long oldUidNext = getOldUidNext(); List<ImapMessage> messageList = getMessages(end, end, null, true, null); if (messageList != null && messageList.size() > 0) { long newUid = Long.parseLong(messageList.get(0).getUid()); if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Got newUid " + newUid + " for message " + end + " on " + getLogId()); } long startUid = oldUidNext; if (startUid < newUid - 10) { startUid = newUid - 10; } if (startUid < 1) { startUid = 1; } if (newUid >= startUid) { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Needs sync from uid " + startUid + " to " + newUid + " for " + getLogId()); } List<Message> messages = new ArrayList<Message>(); for (long uid = startUid; uid <= newUid; uid++) { ImapMessage message = new ImapMessage(Long.toString(uid), ImapFolderPusher.this); messages.add(message); } if (!messages.isEmpty()) { pushReceiver.messagesArrived(ImapFolderPusher.this, messages); } } } } private void syncMessages(List<Long> flagSyncMsgSeqs) { try { List<? extends Message> messageList = getMessages(flagSyncMsgSeqs, true, null); List<Message> messages = new ArrayList<Message>(); messages.addAll(messageList); pushReceiver.messagesFlagsChanged(ImapFolderPusher.this, messages); } catch (Exception e) { pushReceiver.pushError("Exception while processing Push untagged responses", e); } } private void removeMessages(List<String> removeUids) { List<Message> messages = new ArrayList<Message>(removeUids.size()); try { List<ImapMessage> existingMessages = getMessagesFromUids(removeUids); for (Message existingMessage : existingMessages) { needsPoll = true; msgSeqUidMap.clear(); String existingUid = existingMessage.getUid(); Log.w(LOG_TAG, "Message with UID " + existingUid + " still exists on server, not expunging"); removeUids.remove(existingUid); } for (String uid : removeUids) { ImapMessage message = new ImapMessage(uid, ImapFolderPusher.this); try { message.setFlagInternal(Flag.DELETED, true); } catch (MessagingException me) { Log.e(LOG_TAG, "Unable to set DELETED flag on message " + message.getUid()); } messages.add(message); } pushReceiver.messagesRemoved(ImapFolderPusher.this, messages); } catch (Exception e) { Log.e(LOG_TAG, "Cannot remove EXPUNGEd messages", e); } } private void syncFolderOnConnect() throws MessagingException { List<ImapResponse> untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses); storedUntaggedResponses.clear(); processUntaggedResponses(untaggedResponses); if (messageCount == -1) { throw new MessagingException("Message count = -1 for idling"); } pushReceiver.syncFolder(ImapFolderPusher.this); } private void notifyMessagesArrived(long startUid, long uidNext) { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Needs sync from uid " + startUid + " to " + uidNext + " for " + getLogId()); } int count = (int) (uidNext - startUid); List<Message> messages = new ArrayList<Message>(count); for (long uid = startUid; uid < uidNext; uid++) { ImapMessage message = new ImapMessage(Long.toString(uid), ImapFolderPusher.this); messages.add(message); } pushReceiver.messagesArrived(ImapFolderPusher.this, messages); } private long getOldUidNext() { long oldUidNext = -1L; try { String serializedPushState = pushReceiver.getPushState(getName()); ImapPushState pushState = ImapPushState.parse(serializedPushState); oldUidNext = pushState.uidNext; if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId()); } } catch (Exception e) { Log.e(LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e); } return oldUidNext; } } /** * Ensure the DONE continuation is only sent when the IDLE command was sent and hasn't completed yet. */ private static class IdleStopper { private boolean acceptDoneContinuation = false; private ImapConnection imapConnection; public synchronized void startAcceptingDoneContinuation(ImapConnection connection) { if (connection == null) { throw new NullPointerException("connection must not be null"); } acceptDoneContinuation = true; imapConnection = connection; } public synchronized void stopAcceptingDoneContinuation() { acceptDoneContinuation = false; imapConnection = null; } public synchronized void stopIdle() { if (acceptDoneContinuation) { acceptDoneContinuation = false; sendDone(); } } private void sendDone() { try { imapConnection.setReadTimeout(RemoteStore.SOCKET_READ_TIMEOUT); imapConnection.sendContinuation("DONE"); } catch (IOException e) { imapConnection.close(); } } } }
k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolderPusher.java
package com.fsck.k9.mail.store.imap; import java.io.IOException; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.content.Context; import android.os.PowerManager; import android.util.Log; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.K9MailLib; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.PushReceiver; import com.fsck.k9.mail.power.TracingPowerManager; import com.fsck.k9.mail.power.TracingPowerManager.TracingWakeLock; import com.fsck.k9.mail.store.RemoteStore; import static com.fsck.k9.mail.K9MailLib.LOG_TAG; import static com.fsck.k9.mail.K9MailLib.PUSH_WAKE_LOCK_TIMEOUT; import static com.fsck.k9.mail.store.imap.ImapResponseParser.equalsIgnoreCase; class ImapFolderPusher extends ImapFolder { private static final int IDLE_READ_TIMEOUT_INCREMENT = 5 * 60 * 1000; private static final int IDLE_FAILURE_COUNT_LIMIT = 10; private static final int MAX_DELAY_TIME = 5 * 60 * 1000; // 5 minutes private static final int NORMAL_DELAY_TIME = 5000; private final PushReceiver pushReceiver; private final AtomicBoolean stop = new AtomicBoolean(false); private final AtomicBoolean idling = new AtomicBoolean(false); private final AtomicInteger delayTime = new AtomicInteger(NORMAL_DELAY_TIME); private final AtomicInteger idleFailureCount = new AtomicInteger(0); private final AtomicBoolean needsPoll = new AtomicBoolean(false); private final Object threadLock = new Object(); private final IdleStopper idleStopper = new IdleStopper(); private final TracingWakeLock wakeLock; private List<ImapResponse> storedUntaggedResponses = new ArrayList<ImapResponse>(); private Thread listeningThread; public ImapFolderPusher(ImapStore store, String name, PushReceiver pushReceiver) { super(store, name); this.pushReceiver = pushReceiver; Context context = pushReceiver.getContext(); TracingPowerManager powerManager = TracingPowerManager.getPowerManager(context); String tag = "ImapFolderPusher " + store.getStoreConfig().toString() + ":" + getName(); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag); wakeLock.setReferenceCounted(false); } public void start() { synchronized (threadLock) { listeningThread = new Thread(new PushRunnable()); listeningThread.start(); } } public void refresh() throws IOException, MessagingException { if (idling.get()) { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); idleStopper.stopIdle(); } } public void stop() { stop.set(true); interruptListeningThread(); ImapConnection conn = connection; if (conn != null) { if (K9MailLib.isDebug()) { Log.v(LOG_TAG, "Closing connection to stop pushing for " + getLogId()); } conn.close(); } else { Log.w(LOG_TAG, "Attempt to interrupt null connection to stop pushing on folderPusher for " + getLogId()); } } private void interruptListeningThread() { synchronized (threadLock) { if (listeningThread != null) { listeningThread.interrupt(); } } } @Override protected void handleUntaggedResponse(ImapResponse response) { if (response.getTag() == null && response.size() > 1) { Object responseType = response.get(1); if (equalsIgnoreCase(responseType, "FETCH") || equalsIgnoreCase(responseType, "EXPUNGE") || equalsIgnoreCase(responseType, "EXISTS")) { if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Storing response " + response + " for later processing"); } storedUntaggedResponses.add(response); } handlePossibleUidNext(response); } } private void superHandleUntaggedResponse(ImapResponse response) { super.handleUntaggedResponse(response); } private class PushRunnable implements Runnable, UntaggedHandler { @Override public void run() { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Pusher starting for " + getLogId()); } long lastUidNext = -1L; while (!stop.get()) { try { long oldUidNext = getOldUidNext(); /* * This makes sure 'oldUidNext' is never smaller than 'UIDNEXT' from * the last loop iteration. This way we avoid looping endlessly causing * the battery to drain. * * See issue 4907 */ if (oldUidNext < lastUidNext) { oldUidNext = lastUidNext; } ImapConnection oldConnection = connection; internalOpen(OPEN_MODE_RO); ImapConnection conn = connection; checkConnectionNotNull(conn); checkConnectionIdleCapable(conn); if (stop.get()) { break; } boolean pushPollOnConnect = store.getStoreConfig().isPushPollOnConnect(); boolean openedNewConnection = conn != oldConnection; if (pushPollOnConnect && (openedNewConnection || needsPoll.getAndSet(false))) { syncFolderOnConnect(); } if (stop.get()) { break; } long newUidNext = getNewUidNext(); lastUidNext = newUidNext; long startUid = getStartUid(oldUidNext, newUidNext); if (newUidNext > startUid) { notifyMessagesArrived(startUid, newUidNext); } else { processStoredUntaggedResponses(); if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "About to IDLE for " + getLogId()); } prepareForIdle(); setReadTimeoutForIdle(conn); sendIdle(conn); returnFromIdle(); } } catch (Exception e) { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); storedUntaggedResponses.clear(); idling.set(false); pushReceiver.setPushActive(getName(), false); try { close(); } catch (Exception me) { Log.e(LOG_TAG, "Got exception while closing for exception for " + getLogId(), me); } if (stop.get()) { Log.i(LOG_TAG, "Got exception while idling, but stop is set for " + getLogId()); } else { pushReceiver.pushError("Push error for " + getName(), e); Log.e(LOG_TAG, "Got exception while idling for " + getLogId(), e); int delayTimeInt = delayTime.get(); pushReceiver.sleep(wakeLock, delayTimeInt); delayTimeInt *= 2; if (delayTimeInt > MAX_DELAY_TIME) { delayTimeInt = MAX_DELAY_TIME; } delayTime.set(delayTimeInt); if (idleFailureCount.incrementAndGet() > IDLE_FAILURE_COUNT_LIMIT) { Log.e(LOG_TAG, "Disabling pusher for " + getLogId() + " after " + idleFailureCount.get() + " consecutive errors"); pushReceiver.pushError("Push disabled for " + getName() + " after " + idleFailureCount.get() + " consecutive errors", e); stop.set(true); } } } } pushReceiver.setPushActive(getName(), false); try { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Pusher for " + getLogId() + " is exiting"); } close(); } catch (Exception me) { Log.e(LOG_TAG, "Got exception while closing for " + getLogId(), me); } finally { wakeLock.release(); } } private long getNewUidNext() throws MessagingException { long newUidNext = uidNext; if (newUidNext != -1L) { return newUidNext; } if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "uidNext is -1, using search to find highest UID"); } long highestUid = getHighestUid(); if (highestUid == -1L) { return -1L; } newUidNext = highestUid + 1; if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "highest UID = " + highestUid + ", set newUidNext to " + newUidNext); } return newUidNext; } private long getStartUid(long oldUidNext, long newUidNext) { long startUid = oldUidNext; int displayCount = store.getStoreConfig().getDisplayCount(); if (startUid < newUidNext - displayCount) { startUid = newUidNext - displayCount; } if (startUid < 1) { startUid = 1; } return startUid; } private void prepareForIdle() { pushReceiver.setPushActive(getName(), true); idling.set(true); } private void sendIdle(ImapConnection conn) throws MessagingException, IOException { String tag = conn.sendCommand(Commands.IDLE, false); List<ImapResponse> responses; try { try { responses = conn.readStatusResponse(tag, Commands.IDLE, this); } finally { idleStopper.stopAcceptingDoneContinuation(); } } catch (IOException e) { close(); throw e; } handleUntaggedResponses(responses); } private void returnFromIdle() { idling.set(false); delayTime.set(NORMAL_DELAY_TIME); idleFailureCount.set(0); } private void checkConnectionNotNull(ImapConnection conn) throws MessagingException { if (conn == null) { String message = "Could not establish connection for IDLE"; pushReceiver.pushError(message, null); throw new MessagingException(message); } } private void checkConnectionIdleCapable(ImapConnection conn) throws MessagingException { if (!conn.isIdleCapable()) { stop.set(true); String message = "IMAP server is not IDLE capable: " + conn.toString(); pushReceiver.pushError(message, null); throw new MessagingException(message); } } private void setReadTimeoutForIdle(ImapConnection conn) throws SocketException { int idleRefreshTimeout = store.getStoreConfig().getIdleRefreshMinutes() * 60 * 1000; conn.setReadTimeout(idleRefreshTimeout + IDLE_READ_TIMEOUT_INCREMENT); } @Override public void handleAsyncUntaggedResponse(ImapResponse response) { if (K9MailLib.isDebug()) { Log.v(LOG_TAG, "Got async response: " + response); } if (stop.get()) { if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got async untagged response: " + response + ", but stop is set for " + getLogId()); } idleStopper.stopIdle(); } else { if (response.getTag() == null) { if (response.size() > 1) { Object responseType = response.get(1); if (equalsIgnoreCase(responseType, "EXISTS") || equalsIgnoreCase(responseType, "EXPUNGE") || equalsIgnoreCase(responseType, "FETCH")) { wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got useful async untagged response: " + response + " for " + getLogId()); } idleStopper.stopIdle(); } } else if (response.isContinuationRequested()) { if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Idling " + getLogId()); } idleStopper.startAcceptingDoneContinuation(connection); wakeLock.release(); } } } } private void processStoredUntaggedResponses() throws MessagingException { List<ImapResponse> untaggedResponses; while (!storedUntaggedResponses.isEmpty()) { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Processing " + storedUntaggedResponses.size() + " untagged responses from previous commands for " + getLogId()); } untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses); storedUntaggedResponses.clear(); processUntaggedResponses(untaggedResponses); } } private void processUntaggedResponses(List<ImapResponse> responses) throws MessagingException { boolean skipSync = false; int oldMessageCount = messageCount; if (oldMessageCount == -1) { skipSync = true; } List<Long> flagSyncMsgSeqs = new ArrayList<Long>(); List<String> removeMsgUids = new LinkedList<String>(); for (ImapResponse response : responses) { oldMessageCount += processUntaggedResponse(oldMessageCount, response, flagSyncMsgSeqs, removeMsgUids); } if (!skipSync) { if (oldMessageCount < 0) { oldMessageCount = 0; } if (messageCount > oldMessageCount) { syncMessages(messageCount); } } if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "UIDs for messages needing flag sync are " + flagSyncMsgSeqs + " for " + getLogId()); } if (!flagSyncMsgSeqs.isEmpty()) { syncMessages(flagSyncMsgSeqs); } if (!removeMsgUids.isEmpty()) { removeMessages(removeMsgUids); } } private int processUntaggedResponse(long oldMessageCount, ImapResponse response, List<Long> flagSyncMsgSeqs, List<String> removeMsgUids) { superHandleUntaggedResponse(response); int messageCountDelta = 0; if (response.getTag() == null && response.size() > 1) { try { Object responseType = response.get(1); if (equalsIgnoreCase(responseType, "FETCH")) { Log.i(LOG_TAG, "Got FETCH " + response); long msgSeq = response.getLong(0); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got untagged FETCH for msgseq " + msgSeq + " for " + getLogId()); } if (!flagSyncMsgSeqs.contains(msgSeq)) { flagSyncMsgSeqs.add(msgSeq); } } if (equalsIgnoreCase(responseType, "EXPUNGE")) { long msgSeq = response.getLong(0); if (msgSeq <= oldMessageCount) { messageCountDelta = -1; } if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Got untagged EXPUNGE for msgseq " + msgSeq + " for " + getLogId()); } List<Long> newSeqs = new ArrayList<Long>(); Iterator<Long> flagIter = flagSyncMsgSeqs.iterator(); while (flagIter.hasNext()) { long flagMsg = flagIter.next(); if (flagMsg >= msgSeq) { flagIter.remove(); if (flagMsg > msgSeq) { newSeqs.add(flagMsg); } } } flagSyncMsgSeqs.addAll(newSeqs); List<Long> msgSeqs = new ArrayList<Long>(msgSeqUidMap.keySet()); Collections.sort(msgSeqs); // Have to do comparisons in order because of msgSeq reductions for (long msgSeqNum : msgSeqs) { if (K9MailLib.isDebug()) { Log.v(LOG_TAG, "Comparing EXPUNGEd msgSeq " + msgSeq + " to " + msgSeqNum); } if (msgSeqNum == msgSeq) { String uid = msgSeqUidMap.get(msgSeqNum); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Scheduling removal of UID " + uid + " because msgSeq " + msgSeqNum + " was expunged"); } removeMsgUids.add(uid); msgSeqUidMap.remove(msgSeqNum); } else if (msgSeqNum > msgSeq) { String uid = msgSeqUidMap.get(msgSeqNum); if (K9MailLib.isDebug()) { Log.d(LOG_TAG, "Reducing msgSeq for UID " + uid + " from " + msgSeqNum + " to " + (msgSeqNum - 1)); } msgSeqUidMap.remove(msgSeqNum); msgSeqUidMap.put(msgSeqNum - 1, uid); } } } } catch (Exception e) { Log.e(LOG_TAG, "Could not handle untagged FETCH for " + getLogId(), e); } } return messageCountDelta; } private void syncMessages(int end) throws MessagingException { long oldUidNext = getOldUidNext(); List<ImapMessage> messageList = getMessages(end, end, null, true, null); if (messageList != null && messageList.size() > 0) { long newUid = Long.parseLong(messageList.get(0).getUid()); if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Got newUid " + newUid + " for message " + end + " on " + getLogId()); } long startUid = oldUidNext; if (startUid < newUid - 10) { startUid = newUid - 10; } if (startUid < 1) { startUid = 1; } if (newUid >= startUid) { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Needs sync from uid " + startUid + " to " + newUid + " for " + getLogId()); } List<Message> messages = new ArrayList<Message>(); for (long uid = startUid; uid <= newUid; uid++) { ImapMessage message = new ImapMessage(Long.toString(uid), ImapFolderPusher.this); messages.add(message); } if (!messages.isEmpty()) { pushReceiver.messagesArrived(ImapFolderPusher.this, messages); } } } } private void syncMessages(List<Long> flagSyncMsgSeqs) { try { List<? extends Message> messageList = getMessages(flagSyncMsgSeqs, true, null); List<Message> messages = new ArrayList<Message>(); messages.addAll(messageList); pushReceiver.messagesFlagsChanged(ImapFolderPusher.this, messages); } catch (Exception e) { pushReceiver.pushError("Exception while processing Push untagged responses", e); } } private void removeMessages(List<String> removeUids) { List<Message> messages = new ArrayList<Message>(removeUids.size()); try { List<ImapMessage> existingMessages = getMessagesFromUids(removeUids); for (Message existingMessage : existingMessages) { needsPoll.set(true); msgSeqUidMap.clear(); String existingUid = existingMessage.getUid(); Log.w(LOG_TAG, "Message with UID " + existingUid + " still exists on server, not expunging"); removeUids.remove(existingUid); } for (String uid : removeUids) { ImapMessage message = new ImapMessage(uid, ImapFolderPusher.this); try { message.setFlagInternal(Flag.DELETED, true); } catch (MessagingException me) { Log.e(LOG_TAG, "Unable to set DELETED flag on message " + message.getUid()); } messages.add(message); } pushReceiver.messagesRemoved(ImapFolderPusher.this, messages); } catch (Exception e) { Log.e(LOG_TAG, "Cannot remove EXPUNGEd messages", e); } } private void syncFolderOnConnect() throws MessagingException { List<ImapResponse> untaggedResponses = new ArrayList<ImapResponse>(storedUntaggedResponses); storedUntaggedResponses.clear(); processUntaggedResponses(untaggedResponses); if (messageCount == -1) { throw new MessagingException("Message count = -1 for idling"); } pushReceiver.syncFolder(ImapFolderPusher.this); } private void notifyMessagesArrived(long startUid, long uidNext) { if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Needs sync from uid " + startUid + " to " + uidNext + " for " + getLogId()); } int count = (int) (uidNext - startUid); List<Message> messages = new ArrayList<Message>(count); for (long uid = startUid; uid < uidNext; uid++) { ImapMessage message = new ImapMessage(Long.toString(uid), ImapFolderPusher.this); messages.add(message); } pushReceiver.messagesArrived(ImapFolderPusher.this, messages); } private long getOldUidNext() { long oldUidNext = -1L; try { String serializedPushState = pushReceiver.getPushState(getName()); ImapPushState pushState = ImapPushState.parse(serializedPushState); oldUidNext = pushState.uidNext; if (K9MailLib.isDebug()) { Log.i(LOG_TAG, "Got oldUidNext " + oldUidNext + " for " + getLogId()); } } catch (Exception e) { Log.e(LOG_TAG, "Unable to get oldUidNext for " + getLogId(), e); } return oldUidNext; } } /** * Ensure the DONE continuation is only sent when the IDLE command was sent and hasn't completed yet. */ private static class IdleStopper { private boolean acceptDoneContinuation = false; private ImapConnection imapConnection; public synchronized void startAcceptingDoneContinuation(ImapConnection connection) { if (connection == null) { throw new NullPointerException("connection must not be null"); } acceptDoneContinuation = true; imapConnection = connection; } public synchronized void stopAcceptingDoneContinuation() { acceptDoneContinuation = false; imapConnection = null; } public synchronized void stopIdle() { if (acceptDoneContinuation) { acceptDoneContinuation = false; sendDone(); } } private void sendDone() { try { imapConnection.setReadTimeout(RemoteStore.SOCKET_READ_TIMEOUT); imapConnection.sendContinuation("DONE"); } catch (IOException e) { imapConnection.close(); } } } }
Move fields that are only used by listener thread into PushRunnable Also, there's no need for them to use Atomic* instances.
k9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolderPusher.java
Move fields that are only used by listener thread into PushRunnable
<ide><path>9mail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapFolderPusher.java <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.concurrent.atomic.AtomicBoolean; <del>import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import android.content.Context; <ide> import android.os.PowerManager; <ide> private final PushReceiver pushReceiver; <ide> private final AtomicBoolean stop = new AtomicBoolean(false); <ide> private final AtomicBoolean idling = new AtomicBoolean(false); <del> private final AtomicInteger delayTime = new AtomicInteger(NORMAL_DELAY_TIME); <del> private final AtomicInteger idleFailureCount = new AtomicInteger(0); <del> private final AtomicBoolean needsPoll = new AtomicBoolean(false); <ide> private final Object threadLock = new Object(); <ide> private final IdleStopper idleStopper = new IdleStopper(); <ide> private final TracingWakeLock wakeLock; <ide> <ide> <ide> private class PushRunnable implements Runnable, UntaggedHandler { <add> private int delayTime = NORMAL_DELAY_TIME; <add> private int idleFailureCount = 0; <add> private boolean needsPoll = false; <add> <ide> @Override <ide> public void run() { <ide> wakeLock.acquire(PUSH_WAKE_LOCK_TIMEOUT); <ide> <ide> boolean pushPollOnConnect = store.getStoreConfig().isPushPollOnConnect(); <ide> boolean openedNewConnection = conn != oldConnection; <del> if (pushPollOnConnect && (openedNewConnection || needsPoll.getAndSet(false))) { <add> if (pushPollOnConnect && (openedNewConnection || needsPoll)) { <add> needsPoll = false; <ide> syncFolderOnConnect(); <ide> } <ide> <ide> pushReceiver.pushError("Push error for " + getName(), e); <ide> Log.e(LOG_TAG, "Got exception while idling for " + getLogId(), e); <ide> <del> int delayTimeInt = delayTime.get(); <del> pushReceiver.sleep(wakeLock, delayTimeInt); <del> <del> delayTimeInt *= 2; <del> if (delayTimeInt > MAX_DELAY_TIME) { <del> delayTimeInt = MAX_DELAY_TIME; <del> } <del> delayTime.set(delayTimeInt); <del> <del> if (idleFailureCount.incrementAndGet() > IDLE_FAILURE_COUNT_LIMIT) { <del> Log.e(LOG_TAG, "Disabling pusher for " + getLogId() + " after " + <del> idleFailureCount.get() + " consecutive errors"); <del> pushReceiver.pushError("Push disabled for " + getName() + " after " + <del> idleFailureCount.get() + " consecutive errors", e); <add> pushReceiver.sleep(wakeLock, delayTime); <add> <add> delayTime *= 2; <add> if (delayTime > MAX_DELAY_TIME) { <add> delayTime = MAX_DELAY_TIME; <add> } <add> <add> if (++idleFailureCount > IDLE_FAILURE_COUNT_LIMIT) { <add> Log.e(LOG_TAG, "Disabling pusher for " + getLogId() + " after " + idleFailureCount + <add> " consecutive errors"); <add> pushReceiver.pushError("Push disabled for " + getName() + " after " + idleFailureCount + <add> " consecutive errors", e); <ide> stop.set(true); <ide> } <ide> } <ide> <ide> private void returnFromIdle() { <ide> idling.set(false); <del> delayTime.set(NORMAL_DELAY_TIME); <del> idleFailureCount.set(0); <add> delayTime = NORMAL_DELAY_TIME; <add> idleFailureCount = 0; <ide> } <ide> <ide> private void checkConnectionNotNull(ImapConnection conn) throws MessagingException { <ide> try { <ide> List<ImapMessage> existingMessages = getMessagesFromUids(removeUids); <ide> for (Message existingMessage : existingMessages) { <del> needsPoll.set(true); <add> needsPoll = true; <ide> msgSeqUidMap.clear(); <ide> <ide> String existingUid = existingMessage.getUid();
Java
apache-2.0
059b3da24c0309cfc1c28b537b044c28d7a45a3a
0
kirillkrohmal/krohmal,kirillkrohmal/krohmal
package ru.job4j.integrationsql; import java.io.InputStream; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by Comp on 12.06.2017. */ public class IntegrationSQL implements ITracker, AutoCloseable { private int size = 0; private Connection connection; public IntegrationSQL(Connection connection) { this.connection = connection; } @Override public Item add(Item item) { String s1 = "INSERT INTO trackersql(name, description) VALUES (?, ?)"; try (PreparedStatement statement = connection.prepareStatement(s1);) { statement.setString(1, item.getName()); statement.setString(2, item.getDescription()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return item; } @Override public void replace(String id, Item item) { try (Connection connection = init()) { if (id != null) { String s1 = "INSERT INTO trackersql(id, key, name, creat, description) VALUES (?, ?, ?, ?, ?) WHERE id=?"; PreparedStatement statement = connection.prepareStatement(s1); statement.setString(1, item.getId()); statement.setString(2, item.getKey()); statement.setString(3, item.getName()); statement.setLong(4, item.getCreated()); statement.setString(5, item.getDescription()); } } catch (SQLException e) { e.printStackTrace(); } } @Override public void delete(String id) { try (Connection connection = init()) { String s = "DELETE FROM trackersql WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(s); statement.setInt(1, Integer.valueOf(id)); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public void update(Item newItem) { Long nextId = null; try (Connection connection = init()) { if (nextId != null) { String s = "UPDATE trackersql SET key = ?, name = ?, creat = ?, description = ?) WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(s); statement.setLong(1, nextId); statement.setString(2, newItem.getKey()); statement.setString(3, newItem.getName()); statement.setLong(4, newItem.getCreat()); statement.setString(5, newItem.getDescription()); statement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } } @Override public Item[] findByName(String name) throws SQLException { List<Item> items = new ArrayList<>(); ResultSet resultSet; try (Connection connection = init()) { String s = "SELECT id, name, description FROM trackersql WHERE name = ?"; PreparedStatement statement = connection.prepareStatement(s); statement.setString(1, "name"); resultSet = statement.executeQuery(); while (resultSet.next()) { Item item = new Item(); item.setName(String.valueOf(resultSet.getInt("id"))); item.setName(resultSet.getString("name")); item.setName(resultSet.getString("description")); } } return items.toArray(new Item[0]); } @Override public Item findById(String id) { Item item = new Item(); try (Connection connection = init()) { String s = "SELECT id, key, name, creat, description FROM trackersql WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(s); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { item.setId(resultSet.getString("id")); item.setKey(resultSet.getString("key")); item.setName(resultSet.getString("name")); item.setCreat(resultSet.getLong("creat")); item.setDescription(resultSet.getString("description")); } } catch (SQLException e) { e.printStackTrace(); } return item; } @Override public Item[] findAll() { List<Item> items = new ArrayList<>(); try (Connection connection = init()) { String s = "SELECT id, key, name, creat, description FROM trackersql"; PreparedStatement statement = connection.prepareStatement(s); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { Item item = new Item(); item.setId(resultSet.getString("id")); item.setKey(resultSet.getString("key")); item.setName(resultSet.getString("name")); item.setCreat(resultSet.getLong("creat")); item.setDescription(resultSet.getString("description")); } } catch (SQLException ex) { ex.printStackTrace(); } return items.toArray(new Item[0]); } public Connection init() throws SQLException { Properties config = new Properties(); try (InputStream in = IntegrationSQL.class.getClassLoader().getResourceAsStream("app.properties")) { config.load(in); DriverManager.registerDriver(new org.postgresql.Driver()); } catch (Exception e) { throw new IllegalStateException(e); } String url = config.getProperty("url"); String username = config.getProperty("username"); String password = config.getProperty("password"); this.connection = DriverManager.getConnection(url, username, password); return connection; } public static void main(String[] args) { try { DriverManager.registerDriver(new org.postgresql.Driver()); } catch (SQLException e) { e.printStackTrace(); } } @Override public void close() throws Exception { connection.close(); } }
chapter_008/src/main/java/ru/job4j/integrationsql/IntegrationSQL.java
package ru.job4j.integrationsql; import java.io.InputStream; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by Comp on 12.06.2017. */ public class IntegrationSQL implements ITracker, AutoCloseable { private int size = 0; private Connection connection; public IntegrationSQL(Connection connection) { this.connection = connection; } @Override public Item add(Item item) { String s1 = "INSERT INTO trackersql(name, description) VALUES (?, ?)"; try (PreparedStatement statement = connection.prepareStatement(s1);) { statement.setString(1, item.getName()); statement.setString(2, item.getDescription()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return item; } @Override public void replace(String id, Item item) { try (Connection connection = init()) { if (id != null) { String s1 = "INSERT INTO trackersql(id, key, name, creat, description) VALUES (?, ?, ?, ?, ?) WHERE id=?"; PreparedStatement statement = connection.prepareStatement(s1); statement.setString(1, id); statement.setString(2, item.getKey()); statement.setString(3, item.getName()); statement.setLong(4, item.getCreated()); statement.setString(5, item.getDescription()); } } catch (SQLException e) { e.printStackTrace(); } } @Override public void delete(String id) { try (Connection connection = init()) { String s = "DELETE FROM trackersql WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(s); statement.setInt(1, Integer.valueOf(id)); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } public void update(Item newItem) { Long nextId = null; try (Connection connection = init()) { if (nextId != null) { String s = "UPDATE trackersql SET key = ?, name = ?, creat = ?, description = ?) WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(s); statement.setLong(1, nextId); statement.setString(2, newItem.getKey()); statement.setString(3, newItem.getName()); statement.setLong(4, newItem.getCreat()); statement.setString(5, newItem.getDescription()); statement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } } @Override public Item[] findByName(String name) throws SQLException { List<Item> items = new ArrayList<>(); ResultSet resultSet; try (Connection connection = init()) { String s = "SELECT id, name, description FROM trackersql WHERE name = ?"; PreparedStatement statement = connection.prepareStatement(s); statement.setString(1, "name"); resultSet = statement.executeQuery(); while (resultSet.next()) { Item item = new Item(); item.setName(String.valueOf(resultSet.getInt("id"))); item.setName(resultSet.getString("name")); item.setName(resultSet.getString("description")); } } return items.toArray(new Item[0]); } @Override public Item findById(String id) { Item result = null; try (Connection connection = init()) { String s = "SELECT id FROM trackersql WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(s); ResultSet resultSet = statement.executeQuery(); result.setId(resultSet.getString("id")); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return result; } @Override public Item[] findAll() { Item[] items = new Item[size]; try (Connection connection = init()) { String s = "SELECT id, key, name, creat, description FROM trackersql"; PreparedStatement statement = connection.prepareStatement(s); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { Item item = new Item(); item.setId(resultSet.getString("id")); item.setKey(resultSet.getString("key")); item.setName(resultSet.getString("name")); item.setCreat(resultSet.getLong("creat")); item.setDescription(resultSet.getString("description")); for (int i = 0; i < size; i++) { items[i] = item; } } } catch (SQLException ex) { ex.printStackTrace(); } return items; } public Connection init() throws SQLException { Properties config = new Properties(); try (InputStream in = IntegrationSQL.class.getClassLoader().getResourceAsStream("app.properties")) { config.load(in); DriverManager.registerDriver(new org.postgresql.Driver()); } catch (Exception e) { throw new IllegalStateException(e); } String url = config.getProperty("url"); String username = config.getProperty("username"); String password = config.getProperty("password"); this.connection = DriverManager.getConnection(url, username, password); return connection; } public static void main(String[] args) { try { DriverManager.registerDriver(new org.postgresql.Driver()); } catch (SQLException e) { e.printStackTrace(); } } @Override public void close() throws Exception { connection.close(); } }
Liquibase. Интеграционные тесты. Proxy.[#196964]
chapter_008/src/main/java/ru/job4j/integrationsql/IntegrationSQL.java
Liquibase. Интеграционные тесты. Proxy.[#196964]
<ide><path>hapter_008/src/main/java/ru/job4j/integrationsql/IntegrationSQL.java <ide> String s1 = "INSERT INTO trackersql(id, key, name, creat, description) VALUES (?, ?, ?, ?, ?) WHERE id=?"; <ide> PreparedStatement statement = connection.prepareStatement(s1); <ide> <del> statement.setString(1, id); <add> statement.setString(1, item.getId()); <ide> statement.setString(2, item.getKey()); <ide> statement.setString(3, item.getName()); <ide> statement.setLong(4, item.getCreated()); <ide> item.setName(String.valueOf(resultSet.getInt("id"))); <ide> item.setName(resultSet.getString("name")); <ide> item.setName(resultSet.getString("description")); <del> <ide> } <ide> } <ide> return items.toArray(new Item[0]); <ide> <ide> @Override <ide> public Item findById(String id) { <del> Item result = null; <add> Item item = new Item(); <ide> <ide> try (Connection connection = init()) { <del> String s = "SELECT id FROM trackersql WHERE id = ?"; <add> String s = "SELECT id, key, name, creat, description FROM trackersql WHERE id = ?"; <ide> PreparedStatement statement = connection.prepareStatement(s); <ide> <ide> ResultSet resultSet = statement.executeQuery(); <del> result.setId(resultSet.getString("id")); <ide> <del> statement.executeUpdate(); <add> while (resultSet.next()) { <add> item.setId(resultSet.getString("id")); <add> item.setKey(resultSet.getString("key")); <add> item.setName(resultSet.getString("name")); <add> item.setCreat(resultSet.getLong("creat")); <add> item.setDescription(resultSet.getString("description")); <add> } <ide> } catch (SQLException e) { <ide> e.printStackTrace(); <ide> } <del> <del> return result; <add> return item; <ide> } <ide> <ide> @Override <ide> public Item[] findAll() { <del> Item[] items = new Item[size]; <add> List<Item> items = new ArrayList<>(); <ide> <ide> try (Connection connection = init()) { <ide> String s = "SELECT id, key, name, creat, description FROM trackersql"; <ide> item.setName(resultSet.getString("name")); <ide> item.setCreat(resultSet.getLong("creat")); <ide> item.setDescription(resultSet.getString("description")); <del> <del> for (int i = 0; i < size; i++) { <del> items[i] = item; <del> } <ide> } <ide> } catch (SQLException ex) { <ide> ex.printStackTrace(); <ide> } <del> return items; <add> return items.toArray(new Item[0]); <ide> } <ide> <ide> public Connection init() throws SQLException {
Java
mit
7513ea9773f1baec84d9f668c4dc292ac1f9f1a0
0
ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE,ihongs/HongsCORE,ihongs/HongsCORE.new,ihongs/HongsCORE
package app.hongs.dh.lucene; import app.hongs.CoreLocale; import app.hongs.HongsException; import app.hongs.action.ActionHelper; import app.hongs.action.ActionRunner; import app.hongs.action.FormSet; import app.hongs.action.NaviMap; import app.hongs.action.anno.Action; import app.hongs.action.anno.Select; import app.hongs.action.anno.Verify; import app.hongs.action.anno.Spread; import app.hongs.action.anno.CommitSuccess; import app.hongs.action.anno.Preset; import app.hongs.dh.IActing; import app.hongs.dh.IAction; import app.hongs.dh.IEntity; import app.hongs.util.Dict; import java.util.Map; /** * Lucene 模型动作 * @author Hongs */ @Action() public class LuceneAction implements IAction, IActing { protected String mod = null; protected String ent = null; @Override public void initiate(ActionHelper helper, ActionRunner runner) throws HongsException { String act; act = runner.getHandle(); ent = runner.getEntity(); mod = runner.getModule(); try { // 方便自动机处理 if (FormSet.hasConfFile(mod + "/" + ent)) { mod = mod + "/" + ent; } // 下划线开头的为内部资源, 不直接对外开放 if (ent.startsWith("_")) { throw new HongsException(0x1100, "Unsupported Request!"); } // 判断是否禁用了当前动作, 忽略表单不存在 if (Dict.getValue( FormSet.getInstance( mod ).getForm( ent ), false, "@","deny.call."+act)) { throw new HongsException(0x1100, "Unsupported Request."); } } catch (HongsException ex ) { int ec = ex.getErrno( ); if (ec != 0x10e8 && ec != 0x10ea) { throw ex; } } } @Action("retrieve") @Preset(conf="", envm="") @Select(conf="", form="") @Spread(conf="", form="") @Override public void retrieve(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "retrieve", rd); Map sd = sr.retrieve( rd ); sd = getRspMap(helper, sr, "retrieve", sd); // sr.destroy( ); helper.reply(sd); } @Action("create") @Preset(conf="", envm="", used={":defence", ":create"}) @Select(conf="", form="", mode=2) @Verify(conf="", form="") @CommitSuccess @Override public void create(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "create", rd); Map sd = sr.create( rd ); sd = getRspMap(helper, sr, "create", sd); String ss = getRspMsg(helper, sr, "create", 1 ); // sr.destroy(); helper.reply(ss, sd); } @Action("update") @Preset(conf="", envm="", used={":defence", ":update"}) @Verify(conf="", form="") @CommitSuccess @Override public void update(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "update", rd); int sn = sr.update( rd ); String ss = getRspMsg(helper, sr, "update", sn); // sr.destroy(); helper.reply(ss, sn); } @Action("delete") @Preset(conf="", envm="", used={":defence", ":delete"}) @CommitSuccess @Override public void delete(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "delete", rd); int sn = sr.delete( rd ); String ss = getRspMsg(helper, sr, "delete", sn); // sr.destroy(); helper.reply(ss, sn); } /** * 获取模型对象 * 注意: * 对象 Action 注解的命名必须为 "模型路径/实体名称" * 方法 Action 注解的命名只能是 "动作名称", 不得含子级实体名称 * @param helper * @return * @throws HongsException */ public IEntity getEntity(ActionHelper helper) throws HongsException { return LuceneRecord.getInstance(mod, ent); } /** * 获取请求数据 * @param helper * @param ett * @param opr * @param req * @return * @throws HongsException */ protected Map getReqMap(ActionHelper helper, IEntity ett, String opr, Map req) throws HongsException { return req; } /** * 整理返回数据 * @param helper * @param ett * @param opr * @param rsp * @return * @throws HongsException */ protected Map getRspMap(ActionHelper helper, IEntity ett, String opr, Map rsp) throws HongsException { return rsp; } /** * 获取返回消息 * @param helper * @param ett * @param opr * @param num * @return * @throws HongsException */ protected String getRspMsg(ActionHelper helper, IEntity ett, String opr, int num) throws HongsException { CoreLocale lang = CoreLocale.getInstance().clone( ); lang.loadIgnrFNF(mod); String cnt = Integer.toString(num); String key = "fore." + opr + "." + ent + ".success"; if (! lang.containsKey(key)) { key = "fore." + opr + ".success" ; String tit = getTitle(lang); return lang.translate(key, tit, cnt); } else { return lang.translate(key, cnt /**/); } } /** * 获取实体标题, 用于 getRspMsg 中 * @param lang * @return * @throws HongsException */ protected String getTitle(CoreLocale lang) throws HongsException { String disp; Map item; do { // 先从表单取名字 item = getForm(); if (item != null && item.containsKey( "@" )) { item = (Map ) item.get( "@" ); if (item != null && item.containsKey("__disp__")) { disp = (String) item.get("__disp__"); break; } } // 再从菜单取名字 item = getMenu(); if (item != null && item.containsKey( "disp" )) { disp = (String) item.get( "disp" ); break; } // 最后配置取名字 disp = "core.entity."+ent+".name"; } while (false); return lang.translate(disp); } private Map getForm() throws HongsException { String cuf = FormSet.hasConfFile(mod + "/" + ent) ? mod + "/" + ent : mod ; FormSet form = FormSet.getInstance(cuf); try { return form.getFormTranslated (ent); } catch (HongsException ex ) { if (ex.getErrno() == 0x10ea) { return null; } else { throw ex ; } } } private Map getMenu() throws HongsException { String cuf = FormSet.hasConfFile(mod + "/" + ent) ? mod + "/" + ent : mod ; NaviMap navi = NaviMap.getInstance(cuf); return navi.getMenu(mod+"/"+ent+"/" ); } }
hongs-serv-search/src/main/java/app/hongs/dh/lucene/LuceneAction.java
package app.hongs.dh.lucene; import app.hongs.CoreLocale; import app.hongs.HongsException; import app.hongs.action.ActionHelper; import app.hongs.action.ActionRunner; import app.hongs.action.FormSet; import app.hongs.action.NaviMap; import app.hongs.action.anno.Action; import app.hongs.action.anno.Select; import app.hongs.action.anno.Verify; import app.hongs.action.anno.Spread; import app.hongs.action.anno.CommitSuccess; import app.hongs.action.anno.Preset; import app.hongs.dh.IActing; import app.hongs.dh.IAction; import app.hongs.dh.IEntity; import app.hongs.util.Dict; import java.util.Map; /** * Lucene 模型动作 * @author Hongs */ @Action() public class LuceneAction implements IAction, IActing { protected String mod = null; protected String ent = null; @Override public void initiate(ActionHelper helper, ActionRunner runner) throws HongsException { String act; act = runner.getHandle(); ent = runner.getEntity(); mod = runner.getModule(); try { // 方便自动机处理 if (FormSet.hasConfFile(mod + "/" + ent)) { mod = mod + "/" + ent; } // 下划线开头的为内部资源, 不直接对外开放 if (ent.startsWith("_")) { throw new HongsException(0x1100, "Unsupported Request!"); } // 判断是否禁用了当前动作, 忽略表单不存在 if (Dict.getValue( FormSet.getInstance( mod ).getForm( ent ), false, "@","cant.call."+act)) { throw new HongsException(0x1100, "Unsupported Request."); } } catch (HongsException ex ) { int ec = ex.getErrno( ); if (ec != 0x10e8 && ec != 0x10ea) { throw ex; } } } @Action("retrieve") @Preset(conf="", envm="") @Select(conf="", form="") @Spread(conf="", form="") @Override public void retrieve(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "retrieve", rd); Map sd = sr.retrieve( rd ); sd = getRspMap(helper, sr, "retrieve", sd); // sr.destroy( ); helper.reply(sd); } @Action("create") @Preset(conf="", envm="", used={":defence", ":create"}) @Select(conf="", form="", mode=2) @Verify(conf="", form="") @CommitSuccess @Override public void create(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "create", rd); Map sd = sr.create( rd ); sd = getRspMap(helper, sr, "create", sd); String ss = getRspMsg(helper, sr, "create", 1 ); // sr.destroy(); helper.reply(ss, sd); } @Action("update") @Preset(conf="", envm="", used={":defence", ":update"}) @Verify(conf="", form="") @CommitSuccess @Override public void update(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "update", rd); int sn = sr.update( rd ); String ss = getRspMsg(helper, sr, "update", sn); // sr.destroy(); helper.reply(ss, sn); } @Action("delete") @Preset(conf="", envm="", used={":defence", ":delete"}) @CommitSuccess @Override public void delete(ActionHelper helper) throws HongsException { IEntity sr = getEntity(helper); Map rd = helper.getRequestData(); rd = getReqMap(helper, sr, "delete", rd); int sn = sr.delete( rd ); String ss = getRspMsg(helper, sr, "delete", sn); // sr.destroy(); helper.reply(ss, sn); } /** * 获取模型对象 * 注意: * 对象 Action 注解的命名必须为 "模型路径/实体名称" * 方法 Action 注解的命名只能是 "动作名称", 不得含子级实体名称 * @param helper * @return * @throws HongsException */ public IEntity getEntity(ActionHelper helper) throws HongsException { return LuceneRecord.getInstance(mod, ent); } /** * 获取请求数据 * @param helper * @param ett * @param opr * @param req * @return * @throws HongsException */ protected Map getReqMap(ActionHelper helper, IEntity ett, String opr, Map req) throws HongsException { return req; } /** * 整理返回数据 * @param helper * @param ett * @param opr * @param rsp * @return * @throws HongsException */ protected Map getRspMap(ActionHelper helper, IEntity ett, String opr, Map rsp) throws HongsException { return rsp; } /** * 获取返回消息 * @param helper * @param ett * @param opr * @param num * @return * @throws HongsException */ protected String getRspMsg(ActionHelper helper, IEntity ett, String opr, int num) throws HongsException { CoreLocale lang = CoreLocale.getInstance().clone( ); lang.loadIgnrFNF(mod); String cnt = Integer.toString(num); String key = "fore." + opr + "." + ent + ".success"; if (! lang.containsKey(key)) { key = "fore." + opr + ".success" ; String tit = getTitle(lang); return lang.translate(key, tit, cnt); } else { return lang.translate(key, cnt /**/); } } /** * 获取实体标题, 用于 getRspMsg 中 * @param lang * @return * @throws HongsException */ protected String getTitle(CoreLocale lang) throws HongsException { String disp; Map item; do { // 先从表单取名字 item = getForm(); if (item != null && item.containsKey( "@" )) { item = (Map ) item.get( "@" ); if (item != null && item.containsKey("__disp__")) { disp = (String) item.get("__disp__"); break; } } // 再从菜单取名字 item = getMenu(); if (item != null && item.containsKey( "disp" )) { disp = (String) item.get( "disp" ); break; } // 最后配置取名字 disp = "core.entity."+ent+".name"; } while (false); return lang.translate(disp); } private Map getForm() throws HongsException { String cuf = FormSet.hasConfFile(mod + "/" + ent) ? mod + "/" + ent : mod ; FormSet form = FormSet.getInstance(cuf); try { return form.getFormTranslated (ent); } catch (HongsException ex ) { if (ex.getErrno() == 0x10ea) { return null; } else { throw ex ; } } } private Map getMenu() throws HongsException { String cuf = FormSet.hasConfFile(mod + "/" + ent) ? mod + "/" + ent : mod ; NaviMap navi = NaviMap.getInstance(cuf); return navi.getMenu(mod+"/"+ent+"/" ); } }
dont.call. 改为 deny.call.
hongs-serv-search/src/main/java/app/hongs/dh/lucene/LuceneAction.java
dont.call. 改为 deny.call.
<ide><path>ongs-serv-search/src/main/java/app/hongs/dh/lucene/LuceneAction.java <ide> <ide> // 判断是否禁用了当前动作, 忽略表单不存在 <ide> if (Dict.getValue( FormSet.getInstance( mod ).getForm( ent ), <del> false, "@","cant.call."+act)) { <add> false, "@","deny.call."+act)) { <ide> throw new HongsException(0x1100, "Unsupported Request."); <ide> } <ide> }
Java
agpl-3.0
8e8d4117b7af6b5b9f7e0c6da4e4d3ea733bd4aa
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
9c36327c-2e5f-11e5-9284-b827eb9e62be
hello.java
9c309e0c-2e5f-11e5-9284-b827eb9e62be
9c36327c-2e5f-11e5-9284-b827eb9e62be
hello.java
9c36327c-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>9c309e0c-2e5f-11e5-9284-b827eb9e62be <add>9c36327c-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
1c10f140e6e0bc7784f3fe74fd3df07873ba8dc1
0
android10/java-code-examples
package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.optional.Optional; import java.util.Arrays; import java.util.Collections; import java.util.List; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; @See(ref = "") public class UseCaseScenario03 { public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM = new Func1<Optional<List<String>>, Observable<List<String>>>() { @Override public Observable<List<String>> call(Optional<List<String>> ads) { return ads.isPresent() ? Observable.just(ads.get()) : Observable.just(Collections.<String>emptyList()); } }; public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS = new Func1<List<String>, Boolean>() { @Override public Boolean call(List<String> ads) { return !ads.isEmpty(); } }; public UseCaseScenario03() { //empty } @Override public String toString() { final StringBuilder builder = new StringBuilder(); feed().subscribe(new Action1<List<String>>() { @Override public void call(List<String> feed) { for (String feedElement : feed) { builder.append("\n").append(feedElement); } } }); return builder.toString(); } private Observable<List<String>> feed() { return ads() .flatMap(TO_AD_ITEM) .filter(EMPTY_ELEMENTS) .concatWith(users()) .observeOn(Schedulers.immediate()); } private Observable<List<String>> users() { return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman")); } private Observable<Optional<List<String>>> ads() { return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad"))); } }
src/main/java/com/fernandocejas/java/samples/optional/UseCaseScenario03.java
package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.strings.Strings; @See(ref = "") public class UseCaseScenario03 { public UseCaseScenario03() { //empty } @Override public String toString() { return Strings.EMPTY; } }
Add third case scenario for Optional sample.
src/main/java/com/fernandocejas/java/samples/optional/UseCaseScenario03.java
Add third case scenario for Optional sample.
<ide><path>rc/main/java/com/fernandocejas/java/samples/optional/UseCaseScenario03.java <ide> package com.fernandocejas.java.samples.optional; <ide> <ide> import com.fernandocejas.arrow.annotations.See; <del>import com.fernandocejas.arrow.strings.Strings; <add>import com.fernandocejas.arrow.optional.Optional; <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.List; <add>import rx.Observable; <add>import rx.functions.Action1; <add>import rx.functions.Func1; <add>import rx.schedulers.Schedulers; <ide> <ide> @See(ref = "") <ide> public class UseCaseScenario03 { <add> <add> public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM = <add> new Func1<Optional<List<String>>, Observable<List<String>>>() { <add> @Override public Observable<List<String>> call(Optional<List<String>> ads) { <add> return ads.isPresent() <add> ? Observable.just(ads.get()) <add> : Observable.just(Collections.<String>emptyList()); <add> } <add> }; <add> <add> public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS = <add> new Func1<List<String>, Boolean>() { <add> @Override public Boolean call(List<String> ads) { <add> return !ads.isEmpty(); <add> } <add> }; <ide> <ide> public UseCaseScenario03() { <ide> //empty <ide> } <ide> <ide> @Override public String toString() { <del> return Strings.EMPTY; <add> final StringBuilder builder = new StringBuilder(); <add> feed().subscribe(new Action1<List<String>>() { <add> @Override public void call(List<String> feed) { <add> for (String feedElement : feed) { <add> builder.append("\n").append(feedElement); <add> } <add> } <add> }); <add> return builder.toString(); <add> } <add> <add> private Observable<List<String>> feed() { <add> return ads() <add> .flatMap(TO_AD_ITEM) <add> .filter(EMPTY_ELEMENTS) <add> .concatWith(users()) <add> .observeOn(Schedulers.immediate()); <add> } <add> <add> private Observable<List<String>> users() { <add> return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman")); <add> } <add> <add> private Observable<Optional<List<String>>> ads() { <add> return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad"))); <ide> } <ide> }
JavaScript
mit
bc7e3d511e50dd3d1c3387ac9eb133848799aa80
0
narekye/code,narekye/code,narekye/code,narekye/code,narekye/code,narekye/code
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Loading from './loading/gifLoading.js'; // eslint-disable-next-line "use strict"; // class Square extends React.Component { // // constructor() { // // super(); // // this.state = { // // value: null // // } // // } // render() { // return ( // <button className="square" onClick={() => this.props.onClick()}> // {this.props.value} // </button> // ); // } // } function Square(props) { return ( <button className="square" onClick={props.onClick}> {props.value} </button> ); } class Board extends React.Component { constructor() { super(); this.state = { squares: Array(9).fill(null), xIsNext: true } } renderSquare(i) { return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />; } handleClick(i) { const squares = this.state.squares.slice(); console.log(squares); if (calculateWinner(squares)) { return; } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ squares: squares, xIsNext: !this.state.xIsNext }); } render() { const winner = calculateWinner(this.state.squares); let status; if (winner) { status = 'Winner: ' + winner; } else { status = 'Next player is: ' + (this.state.xIsNext ? 'X' : 'O') } return ( <div> <div className="status">{status}</div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> </div> {/* <Loading /> */} </div> ); } } function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') );
react/my-app/src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Loading from './loading/gifLoading.js'; // eslint-disable-next-line "use strict"; // class Square extends React.Component { // // constructor() { // // super(); // // this.state = { // // value: null // // } // // } // render() { // return ( // <button className="square" onClick={() => this.props.onClick()}> // {this.props.value} // </button> // ); // } // } function Square(props) { return ( <button className="square" onClick={props.onClick}> {props.value} </button> ); } class Board extends React.Component { constructor() { super(); this.state = { squares: Array(9).fill(null), xIsNext: true } } renderSquare(i) { return <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} />; } handleClick(i) { const squares = this.state.squares.slice(); if (calculateWinner(squares)) { return; } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ squares: squares, xIsNext: !this.state.xIsNext }); } render() { const winner = calculateWinner(this.state.squares); let status; if (winner) { status = 'Winner: ' + winner; } else { status = 'Next player is: ' + (this.state.xIsNext ? 'X' : 'O') } return ( <div> <div className="status">{status}</div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); } } class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> </div> {/* <Loading /> */} </div> ); } } function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; } // ======================================== ReactDOM.render( <Game />, document.getElementById('root') );
index.js changes
react/my-app/src/index.js
index.js changes
<ide><path>eact/my-app/src/index.js <ide> <ide> handleClick(i) { <ide> const squares = this.state.squares.slice(); <add> console.log(squares); <ide> if (calculateWinner(squares)) { <ide> return; <ide> } <ide> squares[i] = this.state.xIsNext ? 'X' : 'O'; <add> <ide> this.setState({ <ide> squares: squares, <ide> xIsNext: !this.state.xIsNext
Java
apache-2.0
ce94833a344001247ff260be488cab4b54fc8a68
0
blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.service.scopes; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import groovy.lang.GroovyObject; import groovy.transform.Generated; import org.gradle.api.Describable; import org.gradle.api.artifacts.transform.CacheableTransform; import org.gradle.api.artifacts.transform.InputArtifact; import org.gradle.api.artifacts.transform.InputArtifactDependencies; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.internal.DefaultDomainObjectCollection; import org.gradle.api.internal.DefaultDomainObjectSet; import org.gradle.api.internal.DefaultNamedDomainObjectCollection; import org.gradle.api.internal.DefaultNamedDomainObjectList; import org.gradle.api.internal.DefaultNamedDomainObjectSet; import org.gradle.api.internal.DefaultPolymorphicDomainObjectContainer; import org.gradle.api.internal.DynamicObjectAware; import org.gradle.api.internal.IConventionAware; import org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore; import org.gradle.api.internal.project.taskfactory.TaskClassInfoStore; import org.gradle.api.internal.tasks.properties.InspectionScheme; import org.gradle.api.internal.tasks.properties.InspectionSchemeFactory; import org.gradle.api.internal.tasks.properties.ModifierAnnotationCategory; import org.gradle.api.internal.tasks.properties.PropertyWalker; import org.gradle.api.internal.tasks.properties.TaskScheme; import org.gradle.api.internal.tasks.properties.annotations.CacheableTaskTypeAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.DestroysPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.DisableCachingByDefaultTypeAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputDirectoryPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputFilePropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputFilesPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.LocalStatePropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.NestedBeanAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.NoOpPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputDirectoriesPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputDirectoryPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputFilePropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputFilesPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.PropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.TypeAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.UntrackedTaskTypeAnnotationHandler; import org.gradle.api.model.ReplacedBy; import org.gradle.api.plugins.ExtensionAware; import org.gradle.api.provider.Property; import org.gradle.api.tasks.CacheableTask; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.CompileClasspath; import org.gradle.api.tasks.Console; import org.gradle.api.tasks.Destroys; import org.gradle.api.tasks.IgnoreEmptyDirectories; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.LocalState; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputDirectories; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.OutputFiles; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.UntrackedTask; import org.gradle.api.tasks.options.OptionValues; import org.gradle.cache.internal.CrossBuildInMemoryCacheFactory; import org.gradle.internal.execution.DefaultTaskExecutionTracker; import org.gradle.internal.execution.TaskExecutionTracker; import org.gradle.internal.instantiation.InstantiationScheme; import org.gradle.internal.instantiation.InstantiatorFactory; import org.gradle.internal.operations.BuildOperationAncestryTracker; import org.gradle.internal.operations.BuildOperationListenerManager; import org.gradle.internal.reflect.annotations.TypeAnnotationMetadataStore; import org.gradle.internal.reflect.annotations.impl.DefaultTypeAnnotationMetadataStore; import org.gradle.internal.scripts.ScriptOrigin; import org.gradle.util.internal.ClosureBackedAction; import org.gradle.util.internal.ConfigureUtil; import org.gradle.work.DisableCachingByDefault; import org.gradle.work.Incremental; import org.gradle.work.NormalizeLineEndings; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.List; @SuppressWarnings("unused") public class ExecutionGlobalServices { @VisibleForTesting public static final ImmutableSet<Class<? extends Annotation>> PROPERTY_TYPE_ANNOTATIONS = ImmutableSet.of( Console.class, Destroys.class, Input.class, InputArtifact.class, InputArtifactDependencies.class, InputDirectory.class, InputFile.class, InputFiles.class, LocalState.class, Nested.class, OptionValues.class, OutputDirectories.class, OutputDirectory.class, OutputFile.class, OutputFiles.class ); @VisibleForTesting public static final ImmutableSet<Class<? extends Annotation>> IGNORED_METHOD_ANNOTATIONS = ImmutableSet.of( Internal.class, ReplacedBy.class ); TaskExecutionTracker createTaskExecutionTracker(BuildOperationAncestryTracker ancestryTracker, BuildOperationListenerManager operationListenerManager) { return new DefaultTaskExecutionTracker(ancestryTracker, operationListenerManager); } AnnotationHandlerRegistar createAnnotationRegistry(List<AnnotationHandlerRegistration> registrations) { return builder -> registrations.forEach(registration -> builder.addAll(registration.getAnnotations())); } TypeAnnotationMetadataStore createAnnotationMetadataStore(CrossBuildInMemoryCacheFactory cacheFactory, AnnotationHandlerRegistar annotationRegistry) { @SuppressWarnings("deprecation") Class<?> deprecatedHasConvention = org.gradle.api.internal.HasConvention.class; ImmutableSet.Builder<Class<? extends Annotation>> builder = ImmutableSet.builder(); builder.addAll(PROPERTY_TYPE_ANNOTATIONS); annotationRegistry.registerPropertyTypeAnnotations(builder); return new DefaultTypeAnnotationMetadataStore( ImmutableSet.of( CacheableTask.class, CacheableTransform.class, DisableCachingByDefault.class, UntrackedTask.class ), ModifierAnnotationCategory.asMap(builder.build()), ImmutableSet.of( "java", "groovy", "kotlin" ), ImmutableSet.of( ClosureBackedAction.class, ConfigureUtil.WrappedConfigureAction.class, Describable.class, DefaultDomainObjectCollection.class, DefaultDomainObjectSet.class, DefaultNamedDomainObjectCollection.class, DefaultNamedDomainObjectList.class, DefaultNamedDomainObjectSet.class, DefaultPolymorphicDomainObjectContainer.class, DynamicObjectAware.class, ExtensionAware.class, deprecatedHasConvention, IConventionAware.class, ScriptOrigin.class ), ImmutableSet.of( GroovyObject.class, Object.class, ScriptOrigin.class ), ImmutableSet.of( ConfigurableFileCollection.class, Property.class ), IGNORED_METHOD_ANNOTATIONS, method -> method.isAnnotationPresent(Generated.class), cacheFactory); } InspectionSchemeFactory createInspectionSchemeFactory( List<TypeAnnotationHandler> typeHandlers, List<PropertyAnnotationHandler> propertyHandlers, TypeAnnotationMetadataStore typeAnnotationMetadataStore, CrossBuildInMemoryCacheFactory cacheFactory ) { return new InspectionSchemeFactory(typeHandlers, propertyHandlers, typeAnnotationMetadataStore, cacheFactory); } TaskScheme createTaskScheme(InspectionSchemeFactory inspectionSchemeFactory, InstantiatorFactory instantiatorFactory, AnnotationHandlerRegistar annotationRegistry) { InstantiationScheme instantiationScheme = instantiatorFactory.decorateScheme(); ImmutableSet.Builder<Class<? extends Annotation>> allPropertyTypes = ImmutableSet.builder(); allPropertyTypes.addAll(ImmutableSet.of( Input.class, InputFile.class, InputFiles.class, InputDirectory.class, OutputFile.class, OutputFiles.class, OutputDirectory.class, OutputDirectories.class, Destroys.class, LocalState.class, Nested.class, Console.class, ReplacedBy.class, Internal.class, OptionValues.class )); annotationRegistry.registerPropertyTypeAnnotations(allPropertyTypes); InspectionScheme inspectionScheme = inspectionSchemeFactory.inspectionScheme( allPropertyTypes.build(), ImmutableSet.of( Classpath.class, CompileClasspath.class, Incremental.class, Optional.class, PathSensitive.class, SkipWhenEmpty.class, IgnoreEmptyDirectories.class, NormalizeLineEndings.class ), instantiationScheme); return new TaskScheme(instantiationScheme, inspectionScheme); } PropertyWalker createPropertyWalker(TaskScheme taskScheme) { return taskScheme.getInspectionScheme().getPropertyWalker(); } TaskClassInfoStore createTaskClassInfoStore(CrossBuildInMemoryCacheFactory cacheFactory) { return new DefaultTaskClassInfoStore(cacheFactory); } TypeAnnotationHandler createDoNotCacheByDefaultTypeAnnotationHandler() { return new DisableCachingByDefaultTypeAnnotationHandler(); } TypeAnnotationHandler createCacheableTaskAnnotationHandler() { return new CacheableTaskTypeAnnotationHandler(); } TypeAnnotationHandler createUntrackedAnnotationHandler() { return new UntrackedTaskTypeAnnotationHandler(); } PropertyAnnotationHandler createConsoleAnnotationHandler() { return new NoOpPropertyAnnotationHandler(Console.class); } PropertyAnnotationHandler createInternalAnnotationHandler() { return new NoOpPropertyAnnotationHandler(Internal.class); } PropertyAnnotationHandler createReplacedByAnnotationHandler() { return new NoOpPropertyAnnotationHandler(ReplacedBy.class); } PropertyAnnotationHandler createOptionValuesAnnotationHandler() { return new NoOpPropertyAnnotationHandler(OptionValues.class); } PropertyAnnotationHandler createInputPropertyAnnotationHandler() { return new InputPropertyAnnotationHandler(); } PropertyAnnotationHandler createInputFilePropertyAnnotationHandler() { return new InputFilePropertyAnnotationHandler(); } PropertyAnnotationHandler createInputFilesPropertyAnnotationHandler() { return new InputFilesPropertyAnnotationHandler(); } PropertyAnnotationHandler createInputDirectoryPropertyAnnotationHandler() { return new InputDirectoryPropertyAnnotationHandler(); } OutputFilePropertyAnnotationHandler createOutputFilePropertyAnnotationHandler() { return new OutputFilePropertyAnnotationHandler(); } OutputFilesPropertyAnnotationHandler createOutputFilesPropertyAnnotationHandler() { return new OutputFilesPropertyAnnotationHandler(); } OutputDirectoryPropertyAnnotationHandler createOutputDirectoryPropertyAnnotationHandler() { return new OutputDirectoryPropertyAnnotationHandler(); } OutputDirectoriesPropertyAnnotationHandler createOutputDirectoriesPropertyAnnotationHandler() { return new OutputDirectoriesPropertyAnnotationHandler(); } PropertyAnnotationHandler createDestroysPropertyAnnotationHandler() { return new DestroysPropertyAnnotationHandler(); } PropertyAnnotationHandler createLocalStatePropertyAnnotationHandler() { return new LocalStatePropertyAnnotationHandler(); } PropertyAnnotationHandler createNestedBeanPropertyAnnotationHandler() { return new NestedBeanAnnotationHandler(); } public interface AnnotationHandlerRegistration { Collection<Class<? extends Annotation>> getAnnotations(); } interface AnnotationHandlerRegistar { void registerPropertyTypeAnnotations(ImmutableSet.Builder<Class<? extends Annotation>> builder); } }
subprojects/core/src/main/java/org/gradle/internal/service/scopes/ExecutionGlobalServices.java
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.service.scopes; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import groovy.lang.GroovyObject; import groovy.transform.Generated; import org.gradle.api.Describable; import org.gradle.api.artifacts.transform.CacheableTransform; import org.gradle.api.artifacts.transform.InputArtifact; import org.gradle.api.artifacts.transform.InputArtifactDependencies; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.internal.ConventionTask; import org.gradle.api.internal.DefaultDomainObjectCollection; import org.gradle.api.internal.DefaultDomainObjectSet; import org.gradle.api.internal.DefaultNamedDomainObjectCollection; import org.gradle.api.internal.DefaultNamedDomainObjectList; import org.gradle.api.internal.DefaultNamedDomainObjectSet; import org.gradle.api.internal.DefaultPolymorphicDomainObjectContainer; import org.gradle.api.internal.DynamicObjectAware; import org.gradle.api.internal.IConventionAware; import org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore; import org.gradle.api.internal.project.taskfactory.TaskClassInfoStore; import org.gradle.api.internal.tasks.properties.InspectionScheme; import org.gradle.api.internal.tasks.properties.InspectionSchemeFactory; import org.gradle.api.internal.tasks.properties.ModifierAnnotationCategory; import org.gradle.api.internal.tasks.properties.PropertyWalker; import org.gradle.api.internal.tasks.properties.TaskScheme; import org.gradle.api.internal.tasks.properties.annotations.CacheableTaskTypeAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.DestroysPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.DisableCachingByDefaultTypeAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputDirectoryPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputFilePropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputFilesPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.InputPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.LocalStatePropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.NestedBeanAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.NoOpPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputDirectoriesPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputDirectoryPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputFilePropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.OutputFilesPropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.PropertyAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.TypeAnnotationHandler; import org.gradle.api.internal.tasks.properties.annotations.UntrackedTaskTypeAnnotationHandler; import org.gradle.api.model.ReplacedBy; import org.gradle.api.plugins.ExtensionAware; import org.gradle.api.provider.Property; import org.gradle.api.tasks.CacheableTask; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.CompileClasspath; import org.gradle.api.tasks.Console; import org.gradle.api.tasks.Destroys; import org.gradle.api.tasks.IgnoreEmptyDirectories; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.LocalState; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputDirectories; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.OutputFiles; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.UntrackedTask; import org.gradle.api.tasks.options.OptionValues; import org.gradle.cache.internal.CrossBuildInMemoryCacheFactory; import org.gradle.internal.execution.DefaultTaskExecutionTracker; import org.gradle.internal.execution.TaskExecutionTracker; import org.gradle.internal.instantiation.InstantiationScheme; import org.gradle.internal.instantiation.InstantiatorFactory; import org.gradle.internal.operations.BuildOperationAncestryTracker; import org.gradle.internal.operations.BuildOperationListenerManager; import org.gradle.internal.reflect.annotations.TypeAnnotationMetadataStore; import org.gradle.internal.reflect.annotations.impl.DefaultTypeAnnotationMetadataStore; import org.gradle.internal.scripts.ScriptOrigin; import org.gradle.util.internal.ClosureBackedAction; import org.gradle.util.internal.ConfigureUtil; import org.gradle.work.DisableCachingByDefault; import org.gradle.work.Incremental; import org.gradle.work.NormalizeLineEndings; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.List; @SuppressWarnings("unused") public class ExecutionGlobalServices { @VisibleForTesting public static final ImmutableSet<Class<? extends Annotation>> PROPERTY_TYPE_ANNOTATIONS = ImmutableSet.of( Console.class, Destroys.class, Input.class, InputArtifact.class, InputArtifactDependencies.class, InputDirectory.class, InputFile.class, InputFiles.class, LocalState.class, Nested.class, OptionValues.class, OutputDirectories.class, OutputDirectory.class, OutputFile.class, OutputFiles.class ); @VisibleForTesting public static final ImmutableSet<Class<? extends Annotation>> IGNORED_METHOD_ANNOTATIONS = ImmutableSet.of( Internal.class, ReplacedBy.class ); TaskExecutionTracker createTaskExecutionTracker(BuildOperationAncestryTracker ancestryTracker, BuildOperationListenerManager operationListenerManager) { return new DefaultTaskExecutionTracker(ancestryTracker, operationListenerManager); } AnnotationHandlerRegistar createAnnotationRegistry(List<AnnotationHandlerRegistration> registrations) { return builder -> registrations.forEach(registration -> builder.addAll(registration.getAnnotations())); } TypeAnnotationMetadataStore createAnnotationMetadataStore(CrossBuildInMemoryCacheFactory cacheFactory, AnnotationHandlerRegistar annotationRegistry) { @SuppressWarnings("deprecation") Class<?> deprecatedHasConvention = org.gradle.api.internal.HasConvention.class; ImmutableSet.Builder<Class<? extends Annotation>> builder = ImmutableSet.builder(); builder.addAll(PROPERTY_TYPE_ANNOTATIONS); annotationRegistry.registerPropertyTypeAnnotations(builder); return new DefaultTypeAnnotationMetadataStore( ImmutableSet.of( CacheableTask.class, CacheableTransform.class, DisableCachingByDefault.class, UntrackedTask.class ), ModifierAnnotationCategory.asMap(builder.build()), ImmutableSet.of( "java", "groovy", "kotlin" ), ImmutableSet.of( ClosureBackedAction.class, ConfigureUtil.WrappedConfigureAction.class, ConventionTask.class, Describable.class, DefaultDomainObjectCollection.class, DefaultDomainObjectSet.class, DefaultNamedDomainObjectCollection.class, DefaultNamedDomainObjectList.class, DefaultNamedDomainObjectSet.class, DefaultPolymorphicDomainObjectContainer.class, DynamicObjectAware.class, ExtensionAware.class, deprecatedHasConvention, IConventionAware.class, ScriptOrigin.class ), ImmutableSet.of( GroovyObject.class, Object.class, ScriptOrigin.class ), ImmutableSet.of( ConfigurableFileCollection.class, Property.class ), IGNORED_METHOD_ANNOTATIONS, method -> method.isAnnotationPresent(Generated.class), cacheFactory); } InspectionSchemeFactory createInspectionSchemeFactory( List<TypeAnnotationHandler> typeHandlers, List<PropertyAnnotationHandler> propertyHandlers, TypeAnnotationMetadataStore typeAnnotationMetadataStore, CrossBuildInMemoryCacheFactory cacheFactory ) { return new InspectionSchemeFactory(typeHandlers, propertyHandlers, typeAnnotationMetadataStore, cacheFactory); } TaskScheme createTaskScheme(InspectionSchemeFactory inspectionSchemeFactory, InstantiatorFactory instantiatorFactory, AnnotationHandlerRegistar annotationRegistry) { InstantiationScheme instantiationScheme = instantiatorFactory.decorateScheme(); ImmutableSet.Builder<Class<? extends Annotation>> allPropertyTypes = ImmutableSet.builder(); allPropertyTypes.addAll(ImmutableSet.of( Input.class, InputFile.class, InputFiles.class, InputDirectory.class, OutputFile.class, OutputFiles.class, OutputDirectory.class, OutputDirectories.class, Destroys.class, LocalState.class, Nested.class, Console.class, ReplacedBy.class, Internal.class, OptionValues.class )); annotationRegistry.registerPropertyTypeAnnotations(allPropertyTypes); InspectionScheme inspectionScheme = inspectionSchemeFactory.inspectionScheme( allPropertyTypes.build(), ImmutableSet.of( Classpath.class, CompileClasspath.class, Incremental.class, Optional.class, PathSensitive.class, SkipWhenEmpty.class, IgnoreEmptyDirectories.class, NormalizeLineEndings.class ), instantiationScheme); return new TaskScheme(instantiationScheme, inspectionScheme); } PropertyWalker createPropertyWalker(TaskScheme taskScheme) { return taskScheme.getInspectionScheme().getPropertyWalker(); } TaskClassInfoStore createTaskClassInfoStore(CrossBuildInMemoryCacheFactory cacheFactory) { return new DefaultTaskClassInfoStore(cacheFactory); } TypeAnnotationHandler createDoNotCacheByDefaultTypeAnnotationHandler() { return new DisableCachingByDefaultTypeAnnotationHandler(); } TypeAnnotationHandler createCacheableTaskAnnotationHandler() { return new CacheableTaskTypeAnnotationHandler(); } TypeAnnotationHandler createUntrackedAnnotationHandler() { return new UntrackedTaskTypeAnnotationHandler(); } PropertyAnnotationHandler createConsoleAnnotationHandler() { return new NoOpPropertyAnnotationHandler(Console.class); } PropertyAnnotationHandler createInternalAnnotationHandler() { return new NoOpPropertyAnnotationHandler(Internal.class); } PropertyAnnotationHandler createReplacedByAnnotationHandler() { return new NoOpPropertyAnnotationHandler(ReplacedBy.class); } PropertyAnnotationHandler createOptionValuesAnnotationHandler() { return new NoOpPropertyAnnotationHandler(OptionValues.class); } PropertyAnnotationHandler createInputPropertyAnnotationHandler() { return new InputPropertyAnnotationHandler(); } PropertyAnnotationHandler createInputFilePropertyAnnotationHandler() { return new InputFilePropertyAnnotationHandler(); } PropertyAnnotationHandler createInputFilesPropertyAnnotationHandler() { return new InputFilesPropertyAnnotationHandler(); } PropertyAnnotationHandler createInputDirectoryPropertyAnnotationHandler() { return new InputDirectoryPropertyAnnotationHandler(); } OutputFilePropertyAnnotationHandler createOutputFilePropertyAnnotationHandler() { return new OutputFilePropertyAnnotationHandler(); } OutputFilesPropertyAnnotationHandler createOutputFilesPropertyAnnotationHandler() { return new OutputFilesPropertyAnnotationHandler(); } OutputDirectoryPropertyAnnotationHandler createOutputDirectoryPropertyAnnotationHandler() { return new OutputDirectoryPropertyAnnotationHandler(); } OutputDirectoriesPropertyAnnotationHandler createOutputDirectoriesPropertyAnnotationHandler() { return new OutputDirectoriesPropertyAnnotationHandler(); } PropertyAnnotationHandler createDestroysPropertyAnnotationHandler() { return new DestroysPropertyAnnotationHandler(); } PropertyAnnotationHandler createLocalStatePropertyAnnotationHandler() { return new LocalStatePropertyAnnotationHandler(); } PropertyAnnotationHandler createNestedBeanPropertyAnnotationHandler() { return new NestedBeanAnnotationHandler(); } public interface AnnotationHandlerRegistration { Collection<Class<? extends Annotation>> getAnnotations(); } interface AnnotationHandlerRegistar { void registerPropertyTypeAnnotations(ImmutableSet.Builder<Class<? extends Annotation>> builder); } }
Remove also ConventionTask from ignored super types for TypeAnnotationMetadataStore
subprojects/core/src/main/java/org/gradle/internal/service/scopes/ExecutionGlobalServices.java
Remove also ConventionTask from ignored super types for TypeAnnotationMetadataStore
<ide><path>ubprojects/core/src/main/java/org/gradle/internal/service/scopes/ExecutionGlobalServices.java <ide> import org.gradle.api.artifacts.transform.InputArtifact; <ide> import org.gradle.api.artifacts.transform.InputArtifactDependencies; <ide> import org.gradle.api.file.ConfigurableFileCollection; <del>import org.gradle.api.internal.ConventionTask; <ide> import org.gradle.api.internal.DefaultDomainObjectCollection; <ide> import org.gradle.api.internal.DefaultDomainObjectSet; <ide> import org.gradle.api.internal.DefaultNamedDomainObjectCollection; <ide> ImmutableSet.of( <ide> ClosureBackedAction.class, <ide> ConfigureUtil.WrappedConfigureAction.class, <del> ConventionTask.class, <ide> Describable.class, <ide> DefaultDomainObjectCollection.class, <ide> DefaultDomainObjectSet.class,
Java
agpl-3.0
ae78624c2d3fc07476474d94e6b60800c01db2ae
0
cstroe/svndumpapi,cstroe/svndumpgui,cstroe/svndumpgui,cstroe/svndumpapi
package com.github.cstroe.svndumpgui.internal.transform; import com.github.cstroe.svndumpgui.api.Node; import com.github.cstroe.svndumpgui.api.NodeHeader; import com.github.cstroe.svndumpgui.api.Property; import com.github.cstroe.svndumpgui.api.Revision; import com.github.cstroe.svndumpgui.generated.MergeInfoParser; import com.github.cstroe.svndumpgui.generated.ParseException; import com.github.cstroe.svndumpgui.internal.transform.property.MergeInfoData; public class PathChange extends AbstractRepositoryMutator { private final String oldPath; private final String newPath; public PathChange(String oldPath, String newPath) { this.oldPath = oldPath; this.newPath = newPath; } @Override public void consume(Revision revision) { if(revision.getProperties().containsKey(Property.MERGEINFO)) { final String newMergeInfo = updateMergeInfo(revision.getProperties().get(Property.MERGEINFO)); if(newMergeInfo != null) { revision.getProperties().put(Property.MERGEINFO, newMergeInfo); } } super.consume(revision); } @Override public void consume(Node node) { final String nodePath = node.get(NodeHeader.PATH); if(nodePath.startsWith(oldPath)) { final String changed = newPath + nodePath.substring(oldPath.length()); node.getHeaders().put(NodeHeader.PATH, changed); } if(node.getHeaders().containsKey(NodeHeader.COPY_FROM_PATH)) { final String copyPath = node.get(NodeHeader.COPY_FROM_PATH); if(copyPath.startsWith(oldPath)) { final String changed = newPath + copyPath.substring(oldPath.length()); node.getHeaders().put(NodeHeader.COPY_FROM_PATH, changed); } } if(node.getProperties() != null && node.getProperties().containsKey(Property.MERGEINFO)) { final String newMergeInfo = updateMergeInfo(node.getProperties().get(Property.MERGEINFO)); if(newMergeInfo != null) { node.getProperties().put(Property.MERGEINFO, newMergeInfo); } } super.consume(node); } /** * @return null if the string was not updated */ private String updateMergeInfo(String currentMergeInfo) { MergeInfoData data; try { data = MergeInfoParser.parse(currentMergeInfo); } catch(ParseException ex) { throw new RuntimeException(ex); } boolean changedMergeInfo = false; for(MergeInfoData.Path path : data.getPaths()) { String pathName = path.getPath(); if(pathName.startsWith("/" + oldPath)) { final String newPathName = "/" + newPath + pathName.substring(oldPath.length() + 1); path.setPath(newPathName); changedMergeInfo = true; } } if(changedMergeInfo) { return data.toString(); } else { return null; } } }
src/main/java/com/github/cstroe/svndumpgui/internal/transform/PathChange.java
package com.github.cstroe.svndumpgui.internal.transform; import com.github.cstroe.svndumpgui.api.Node; import com.github.cstroe.svndumpgui.api.NodeHeader; import com.github.cstroe.svndumpgui.api.Property; import com.github.cstroe.svndumpgui.api.Revision; public class PathChange extends AbstractRepositoryMutator { private final String oldPath; private final String newPath; public PathChange(String oldPath, String newPath) { this.oldPath = oldPath; this.newPath = newPath; } @Override public void consume(Revision revision) { if(revision.getProperties().containsKey(Property.MERGEINFO)) { final String mergeInfo = revision.get(Property.MERGEINFO); if(mergeInfo.startsWith(oldPath)) { final String newMergeInfo = newPath + mergeInfo.substring(oldPath.length()); revision.getProperties().put(Property.MERGEINFO, newMergeInfo); } } super.consume(revision); } @Override public void consume(Node node) { final String nodePath = node.get(NodeHeader.PATH); if(nodePath.startsWith(oldPath)) { final String changed = newPath + nodePath.substring(oldPath.length()); node.getHeaders().put(NodeHeader.PATH, changed); } if(node.getHeaders().containsKey(NodeHeader.COPY_FROM_PATH)) { final String copyPath = node.get(NodeHeader.COPY_FROM_PATH); if(copyPath.startsWith(oldPath)) { final String changed = newPath + copyPath.substring(oldPath.length()); node.getHeaders().put(NodeHeader.COPY_FROM_PATH, changed); } } if(node.getProperties() != null && node.getProperties().containsKey(Property.MERGEINFO)) { final String mergeInfo = node.getProperties().get(Property.MERGEINFO); if(mergeInfo.startsWith(oldPath)) { final String newMergeInfo = newPath + mergeInfo.substring(oldPath.length()); node.getProperties().put(Property.MERGEINFO, newMergeInfo); } final String leadingSlashPath = "/" + oldPath; if(mergeInfo.startsWith(leadingSlashPath)) { final String newMergeInfo = "/" + newPath + mergeInfo.substring(oldPath.length() + 1); node.getProperties().put(Property.MERGEINFO, newMergeInfo); } } super.consume(node); } }
Update PathChange to use the MergeInfoParser for parsing mergeinfo properties. * This fixes the bug where PathChange was only updating the first line of the mergeinfo.
src/main/java/com/github/cstroe/svndumpgui/internal/transform/PathChange.java
Update PathChange to use the MergeInfoParser for parsing mergeinfo properties. * This fixes the bug where PathChange was only updating the first line of the mergeinfo.
<ide><path>rc/main/java/com/github/cstroe/svndumpgui/internal/transform/PathChange.java <ide> import com.github.cstroe.svndumpgui.api.NodeHeader; <ide> import com.github.cstroe.svndumpgui.api.Property; <ide> import com.github.cstroe.svndumpgui.api.Revision; <add>import com.github.cstroe.svndumpgui.generated.MergeInfoParser; <add>import com.github.cstroe.svndumpgui.generated.ParseException; <add>import com.github.cstroe.svndumpgui.internal.transform.property.MergeInfoData; <ide> <ide> public class PathChange extends AbstractRepositoryMutator { <ide> <ide> @Override <ide> public void consume(Revision revision) { <ide> if(revision.getProperties().containsKey(Property.MERGEINFO)) { <del> final String mergeInfo = revision.get(Property.MERGEINFO); <del> if(mergeInfo.startsWith(oldPath)) { <del> final String newMergeInfo = newPath + mergeInfo.substring(oldPath.length()); <add> final String newMergeInfo = updateMergeInfo(revision.getProperties().get(Property.MERGEINFO)); <add> if(newMergeInfo != null) { <ide> revision.getProperties().put(Property.MERGEINFO, newMergeInfo); <ide> } <ide> } <ide> } <ide> <ide> if(node.getProperties() != null && node.getProperties().containsKey(Property.MERGEINFO)) { <del> final String mergeInfo = node.getProperties().get(Property.MERGEINFO); <del> if(mergeInfo.startsWith(oldPath)) { <del> final String newMergeInfo = newPath + mergeInfo.substring(oldPath.length()); <del> node.getProperties().put(Property.MERGEINFO, newMergeInfo); <del> } <del> <del> final String leadingSlashPath = "/" + oldPath; <del> if(mergeInfo.startsWith(leadingSlashPath)) { <del> final String newMergeInfo = "/" + newPath + mergeInfo.substring(oldPath.length() + 1); <add> final String newMergeInfo = updateMergeInfo(node.getProperties().get(Property.MERGEINFO)); <add> if(newMergeInfo != null) { <ide> node.getProperties().put(Property.MERGEINFO, newMergeInfo); <ide> } <ide> } <ide> super.consume(node); <ide> } <add> <add> /** <add> * @return null if the string was not updated <add> */ <add> private String updateMergeInfo(String currentMergeInfo) { <add> MergeInfoData data; <add> try { <add> data = MergeInfoParser.parse(currentMergeInfo); <add> } catch(ParseException ex) { <add> throw new RuntimeException(ex); <add> } <add> <add> boolean changedMergeInfo = false; <add> for(MergeInfoData.Path path : data.getPaths()) { <add> String pathName = path.getPath(); <add> if(pathName.startsWith("/" + oldPath)) { <add> final String newPathName = "/" + newPath + pathName.substring(oldPath.length() + 1); <add> path.setPath(newPathName); <add> changedMergeInfo = true; <add> } <add> } <add> <add> if(changedMergeInfo) { <add> return data.toString(); <add> } else { <add> return null; <add> } <add> } <ide> }
Java
apache-2.0
fc86dd521a6d454c2792e2dc5cd1ab14a4785b70
0
electric-cloud/EC-ESX,electric-cloud/EC-ESX,electric-cloud/EC-ESX
// CreateConfiguration.java -- // // CreateConfiguration.java is part of ElectricCommander. // // Copyright (c) 2005-2011 Electric Cloud, Inc. // All rights reserved. // package ecplugins.esx.client; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.ui.Anchor; import ecinternal.client.InternalFormBase; import ecinternal.client.ui.CustomEditorLoader; import com.electriccloud.commander.gwt.client.requests.CgiRequestProxy; import com.electriccloud.commander.gwt.client.requests.RunProcedureRequest; import com.electriccloud.commander.gwt.client.responses.DefaultRunProcedureResponseCallback; import com.electriccloud.commander.gwt.client.responses.RunProcedureResponse; import com.electriccloud.commander.gwt.client.ui.CredentialEditor; import com.electriccloud.commander.gwt.client.ui.FormBuilder; import com.electriccloud.commander.gwt.client.ui.FormTable; import com.electriccloud.commander.gwt.client.ui.SimpleErrorBox; import com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder; import static com.electriccloud.commander.gwt.client.ComponentBaseFactory.getPluginName; import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createPageUrl; import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createUrl; /** * Create ESX Configuration. */ public class CreateConfiguration extends InternalFormBase { //~ Constructors ----------------------------------------------------------- public CreateConfiguration() { super("New ESX Configuration", "ESX Configurations"); CommanderUrlBuilder urlBuilder = createPageUrl(getPluginName(), "configurations"); setDefaultRedirectToUrl(urlBuilder.buildString()); } //~ Methods ---------------------------------------------------------------- @Override protected FormTable initializeFormTable() { return getUIFactory().createFormBuilder(); } @Override protected void load() { FormBuilder fb = (FormBuilder) getFormTable(); setStatus("Loading..."); CustomEditorLoader loader = new CustomEditorLoader(fb, this); loader.setCustomEditorPath("/plugins/EC-ESX" + "/project/ui_forms/ESXCreateConfigForm"); loader.load(); clearStatus(); } @Override protected void submit() { setStatus("Saving..."); clearAllErrors(); FormBuilder fb = (FormBuilder) getFormTable(); if (!fb.validate()) { clearStatus(); return; } // Build runProcedure request RunProcedureRequest request = getRequestFactory() .createRunProcedureRequest(); request.setProjectName("/plugins/EC-ESX/project"); request.setProcedureName("CreateConfiguration"); Map<String, String> params = fb.getValues(); Collection<String> credentialParams = fb.getCredentialIds(); for (String paramName : params.keySet()) { if (credentialParams.contains(paramName)) { CredentialEditor credential = fb.getCredential(paramName); request.addCredentialParameter(paramName, credential.getUsername(), credential.getPassword()); } else { request.addActualParameter(paramName, params.get(paramName)); } } request.setCallback(new DefaultRunProcedureResponseCallback(this) { @Override public void handleResponse( RunProcedureResponse response) { if (getLog().isDebugEnabled()) { getLog().debug( "Commander runProcedure request returned job id: " + response.getJobId()); } waitForJob(response.getJobId()); } }); if (getLog().isDebugEnabled()) { getLog().debug("Issuing Commander request: " + request); } doRequest(request); } private void waitForJob(final String jobId) { CgiRequestProxy cgiRequestProxy = new CgiRequestProxy( getPluginName(), "esxMonitor.cgi"); Map<String, String> cgiParams = new HashMap<String, String>(); cgiParams.put("jobId", jobId); // Pass debug flag to CGI, which will use it to determine whether to // clean up a successful job if ("1".equals(getGetParameter("debug"))) { cgiParams.put("debug", "1"); } try { cgiRequestProxy.issueGetRequest(cgiParams, new RequestCallback() { @Override public void onError( Request request, Throwable exception) { addErrorMessage("CGI request failed: ", exception); } @Override public void onResponseReceived( Request request, Response response) { String responseString = response.getText(); if (getLog().isDebugEnabled()) { getLog().debug( "CGI response received: " + responseString); } if (responseString.startsWith("Success")) { // We're done! cancel(); } else { SimpleErrorBox error = getUIFactory() .createSimpleErrorBox( "Error occurred during configuration creation: " + responseString); CommanderUrlBuilder urlBuilder = createUrl( "jobDetails.php").setParameter("jobId", jobId); error.add( new Anchor("(See job for details)", urlBuilder.buildString())); addErrorMessage(error); } } }); } catch (RequestException e) { addErrorMessage("CGI request failed: ", e); } } }
src/ecplugins/esx/client/CreateConfiguration.java
// CreateConfiguration.java -- // // CreateConfiguration.java is part of ElectricCommander. // // Copyright (c) 2005-2010 Electric Cloud, Inc. // All rights reserved. // package ecplugins.esx.client; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.ui.Anchor; import ecinternal.client.InternalFormBase; import ecinternal.client.ui.FormBuilderLoader; import com.electriccloud.commander.gwt.client.requests.CgiRequestProxy; import com.electriccloud.commander.gwt.client.requests.RunProcedureRequest; import com.electriccloud.commander.gwt.client.responses.DefaultRunProcedureResponseCallback; import com.electriccloud.commander.gwt.client.responses.RunProcedureResponse; import com.electriccloud.commander.gwt.client.ui.CredentialEditor; import com.electriccloud.commander.gwt.client.ui.FormBuilder; import com.electriccloud.commander.gwt.client.ui.FormTable; import com.electriccloud.commander.gwt.client.ui.SimpleErrorBox; import com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder; import static com.electriccloud.commander.gwt.client.ComponentBaseFactory.getPluginName; import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createPageUrl; import static com.electriccloud.commander.gwt.client.util.CommanderUrlBuilder.createUrl; /** * Create ESX Configuration. */ public class CreateConfiguration extends InternalFormBase { //~ Constructors ----------------------------------------------------------- public CreateConfiguration() { super("New ESX Configuration", "ESX Configurations"); CommanderUrlBuilder urlBuilder = createPageUrl(getPluginName(), "configurations"); setDefaultRedirectToUrl(urlBuilder.buildString()); } //~ Methods ---------------------------------------------------------------- @Override protected FormTable initializeFormTable() { FormBuilder fb = getUIFactory().createFormBuilder(); return fb; } @Override protected void load() { FormBuilder fb = (FormBuilder) getFormTable(); setStatus("Loading..."); FormBuilderLoader loader = new FormBuilderLoader(fb, this); loader.setCustomEditorPath("/plugins/EC-ESX" + "/project/ui_forms/ESXCreateConfigForm"); loader.load(); clearStatus(); } @Override protected void submit() { setStatus("Saving..."); clearAllErrors(); FormBuilder fb = (FormBuilder) getFormTable(); if (!fb.validate()) { clearStatus(); return; } // Build runProcedure request RunProcedureRequest request = getRequestFactory() .createRunProcedureRequest(); request.setProjectName("/plugins/EC-ESX/project"); request.setProcedureName("CreateConfiguration"); Map<String, String> params = fb.getValues(); Collection<String> credentialParams = fb.getCredentialIds(); for (String paramName : params.keySet()) { if (credentialParams.contains(paramName)) { CredentialEditor credential = fb.getCredential(paramName); request.addCredentialParameter(paramName, credential.getUsername(), credential.getPassword()); } else { request.addActualParameter(paramName, params.get(paramName)); } } request.setCallback(new DefaultRunProcedureResponseCallback(this) { @Override public void handleResponse( RunProcedureResponse response) { if (getLog().isDebugEnabled()) { getLog().debug( "Commander runProcedure request returned job id: " + response.getJobId()); } waitForJob(response.getJobId()); } }); if (getLog().isDebugEnabled()) { getLog().debug("Issuing Commander request: " + request); } doRequest(request); } private void waitForJob(final String jobId) { CgiRequestProxy cgiRequestProxy = new CgiRequestProxy( getPluginName(), "esxMonitor.cgi"); Map<String, String> cgiParams = new HashMap<String, String>(); cgiParams.put("jobId", jobId); // Pass debug flag to CGI, which will use it to determine whether to // clean up a successful job if ("1".equals(getGetParameter("debug"))) { cgiParams.put("debug", "1"); } try { cgiRequestProxy.issueGetRequest(cgiParams, new RequestCallback() { @Override public void onError( Request request, Throwable exception) { addErrorMessage("CGI request failed: ", exception); } @Override public void onResponseReceived( Request request, Response response) { String responseString = response.getText(); if (getLog().isDebugEnabled()) { getLog().debug( "CGI response received: " + responseString); } if (responseString.startsWith("Success")) { // We're done! cancel(); } else { SimpleErrorBox error = getUIFactory() .createSimpleErrorBox( "Error occurred during configuration creation: " + responseString); CommanderUrlBuilder urlBuilder = createUrl( "jobDetails.php").setParameter("jobId", jobId); error.add( new Anchor("(See job for details)", urlBuilder.buildString())); addErrorMessage(error); } } }); } catch (RequestException e) { addErrorMessage("CGI request failed: ", e); } } }
Fixing plugins for the parameter rework branch changes to ec_internal. [git-p4: depot-paths = "//depot/nimbus/integrations/EC-ESX/main/": change = 52460]
src/ecplugins/esx/client/CreateConfiguration.java
Fixing plugins for the parameter rework branch changes to ec_internal.
<ide><path>rc/ecplugins/esx/client/CreateConfiguration.java <ide> // <ide> // CreateConfiguration.java is part of ElectricCommander. <ide> // <del>// Copyright (c) 2005-2010 Electric Cloud, Inc. <add>// Copyright (c) 2005-2011 Electric Cloud, Inc. <ide> // All rights reserved. <ide> // <ide> <ide> <ide> import ecinternal.client.InternalFormBase; <ide> <del>import ecinternal.client.ui.FormBuilderLoader; <add>import ecinternal.client.ui.CustomEditorLoader; <ide> <ide> import com.electriccloud.commander.gwt.client.requests.CgiRequestProxy; <ide> import com.electriccloud.commander.gwt.client.requests.RunProcedureRequest; <ide> <ide> @Override protected FormTable initializeFormTable() <ide> { <del> FormBuilder fb = getUIFactory().createFormBuilder(); <del> <del> return fb; <add> return getUIFactory().createFormBuilder(); <ide> } <ide> <ide> @Override protected void load() <ide> <ide> setStatus("Loading..."); <ide> <del> FormBuilderLoader loader = new FormBuilderLoader(fb, this); <add> CustomEditorLoader loader = new CustomEditorLoader(fb, this); <ide> <ide> loader.setCustomEditorPath("/plugins/EC-ESX" <ide> + "/project/ui_forms/ESXCreateConfigForm");
Java
mit
db2f4a2ad33385c8132e18583886a975e2953d9e
0
hhu-stups/bmoth
package de.bmoth.backend; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Sort; import de.bmoth.parser.ast.nodes.*; import java.util.*; public class MachineToZ3Translator { private final MachineNode machineNode; private final Context z3Context; private BoolExpr initialisationConstraint = null; private BoolExpr invariantConstraint = null; private final HashMap<String, String> primedVariablesToVariablesMap; private final List<BoolExpr> operationConstraints; public MachineToZ3Translator(MachineNode machineNode, Context ctx) { this.machineNode = machineNode; this.z3Context = ctx; if (machineNode.getInitialisation() != null) { this.initialisationConstraint = visitSubstitution(machineNode.getInitialisation()); } if (machineNode.getInvariant() != null) { this.invariantConstraint = (BoolExpr) FormulaToZ3Translator.translatePredicate(machineNode.getInvariant(), z3Context); } else { this.invariantConstraint = z3Context.mkTrue(); } this.operationConstraints = visitOperations(machineNode.getOperations()); { primedVariablesToVariablesMap = new HashMap<>(); for (DeclarationNode node : machineNode.getVariables()) { primedVariablesToVariablesMap.put(getPrimedName(node.getName()), node.getName()); } } } private List<BoolExpr> visitOperations(List<OperationNode> operations) { List<BoolExpr> results = new ArrayList<>(operations.size()); for (OperationNode operationNode : this.machineNode.getOperations()) { BoolExpr temp = visitSubstitution(operationNode.getSubstitution()); // for unassigned variables add a dummy assignment, e.g. x' = x Set<DeclarationNode> set = new HashSet<>(this.getVariables()); set.removeAll(operationNode.getSubstitution().getAssignedVariables()); for (DeclarationNode node : set) { BoolExpr mkEq = z3Context.mkEq(getPrimedVariable(node), getVariableAsZ3Expression(node)); temp = z3Context.mkAnd(temp, mkEq); } results.add(temp); } return results; } public List<DeclarationNode> getVariables() { return machineNode.getVariables(); } public List<DeclarationNode> getConstants() { return machineNode.getConstants(); } public Expr getVariableAsZ3Expression(DeclarationNode node) { Sort type = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getType()); Expr expr = z3Context.mkConst(node.getName(), type); return expr; } public Expr getPrimedVariable(DeclarationNode node) { String primedName = getPrimedName(node.getName()); Sort type = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getType()); Expr expr = z3Context.mkConst(primedName, type); return expr; } public BoolExpr getInitialValueConstraint() { PredicateNode properties = machineNode.getProperties(); BoolExpr prop = z3Context.mkTrue(); if (properties != null) { prop = FormulaToZ3Translator.translatePredicate(machineNode.getProperties(), z3Context, new TranslationOptions(1)); } if (initialisationConstraint == null) { return prop; } return z3Context.mkAnd(initialisationConstraint, prop); } public BoolExpr getInvariantConstraint() { return invariantConstraint; } private BoolExpr visitSubstitution(SubstitutionNode node) { if (node instanceof SingleAssignSubstitutionNode) { return visitSingleAssignSubstitution((SingleAssignSubstitutionNode) node); } else if (node instanceof ParallelSubstitutionNode) { return visitParallelSubstitution((ParallelSubstitutionNode) node); } else if (node instanceof AnySubstitutionNode) { return visitAnySubstitution((AnySubstitutionNode) node); } else if (node instanceof SelectSubstitutionNode) { return visitSelectSubstitutionNode((SelectSubstitutionNode) node); } throw new AssertionError("Not implemented" + node.getClass()); } private BoolExpr visitSelectSubstitutionNode(SelectSubstitutionNode node) { BoolExpr condition = (BoolExpr) FormulaToZ3Translator.translatePredicate(node.getCondition(), z3Context); BoolExpr substitution = visitSubstitution(node.getSubstitution()); return z3Context.mkAnd(condition, substitution); } private BoolExpr visitAnySubstitution(AnySubstitutionNode node) { throw new AssertionError("Not implemented: " + node.getClass());// TODO } private BoolExpr visitParallelSubstitution(ParallelSubstitutionNode node) { List<SubstitutionNode> substitutions = node.getSubstitutions(); BoolExpr boolExpr = null; for (SubstitutionNode substitutionNode : substitutions) { BoolExpr temp = visitSubstitution(substitutionNode); if (boolExpr == null) { boolExpr = temp; } else { boolExpr = z3Context.mkAnd(boolExpr, temp); } } return boolExpr; } private BoolExpr visitSingleAssignSubstitution(SingleAssignSubstitutionNode node) { Sort bTypeToZ3Sort = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getIdentifier().getType()); Expr value = FormulaToZ3Translator.translateExpr(node.getValue(), z3Context); String name = getPrimedName(node.getIdentifier().getName()); Expr variable = z3Context.mkConst(name, bTypeToZ3Sort); return this.z3Context.mkEq(variable, value); } private String getPrimedName(String name) { return name + "'"; } public List<BoolExpr> getOperationConstraints() { return operationConstraints; } }
src/main/java/de/bmoth/backend/MachineToZ3Translator.java
package de.bmoth.backend; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.Expr; import com.microsoft.z3.Sort; import de.bmoth.parser.ast.nodes.*; import java.util.*; public class MachineToZ3Translator { private final MachineNode machineNode; private final Context z3Context; private final BoolExpr initialisationConstraint; private final BoolExpr invariantConstraint; private final HashMap<String, String> primedVariablesToVariablesMap; private final List<BoolExpr> operationConstraints; public MachineToZ3Translator(MachineNode machineNode, Context ctx) { this.machineNode = machineNode; this.z3Context = ctx; this.initialisationConstraint = visitSubstitution(machineNode.getInitialisation()); this.invariantConstraint = (BoolExpr) FormulaToZ3Translator.translatePredicate(machineNode.getInvariant(), z3Context); this.operationConstraints = visitOperations(machineNode.getOperations()); { primedVariablesToVariablesMap = new HashMap<>(); for (DeclarationNode node : machineNode.getVariables()) { primedVariablesToVariablesMap.put(getPrimedName(node.getName()), node.getName()); } } } private List<BoolExpr> visitOperations(List<OperationNode> operations) { List<BoolExpr> results = new ArrayList<>(operations.size()); for (OperationNode operationNode : this.machineNode.getOperations()) { BoolExpr temp = visitSubstitution(operationNode.getSubstitution()); // for unassigned variables add a dummy assignment, e.g. x' = x Set<DeclarationNode> set = new HashSet<>(this.getVariables()); set.removeAll(operationNode.getSubstitution().getAssignedVariables()); for (DeclarationNode node : set) { BoolExpr mkEq = z3Context.mkEq(getPrimedVariable(node), getVariableAsZ3Expression(node)); temp = z3Context.mkAnd(temp, mkEq); } results.add(temp); } return results; } public List<DeclarationNode> getVariables() { return machineNode.getVariables(); } public List<DeclarationNode> getConstants() { return machineNode.getConstants(); } public Expr getVariableAsZ3Expression(DeclarationNode node) { Sort type = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getType()); Expr expr = z3Context.mkConst(node.getName(), type); return expr; } public Expr getPrimedVariable(DeclarationNode node) { String primedName = getPrimedName(node.getName()); Sort type = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getType()); Expr expr = z3Context.mkConst(primedName, type); return expr; } public BoolExpr getInitialValueConstraint() { PredicateNode properties = machineNode.getProperties(); if (properties != null) { BoolExpr prop = FormulaToZ3Translator.translatePredicate(machineNode.getProperties(), z3Context, new TranslationOptions(1)); return z3Context.mkAnd(initialisationConstraint, prop); } else { return initialisationConstraint; } } public BoolExpr getInvariantConstraint() { return invariantConstraint; } private BoolExpr visitSubstitution(SubstitutionNode node) { if (node instanceof SingleAssignSubstitutionNode) { return visitSingleAssignSubstitution((SingleAssignSubstitutionNode) node); } else if (node instanceof ParallelSubstitutionNode) { return visitParallelSubstitution((ParallelSubstitutionNode) node); } else if (node instanceof AnySubstitutionNode) { return visitAnySubstitution((AnySubstitutionNode) node); } else if (node instanceof SelectSubstitutionNode) { return visitSelectSubstitutionNode((SelectSubstitutionNode) node); } throw new AssertionError("Not implemented" + node.getClass()); } private BoolExpr visitSelectSubstitutionNode(SelectSubstitutionNode node) { BoolExpr condition = (BoolExpr) FormulaToZ3Translator.translatePredicate(node.getCondition(), z3Context); BoolExpr substitution = visitSubstitution(node.getSubstitution()); return z3Context.mkAnd(condition, substitution); } private BoolExpr visitAnySubstitution(AnySubstitutionNode node) { throw new AssertionError("Not implemented: " + node.getClass());// TODO } private BoolExpr visitParallelSubstitution(ParallelSubstitutionNode node) { List<SubstitutionNode> substitutions = node.getSubstitutions(); BoolExpr boolExpr = null; for (SubstitutionNode substitutionNode : substitutions) { BoolExpr temp = visitSubstitution(substitutionNode); if (boolExpr == null) { boolExpr = temp; } else { boolExpr = z3Context.mkAnd(boolExpr, temp); } } return boolExpr; } private BoolExpr visitSingleAssignSubstitution(SingleAssignSubstitutionNode node) { Sort bTypeToZ3Sort = FormulaToZ3Translator.bTypeToZ3Sort(z3Context, node.getIdentifier().getType()); Expr value = FormulaToZ3Translator.translateExpr(node.getValue(), z3Context); String name = getPrimedName(node.getIdentifier().getName()); Expr variable = z3Context.mkConst(name, bTypeToZ3Sort); return this.z3Context.mkEq(variable, value); } private String getPrimedName(String name) { return name + "'"; } public List<BoolExpr> getOperationConstraints() { return operationConstraints; } }
handle machines without variables / initialisations / invariants
src/main/java/de/bmoth/backend/MachineToZ3Translator.java
handle machines without variables / initialisations / invariants
<ide><path>rc/main/java/de/bmoth/backend/MachineToZ3Translator.java <ide> public class MachineToZ3Translator { <ide> private final MachineNode machineNode; <ide> private final Context z3Context; <del> private final BoolExpr initialisationConstraint; <del> private final BoolExpr invariantConstraint; <add> private BoolExpr initialisationConstraint = null; <add> private BoolExpr invariantConstraint = null; <ide> private final HashMap<String, String> primedVariablesToVariablesMap; <ide> private final List<BoolExpr> operationConstraints; <ide> <ide> public MachineToZ3Translator(MachineNode machineNode, Context ctx) { <ide> this.machineNode = machineNode; <ide> this.z3Context = ctx; <del> this.initialisationConstraint = visitSubstitution(machineNode.getInitialisation()); <del> this.invariantConstraint = (BoolExpr) FormulaToZ3Translator.translatePredicate(machineNode.getInvariant(), <del> z3Context); <add> <add> if (machineNode.getInitialisation() != null) { <add> this.initialisationConstraint = visitSubstitution(machineNode.getInitialisation()); <add> } <add> if (machineNode.getInvariant() != null) { <add> this.invariantConstraint = (BoolExpr) FormulaToZ3Translator.translatePredicate(machineNode.getInvariant(), <add> z3Context); <add> } else { <add> this.invariantConstraint = z3Context.mkTrue(); <add> } <add> <ide> this.operationConstraints = visitOperations(machineNode.getOperations()); <ide> <ide> { <ide> <ide> public BoolExpr getInitialValueConstraint() { <ide> PredicateNode properties = machineNode.getProperties(); <add> BoolExpr prop = z3Context.mkTrue(); <ide> if (properties != null) { <del> BoolExpr prop = FormulaToZ3Translator.translatePredicate(machineNode.getProperties(), z3Context, <add> prop = FormulaToZ3Translator.translatePredicate(machineNode.getProperties(), z3Context, <ide> new TranslationOptions(1)); <del> return z3Context.mkAnd(initialisationConstraint, prop); <del> } else { <del> return initialisationConstraint; <add> <ide> } <add> if (initialisationConstraint == null) { <add> return prop; <add> } <add> return z3Context.mkAnd(initialisationConstraint, prop); <ide> } <ide> <ide> public BoolExpr getInvariantConstraint() {
Java
apache-2.0
7760bc08750fd65b32caa7b5660d476eb879f4da
0
Curzibn/Luban,XConstantine/Luban
package top.zibin.luban; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.annotation.NonNull; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import static top.zibin.luban.Preconditions.checkNotNull; public class Luban { public static final int FIRST_GEAR = 1; public static final int THIRD_GEAR = 3; private static final String TAG = "Luban"; public static String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache"; private static volatile Luban INSTANCE; private final File mCacheDir; private OnCompressListener compressListener; private File mFile; private int gear = THIRD_GEAR; Luban(File cacheDir) { mCacheDir = cacheDir; } /** * Returns a directory with a default name in the private cache directory of the application to use to store * retrieved media and thumbnails. * * @param context A context. * @see #getPhotoCacheDir(android.content.Context, String) */ public static File getPhotoCacheDir(Context context) { return getPhotoCacheDir(context, Luban.DEFAULT_DISK_CACHE_DIR); } /** * Returns a directory with the given name in the private cache directory of the application to use to store * retrieved media and thumbnails. * * @param context A context. * @param cacheName The name of the subdirectory in which to store the cache. * @see #getPhotoCacheDir(android.content.Context) */ public static File getPhotoCacheDir(Context context, String cacheName) { File cacheDir = context.getCacheDir(); if (cacheDir != null) { File result = new File(cacheDir, cacheName); if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) { // File wasn't able to create a directory, or the result exists but not a directory return null; } return result; } if (Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "default disk cache dir is null"); } return null; } public static Luban get(Context context) { if (INSTANCE == null) INSTANCE = new Luban(Luban.getPhotoCacheDir(context)); return INSTANCE; } public Luban launch() { checkNotNull(mFile, "the image file cannot be null, please call .load() before this method!"); if (compressListener != null) compressListener.onStart(); if (gear == Luban.FIRST_GEAR) Observable.just(mFile) .map(new Func1<File, File>() { @Override public File call(File file) { return firstCompress(file); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { if (compressListener != null) compressListener.onError(throwable); } }) .onErrorResumeNext(Observable.<File>empty()) .filter(new Func1<File, Boolean>() { @Override public Boolean call(File file) { return file != null; } }) .subscribe(new Action1<File>() { @Override public void call(File file) { if (compressListener != null) compressListener.onSuccess(file); } }); else if (gear == Luban.THIRD_GEAR) Observable.just(mFile) .map(new Func1<File, File>() { @Override public File call(File file) { return thirdCompress(file); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { if (compressListener != null) compressListener.onError(throwable); } }) .onErrorResumeNext(Observable.<File>empty()) .filter(new Func1<File, Boolean>() { @Override public Boolean call(File file) { return file != null; } }) .subscribe(new Action1<File>() { @Override public void call(File file) { if (compressListener != null) compressListener.onSuccess(file); } }); return this; } public Luban load(File file) { mFile = file; return this; } public Luban setCompressListener(OnCompressListener listener) { compressListener = listener; return this; } public Luban putGear(int gear) { this.gear = gear; return this; } public Observable<File> asObservable() { if (gear == FIRST_GEAR) return Observable.just(mFile).map(new Func1<File, File>() { @Override public File call(File file) { return firstCompress(file); } }); else if (gear == THIRD_GEAR) return Observable.just(mFile).map(new Func1<File, File>() { @Override public File call(File file) { return thirdCompress(file); } }); else return Observable.empty(); } private File thirdCompress(@NonNull File file) { String thumb = mCacheDir.getAbsolutePath() + "/" + System.currentTimeMillis(); double size; String filePath = file.getAbsolutePath(); int angle = getImageSpinAngle(filePath); int width = getImageSize(filePath)[0]; int height = getImageSize(filePath)[1]; int thumbW = width % 2 == 1 ? width + 1 : width; int thumbH = height % 2 == 1 ? height + 1 : height; width = thumbW > thumbH ? thumbH : thumbW; height = thumbW > thumbH ? thumbW : thumbH; double scale = ((double) width / height); if (scale <= 1 && scale > 0.5625) { if (height < 1664) { if (file.length() / 1024 < 150) return file; size = (width * height) / Math.pow(1664, 2) * 150; size = size < 60 ? 60 : size; } else if (height >= 1664 && height < 4990) { thumbW = width / 2; thumbH = height / 2; size = (thumbW * thumbH) / Math.pow(2495, 2) * 300; size = size < 60 ? 60 : size; } else if (height >= 4990 && height < 10240) { thumbW = width / 4; thumbH = height / 4; size = (thumbW * thumbH) / Math.pow(2560, 2) * 300; size = size < 100 ? 100 : size; } else { int multiple = height / 1280 == 0 ? 1 : height / 1280; thumbW = width / multiple; thumbH = height / multiple; size = (thumbW * thumbH) / Math.pow(2560, 2) * 300; size = size < 100 ? 100 : size; } } else if (scale <= 0.5625 && scale > 0.5) { if (height < 1280 && file.length() / 1024 < 200) return file; int multiple = height / 1280 == 0 ? 1 : height / 1280; thumbW = width / multiple; thumbH = height / multiple; size = (thumbW * thumbH) / (1440.0 * 2560.0) * 400; size = size < 100 ? 100 : size; } else { int multiple = (int) Math.ceil(height / (1280.0 / scale)); thumbW = width / multiple; thumbH = height / multiple; size = ((thumbW * thumbH) / (1280.0 * (1280 / scale))) * 500; size = size < 100 ? 100 : size; } return compress(filePath, thumb, thumbW, thumbH, angle, (long) size); } private File firstCompress(@NonNull File file) { int minSize = 60; int longSide = 720; int shortSide = 1280; String filePath = file.getAbsolutePath(); String thumbFilePath = mCacheDir.getAbsolutePath() + "/" + System.currentTimeMillis(); long size = 0; long maxSize = file.length() / 5; int angle = getImageSpinAngle(filePath); int[] imgSize = getImageSize(filePath); int width = 0, height = 0; if (imgSize[0] <= imgSize[1]) { double scale = (double) imgSize[0] / (double) imgSize[1]; if (scale <= 1.0 && scale > 0.5625) { width = imgSize[0] > shortSide ? shortSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = minSize; } else if (scale <= 0.5625) { height = imgSize[1] > longSide ? longSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = maxSize; } } else { double scale = (double) imgSize[1] / (double) imgSize[0]; if (scale <= 1.0 && scale > 0.5625) { height = imgSize[1] > shortSide ? shortSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = minSize; } else if (scale <= 0.5625) { width = imgSize[0] > longSide ? longSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = maxSize; } } return compress(filePath, thumbFilePath, width, height, angle, size); } /** * obtain the image's width and height * * @param imagePath the path of image */ public int[] getImageSize(String imagePath) { int[] res = new int[2]; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = 1; BitmapFactory.decodeFile(imagePath, options); res[0] = options.outWidth; res[1] = options.outHeight; return res; } /** * obtain the thumbnail that specify the size * * @param imagePath the target image path * @param width the width of thumbnail * @param height the height of thumbnail * @return {@link Bitmap} */ private Bitmap compress(String imagePath, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); int outH = options.outHeight; int outW = options.outWidth; int inSampleSize = 1; if (outH > height || outW > width) { int halfH = outH / 2; int halfW = outW / 2; while ((halfH / inSampleSize) > height && (halfW / inSampleSize) > width) { inSampleSize *= 2; } } options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; int heightRatio = (int) Math.ceil(options.outHeight / (float) height); int widthRatio = (int) Math.ceil(options.outWidth / (float) width); if (heightRatio > 1 || widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(imagePath, options); } /** * obtain the image rotation angle * * @param path path of target image */ private int getImageSpinAngle(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 指定参数压缩图片 * create the thumbnail with the true rotate angle * * @param largeImagePath the big image path * @param thumbFilePath the thumbnail path * @param width width of thumbnail * @param height height of thumbnail * @param angle rotation angle of thumbnail * @param size the file size of image */ private File compress(String largeImagePath, String thumbFilePath, int width, int height, int angle, long size) { Bitmap thbBitmap = compress(largeImagePath, width, height); thbBitmap = rotatingImage(angle, thbBitmap); return saveImage(thumbFilePath, thbBitmap, size); } /** * 旋转图片 * rotate the image with specified angle * * @param angle the angle will be rotating 旋转的角度 * @param bitmap target image 目标图片 */ private static Bitmap rotatingImage(int angle, Bitmap bitmap) { //rotate image Matrix matrix = new Matrix(); matrix.postRotate(angle); //create a new image return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * 保存图片到指定路径 * Save image with specified size * * @param filePath the image file save path 储存路径 * @param bitmap the image what be save 目标图片 * @param size the file size of image 期望大小 */ private File saveImage(String filePath, Bitmap bitmap, long size) { checkNotNull(bitmap, TAG + "bitmap cannot be null"); File result = new File(filePath.substring(0, filePath.lastIndexOf("/"))); if (!result.exists() && !result.mkdirs()) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); int options = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); while (stream.toByteArray().length / 1024 > size) { stream.reset(); options -= 6; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); } try { FileOutputStream fos = new FileOutputStream(filePath); fos.write(stream.toByteArray()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } return new File(filePath); } }
library/src/main/java/top/zibin/luban/Luban.java
package top.zibin.luban; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.support.annotation.NonNull; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import static top.zibin.luban.Preconditions.checkNotNull; public class Luban { public static final int FIRST_GEAR = 1; public static final int THIRD_GEAR = 3; private static final String TAG = "Luban"; public static String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache"; private static volatile Luban INSTANCE; private final File mCacheDir; private OnCompressListener compressListener; private File mFile; private int gear = THIRD_GEAR; Luban(File cacheDir) { mCacheDir = cacheDir; } /** * Returns a directory with a default name in the private cache directory of the application to use to store * retrieved media and thumbnails. * * @param context A context. * @see #getPhotoCacheDir(android.content.Context, String) */ public static File getPhotoCacheDir(Context context) { return getPhotoCacheDir(context, Luban.DEFAULT_DISK_CACHE_DIR); } /** * Returns a directory with the given name in the private cache directory of the application to use to store * retrieved media and thumbnails. * * @param context A context. * @param cacheName The name of the subdirectory in which to store the cache. * @see #getPhotoCacheDir(android.content.Context) */ public static File getPhotoCacheDir(Context context, String cacheName) { File cacheDir = context.getCacheDir(); if (cacheDir != null) { File result = new File(cacheDir, cacheName); if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) { // File wasn't able to create a directory, or the result exists but not a directory return null; } return result; } if (Log.isLoggable(TAG, Log.ERROR)) { Log.e(TAG, "default disk cache dir is null"); } return null; } public static Luban get(Context context) { if (INSTANCE == null) INSTANCE = new Luban(Luban.getPhotoCacheDir(context)); return INSTANCE; } public Luban launch() { checkNotNull(mFile, "the image file cannot be null, please call .load() before this method!"); if (compressListener != null) compressListener.onStart(); if (gear == Luban.FIRST_GEAR) Observable.just(mFile) .map(new Func1<File, File>() { @Override public File call(File file) { return firstCompress(file); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { if (compressListener != null) compressListener.onError(throwable); } }) .onErrorResumeNext(Observable.<File>empty()) .filter(new Func1<File, Boolean>() { @Override public Boolean call(File file) { return file != null; } }) .subscribe(new Action1<File>() { @Override public void call(File file) { if (compressListener != null) compressListener.onSuccess(file); } }); else if (gear == Luban.THIRD_GEAR) Observable.just(mFile) .map(new Func1<File, File>() { @Override public File call(File file) { return thirdCompress(file); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(new Action1<Throwable>() { @Override public void call(Throwable throwable) { if (compressListener != null) compressListener.onError(throwable); } }) .onErrorResumeNext(Observable.<File>empty()) .filter(new Func1<File, Boolean>() { @Override public Boolean call(File file) { return file != null; } }) .subscribe(new Action1<File>() { @Override public void call(File file) { if (compressListener != null) compressListener.onSuccess(file); } }); return this; } public Luban load(File file) { mFile = file; return this; } public Luban setCompressListener(OnCompressListener listener) { compressListener = listener; return this; } public Luban putGear(int gear) { this.gear = gear; return this; } public Observable<File> asObservable() { if (gear == FIRST_GEAR) return Observable.just(mFile).map(new Func1<File, File>() { @Override public File call(File file) { return firstCompress(file); } }); else if (gear == THIRD_GEAR) return Observable.just(mFile).map(new Func1<File, File>() { @Override public File call(File file) { return thirdCompress(file); } }); else return Observable.empty(); } private File thirdCompress(@NonNull File file) { String thumb = mCacheDir.getAbsolutePath() + "/" + System.currentTimeMillis(); double size; String filePath = file.getAbsolutePath(); int angle = getImageSpinAngle(filePath); int width = getImageSize(filePath)[0]; int height = getImageSize(filePath)[1]; int thumbW = width % 2 == 1 ? width + 1 : width; int thumbH = height % 2 == 1 ? height + 1 : height; width = thumbW > thumbH ? thumbH : thumbW; height = thumbW > thumbH ? thumbW : thumbH; double scale = ((double) width / height); if (scale <= 1 && scale > 0.5625) { if (height < 1664) { if (file.length() / 1024 < 150) return file; size = (width * height) / Math.pow(1664, 2) * 150; size = size < 60 ? 60 : size; } else if (height >= 1664 && height < 4990) { thumbW = width / 2; thumbH = height / 2; size = (thumbW * thumbH) / Math.pow(2495, 2) * 300; size = size < 60 ? 60 : size; } else if (height >= 4990 && height < 10240) { thumbW = width / 4; thumbH = height / 4; size = (thumbW * thumbH) / Math.pow(2560, 2) * 300; size = size < 100 ? 100 : size; } else { int multiple = height / 1280 == 0 ? 1 : height / 1280; thumbW = width / multiple; thumbH = height / multiple; size = (thumbW * thumbH) / Math.pow(2560, 2) * 300; size = size < 100 ? 100 : size; } } else if (scale <= 0.5625 && scale > 0.5) { if (height < 1280 && file.length() / 1024 < 200) return file; int multiple = height / 1280 == 0 ? 1 : height / 1280; thumbW = width / multiple; thumbH = height / multiple; size = (thumbW * thumbH) / (1440.0 * 2560.0) * 200; size = size < 100 ? 100 : size; } else { int multiple = (int) Math.ceil(height / (1280.0 / scale)); thumbW = width / multiple; thumbH = height / multiple; size = ((thumbW * thumbH) / (1280.0 * (1280 / scale))) * 500; size = size < 100 ? 100 : size; } return compress(filePath, thumb, thumbW, thumbH, angle, (long) size); } private File firstCompress(@NonNull File file) { int minSize = 60; int longSide = 720; int shortSide = 1280; String filePath = file.getAbsolutePath(); String thumbFilePath = mCacheDir.getAbsolutePath() + "/" + System.currentTimeMillis(); long size = 0; long maxSize = file.length() / 5; int angle = getImageSpinAngle(filePath); int[] imgSize = getImageSize(filePath); int width = 0, height = 0; if (imgSize[0] <= imgSize[1]) { double scale = (double) imgSize[0] / (double) imgSize[1]; if (scale <= 1.0 && scale > 0.5625) { width = imgSize[0] > shortSide ? shortSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = minSize; } else if (scale <= 0.5625) { height = imgSize[1] > longSide ? longSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = maxSize; } } else { double scale = (double) imgSize[1] / (double) imgSize[0]; if (scale <= 1.0 && scale > 0.5625) { height = imgSize[1] > shortSide ? shortSide : imgSize[1]; width = height * imgSize[0] / imgSize[1]; size = minSize; } else if (scale <= 0.5625) { width = imgSize[0] > longSide ? longSide : imgSize[0]; height = width * imgSize[1] / imgSize[0]; size = maxSize; } } return compress(filePath, thumbFilePath, width, height, angle, size); } /** * obtain the image's width and height * * @param imagePath the path of image */ public int[] getImageSize(String imagePath) { int[] res = new int[2]; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = 1; BitmapFactory.decodeFile(imagePath, options); res[0] = options.outWidth; res[1] = options.outHeight; return res; } /** * obtain the thumbnail that specify the size * * @param imagePath the target image path * @param width the width of thumbnail * @param height the height of thumbnail * @return {@link Bitmap} */ private Bitmap compress(String imagePath, int width, int height) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); int outH = options.outHeight; int outW = options.outWidth; int inSampleSize = 1; if (outH > height || outW > width) { int halfH = outH / 2; int halfW = outW / 2; while ((halfH / inSampleSize) > height && (halfW / inSampleSize) > width) { inSampleSize *= 2; } } options.inSampleSize = inSampleSize; options.inJustDecodeBounds = false; int heightRatio = (int) Math.ceil(options.outHeight / (float) height); int widthRatio = (int) Math.ceil(options.outWidth / (float) width); if (heightRatio > 1 || widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(imagePath, options); } /** * obtain the image rotation angle * * @param path path of target image */ private int getImageSpinAngle(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /** * 指定参数压缩图片 * create the thumbnail with the true rotate angle * * @param largeImagePath the big image path * @param thumbFilePath the thumbnail path * @param width width of thumbnail * @param height height of thumbnail * @param angle rotation angle of thumbnail * @param size the file size of image */ private File compress(String largeImagePath, String thumbFilePath, int width, int height, int angle, long size) { Bitmap thbBitmap = compress(largeImagePath, width, height); thbBitmap = rotatingImage(angle, thbBitmap); return saveImage(thumbFilePath, thbBitmap, size); } /** * 旋转图片 * rotate the image with specified angle * * @param angle the angle will be rotating 旋转的角度 * @param bitmap target image 目标图片 */ private static Bitmap rotatingImage(int angle, Bitmap bitmap) { //rotate image Matrix matrix = new Matrix(); matrix.postRotate(angle); //create a new image return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /** * 保存图片到指定路径 * Save image with specified size * * @param filePath the image file save path 储存路径 * @param bitmap the image what be save 目标图片 * @param size the file size of image 期望大小 */ private File saveImage(String filePath, Bitmap bitmap, long size) { checkNotNull(bitmap, TAG + "bitmap cannot be null"); File result = new File(filePath.substring(0, filePath.lastIndexOf("/"))); if (!result.exists() && !result.mkdirs()) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); int options = 100; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); while (stream.toByteArray().length / 1024 > size) { stream.reset(); options -= 6; bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream); } try { FileOutputStream fos = new FileOutputStream(filePath); fos.write(stream.toByteArray()); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } return new File(filePath); } }
修复[0.5625,0.5)区间成像模糊的问题
library/src/main/java/top/zibin/luban/Luban.java
修复[0.5625,0.5)区间成像模糊的问题
<ide><path>ibrary/src/main/java/top/zibin/luban/Luban.java <ide> int multiple = height / 1280 == 0 ? 1 : height / 1280; <ide> thumbW = width / multiple; <ide> thumbH = height / multiple; <del> size = (thumbW * thumbH) / (1440.0 * 2560.0) * 200; <add> size = (thumbW * thumbH) / (1440.0 * 2560.0) * 400; <ide> size = size < 100 ? 100 : size; <ide> } else { <ide> int multiple = (int) Math.ceil(height / (1280.0 / scale));
Java
apache-2.0
0ae29f4a0ce4ad7470dffe9f15370d3acbae0995
0
jcnoir/dmix,philchand/mpdroid-2014,eisnerd/mupeace,eisnerd/mupeace,hurzl/dmix,0359xiaodong/dmix,hurzl/dmix,philchand/mpdroid-2014,abarisain/dmix,jcnoir/dmix,philchand/mpdroid-2014,philchand/mpdroid-2014,abarisain/dmix,0359xiaodong/dmix,joansmith/dmix,eisnerd/mupeace,joansmith/dmix
package com.namelessdev.mpdroid; import java.util.Collection; import java.util.LinkedList; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnKeyListener; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.ConnectivityManager; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.preference.PreferenceManager; import android.view.KeyEvent; import com.namelessdev.mpdroid.MPDAsyncHelper.ConnectionListener; public class MPDApplication extends Application implements ConnectionListener, OnSharedPreferenceChangeListener { private Collection<Activity> connectionLocks = new LinkedList<Activity>(); private AlertDialog ad; private DialogClickListener oDialogClickListener; private boolean bWifiConnected = false; private boolean streamingMode = false; private boolean settingsShown = false; private boolean warningShown = false; private Activity currentActivity; public static final int SETTINGS = 5; public void setActivity(Activity activity) { currentActivity = activity; connectionLocks.add(activity); checkMonitorNeeded(); checkConnectionNeeded(); } public void unsetActivity(Activity activity) { connectionLocks.remove(activity); checkMonitorNeeded(); checkConnectionNeeded(); if (currentActivity == activity) currentActivity = null; } private void checkMonitorNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.isMonitorAlive()) oMPDAsyncHelper.startMonitor(); } else oMPDAsyncHelper.stopMonitor(); } private void checkConnectionNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.oMPD.isConnected() && !currentActivity.getClass().equals(WifiConnectionSettings.class)) { connect(); } } else { disconnect(); } } public void disconnect() { oMPDAsyncHelper.disconnect(); } public void connect() { // Get Settings... SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);// getSharedPreferences("org.pmix", MODE_PRIVATE); settings.registerOnSharedPreferenceChangeListener(this); String wifiSSID = getCurrentSSID(); if (!settings.getString(wifiSSID + "hostname", "").equals("")) { String sServer = settings.getString(wifiSSID + "hostname", ""); int iPort = Integer.parseInt(settings.getString(wifiSSID + "port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString(wifiSSID + "portStreaming", "8000")); String sPassword = settings.getString(wifiSSID + "password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else if (!settings.getString("hostname", "").equals("")) { String sServer = settings.getString("hostname", ""); int iPort = Integer.parseInt(settings.getString("port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString("portStreaming", "6600")); String sPassword = settings.getString("password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else { // Absolutely no settings defined! Open Settings! if (currentActivity != null && !settingsShown) { currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); settingsShown = true; } } if (currentActivity != null && !settings.getBoolean("warningShown", false) && !warningShown) { currentActivity.startActivity(new Intent(currentActivity, WarningActivity.class)); warningShown = true; } connectMPD(); } private void connectMPD() { if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } if (!isNetworkConnected()) { connectionFailed("No network."); return; } ad = new ProgressDialog(currentActivity); ad.setTitle(getResources().getString(R.string.connecting)); ad.setMessage(getResources().getString(R.string.connectingToServer)); ad.setCancelable(false); ad.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // Handle all keys! return true; } }); ad.show(); oMPDAsyncHelper.doConnect(); } public void onSharedPreferenceChanged(SharedPreferences settings, String key) { String wifiSSID = getCurrentSSID(); if (key.equals("albumartist")) { // clear current cached artist list on change of tag settings // ArtistsActivity.items = null; } else if (!settings.getString(wifiSSID + "hostname", "").equals("")) { String sServer = settings.getString(wifiSSID + "hostname", ""); int iPort = Integer.parseInt(settings.getString(wifiSSID + "port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString(wifiSSID + "portStreaming", "8000")); String sPassword = settings.getString(wifiSSID + "password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else if (!settings.getString("hostname", "").equals("")) { String sServer = settings.getString("hostname", ""); int iPort = Integer.parseInt(settings.getString("port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString("portStreaming", "6600")); String sPassword = settings.getString("password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else { return; } } @Override public void connectionFailed(String message) { System.out.println("Connection Failed: " + message); if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } if (currentActivity == null) { return; } if (currentActivity != null && connectionLocks.size() > 0 && currentActivity.getClass() != null) { if (currentActivity.getClass().equals(SettingsActivity.class)) { AlertDialog.Builder test = new AlertDialog.Builder(currentActivity); test.setMessage("Connection failed, check your connection settings. (" + message + ")"); test.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } }); ad = test.show(); } else { System.out.println(this.getClass()); oDialogClickListener = new DialogClickListener(); AlertDialog.Builder test = new AlertDialog.Builder(currentActivity); test.setTitle(getResources().getString(R.string.connectionFailed)); test.setMessage(String.format(getResources().getString(R.string.connectionFailedMessage), message)); test.setNegativeButton(getResources().getString(R.string.quit), oDialogClickListener); test.setNeutralButton(getResources().getString(R.string.settings), oDialogClickListener); test.setPositiveButton(getResources().getString(R.string.retry), oDialogClickListener); ad = test.show(); } } } @Override public void connectionSucceeded(String message) { ad.dismiss(); // checkMonitorNeeded(); } public class DialogClickListener implements OnClickListener { public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON3: // Show Settings currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); break; case AlertDialog.BUTTON2: currentActivity.finish(); break; case AlertDialog.BUTTON1: connectMPD(); break; } } } private WifiManager mWifiManager; // Change this... (sag) public MPDAsyncHelper oMPDAsyncHelper = null; @Override public void onCreate() { super.onCreate(); System.err.println("onCreate Application"); oMPDAsyncHelper = new MPDAsyncHelper(); oMPDAsyncHelper.addConnectionListener((MPDApplication) getApplicationContext()); mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE); } public String getCurrentSSID() { WifiInfo info = mWifiManager.getConnectionInfo(); return info.getSSID(); } public void setWifiConnected(boolean bWifiConnected) { this.bWifiConnected = bWifiConnected; if (bWifiConnected) { connect(); // checkMonitorNeeded(); } else { // disconnect(); } } public boolean isWifiConnected() { return true; // return bWifiConnected; // TODO : DIRTY WIFI HACK :( } public boolean isNetworkConnected() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (conMgr.getActiveNetworkInfo() == null) return false; return (conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()); } public void setStreamingMode(boolean streamingMode) { this.streamingMode = streamingMode; } public boolean isStreamingMode() { return streamingMode; } }
MPDroid/src/com/namelessdev/mpdroid/MPDApplication.java
package com.namelessdev.mpdroid; import java.util.Collection; import java.util.LinkedList; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnKeyListener; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.ConnectivityManager; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.preference.PreferenceManager; import android.view.KeyEvent; import com.namelessdev.mpdroid.MPDAsyncHelper.ConnectionListener; public class MPDApplication extends Application implements ConnectionListener, OnSharedPreferenceChangeListener { private Collection<Activity> connectionLocks = new LinkedList<Activity>(); private AlertDialog ad; private DialogClickListener oDialogClickListener; private boolean bWifiConnected = false; private boolean streamingMode = false; private boolean settingsShown = false; private boolean warningShown = false; private Activity currentActivity; public static final int SETTINGS = 5; public void setActivity(Activity activity) { currentActivity = activity; connectionLocks.add(activity); checkMonitorNeeded(); checkConnectionNeeded(); } public void unsetActivity(Activity activity) { connectionLocks.remove(activity); checkMonitorNeeded(); checkConnectionNeeded(); if (currentActivity == activity) currentActivity = null; } private void checkMonitorNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.isMonitorAlive()) oMPDAsyncHelper.startMonitor(); } else oMPDAsyncHelper.stopMonitor(); } private void checkConnectionNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.oMPD.isConnected() && !currentActivity.getClass().equals(WifiConnectionSettings.class)) { connect(); } } else { disconnect(); } } public void disconnect() { oMPDAsyncHelper.disconnect(); } public void connect() { // Get Settings... SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);// getSharedPreferences("org.pmix", MODE_PRIVATE); settings.registerOnSharedPreferenceChangeListener(this); String wifiSSID = getCurrentSSID(); if (!settings.getString(wifiSSID + "hostname", "").equals("")) { String sServer = settings.getString(wifiSSID + "hostname", ""); int iPort = Integer.parseInt(settings.getString(wifiSSID + "port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString(wifiSSID + "portStreaming", "8000")); String sPassword = settings.getString(wifiSSID + "password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else if (!settings.getString("hostname", "").equals("")) { String sServer = settings.getString("hostname", ""); int iPort = Integer.parseInt(settings.getString("port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString("portStreaming", "6600")); String sPassword = settings.getString("password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else { // Absolutely no settings defined! Open Settings! if (currentActivity != null && !settingsShown) { currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); settingsShown = true; } } if (currentActivity != null && !settings.getBoolean("warningShown", false) && !warningShown) { currentActivity.startActivity(new Intent(currentActivity, WarningActivity.class)); warningShown = true; } connectMPD(); } private void connectMPD() { if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } if (!isNetworkConnected()) { connectionFailed("No network."); return; } ad = new ProgressDialog(currentActivity); ad.setTitle(getResources().getString(R.string.connecting)); ad.setMessage(getResources().getString(R.string.connectingToServer)); ad.setCancelable(false); ad.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // Handle all keys! return true; } }); ad.show(); oMPDAsyncHelper.doConnect(); } public void onSharedPreferenceChanged(SharedPreferences settings, String key) { String wifiSSID = getCurrentSSID(); if (key.equals("albumartist")) { // clear current cached artist list on change of tag settings //ArtistsActivity.items = null; } else if (!settings.getString(wifiSSID + "hostname", "").equals("")) { String sServer = settings.getString(wifiSSID + "hostname", ""); int iPort = Integer.parseInt(settings.getString(wifiSSID + "port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString(wifiSSID + "portStreaming", "8000")); String sPassword = settings.getString(wifiSSID + "password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else if (!settings.getString("hostname", "").equals("")) { String sServer = settings.getString("hostname", ""); int iPort = Integer.parseInt(settings.getString("port", "6600")); int iPortStreaming = Integer.parseInt(settings.getString("portStreaming", "6600")); String sPassword = settings.getString("password", ""); oMPDAsyncHelper.setConnectionInfo(sServer, iPort, sPassword, iPortStreaming); } else { return; } } @Override public void connectionFailed(String message) { System.out.println("Connection Failed: " + message); if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } if (currentActivity == null) { return; } if (currentActivity != null && connectionLocks.size() > 0 && currentActivity.getClass() != null) { if (currentActivity.getClass().equals(SettingsActivity.class)) { AlertDialog.Builder test = new AlertDialog.Builder(currentActivity); test.setMessage("Connection failed, check your connection settings. (" + message + ")"); test.setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } }); ad = test.show(); } else { System.out.println(this.getClass()); oDialogClickListener = new DialogClickListener(); AlertDialog.Builder test = new AlertDialog.Builder(currentActivity); test.setTitle(getResources().getString(R.string.connectionFailed)); test.setMessage(String.format(getResources().getString(R.string.connectionFailedMessage), message)); test.setNegativeButton(getResources().getString(R.string.quit), oDialogClickListener); test.setNeutralButton(getResources().getString(R.string.settings), oDialogClickListener); test.setPositiveButton(getResources().getString(R.string.retry), oDialogClickListener); ad = test.show(); } } } @Override public void connectionSucceeded(String message) { ad.dismiss(); // checkMonitorNeeded(); } public class DialogClickListener implements OnClickListener { public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON3: // Show Settings currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); break; case AlertDialog.BUTTON2: currentActivity.finish(); break; case AlertDialog.BUTTON1: connectMPD(); break; } } } private WifiManager mWifiManager; // Change this... (sag) public MPDAsyncHelper oMPDAsyncHelper = null; @Override public void onCreate() { super.onCreate(); System.err.println("onCreate Application"); oMPDAsyncHelper = new MPDAsyncHelper(); oMPDAsyncHelper.addConnectionListener((MPDApplication) getApplicationContext()); mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE); } public String getCurrentSSID() { WifiInfo info = mWifiManager.getConnectionInfo(); return info.getSSID(); } public void setWifiConnected(boolean bWifiConnected) { this.bWifiConnected = bWifiConnected; if (bWifiConnected) { if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } if (currentActivity == null && isStreamingMode() == false) return; connect(); // checkMonitorNeeded(); } else { disconnect(); if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } if (currentActivity == null) return; AlertDialog.Builder test = new AlertDialog.Builder(currentActivity); test.setMessage(getResources().getString(R.string.waitForWLAN)); ad = test.show(); } } public boolean isWifiConnected() { return true; // return bWifiConnected; // TODO : DIRTY WIFI HACK :( } public boolean isNetworkConnected() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (conMgr.getActiveNetworkInfo() == null) return false; return (conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()); } public void setStreamingMode(boolean streamingMode) { this.streamingMode = streamingMode; } public boolean isStreamingMode() { return streamingMode; } }
Removed a WLAN popup, syko can be happy now.
MPDroid/src/com/namelessdev/mpdroid/MPDApplication.java
Removed a WLAN popup, syko can be happy now.
<ide><path>PDroid/src/com/namelessdev/mpdroid/MPDApplication.java <ide> <ide> if (key.equals("albumartist")) { <ide> // clear current cached artist list on change of tag settings <del> //ArtistsActivity.items = null; <add> // ArtistsActivity.items = null; <ide> <ide> } else if (!settings.getString(wifiSSID + "hostname", "").equals("")) { <ide> String sServer = settings.getString(wifiSSID + "hostname", ""); <ide> public void setWifiConnected(boolean bWifiConnected) { <ide> this.bWifiConnected = bWifiConnected; <ide> if (bWifiConnected) { <del> if (ad != null) { <del> if (ad.isShowing()) { <del> try { <del> ad.dismiss(); <del> } catch (IllegalArgumentException e) { <del> // We don't care, it has already been destroyed <del> } <del> } <del> } <del> if (currentActivity == null && isStreamingMode() == false) <del> return; <ide> connect(); <ide> // checkMonitorNeeded(); <ide> } else { <del> disconnect(); <del> if (ad != null) { <del> if (ad.isShowing()) { <del> try { <del> ad.dismiss(); <del> } catch (IllegalArgumentException e) { <del> // We don't care, it has already been destroyed <del> } <del> } <del> } <del> if (currentActivity == null) <del> return; <del> AlertDialog.Builder test = new AlertDialog.Builder(currentActivity); <del> test.setMessage(getResources().getString(R.string.waitForWLAN)); <del> ad = test.show(); <add> // disconnect(); <ide> } <ide> } <ide>
JavaScript
bsd-3-clause
b90289382234c708feca532f55f681a7ba54d544
0
redaktor/deliteful
dojo.provide("dijit._editor._Plugin"); dojo.require("dijit._Widget"); dojo.require("dijit.form.Button"); dojo.declare("dijit._editor._Plugin", null, { // summary // Base class for a "plugin" to the editor, which is usually // a single button on the Toolbar and some associated code constructor: function(/*Object?*/args, /*DomNode?*/node){ this.params = args || {}; dojo.mixin(this, this.params); this._connects=[]; }, // editor: [const] dijit.Editor // Points to the parent editor editor: null, // iconClassPrefix: [const] String // The CSS class name for the button node is formed from `iconClassPrefix` and `command` iconClassPrefix: "dijitEditorIcon", // button: dijit._Widget? // Pointer to `dijit.form.Button` or other widget (ex: `dijit.form.FilteringSelect`) // that is added to the toolbar to control this plugin. // If not specified, will be created on initialization according to `buttonClass` button: null, // command: String // String like "insertUnorderedList", "outdent", "justifyCenter", etc. that represents an editor command. // Passed to editor.execCommand() if `useDefaultCommand` is true. command: "", // useDefaultCommand: Boolean // If true, this plugin executes by calling Editor.execCommand() with the argument specified in `command`. useDefaultCommand: true, // buttonClass: Widget Class // Class of widget (ex: dijit.form.Button or dijit.form.FilteringSelect) // that is added to the toolbar to control this plugin. // This is used to instantiate the button, unless `button` itself is specified directly. buttonClass: dijit.form.Button, getLabel: function(/*String*/key){ // summary: // Returns the label to use for the button // tags: // private return this.editor.commands[key]; // String }, _initButton: function(){ // summary: // Initialize the button or other widget that will control this plugin. // This code only works for plugins controlling built-in commands in the editor. // tags: // protected extension if(this.command.length){ var label = this.getLabel(this.command), editor = this.editor, className = this.iconClassPrefix+" "+this.iconClassPrefix + this.command.charAt(0).toUpperCase() + this.command.substr(1); if(!this.button){ var props = dojo.mixin({ label: label, dir: editor.dir, lang: editor.lang, showLabel: false, iconClass: className, dropDown: this.dropDown, tabIndex: "-1" }, this.params || {}); this.button = new this.buttonClass(props); } } }, destroy: function(){ // summary: // Destroy this plugin dojo.forEach(this._connects, dojo.disconnect); if(this.dropDown){ this.dropDown.destroyRecursive(); } }, connect: function(o, f, tf){ // summary: // Make a dojo.connect() that is automatically disconnected when this plugin is destroyed. // Similar to `dijit._Widget.connect`. // tags: // protected this._connects.push(dojo.connect(o, f, this, tf)); }, updateState: function(){ // summary: // Change state of the plugin to respond to events in the editor. // description: // This is called on meaningful events in the editor, such as change of selection // or caret position (but not simple typing of alphanumeric keys). It gives the // plugin a chance to update the CSS of its button. // // For example, the "bold" plugin will highlight/unhighlight the bold button depending on whether the // characters next to the caret are bold or not. // // Only makes sense when `useDefaultCommand` is true, as it calls Editor.queryCommandEnabled(`command`). var e = this.editor, c = this.command, checked, enabled; if(!e || !e.isLoaded || !c.length){ return; } if(this.button){ try{ enabled = e.queryCommandEnabled(c); if(this.enabled !== enabled){ this.enabled = enabled; this.button.set('disabled', !enabled); } if(typeof this.button.checked == 'boolean'){ checked = e.queryCommandState(c); if(this.checked !== checked){ this.checked = checked; this.button.set('checked', e.queryCommandState(c)); } } }catch(e){ console.log(e); // FIXME: we shouldn't have debug statements in our code. Log as an error? } } }, setEditor: function(/*dijit.Editor*/ editor){ // summary: // Tell the plugin which Editor it is associated with. // TODO: refactor code to just pass editor to constructor. // FIXME: detach from previous editor!! this.editor = editor; // FIXME: prevent creating this if we don't need to (i.e., editor can't handle our command) this._initButton(); // Processing for buttons that execute by calling editor.execCommand() if(this.button && this.useDefaultCommand){ if(this.editor.queryCommandAvailable(this.command)){ this.connect(this.button, "onClick", dojo.hitch(this.editor, "execCommand", this.command, this.commandArg) ); }else{ // hide button because editor doesn't support command (due to browser limitations) this.button.domNode.style.display = "none"; } } this.connect(this.editor, "onNormalizedDisplayChanged", "updateState"); }, setToolbar: function(/*dijit.Toolbar*/ toolbar){ // summary: // Tell the plugin to add it's controller widget (often a button) // to the toolbar. Does nothing if there is no controller widget. // TODO: refactor code to just pass toolbar to constructor. if(this.button){ toolbar.addChild(this.button); } // console.debug("adding", this.button, "to:", toolbar); } });
_editor/_Plugin.js
dojo.provide("dijit._editor._Plugin"); dojo.require("dijit._Widget"); dojo.require("dijit.form.Button"); dojo.declare("dijit._editor._Plugin", null, { // summary // Base class for a "plugin" to the editor, which is usually // a single button on the Toolbar and some associated code constructor: function(/*Object?*/args, /*DomNode?*/node){ this.params = args || {}; dojo.mixin(this, this.params); this._connects=[]; }, // editor: [const] dijit.Editor // Points to the parent editor editor: null, // iconClassPrefix: [const] String // The CSS class name for the button node is formed from `iconClassPrefix` and `command` iconClassPrefix: "dijitEditorIcon", // button: dijit._Widget? // Pointer to `dijit.form.Button` or other widget (ex: `dijit.form.FilteringSelect`) // that is added to the toolbar to control this plugin. // If not specified, will be created on initialization according to `buttonClass` button: null, // command: String // String like "insertUnorderedList", "outdent", "justifyCenter", etc. that represents an editor command. // Passed to editor.execCommand() if `useDefaultCommand` is true. command: "", // useDefaultCommand: Boolean // If true, this plugin executes by calling Editor.execCommand() with the argument specified in `command`. useDefaultCommand: true, // buttonClass: Widget Class // Class of widget (ex: dijit.form.Button or dijit.form.FilteringSelect) // that is added to the toolbar to control this plugin. // This is used to instantiate the button, unless `button` itself is specified directly. buttonClass: dijit.form.Button, getLabel: function(/*String*/key){ // summary: // Returns the label to use for the button // tags: // private return this.editor.commands[key]; // String }, _initButton: function(){ // summary: // Initialize the button or other widget that will control this plugin. // This code only works for plugins controlling built-in commands in the editor. // tags: // protected extension if(this.command.length){ var label = this.getLabel(this.command); var className = this.iconClassPrefix+" "+this.iconClassPrefix + this.command.charAt(0).toUpperCase() + this.command.substr(1); if(!this.button){ var props = dojo.mixin({ label: label, dir: this.dir, lang: this.lang, showLabel: false, iconClass: className, dropDown: this.dropDown, tabIndex: "-1" }, this.params || {}); this.button = new this.buttonClass(props); } } }, destroy: function(){ // summary: // Destroy this plugin dojo.forEach(this._connects, dojo.disconnect); if(this.dropDown){ this.dropDown.destroyRecursive(); } }, connect: function(o, f, tf){ // summary: // Make a dojo.connect() that is automatically disconnected when this plugin is destroyed. // Similar to `dijit._Widget.connect`. // tags: // protected this._connects.push(dojo.connect(o, f, this, tf)); }, updateState: function(){ // summary: // Change state of the plugin to respond to events in the editor. // description: // This is called on meaningful events in the editor, such as change of selection // or caret position (but not simple typing of alphanumeric keys). It gives the // plugin a chance to update the CSS of its button. // // For example, the "bold" plugin will highlight/unhighlight the bold button depending on whether the // characters next to the caret are bold or not. // // Only makes sense when `useDefaultCommand` is true, as it calls Editor.queryCommandEnabled(`command`). var e = this.editor, c = this.command, checked, enabled; if(!e || !e.isLoaded || !c.length){ return; } if(this.button){ try{ enabled = e.queryCommandEnabled(c); if(this.enabled !== enabled){ this.enabled = enabled; this.button.set('disabled', !enabled); } if(typeof this.button.checked == 'boolean'){ checked = e.queryCommandState(c); if(this.checked !== checked){ this.checked = checked; this.button.set('checked', e.queryCommandState(c)); } } }catch(e){ console.log(e); // FIXME: we shouldn't have debug statements in our code. Log as an error? } } }, setEditor: function(/*dijit.Editor*/ editor){ // summary: // Tell the plugin which Editor it is associated with. // TODO: refactor code to just pass editor to constructor. // FIXME: detach from previous editor!! this.editor = editor; // FIXME: prevent creating this if we don't need to (i.e., editor can't handle our command) this._initButton(); // Processing for buttons that execute by calling editor.execCommand() if(this.button && this.useDefaultCommand){ if(this.editor.queryCommandAvailable(this.command)){ this.connect(this.button, "onClick", dojo.hitch(this.editor, "execCommand", this.command, this.commandArg) ); }else{ // hide button because editor doesn't support command (due to browser limitations) this.button.domNode.style.display = "none"; } } this.connect(this.editor, "onNormalizedDisplayChanged", "updateState"); }, setToolbar: function(/*dijit.Toolbar*/ toolbar){ // summary: // Tell the plugin to add it's controller widget (often a button) // to the toolbar. Does nothing if there is no controller widget. // TODO: refactor code to just pass toolbar to constructor. if(this.button){ toolbar.addChild(this.button); } // console.debug("adding", this.button, "to:", toolbar); } });
fix dir/lang setting for buttons in editor toolbar (and thus orientation of dropdown from dropdown buttons), refs #10880 !strict git-svn-id: 674a2d6b1e32e53f607eb824547723f32280967e@21962 560b804f-0ae3-0310-86f3-f6aa0a117693
_editor/_Plugin.js
fix dir/lang setting for buttons in editor toolbar (and thus orientation of dropdown from dropdown buttons), refs #10880 !strict
<ide><path>editor/_Plugin.js <ide> // tags: <ide> // protected extension <ide> if(this.command.length){ <del> var label = this.getLabel(this.command); <del> var className = this.iconClassPrefix+" "+this.iconClassPrefix + this.command.charAt(0).toUpperCase() + this.command.substr(1); <add> var label = this.getLabel(this.command), <add> editor = this.editor, <add> className = this.iconClassPrefix+" "+this.iconClassPrefix + this.command.charAt(0).toUpperCase() + this.command.substr(1); <ide> if(!this.button){ <ide> var props = dojo.mixin({ <ide> label: label, <del> dir: this.dir, <del> lang: this.lang, <add> dir: editor.dir, <add> lang: editor.lang, <ide> showLabel: false, <ide> iconClass: className, <ide> dropDown: this.dropDown,
Java
apache-2.0
error: pathspec 'okio/src/main/java/okio/ForwardingTimeout.java' did not match any file(s) known to git
c9eb0de789fdd9b388eaf7a842fc69460fbd6c19
1
zzuhtzy/okio-source-read,zzuhtzy/okio-source-read
/* * Copyright (C) 2015 Square, 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 okio; import java.io.IOException; import java.util.concurrent.TimeUnit; /** A {@link Timeout} which forwards calls to another. Useful for subclassing. */ public class ForwardingTimeout extends Timeout { private Timeout delegate; public ForwardingTimeout(Timeout delegate) { if (delegate == null) throw new IllegalArgumentException("delegate == null"); this.delegate = delegate; } /** {@link Timeout} instance to which this instance is currently delegating. */ public final Timeout delegate() { return delegate; } public final ForwardingTimeout setDelegate(Timeout delegate) { if (delegate == null) throw new IllegalArgumentException("delegate == null"); this.delegate = delegate; return this; } @Override public Timeout timeout(long timeout, TimeUnit unit) { return delegate.timeout(timeout, unit); } @Override public long timeoutNanos() { return delegate.timeoutNanos(); } @Override public boolean hasDeadline() { return delegate.hasDeadline(); } @Override public long deadlineNanoTime() { return delegate.deadlineNanoTime(); } @Override public Timeout deadlineNanoTime(long deadlineNanoTime) { return delegate.deadlineNanoTime(deadlineNanoTime); } @Override public Timeout clearTimeout() { return delegate.clearTimeout(); } @Override public Timeout clearDeadline() { return delegate.clearDeadline(); } @Override public void throwIfReached() throws IOException { delegate.throwIfReached(); } }
okio/src/main/java/okio/ForwardingTimeout.java
add ForwardingTimeout.java
okio/src/main/java/okio/ForwardingTimeout.java
add ForwardingTimeout.java
<ide><path>kio/src/main/java/okio/ForwardingTimeout.java <add>/* <add> * Copyright (C) 2015 Square, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package okio; <add> <add>import java.io.IOException; <add>import java.util.concurrent.TimeUnit; <add> <add>/** A {@link Timeout} which forwards calls to another. Useful for subclassing. */ <add>public class ForwardingTimeout extends Timeout { <add> private Timeout delegate; <add> <add> public ForwardingTimeout(Timeout delegate) { <add> if (delegate == null) throw new IllegalArgumentException("delegate == null"); <add> this.delegate = delegate; <add> } <add> <add> /** {@link Timeout} instance to which this instance is currently delegating. */ <add> public final Timeout delegate() { <add> return delegate; <add> } <add> <add> public final ForwardingTimeout setDelegate(Timeout delegate) { <add> if (delegate == null) throw new IllegalArgumentException("delegate == null"); <add> this.delegate = delegate; <add> return this; <add> } <add> <add> @Override public Timeout timeout(long timeout, TimeUnit unit) { <add> return delegate.timeout(timeout, unit); <add> } <add> <add> @Override public long timeoutNanos() { <add> return delegate.timeoutNanos(); <add> } <add> <add> @Override public boolean hasDeadline() { <add> return delegate.hasDeadline(); <add> } <add> <add> @Override public long deadlineNanoTime() { <add> return delegate.deadlineNanoTime(); <add> } <add> <add> @Override public Timeout deadlineNanoTime(long deadlineNanoTime) { <add> return delegate.deadlineNanoTime(deadlineNanoTime); <add> } <add> <add> @Override public Timeout clearTimeout() { <add> return delegate.clearTimeout(); <add> } <add> <add> @Override public Timeout clearDeadline() { <add> return delegate.clearDeadline(); <add> } <add> <add> @Override public void throwIfReached() throws IOException { <add> delegate.throwIfReached(); <add> } <add>}
Java
mit
be150bede43b35c71a0e6da2bc4800c5e8b9853e
0
IPPETAD/adventure.datetime
/* * Copyright (c) 2013 Andrew Fontaine, James Finlay, Jesse Tucker, Jacob Viau, and * Evan DeGraff * * 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 ca.cmput301f13t03.adventure_datetime.model; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.UUID; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ILocalStorage; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * The local database containing all stories, fragments, bookmarks, and subscriptions * * @author Andrew Fontaine * @version 1.0 * @since 28/10/13 */ public class StoryDB implements BaseColumns, ILocalStorage { private static final String TAG = "StoryDB"; public static final String COLUMN_GUID = "GUID"; public static final String STORY_TABLE_NAME = "Story"; public static final String STORY_COLUMN_AUTHOR = "Author"; public static final String STORY_COLUMN_HEAD_FRAGMENT = "HeadFragment"; public static final String STORY_COLUMN_TIMESTAMP = "Timestamp"; public static final String STORY_COLUMN_SYNOPSIS = "Synopsis"; public static final String STORY_COLUMN_THUMBNAIL = "Thumbnail"; public static final String STORY_COLUMN_TITLE = "Title"; public static final String STORYFRAGMENT_TABLE_NAME = "StoryFragment"; public static final String STORYFRAGMENT_COLUMN_STORYID = "StoryID"; public static final String STORYFRAGMENT_COLUMN_CONTENT = "Content"; public static final String STORYFRAGMENT_COLUMN_CHOICES = "Choices"; public static final String BOOKMARK_TABLE_NAME = "Bookmark"; public static final String BOOKMARK_COLUMN_STORYID = "StoryID"; public static final String BOOKMARK_COLUMN_FRAGMENTID = "FragmentID"; public static final String BOOKMARK_COLUMN_DATE = "Date"; public static final String AUTHORED_STORIES_TABLE_NAME = "AuthoredStories"; private StoryDBHelper mDbHelper; public StoryDB(Context context) { mDbHelper = new StoryDBHelper(context); } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStory(java.util.UUID) */ @Override public Story getStory(UUID id) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORY_TABLE_NAME, new String[]{_ID, COLUMN_GUID, STORY_COLUMN_TITLE, STORY_COLUMN_AUTHOR, STORY_COLUMN_TITLE, STORY_COLUMN_HEAD_FRAGMENT, STORY_COLUMN_SYNOPSIS, STORY_COLUMN_TIMESTAMP, STORY_COLUMN_THUMBNAIL}, COLUMN_GUID + " = ?", new String[] {id.toString()}, null, null, null, "1"); Story story; if (cursor.moveToFirst()) { Log.v(TAG, "Story with UUID " + id + " retrieved"); story = createStory(cursor); } else { story = null; Log.v(TAG, "No story found"); } cursor.close(); db.close(); return story; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStories() */ @Override public ArrayList<Story> getStories() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORY_TABLE_NAME, new String[] {_ID, COLUMN_GUID, STORY_COLUMN_AUTHOR, STORY_COLUMN_TITLE, STORY_COLUMN_HEAD_FRAGMENT, STORY_COLUMN_SYNOPSIS, STORY_COLUMN_TIMESTAMP, STORY_COLUMN_THUMBNAIL}, null, null, null, null, null); ArrayList<Story> stories = new ArrayList<Story>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "Story with id " + cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) + " retrieved"); stories.add(createStory(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, stories.size() + " stories retrieved"); cursor.close(); db.close(); return stories; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStoriesAuthoredBy(java.lang.String) */ @Override public ArrayList<Story> getStoriesAuthoredBy(String author) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORY_TABLE_NAME, new String[]{_ID, COLUMN_GUID, STORY_COLUMN_AUTHOR, STORY_COLUMN_HEAD_FRAGMENT, STORY_COLUMN_SYNOPSIS, STORY_COLUMN_TIMESTAMP, STORY_COLUMN_THUMBNAIL}, STORY_COLUMN_AUTHOR + " = ?", new String[] {author}, null, null, null); ArrayList<Story> stories = new ArrayList<Story>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "Story with id " + cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) + " retrieved"); stories.add(createStory(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, stories.size() + " stories retrieved"); cursor.close(); db.close(); return stories; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStoryFragment(java.util.UUID) */ @Override public StoryFragment getStoryFragment(UUID id) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORYFRAGMENT_TABLE_NAME, new String[] {_ID, COLUMN_GUID, STORYFRAGMENT_COLUMN_STORYID, STORYFRAGMENT_COLUMN_CHOICES, STORYFRAGMENT_COLUMN_CONTENT}, COLUMN_GUID + " = ?", new String[] {id.toString()}, null, null, "1"); StoryFragment frag; if(cursor.moveToFirst()) { Log.v(TAG, "StoryFragment " + id + " retrieved"); frag = createStoryFragment(cursor); } else { frag = null; Log.v(TAG, "No fragment found"); } cursor.close(); db.close(); return frag; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStoryFragments(java.util.UUID) */ @Override public ArrayList<StoryFragment> getStoryFragments(UUID storyid) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORYFRAGMENT_TABLE_NAME, new String[]{_ID, COLUMN_GUID, STORYFRAGMENT_COLUMN_STORYID, STORYFRAGMENT_COLUMN_CHOICES, STORYFRAGMENT_COLUMN_CONTENT}, STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[]{storyid.toString()}, null, null, null); ArrayList<StoryFragment> fragments = new ArrayList<StoryFragment>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "StoryFragment with id " + cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) + " retrieved"); fragments.add(createStoryFragment(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, fragments.size() + " StoryFragments retrieved"); cursor.close(); db.close(); return fragments; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getBookmark(java.util.UUID) */ @Override public Bookmark getBookmark(UUID storyid) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(BOOKMARK_TABLE_NAME, new String[] {_ID, BOOKMARK_COLUMN_STORYID, BOOKMARK_COLUMN_FRAGMENTID, BOOKMARK_COLUMN_DATE}, BOOKMARK_COLUMN_STORYID + " = ?", new String[] {storyid.toString()}, null, null, null); Bookmark bookmark; if(cursor.moveToFirst()) { Log.v(TAG, "Bookmark with Story id " + cursor.getString(cursor.getColumnIndex(BOOKMARK_COLUMN_STORYID)) + "retrieved"); bookmark = createBookmark(cursor); } else { Log.v(TAG, "No bookmark found"); bookmark = null; } cursor.close(); db.close(); return bookmark; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getAllBookmarks() */ @Override public ArrayList<Bookmark> getAllBookmarks() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(BOOKMARK_TABLE_NAME, new String[] {BOOKMARK_COLUMN_STORYID, BOOKMARK_COLUMN_FRAGMENTID, BOOKMARK_COLUMN_DATE}, null, null, null, null, null); ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "Bookmark with Story id " + cursor.getString(cursor.getColumnIndex(BOOKMARK_COLUMN_STORYID)) + " retrieved"); bookmarks.add(createBookmark(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, bookmarks.size() + " bookmarks retrieved"); return bookmarks; } public boolean getAuthoredStory(UUID storyId) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(AUTHORED_STORIES_TABLE_NAME, new String[] {COLUMN_GUID}, COLUMN_GUID + " = ?", new String[] {storyId.toString()}, null, null, null); boolean authoredStory = cursor.moveToFirst(); cursor.close(); db.close(); return authoredStory; } public ArrayList<UUID> getAuthoredStories() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(AUTHORED_STORIES_TABLE_NAME, new String[] {COLUMN_GUID}, null, null, null, null, null); ArrayList<UUID> authoredStories = new ArrayList<UUID>(); if(cursor.moveToFirst()) { do { authoredStories.add(UUID.fromString(cursor.getString(cursor.getColumnIndex(COLUMN_GUID)))); } while(cursor.moveToNext()); } cursor.close(); db.close(); return authoredStories; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#setBookmark(ca.cmput301f13t03.adventure_datetime.model.Bookmark) */ @Override public boolean setBookmark(Bookmark bookmark) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); Cursor cursor = db.query(BOOKMARK_TABLE_NAME, new String[] {_ID, BOOKMARK_COLUMN_FRAGMENTID, BOOKMARK_COLUMN_STORYID, BOOKMARK_COLUMN_DATE}, BOOKMARK_COLUMN_STORYID + " = ?", new String[] {bookmark.getStoryID().toString()}, null, null, null); ContentValues values = new ContentValues(); values.put(BOOKMARK_COLUMN_STORYID, bookmark.getStoryID().toString()); values.put(BOOKMARK_COLUMN_FRAGMENTID, bookmark.getFragmentID().toString()); values.put(BOOKMARK_COLUMN_DATE, bookmark.getDate().getTime()/1000); long updated; if(cursor.moveToFirst()) { Bookmark bookmark1 = createBookmark(cursor); if(bookmark.getDate().compareTo(bookmark1.getDate()) > 0) { updated = db.update(BOOKMARK_TABLE_NAME,values,BOOKMARK_COLUMN_STORYID + " = ?", new String[] {BOOKMARK_COLUMN_STORYID}); Log.v(TAG, updated + " Bookmarks updated"); cursor.close(); db.close(); return updated == 1; } Log.v(TAG, "No Bookmarks updated"); cursor.close(); db.close(); return false; } updated = db.insert(BOOKMARK_TABLE_NAME, null, values); Log.v(TAG, updated + " Bookmark inserted"); cursor.close(); db.close(); return updated != -1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#setStory(ca.cmput301f13t03.adventure_datetime.model.Story) */ @Override public boolean setStory(Story story) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(STORY_COLUMN_TITLE, story.getTitle()); values.put(STORY_COLUMN_AUTHOR, story.getAuthor()); values.put(STORY_COLUMN_HEAD_FRAGMENT, story.getHeadFragmentId().toString()); values.put(STORY_COLUMN_SYNOPSIS, story.getSynopsis()); values.put(STORY_COLUMN_TIMESTAMP, story.getTimestamp()); values.put(STORY_COLUMN_THUMBNAIL, (story.getThumbnail() == null ? null : story.getThumbnail().getEncodedBitmap())); values.put(COLUMN_GUID, story.getId().toString()); Cursor cursor = db.query(STORY_TABLE_NAME, new String[] {_ID}, COLUMN_GUID + " = ?", new String[] {story.getId().toString()}, null, null, null); if(cursor.moveToFirst()) { int updated; updated = db.update(STORY_TABLE_NAME, values, COLUMN_GUID + " = ?", new String [] {story.getId().toString()}); Log.v(TAG, updated + " stories updated"); cursor.close(); db.close(); return updated == 1; } cursor.close(); long inserted; inserted = db.insert(STORY_TABLE_NAME, null, values); Log.v(TAG, inserted + " story inserted"); db.close(); return inserted != -1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#setStoryFragment(ca.cmput301f13t03.adventure_datetime.model.StoryFragment) */ @Override public boolean setStoryFragment(StoryFragment frag) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(STORYFRAGMENT_COLUMN_STORYID, frag.getStoryID().toString()); values.put(STORYFRAGMENT_COLUMN_CONTENT, frag.getStoryText()); values.put(STORYFRAGMENT_COLUMN_CHOICES, frag.getChoicesInJson()); values.put(COLUMN_GUID, frag.getFragmentID().toString()); Cursor cursor = db.query(STORYFRAGMENT_TABLE_NAME, new String[] {_ID, STORYFRAGMENT_COLUMN_STORYID}, COLUMN_GUID + " = ? AND " + STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[] {frag.getFragmentID().toString(), frag.getStoryID().toString()}, null, null, null); if(cursor.moveToFirst()) { int updated; updated = db.update(STORYFRAGMENT_TABLE_NAME, values, COLUMN_GUID + " = ? AND " + STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[] {frag.getFragmentID().toString(), frag.getStoryID().toString()}); Log.v(TAG, updated + " fragments updated"); cursor.close(); db.close(); return updated == 1; } long inserted; inserted = db.insert(STORYFRAGMENT_TABLE_NAME, null, values); Log.v(TAG, inserted + " fragment inserted"); db.close(); return inserted != -1; } public boolean setAuthoredStory(Story story) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); Story story2 = getStory(story.getId()); if(story2 == null) { Log.v(TAG, "Story doesn't exist in local DB!"); return false; } if(getAuthoredStory(story.getId())) { Log.v(TAG, "Story already in AuthoredStory table"); return true; } ContentValues values = new ContentValues(); values.put(COLUMN_GUID, story.getId().toString()); long insert = db.insert(AUTHORED_STORIES_TABLE_NAME, null, values); db.close(); return insert != -1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStory(java.util.UUID) */ public boolean deleteStory(UUID id) { boolean fragments; fragments = deleteStoryFragments(id); deleteBookmarkByStory(id); SQLiteDatabase db = mDbHelper.getWritableDatabase(); int story; story = db.delete(STORY_TABLE_NAME, COLUMN_GUID + " = ?", new String[] {id.toString()}); Log.v(TAG, story + " deleted, had UUID " + id); db.close(); return story == 1 && fragments; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStoryFragments(java.util.UUID) */ public boolean deleteStoryFragments(UUID storyID) { int fragments; deleteBookmarkByStory(storyID); SQLiteDatabase db = mDbHelper.getWritableDatabase(); fragments = db.delete(STORYFRAGMENT_TABLE_NAME, STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[] {storyID.toString()}); Log.v(TAG, fragments + " deleted from DB, all with StoryID " + storyID); db.close(); return fragments > 0; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStoryFragment(java.util.UUID) */ public boolean deleteStoryFragment(UUID fragmentID) { int fragment; deleteBookmarkByFragment(fragmentID); SQLiteDatabase db = mDbHelper.getWritableDatabase(); fragment = db.delete(STORYFRAGMENT_TABLE_NAME, COLUMN_GUID + " = ?", new String[] {fragmentID.toString()}); Log.v(TAG, fragment + " fragment deleted, with fragmentID " + fragmentID); db.close(); return fragment == 1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteBookmarkByStory(java.util.UUID) */ public boolean deleteBookmarkByStory(UUID storyID) { int bookmark; SQLiteDatabase db = mDbHelper.getWritableDatabase(); bookmark = db.delete(BOOKMARK_TABLE_NAME, BOOKMARK_COLUMN_STORYID + " = ?", new String[] {storyID.toString()}); Log.v(TAG, bookmark + " bookmark deleted, with storyID " + storyID); db.close(); return bookmark == 1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteBookmarkByFragment(java.util.UUID) */ public boolean deleteBookmarkByFragment(UUID fragmentID) { int bookmark; SQLiteDatabase db = mDbHelper.getWritableDatabase(); bookmark = db.delete(BOOKMARK_TABLE_NAME, BOOKMARK_COLUMN_FRAGMENTID + " = ?", new String[] {fragmentID.toString()}); Log.v(TAG, bookmark + " bookmark deleted, with fragmentID " + fragmentID); db.close(); return bookmark == 1; } /** * Creates story from a cursor * * @param cursor A Cursor pointing to a Story * * @return A Story instance from the Database */ private Story createStory(Cursor cursor) { String title, author, synopsis, thumbnail; UUID headFragmentId, id; long timestamp; id = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.COLUMN_GUID))); title = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_TITLE)); headFragmentId = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_HEAD_FRAGMENT))); author = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_AUTHOR)); synopsis = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_SYNOPSIS)); thumbnail = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_THUMBNAIL)); timestamp = cursor.getLong(cursor.getColumnIndex(StoryDB.STORY_COLUMN_TIMESTAMP)); Story newStory = new Story(headFragmentId, id, author, timestamp, synopsis, thumbnail, title); ArrayList<StoryFragment> referencedFragments = this.getStoryFragments(id); for(StoryFragment frag : referencedFragments) { newStory.addFragment(frag); } return newStory; } /** * Creates a StoryFragment from a cursor * * @param cursor A Cursor pointing to a StoryFragment * * @return A StoryFragment instance from the Database */ private StoryFragment createStoryFragment(Cursor cursor) { UUID storyID, fragmentID; String storyText; ArrayList<Choice> choices; storyID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_STORYID))); fragmentID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.COLUMN_GUID))); storyText = cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_CONTENT)); /* TODO figure out JSON serialization for choices and media */ String json = cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_CHOICES)); Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<Choice>>(){}.getType(); choices = gson.fromJson(json, collectionType); return new StoryFragment(choices, storyID, fragmentID, storyText); } /** * Creates a Bookmark from a cursor * * @param cursor A Cursor pointing to a Bookmark * * @return A Bookmark instance from the Database */ private Bookmark createBookmark(Cursor cursor) { UUID fragmentID, storyID; Date date; fragmentID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.BOOKMARK_COLUMN_FRAGMENTID))); storyID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.BOOKMARK_COLUMN_STORYID))); long unix = cursor.getLong(cursor.getColumnIndex(StoryDB.BOOKMARK_COLUMN_DATE)); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(unix); date = cal.getTime(); return new Bookmark(fragmentID, storyID, date); } public class StoryDBHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 5; public static final String DATABASE_NAME = "adventure.database"; private static final String TAG = "StoryDBHelper"; private static final String CREATE_STORY_TABLE = "CREATE TABLE " + STORY_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_GUID + " TEXT, " + STORY_COLUMN_TITLE + " TEXT, " + STORY_COLUMN_AUTHOR + " TEXT, " + STORY_COLUMN_SYNOPSIS + " TEXT, " + STORY_COLUMN_HEAD_FRAGMENT + " INTEGER, " + STORY_COLUMN_TIMESTAMP + " INTEGER, " + STORY_COLUMN_THUMBNAIL + " TEXT, " + "FOREIGN KEY(" + STORY_COLUMN_HEAD_FRAGMENT + ") REFERENCES " + STORYFRAGMENT_TABLE_NAME + "(" + COLUMN_GUID + ") )"; private static final String CREATE_STORYFRAGMENT_TABLE = "CREATE TABLE " + STORYFRAGMENT_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_GUID + " TEXT, " + STORYFRAGMENT_COLUMN_STORYID + " INTEGER, " + STORYFRAGMENT_COLUMN_CONTENT + " TEXT, " + STORYFRAGMENT_COLUMN_CHOICES + " BLOB, " + "FOREIGN KEY(" + STORYFRAGMENT_COLUMN_STORYID + ") REFERENCES " + STORY_TABLE_NAME + "(" + COLUMN_GUID + "))"; private static final String CREATE_BOOKMARK_TABLE = "CREATE TABLE " + BOOKMARK_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + BOOKMARK_COLUMN_FRAGMENTID + " INTEGER, " + BOOKMARK_COLUMN_STORYID + " INTEGER, " + BOOKMARK_COLUMN_DATE + " INTEGER, " + "FOREIGN KEY(" + BOOKMARK_COLUMN_FRAGMENTID + ") REFERENCES " + STORYFRAGMENT_TABLE_NAME + "(" + COLUMN_GUID + "), FOREIGN KEY (" + BOOKMARK_COLUMN_STORYID + ") REFERENCES " + STORY_TABLE_NAME + "(" + COLUMN_GUID + "))"; private static final String CREATE_AUTHORED_STORIES_TABLE = "CREATE TABLE " + AUTHORED_STORIES_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_GUID + " TEXT, " + "FOREIGN KEY(" + COLUMN_GUID + ") REFERENCES " + STORY_TABLE_NAME + "(" + COLUMN_GUID + "))"; private static final String DELETE_STORY_TABLE = "DROP TABLE IF EXISTS " + STORY_TABLE_NAME; private static final String DELETE_STORYFRAGMENT_TABLE = "DROP TABLE IF EXISTS " + STORYFRAGMENT_TABLE_NAME; private static final String DELETE_BOOKMARK_TABLE = "DROP TABLE IF EXISTS " + BOOKMARK_TABLE_NAME; private static final String DELETE_AUTHORED_STORIES_TABLE = "DROP TABLE IF EXISTS " + AUTHORED_STORIES_TABLE_NAME; public StoryDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.v(TAG, "Creating DB"); db.execSQL(CREATE_STORY_TABLE); db.execSQL(CREATE_STORYFRAGMENT_TABLE); db.execSQL(CREATE_BOOKMARK_TABLE); db.execSQL(CREATE_AUTHORED_STORIES_TABLE); populateDB(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DELETE_STORYFRAGMENT_TABLE); db.execSQL(DELETE_STORY_TABLE); db.execSQL(DELETE_BOOKMARK_TABLE); db.execSQL(DELETE_AUTHORED_STORIES_TABLE); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } private void populateDB(SQLiteDatabase db) { Bitmap bit = Bitmap.createBitmap(new int[]{Color.BLACK}, 1, 1, Bitmap.Config.ARGB_8888); Story story = new Story(UUID.fromString("5582f797-29b8-4d9d-83bf-88c434c1944a"), UUID.fromString("fc662870-5d6a-4ae2-98f6-0cdfe36013bb"), "Andrew", 706232100, "A tale of romance and might", bit, "Super Kewl Story, GUIZ"); String storyText = "You wake up. The room is spinning very gently round your head. Or at least it would be " + "if you could see it which you can't"; StoryFragment frag = new StoryFragment(story.getId(), UUID.fromString("5582f797-29b8-4d9d-83bf-88c434c1944a"), storyText, new ArrayList<Uri>(), new ArrayList<Choice>()); StoryFragment frag2 = new StoryFragment(story.getId(), UUID.fromString("b10ef8ca-1180-44f6-b11b-170fef5ec071"), "You break" + " your neck in the dark.", new ArrayList<Uri>(), new ArrayList<Choice>()); Choice choice = new Choice("Get out of bed", frag2.getFragmentID()); frag.addChoice(choice); story.addFragment(frag); story.addFragment(frag2); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(1383652800L * 1000L); Bookmark bookmark = new Bookmark(frag2.getFragmentID(), story.getId(), cal.getTime()); db.beginTransaction(); long inserted; ContentValues values = new ContentValues(); values.put(STORY_COLUMN_TITLE, story.getTitle()); values.put(STORY_COLUMN_AUTHOR, story.getAuthor()); values.put(STORY_COLUMN_HEAD_FRAGMENT, story.getHeadFragmentId().toString()); values.put(STORY_COLUMN_SYNOPSIS, story.getSynopsis()); values.put(STORY_COLUMN_TIMESTAMP, story.getTimestamp()); values.put(STORY_COLUMN_THUMBNAIL, story.getThumbnail().getEncodedBitmap()); values.put(COLUMN_GUID, story.getId().toString()); inserted = db.insert(STORY_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(STORYFRAGMENT_COLUMN_STORYID, frag.getStoryID().toString()); values.put(STORYFRAGMENT_COLUMN_CONTENT, frag.getStoryText()); values.put(STORYFRAGMENT_COLUMN_CHOICES, frag.getChoicesInJson()); values.put(COLUMN_GUID, frag.getFragmentID().toString()); inserted = db.insert(STORYFRAGMENT_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(STORYFRAGMENT_COLUMN_STORYID, frag2.getStoryID().toString()); values.put(STORYFRAGMENT_COLUMN_CONTENT, frag2.getStoryText()); values.put(STORYFRAGMENT_COLUMN_CHOICES, frag2.getChoicesInJson()); values.put(COLUMN_GUID, frag2.getFragmentID().toString()); inserted = db.insert(STORYFRAGMENT_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(BOOKMARK_COLUMN_STORYID, bookmark.getStoryID().toString()); values.put(BOOKMARK_COLUMN_FRAGMENTID, bookmark.getFragmentID().toString()); values.put(BOOKMARK_COLUMN_DATE, bookmark.getDate().getTime() / 1000L); inserted = db.insert(BOOKMARK_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(COLUMN_GUID, story.getId().toString()); inserted = db.insert(AUTHORED_STORIES_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); db.setTransactionSuccessful(); db.endTransaction(); } } }
adventure.datetime/src/ca/cmput301f13t03/adventure_datetime/model/StoryDB.java
/* * Copyright (c) 2013 Andrew Fontaine, James Finlay, Jesse Tucker, Jacob Viau, and * Evan DeGraff * * 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 ca.cmput301f13t03.adventure_datetime.model; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.UUID; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ILocalStorage; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * The local database containing all stories, fragments, bookmarks, and subscriptions * * @author Andrew Fontaine * @version 1.0 * @since 28/10/13 */ public class StoryDB implements BaseColumns, ILocalStorage { private static final String TAG = "StoryDB"; public static final String COLUMN_GUID = "GUID"; public static final String STORY_TABLE_NAME = "Story"; public static final String STORY_COLUMN_AUTHOR = "Author"; public static final String STORY_COLUMN_HEAD_FRAGMENT = "HeadFragment"; public static final String STORY_COLUMN_TIMESTAMP = "Timestamp"; public static final String STORY_COLUMN_SYNOPSIS = "Synopsis"; public static final String STORY_COLUMN_THUMBNAIL = "Thumbnail"; public static final String STORY_COLUMN_TITLE = "Title"; public static final String STORYFRAGMENT_TABLE_NAME = "StoryFragment"; public static final String STORYFRAGMENT_COLUMN_STORYID = "StoryID"; public static final String STORYFRAGMENT_COLUMN_CONTENT = "Content"; public static final String STORYFRAGMENT_COLUMN_CHOICES = "Choices"; public static final String BOOKMARK_TABLE_NAME = "Bookmark"; public static final String BOOKMARK_COLUMN_STORYID = "StoryID"; public static final String BOOKMARK_COLUMN_FRAGMENTID = "FragmentID"; public static final String BOOKMARK_COLUMN_DATE = "Date"; public static final String AUTHORED_STORIES_TABLE_NAME = "AuthoredStories"; private StoryDBHelper mDbHelper; public StoryDB(Context context) { mDbHelper = new StoryDBHelper(context); } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStory(java.util.UUID) */ @Override public Story getStory(UUID id) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORY_TABLE_NAME, new String[]{_ID, COLUMN_GUID, STORY_COLUMN_TITLE, STORY_COLUMN_AUTHOR, STORY_COLUMN_TITLE, STORY_COLUMN_HEAD_FRAGMENT, STORY_COLUMN_SYNOPSIS, STORY_COLUMN_TIMESTAMP, STORY_COLUMN_THUMBNAIL}, COLUMN_GUID + " = ?", new String[] {id.toString()}, null, null, null, "1"); Story story; if (cursor.moveToFirst()) { Log.v(TAG, "Story with UUID " + id + " retrieved"); story = createStory(cursor); } else { story = null; Log.v(TAG, "No story found"); } cursor.close(); db.close(); return story; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStories() */ @Override public ArrayList<Story> getStories() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORY_TABLE_NAME, new String[] {_ID, COLUMN_GUID, STORY_COLUMN_AUTHOR, STORY_COLUMN_TITLE, STORY_COLUMN_HEAD_FRAGMENT, STORY_COLUMN_SYNOPSIS, STORY_COLUMN_TIMESTAMP, STORY_COLUMN_THUMBNAIL}, null, null, null, null, null); ArrayList<Story> stories = new ArrayList<Story>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "Story with id " + cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) + " retrieved"); stories.add(createStory(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, stories.size() + " stories retrieved"); cursor.close(); db.close(); return stories; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStoriesAuthoredBy(java.lang.String) */ @Override public ArrayList<Story> getStoriesAuthoredBy(String author) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORY_TABLE_NAME, new String[]{_ID, COLUMN_GUID, STORY_COLUMN_AUTHOR, STORY_COLUMN_HEAD_FRAGMENT, STORY_COLUMN_SYNOPSIS, STORY_COLUMN_TIMESTAMP, STORY_COLUMN_THUMBNAIL}, STORY_COLUMN_AUTHOR + " = ?", new String[] {author}, null, null, null); ArrayList<Story> stories = new ArrayList<Story>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "Story with id " + cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) + " retrieved"); stories.add(createStory(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, stories.size() + " stories retrieved"); cursor.close(); db.close(); return stories; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStoryFragment(java.util.UUID) */ @Override public StoryFragment getStoryFragment(UUID id) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORYFRAGMENT_TABLE_NAME, new String[] {_ID, COLUMN_GUID, STORYFRAGMENT_COLUMN_STORYID, STORYFRAGMENT_COLUMN_CHOICES, STORYFRAGMENT_COLUMN_CONTENT}, COLUMN_GUID + " = ?", new String[] {id.toString()}, null, null, "1"); StoryFragment frag; if(cursor.moveToFirst()) { Log.v(TAG, "StoryFragment " + id + " retrieved"); frag = createStoryFragment(cursor); } else { frag = null; Log.v(TAG, "No fragment found"); } cursor.close(); db.close(); return frag; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getStoryFragments(java.util.UUID) */ @Override public ArrayList<StoryFragment> getStoryFragments(UUID storyid) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(STORYFRAGMENT_TABLE_NAME, new String[]{_ID, COLUMN_GUID, STORYFRAGMENT_COLUMN_STORYID, STORYFRAGMENT_COLUMN_CHOICES, STORYFRAGMENT_COLUMN_CONTENT}, STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[]{storyid.toString()}, null, null, null); ArrayList<StoryFragment> fragments = new ArrayList<StoryFragment>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "StoryFragment with id " + cursor.getString(cursor.getColumnIndex(COLUMN_GUID)) + " retrieved"); fragments.add(createStoryFragment(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, fragments.size() + " StoryFragments retrieved"); cursor.close(); db.close(); return fragments; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getBookmark(java.util.UUID) */ @Override public Bookmark getBookmark(UUID storyid) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(BOOKMARK_TABLE_NAME, new String[] {_ID, BOOKMARK_COLUMN_STORYID, BOOKMARK_COLUMN_FRAGMENTID, BOOKMARK_COLUMN_DATE}, BOOKMARK_COLUMN_STORYID + " = ?", new String[] {storyid.toString()}, null, null, null); Bookmark bookmark; if(cursor.moveToFirst()) { Log.v(TAG, "Bookmark with Story id " + cursor.getString(cursor.getColumnIndex(BOOKMARK_COLUMN_STORYID)) + "retrieved"); bookmark = createBookmark(cursor); } else { Log.v(TAG, "No bookmark found"); bookmark = null; } cursor.close(); db.close(); return bookmark; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#getAllBookmarks() */ @Override public ArrayList<Bookmark> getAllBookmarks() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(BOOKMARK_TABLE_NAME, new String[] {BOOKMARK_COLUMN_STORYID, BOOKMARK_COLUMN_FRAGMENTID, BOOKMARK_COLUMN_DATE}, null, null, null, null, null); ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>(); if(cursor.moveToFirst()) { do { Log.v(TAG, "Bookmark with Story id " + cursor.getString(cursor.getColumnIndex(BOOKMARK_COLUMN_STORYID)) + " retrieved"); bookmarks.add(createBookmark(cursor)); } while(cursor.moveToNext()); } Log.v(TAG, bookmarks.size() + " bookmarks retrieved"); return bookmarks; } public boolean getAuthoredStory(UUID storyId) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(AUTHORED_STORIES_TABLE_NAME, new String[] {COLUMN_GUID}, COLUMN_GUID + " = ?", new String[] {storyId.toString()}, null, null, null); boolean authoredStory = cursor.moveToFirst(); cursor.close(); db.close(); return authoredStory; } public ArrayList<UUID> getAuthoredStories() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(AUTHORED_STORIES_TABLE_NAME, new String[] {COLUMN_GUID}, null, null, null, null, null); ArrayList<UUID> authoredStories = new ArrayList<UUID>(); if(cursor.moveToFirst()) { do { authoredStories.add(UUID.fromString(cursor.getString(cursor.getColumnIndex(COLUMN_GUID)))); } while(cursor.moveToNext()); } cursor.close(); db.close(); return authoredStories; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#setBookmark(ca.cmput301f13t03.adventure_datetime.model.Bookmark) */ @Override public boolean setBookmark(Bookmark bookmark) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); Cursor cursor = db.query(BOOKMARK_TABLE_NAME, new String[] {_ID, BOOKMARK_COLUMN_FRAGMENTID, BOOKMARK_COLUMN_STORYID, BOOKMARK_COLUMN_DATE}, BOOKMARK_COLUMN_STORYID + " = ?", new String[] {bookmark.getStoryID().toString()}, null, null, null); ContentValues values = new ContentValues(); values.put(BOOKMARK_COLUMN_STORYID, bookmark.getStoryID().toString()); values.put(BOOKMARK_COLUMN_FRAGMENTID, bookmark.getFragmentID().toString()); values.put(BOOKMARK_COLUMN_DATE, bookmark.getDate().getTime()/1000); long updated; if(cursor.moveToFirst()) { Bookmark bookmark1 = createBookmark(cursor); if(bookmark.getDate().compareTo(bookmark1.getDate()) > 0) { updated = db.update(BOOKMARK_TABLE_NAME,values,BOOKMARK_COLUMN_STORYID + " = ?", new String[] {BOOKMARK_COLUMN_STORYID}); Log.v(TAG, updated + " Bookmarks updated"); cursor.close(); db.close(); return updated == 1; } Log.v(TAG, "No Bookmarks updated"); cursor.close(); db.close(); return false; } updated = db.insert(BOOKMARK_TABLE_NAME, null, values); Log.v(TAG, updated + " Bookmark inserted"); cursor.close(); db.close(); return updated != -1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#setStory(ca.cmput301f13t03.adventure_datetime.model.Story) */ @Override public boolean setStory(Story story) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(STORY_COLUMN_TITLE, story.getTitle()); values.put(STORY_COLUMN_AUTHOR, story.getAuthor()); values.put(STORY_COLUMN_HEAD_FRAGMENT, story.getHeadFragmentId().toString()); values.put(STORY_COLUMN_SYNOPSIS, story.getSynopsis()); values.put(STORY_COLUMN_TIMESTAMP, story.getTimestamp()); values.put(STORY_COLUMN_THUMBNAIL, (story.getThumbnail() == null ? null : story.getThumbnail().getEncodedBitmap())); values.put(COLUMN_GUID, story.getId().toString()); Cursor cursor = db.query(STORY_TABLE_NAME, new String[] {_ID}, COLUMN_GUID + " = ?", new String[] {story.getId().toString()}, null, null, null); if(cursor.moveToFirst()) { int updated; updated = db.update(STORY_TABLE_NAME, values, COLUMN_GUID + " = ?", new String [] {story.getId().toString()}); Log.v(TAG, updated + " stories updated"); cursor.close(); db.close(); return updated == 1; } cursor.close(); long inserted; inserted = db.insert(STORY_TABLE_NAME, null, values); Log.v(TAG, inserted + " story inserted"); db.close(); return inserted != -1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#setStoryFragment(ca.cmput301f13t03.adventure_datetime.model.StoryFragment) */ @Override public boolean setStoryFragment(StoryFragment frag) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(STORYFRAGMENT_COLUMN_STORYID, frag.getStoryID().toString()); values.put(STORYFRAGMENT_COLUMN_CONTENT, frag.getStoryText()); values.put(STORYFRAGMENT_COLUMN_CHOICES, frag.getChoicesInJson()); values.put(COLUMN_GUID, frag.getFragmentID().toString()); Cursor cursor = db.query(STORYFRAGMENT_TABLE_NAME, new String[] {_ID, STORYFRAGMENT_COLUMN_STORYID}, COLUMN_GUID + " = ? AND " + STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[] {frag.getFragmentID().toString(), frag.getStoryID().toString()}, null, null, null); if(cursor.moveToFirst()) { int updated; updated = db.update(STORYFRAGMENT_TABLE_NAME, values, COLUMN_GUID + " = ? AND " + STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[] {frag.getFragmentID().toString(), frag.getStoryID().toString()}); Log.v(TAG, updated + " fragments updated"); cursor.close(); db.close(); return updated == 1; } long inserted; inserted = db.insert(STORYFRAGMENT_TABLE_NAME, null, values); Log.v(TAG, inserted + " fragment inserted"); db.close(); return inserted != -1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStory(java.util.UUID) */ public boolean deleteStory(UUID id) { boolean fragments; fragments = deleteStoryFragments(id); deleteBookmarkByStory(id); SQLiteDatabase db = mDbHelper.getWritableDatabase(); int story; story = db.delete(STORY_TABLE_NAME, COLUMN_GUID + " = ?", new String[] {id.toString()}); Log.v(TAG, story + " deleted, had UUID " + id); db.close(); return story == 1 && fragments; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStoryFragments(java.util.UUID) */ public boolean deleteStoryFragments(UUID storyID) { int fragments; deleteBookmarkByStory(storyID); SQLiteDatabase db = mDbHelper.getWritableDatabase(); fragments = db.delete(STORYFRAGMENT_TABLE_NAME, STORYFRAGMENT_COLUMN_STORYID + " = ?", new String[] {storyID.toString()}); Log.v(TAG, fragments + " deleted from DB, all with StoryID " + storyID); db.close(); return fragments > 0; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStoryFragment(java.util.UUID) */ public boolean deleteStoryFragment(UUID fragmentID) { int fragment; deleteBookmarkByFragment(fragmentID); SQLiteDatabase db = mDbHelper.getWritableDatabase(); fragment = db.delete(STORYFRAGMENT_TABLE_NAME, COLUMN_GUID + " = ?", new String[] {fragmentID.toString()}); Log.v(TAG, fragment + " fragment deleted, with fragmentID " + fragmentID); db.close(); return fragment == 1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteBookmarkByStory(java.util.UUID) */ public boolean deleteBookmarkByStory(UUID storyID) { int bookmark; SQLiteDatabase db = mDbHelper.getWritableDatabase(); bookmark = db.delete(BOOKMARK_TABLE_NAME, BOOKMARK_COLUMN_STORYID + " = ?", new String[] {storyID.toString()}); Log.v(TAG, bookmark + " bookmark deleted, with storyID " + storyID); db.close(); return bookmark == 1; } /* (non-Javadoc) * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteBookmarkByFragment(java.util.UUID) */ public boolean deleteBookmarkByFragment(UUID fragmentID) { int bookmark; SQLiteDatabase db = mDbHelper.getWritableDatabase(); bookmark = db.delete(BOOKMARK_TABLE_NAME, BOOKMARK_COLUMN_FRAGMENTID + " = ?", new String[] {fragmentID.toString()}); Log.v(TAG, bookmark + " bookmark deleted, with fragmentID " + fragmentID); db.close(); return bookmark == 1; } /** * Creates story from a cursor * * @param cursor A Cursor pointing to a Story * * @return A Story instance from the Database */ private Story createStory(Cursor cursor) { String title, author, synopsis, thumbnail; UUID headFragmentId, id; long timestamp; id = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.COLUMN_GUID))); title = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_TITLE)); headFragmentId = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_HEAD_FRAGMENT))); author = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_AUTHOR)); synopsis = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_SYNOPSIS)); thumbnail = cursor.getString(cursor.getColumnIndex(StoryDB.STORY_COLUMN_THUMBNAIL)); timestamp = cursor.getLong(cursor.getColumnIndex(StoryDB.STORY_COLUMN_TIMESTAMP)); Story newStory = new Story(headFragmentId, id, author, timestamp, synopsis, thumbnail, title); ArrayList<StoryFragment> referencedFragments = this.getStoryFragments(id); for(StoryFragment frag : referencedFragments) { newStory.addFragment(frag); } return newStory; } /** * Creates a StoryFragment from a cursor * * @param cursor A Cursor pointing to a StoryFragment * * @return A StoryFragment instance from the Database */ private StoryFragment createStoryFragment(Cursor cursor) { UUID storyID, fragmentID; String storyText; ArrayList<Choice> choices; storyID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_STORYID))); fragmentID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.COLUMN_GUID))); storyText = cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_CONTENT)); /* TODO figure out JSON serialization for choices and media */ String json = cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_CHOICES)); Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<Choice>>(){}.getType(); choices = gson.fromJson(json, collectionType); return new StoryFragment(choices, storyID, fragmentID, storyText); } /** * Creates a Bookmark from a cursor * * @param cursor A Cursor pointing to a Bookmark * * @return A Bookmark instance from the Database */ private Bookmark createBookmark(Cursor cursor) { UUID fragmentID, storyID; Date date; fragmentID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.BOOKMARK_COLUMN_FRAGMENTID))); storyID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.BOOKMARK_COLUMN_STORYID))); long unix = cursor.getLong(cursor.getColumnIndex(StoryDB.BOOKMARK_COLUMN_DATE)); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(unix); date = cal.getTime(); return new Bookmark(fragmentID, storyID, date); } public class StoryDBHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 5; public static final String DATABASE_NAME = "adventure.database"; private static final String TAG = "StoryDBHelper"; private static final String CREATE_STORY_TABLE = "CREATE TABLE " + STORY_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_GUID + " TEXT, " + STORY_COLUMN_TITLE + " TEXT, " + STORY_COLUMN_AUTHOR + " TEXT, " + STORY_COLUMN_SYNOPSIS + " TEXT, " + STORY_COLUMN_HEAD_FRAGMENT + " INTEGER, " + STORY_COLUMN_TIMESTAMP + " INTEGER, " + STORY_COLUMN_THUMBNAIL + " TEXT, " + "FOREIGN KEY(" + STORY_COLUMN_HEAD_FRAGMENT + ") REFERENCES " + STORYFRAGMENT_TABLE_NAME + "(" + COLUMN_GUID + ") )"; private static final String CREATE_STORYFRAGMENT_TABLE = "CREATE TABLE " + STORYFRAGMENT_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_GUID + " TEXT, " + STORYFRAGMENT_COLUMN_STORYID + " INTEGER, " + STORYFRAGMENT_COLUMN_CONTENT + " TEXT, " + STORYFRAGMENT_COLUMN_CHOICES + " BLOB, " + "FOREIGN KEY(" + STORYFRAGMENT_COLUMN_STORYID + ") REFERENCES " + STORY_TABLE_NAME + "(" + COLUMN_GUID + "))"; private static final String CREATE_BOOKMARK_TABLE = "CREATE TABLE " + BOOKMARK_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + BOOKMARK_COLUMN_FRAGMENTID + " INTEGER, " + BOOKMARK_COLUMN_STORYID + " INTEGER, " + BOOKMARK_COLUMN_DATE + " INTEGER, " + "FOREIGN KEY(" + BOOKMARK_COLUMN_FRAGMENTID + ") REFERENCES " + STORYFRAGMENT_TABLE_NAME + "(" + COLUMN_GUID + "), FOREIGN KEY (" + BOOKMARK_COLUMN_STORYID + ") REFERENCES " + STORY_TABLE_NAME + "(" + COLUMN_GUID + "))"; private static final String CREATE_AUTHORED_STORIES_TABLE = "CREATE TABLE " + AUTHORED_STORIES_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY, " + COLUMN_GUID + " TEXT, " + "FOREIGN KEY(" + COLUMN_GUID + ") REFERENCES " + STORY_TABLE_NAME + "(" + COLUMN_GUID + "))"; private static final String DELETE_STORY_TABLE = "DROP TABLE IF EXISTS " + STORY_TABLE_NAME; private static final String DELETE_STORYFRAGMENT_TABLE = "DROP TABLE IF EXISTS " + STORYFRAGMENT_TABLE_NAME; private static final String DELETE_BOOKMARK_TABLE = "DROP TABLE IF EXISTS " + BOOKMARK_TABLE_NAME; private static final String DELETE_AUTHORED_STORIES_TABLE = "DROP TABLE IF EXISTS " + AUTHORED_STORIES_TABLE_NAME; public StoryDBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.v(TAG, "Creating DB"); db.execSQL(CREATE_STORY_TABLE); db.execSQL(CREATE_STORYFRAGMENT_TABLE); db.execSQL(CREATE_BOOKMARK_TABLE); db.execSQL(CREATE_AUTHORED_STORIES_TABLE); populateDB(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DELETE_STORYFRAGMENT_TABLE); db.execSQL(DELETE_STORY_TABLE); db.execSQL(DELETE_BOOKMARK_TABLE); db.execSQL(DELETE_AUTHORED_STORIES_TABLE); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } private void populateDB(SQLiteDatabase db) { Bitmap bit = Bitmap.createBitmap(new int[]{Color.BLACK}, 1, 1, Bitmap.Config.ARGB_8888); Story story = new Story(UUID.fromString("5582f797-29b8-4d9d-83bf-88c434c1944a"), UUID.fromString("fc662870-5d6a-4ae2-98f6-0cdfe36013bb"), "Andrew", 706232100, "A tale of romance and might", bit, "Super Kewl Story, GUIZ"); String storyText = "You wake up. The room is spinning very gently round your head. Or at least it would be " + "if you could see it which you can't"; StoryFragment frag = new StoryFragment(story.getId(), UUID.fromString("5582f797-29b8-4d9d-83bf-88c434c1944a"), storyText, new ArrayList<Uri>(), new ArrayList<Choice>()); StoryFragment frag2 = new StoryFragment(story.getId(), UUID.fromString("b10ef8ca-1180-44f6-b11b-170fef5ec071"), "You break" + " your neck in the dark.", new ArrayList<Uri>(), new ArrayList<Choice>()); Choice choice = new Choice("Get out of bed", frag2.getFragmentID()); frag.addChoice(choice); story.addFragment(frag); story.addFragment(frag2); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(1383652800L * 1000L); Bookmark bookmark = new Bookmark(frag2.getFragmentID(), story.getId(), cal.getTime()); db.beginTransaction(); long inserted; ContentValues values = new ContentValues(); values.put(STORY_COLUMN_TITLE, story.getTitle()); values.put(STORY_COLUMN_AUTHOR, story.getAuthor()); values.put(STORY_COLUMN_HEAD_FRAGMENT, story.getHeadFragmentId().toString()); values.put(STORY_COLUMN_SYNOPSIS, story.getSynopsis()); values.put(STORY_COLUMN_TIMESTAMP, story.getTimestamp()); values.put(STORY_COLUMN_THUMBNAIL, story.getThumbnail().getEncodedBitmap()); values.put(COLUMN_GUID, story.getId().toString()); inserted = db.insert(STORY_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(STORYFRAGMENT_COLUMN_STORYID, frag.getStoryID().toString()); values.put(STORYFRAGMENT_COLUMN_CONTENT, frag.getStoryText()); values.put(STORYFRAGMENT_COLUMN_CHOICES, frag.getChoicesInJson()); values.put(COLUMN_GUID, frag.getFragmentID().toString()); inserted = db.insert(STORYFRAGMENT_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(STORYFRAGMENT_COLUMN_STORYID, frag2.getStoryID().toString()); values.put(STORYFRAGMENT_COLUMN_CONTENT, frag2.getStoryText()); values.put(STORYFRAGMENT_COLUMN_CHOICES, frag2.getChoicesInJson()); values.put(COLUMN_GUID, frag2.getFragmentID().toString()); inserted = db.insert(STORYFRAGMENT_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(BOOKMARK_COLUMN_STORYID, bookmark.getStoryID().toString()); values.put(BOOKMARK_COLUMN_FRAGMENTID, bookmark.getFragmentID().toString()); values.put(BOOKMARK_COLUMN_DATE, bookmark.getDate().getTime() / 1000L); inserted = db.insert(BOOKMARK_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); values = new ContentValues(); values.put(COLUMN_GUID, story.getId().toString()); inserted = db.insert(AUTHORED_STORIES_TABLE_NAME, null, values); Log.d(TAG, String.valueOf(inserted)); db.setTransactionSuccessful(); db.endTransaction(); } } }
setAuthoredStory
adventure.datetime/src/ca/cmput301f13t03/adventure_datetime/model/StoryDB.java
setAuthoredStory
<ide><path>dventure.datetime/src/ca/cmput301f13t03/adventure_datetime/model/StoryDB.java <ide> return inserted != -1; <ide> <ide> } <add> <add> public boolean setAuthoredStory(Story story) { <add> SQLiteDatabase db = mDbHelper.getWritableDatabase(); <add> <add> Story story2 = getStory(story.getId()); <add> <add> if(story2 == null) { <add> Log.v(TAG, "Story doesn't exist in local DB!"); <add> return false; <add> } <add> <add> if(getAuthoredStory(story.getId())) { <add> Log.v(TAG, "Story already in AuthoredStory table"); <add> return true; <add> } <add> <add> ContentValues values = new ContentValues(); <add> <add> values.put(COLUMN_GUID, story.getId().toString()); <add> <add> long insert = db.insert(AUTHORED_STORIES_TABLE_NAME, null, values); <add> <add> db.close(); <add> <add> return insert != -1; <add> } <ide> <ide> /* (non-Javadoc) <ide> * @see ca.cmput301f13t03.adventure_datetime.model.ILocalDatabase#deleteStory(java.util.UUID)
JavaScript
apache-2.0
d0ab3687e6fef3c2313c84cf322228e3db142c56
0
mozilla/gcli,mozilla/gcli,joewalker/gcli,mozilla/gcli,joewalker/gcli
/* * Copyright 2012, Mozilla Foundation and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(function(require, exports, module) { 'use strict'; var promise = require('util/promise'); var util = require('util/util'); var l10n = require('util/l10n'); var view = require('gcli/ui/view'); var converters = require('gcli/converters'); var canon = require('gcli/canon'); var CommandOutputManager = require('gcli/canon').CommandOutputManager; var Status = require('gcli/types').Status; var Conversion = require('gcli/types').Conversion; var Argument = require('gcli/argument').Argument; var ArrayArgument = require('gcli/argument').ArrayArgument; var NamedArgument = require('gcli/argument').NamedArgument; var TrueNamedArgument = require('gcli/argument').TrueNamedArgument; var MergedArgument = require('gcli/argument').MergedArgument; var ScriptArgument = require('gcli/argument').ScriptArgument; /** * Some manual intervention is needed in parsing the { command. */ function getEvalCommand() { if (getEvalCommand._cmd == null) { getEvalCommand._cmd = canon.getCommand(evalCmd.name); } return getEvalCommand._cmd; } /** * Assignment is a link between a parameter and the data for that parameter. * The data for the parameter is available as in the preferred type and as * an Argument for the CLI. * <p>We also record validity information where applicable. * <p>For values, null and undefined have distinct definitions. null means * that a value has been provided, undefined means that it has not. * Thus, null is a valid default value, and common because it identifies an * parameter that is optional. undefined means there is no value from * the command line. * @constructor */ function Assignment(param, paramIndex) { // The parameter that we are assigning to this.param = param; this.conversion = undefined; // The index of this parameter in the parent Requisition. paramIndex === -1 // is the command assignment although this should not be relied upon, it is // better to test param instanceof CommandAssignment this.paramIndex = paramIndex; } /** * Easy accessor for conversion.arg. * This is a read-only property because writes to arg should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'arg', { get: function() { return this.conversion == null ? undefined : this.conversion.arg; }, enumerable: true }); /** * Easy accessor for conversion.value. * This is a read-only property because writes to value should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'value', { get: function() { return this.conversion == null ? undefined : this.conversion.value; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.message */ Object.defineProperty(Assignment.prototype, 'message', { get: function() { return this.conversion == null || !this.conversion.message ? '' : this.conversion.message; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.getPredictions() * @return An array of objects with name and value elements. For example: * [ { name:'bestmatch', value:foo1 }, { name:'next', value:foo2 }, ... ] */ Assignment.prototype.getPredictions = function() { return this.conversion == null ? [] : this.conversion.getPredictions(); }; /** * Accessor for a prediction by index. * This is useful above <tt>getPredictions()[index]</tt> because it normalizes * index to be within the bounds of the predictions, which means that the UI * can maintain an index of which prediction to choose without caring how many * predictions there are. * @param index The index of the prediction to choose */ Assignment.prototype.getPredictionAt = function(index) { if (index == null) { index = 0; } if (this.isInName()) { return promise.resolve(undefined); } return this.getPredictions().then(function(predictions) { if (predictions.length === 0) { return undefined; } index = index % predictions.length; if (index < 0) { index = predictions.length + index; } return predictions[index]; }.bind(this)); }; /** * Some places want to take special action if we are in the name part of a * named argument (i.e. the '--foo' bit). * Currently this does not take actual cursor position into account, it just * assumes that the cursor is at the end. In the future we will probably want * to take this into account. */ Assignment.prototype.isInName = function() { return this.conversion.arg.type === 'NamedArgument' && this.conversion.arg.prefix.slice(-1) !== ' '; }; /** * Work out what the status of the current conversion is which involves looking * not only at the conversion, but also checking if data has been provided * where it should. * @param arg For assignments with multiple args (e.g. array assignments) we * can narrow the search for status to a single argument. */ Assignment.prototype.getStatus = function(arg) { if (this.param.isDataRequired && !this.conversion.isDataProvided()) { return Status.INCOMPLETE; } // Selection/Boolean types with a defined range of values will say that // '' is INCOMPLETE, but the parameter may be optional, so we don't ask // if the user doesn't need to enter something and hasn't done so. if (!this.param.isDataRequired && this.arg.type === 'BlankArgument') { return Status.VALID; } return this.conversion.getStatus(arg); }; /** * Helper when we're rebuilding command lines. */ Assignment.prototype.toString = function() { return this.conversion.toString(); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Assignment.prototype, '_summaryJson', { get: function() { var predictionCount = '<async>'; this.getPredictions().then(function(predictions) { predictionCount = predictions.length; }, console.log); return { param: this.param.name + '/' + this.param.type.name, defaultValue: this.param.defaultValue, arg: this.conversion.arg._summaryJson, value: this.value, message: this.message, status: this.getStatus().toString(), predictionCount: predictionCount }; }, enumerable: true }); exports.Assignment = Assignment; /** * How to dynamically execute JavaScript code */ var customEval = eval; /** * Setup a function to be called in place of 'eval', generally for security * reasons */ exports.setEvalFunction = function(newCustomEval) { customEval = newCustomEval; }; /** * Remove the binding done by setEvalFunction(). * We purposely set customEval to undefined rather than to 'eval' because there * is an implication of setEvalFunction that we're in a security sensitive * situation. What if we can trick GCLI into calling unsetEvalFunction() at the * wrong time? * So to properly undo the effects of setEvalFunction(), you need to call * setEvalFunction(eval) rather than unsetEvalFunction(), however the latter is * preferred in most cases. */ exports.unsetEvalFunction = function() { customEval = undefined; }; /** * 'eval' command */ var evalCmd = { item: 'command', name: '{', params: [ { name: 'javascript', type: 'javascript', description: '' } ], hidden: true, returnType: 'object', description: { key: 'cliEvalJavascript' }, exec: function(args, context) { return customEval(args.javascript); }, isCommandRegexp: /^\s*{\s*/ }; exports.items = [ evalCmd ]; /** * This is a special assignment to reflect the command itself. */ function CommandAssignment() { var commandParamMetadata = { name: '__command', type: { name: 'command', allowNonExec: false } }; // This is a hack so that rather than reply with a generic description of the // command assignment, we reply with the description of the assigned command, // (using a generic term if there is no assigned command) var self = this; Object.defineProperty(commandParamMetadata, 'description', { get: function() { var value = self.value; return value && value.description ? value.description : 'The command to execute'; }, enumerable: true }); this.param = new canon.Parameter(commandParamMetadata); this.paramIndex = -1; } CommandAssignment.prototype = Object.create(Assignment.prototype); CommandAssignment.prototype.getStatus = function(arg) { return Status.combine( Assignment.prototype.getStatus.call(this, arg), this.conversion.value && this.conversion.value.exec ? Status.VALID : Status.INCOMPLETE ); }; exports.CommandAssignment = CommandAssignment; /** * Special assignment used when ignoring parameters that don't have a home */ function UnassignedAssignment(requisition, arg) { this.param = new canon.Parameter({ name: '__unassigned', description: l10n.lookup('cliOptions'), type: { name: 'param', requisition: requisition, isIncompleteName: (arg.text.charAt(0) === '-') } }); this.paramIndex = -1; // synchronize is ok because we can be sure that param type is synchronous var parsed = this.param.type.parse(arg, requisition.executionContext); this.conversion = util.synchronize(parsed); this.conversion.assignment = this; } UnassignedAssignment.prototype = Object.create(Assignment.prototype); UnassignedAssignment.prototype.getStatus = function(arg) { return this.conversion.getStatus(); }; exports.logErrors = true; /** * A Requisition collects the information needed to execute a command. * * (For a definition of the term, see http://en.wikipedia.org/wiki/Requisition) * This term is used because carries the notion of a work-flow, or process to * getting the information to execute a command correct. * There is little point in a requisition for parameter-less commands because * there is no information to collect. A Requisition is a collection of * assignments of values to parameters, each handled by an instance of * Assignment. * * <h2>Events<h2> * <p>Requisition publishes the following events: * <ul> * <li>onTextChange: The text to be mirrored in a command line has changed. * </ul> * * @param environment An optional opaque object passed to commands in the * Execution Context. * @param doc A DOM Document passed to commands using the Execution Context in * order to allow creation of DOM nodes. If missing Requisition will use the * global 'document'. * @param commandOutputManager A custom commandOutputManager to which output * should be sent (optional) * @constructor */ function Requisition(environment, doc, commandOutputManager) { this.environment = environment; this.document = doc; if (this.document == null) { try { this.document = document; } catch (ex) { // Ignore } } this.commandOutputManager = commandOutputManager || new CommandOutputManager(); this.shell = { cwd: '/', // Where we store the current working directory env: {} // Where we store the current environment }; this.onTextChange = util.createEvent('Requisition.onTextChange'); // The command that we are about to execute. // @see setCommandConversion() this.commandAssignment = new CommandAssignment(); var assignPromise = this.setAssignment(this.commandAssignment, null, { internal: true }); util.synchronize(assignPromise); // The object that stores of Assignment objects that we are filling out. // The Assignment objects are stored under their param.name for named // lookup. Note: We make use of the property of Javascript objects that // they are not just hashmaps, but linked-list hashmaps which iterate in // insertion order. // _assignments excludes the commandAssignment. this._assignments = {}; // The count of assignments. Excludes the commandAssignment this.assignmentCount = 0; // Used to store cli arguments in the order entered on the cli this._args = []; // Used to store cli arguments that were not assigned to parameters this._unassigned = []; // Changes can be asynchronous, when one update starts before another // finishes we abandon the former change this._nextUpdateId = 0; // We can set a prefix to typed commands to make it easier to focus on // Allowing us to type "add -a; commit" in place of "git add -a; git commit" this.prefix = ''; } /** * Avoid memory leaks */ Requisition.prototype.destroy = function() { delete this.document; delete this.environment; }; /** * If we're about to make an asynchronous change when other async changes could * overtake this one, then we want to be able to bail out if overtaken. The * value passed back from beginChange should be passed to endChangeCheckOrder * on completion of calculation, before the results are applied in order to * check that the calculation has not been overtaken */ Requisition.prototype._beginChange = function() { this.onTextChange.holdFire(); var updateId = this._nextUpdateId; this._nextUpdateId++; return updateId; }; /** * Check to see if another change has started since updateId started. * This allows us to bail out of an update. * It's hard to make updates atomic because until you've responded to a parse * of the command argument, you don't know how to parse the arguments to that * command. */ Requisition.prototype._isChangeCurrent = function(updateId) { return updateId + 1 === this._nextUpdateId; }; /** * See notes on beginChange */ Requisition.prototype._endChangeCheckOrder = function(updateId) { this.onTextChange.resumeFire(); if (updateId + 1 !== this._nextUpdateId) { // An update that started after we did has already finished, so our // changes are out of date. Abandon further work. return false; } return true; }; var legacy = false; /** * Functions and data related to the execution of a command */ Object.defineProperty(Requisition.prototype, 'executionContext', { get: function() { if (this._executionContext == null) { this._executionContext = { defer: function() { return promise.defer(); }, typedData: function(type, data) { return { isTypedData: true, data: data, type: type }; }, getArgsObject: this.getArgsObject.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._executionContext, 'typed', { get: function() { return requisition.toString(); }, enumerable: true }); Object.defineProperty(this._executionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); Object.defineProperty(this._executionContext, 'shell', { get: function() { return requisition.shell; }, enumerable : true }); /** * This is a temporary property that will change and/or be removed. * Do not use it */ Object.defineProperty(this._executionContext, '__dlhjshfw', { get: function() { return requisition; }, enumerable: false }); if (legacy) { this._executionContext.createView = view.createView; this._executionContext.exec = this.exec.bind(this); this._executionContext.update = this.update.bind(this); this._executionContext.updateExec = this.updateExec.bind(this); Object.defineProperty(this._executionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); } } return this._executionContext; }, enumerable: true }); /** * Functions and data related to the conversion of the output of a command */ Object.defineProperty(Requisition.prototype, 'conversionContext', { get: function() { if (this._conversionContext == null) { this._conversionContext = { defer: function() { return promise.defer(); }, createView: view.createView, exec: this.exec.bind(this), update: this.update.bind(this), updateExec: this.updateExec.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._conversionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); Object.defineProperty(this._conversionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); /** * This is a temporary property that will change and/or be removed. * Do not use it */ Object.defineProperty(this._conversionContext, '__dlhjshfw', { get: function() { return requisition; }, enumerable: false }); } return this._conversionContext; }, enumerable: true }); /** * Assignments have an order, so we need to store them in an array. * But we also need named access ... * @return The found assignment, or undefined, if no match was found */ Requisition.prototype.getAssignment = function(nameOrNumber) { var name = (typeof nameOrNumber === 'string') ? nameOrNumber : Object.keys(this._assignments)[nameOrNumber]; return this._assignments[name] || undefined; }; /** * There are a few places where we need to know what the 'next thing' is. What * is the user going to be filling out next (assuming they don't enter a named * argument). The next argument is the first in line that is both blank, and * that can be filled in positionally. * @return The next assignment to be used, or null if all the positional * parameters have values. */ Requisition.prototype._getFirstBlankPositionalAssignment = function() { var reply = null; Object.keys(this._assignments).some(function(name) { var assignment = this.getAssignment(name); if (assignment.arg.type === 'BlankArgument' && assignment.param.isPositionalAllowed) { reply = assignment; return true; // i.e. break } return false; }, this); return reply; }; /** * Where parameter name == assignment names - they are the same */ Requisition.prototype.getParameterNames = function() { return Object.keys(this._assignments); }; /** * A *shallow* clone of the assignments. * This is useful for systems that wish to go over all the assignments * finding values one way or another and wish to trim an array as they go. */ Requisition.prototype.cloneAssignments = function() { return Object.keys(this._assignments).map(function(name) { return this._assignments[name]; }, this); }; /** * The overall status is the most severe status. * There is no such thing as an INCOMPLETE overall status because the * definition of INCOMPLETE takes into account the cursor position to say 'this * isn't quite ERROR because the user can fix it by typing', however overall, * this is still an error status. */ Object.defineProperty(Requisition.prototype, 'status', { get : function() { var status = Status.VALID; if (this._unassigned.length !== 0) { var isAllIncomplete = true; this._unassigned.forEach(function(assignment) { if (!assignment.param.type.isIncompleteName) { isAllIncomplete = false; } }); status = isAllIncomplete ? Status.INCOMPLETE : Status.ERROR; } this.getAssignments(true).forEach(function(assignment) { var assignStatus = assignment.getStatus(); if (assignStatus > status) { status = assignStatus; } }, this); if (status === Status.INCOMPLETE) { status = Status.ERROR; } return status; }, enumerable : true }); /** * If ``requisition.status != VALID`` message then return a string which * best describes what is wrong. Generally error messages are delivered by * looking at the error associated with the argument at the cursor, but there * are times when you just want to say 'tell me the worst'. * If ``requisition.status != VALID`` then return ``null``. */ Requisition.prototype.getStatusMessage = function() { if (this.commandAssignment.getStatus() !== Status.VALID) { return l10n.lookup('cliUnknownCommand'); } var assignments = this.getAssignments(); for (var i = 0; i < assignments.length; i++) { if (assignments[i].getStatus() !== Status.VALID) { return assignments[i].message; } } if (this._unassigned.length !== 0) { return l10n.lookup('cliUnusedArg'); } return null; }; /** * Extract the names and values of all the assignments, and return as * an object. */ Requisition.prototype.getArgsObject = function() { var args = {}; this.getAssignments().forEach(function(assignment) { args[assignment.param.name] = assignment.conversion.isDataProvided() ? assignment.value : assignment.param.defaultValue; }, this); return args; }; /** * Access the arguments as an array. * @param includeCommand By default only the parameter arguments are * returned unless (includeCommand === true), in which case the list is * prepended with commandAssignment.arg */ Requisition.prototype.getAssignments = function(includeCommand) { var assignments = []; if (includeCommand === true) { assignments.push(this.commandAssignment); } Object.keys(this._assignments).forEach(function(name) { assignments.push(this.getAssignment(name)); }, this); return assignments; }; /** * When any assignment changes, we might need to update the _args array to * match and inform people of changes to the typed input text. */ Requisition.prototype._setAssignmentInternal = function(assignment, conversion) { var oldConversion = assignment.conversion; assignment.conversion = conversion; assignment.conversion.assignment = assignment; // Do nothing if the value is unchanged if (assignment.conversion.equals(oldConversion) || assignment.conversion.valueEquals(oldConversion)) { return; } // When the command changes, we need to keep a bunch of stuff in sync if (assignment === this.commandAssignment) { this._assignments = {}; var command = this.commandAssignment.value; if (command) { for (var i = 0; i < command.params.length; i++) { var param = command.params[i]; var newAssignment = new Assignment(param, i); var assignPromise = this.setAssignment(newAssignment, null, { internal: true }); util.synchronize(assignPromise); this._assignments[param.name] = newAssignment; } } this.assignmentCount = Object.keys(this._assignments).length; } // For the onTextChange event, we only care about changes to the argument if (!assignment.conversion.argEquals(oldConversion)) { this.onTextChange(); } }; /** * Internal function to alter the given assignment using the given arg. * @param assignment The assignment to alter * @param arg The new value for the assignment. An instance of Argument, or an * instance of Conversion, or null to set the blank value. * @param options There are a number of ways to customize how the assignment * is made, including: * - internal: (default:false) External updates are required to do more work, * including adjusting the args in this requisition to stay in sync. * On the other hand non internal changes use beginChange to back out of * changes when overtaken asynchronously. * Setting internal:true effectively means this is being called as part of * the update process. * - matchPadding: (default:false) Alter the whitespace on the prefix and * suffix of the new argument to match that of the old argument. This only * makes sense with internal=false */ Requisition.prototype.setAssignment = function(assignment, arg, options) { options = options || {}; if (!options.internal) { var originalArgs = assignment.arg.getArgs(); // Update the args array var replacementArgs = arg.getArgs(); var maxLen = Math.max(originalArgs.length, replacementArgs.length); for (var i = 0; i < maxLen; i++) { // If there are no more original args, or if the original arg was blank // (i.e. not typed by the user), we'll just need to add at the end if (i >= originalArgs.length || originalArgs[i].type === 'BlankArgument') { this._args.push(replacementArgs[i]); continue; } var index = this._args.indexOf(originalArgs[i]); if (index === -1) { console.error('Couldn\'t find ', originalArgs[i], ' in ', this._args); throw new Error('Couldn\'t find ' + originalArgs[i]); } // If there are no more replacement args, we just remove the original args // Otherwise swap original args and replacements if (i >= replacementArgs.length) { this._args.splice(index, 1); } else { if (options.matchPadding) { if (replacementArgs[i].prefix.length === 0 && this._args[index].prefix.length !== 0) { replacementArgs[i].prefix = this._args[index].prefix; } if (replacementArgs[i].suffix.length === 0 && this._args[index].suffix.length !== 0) { replacementArgs[i].suffix = this._args[index].suffix; } } this._args[index] = replacementArgs[i]; } } } var updateId = options.internal ? null : this._beginChange(); var setAssignmentInternal = function(conversion) { if (options.internal || this._endChangeCheckOrder(updateId)) { this._setAssignmentInternal(assignment, conversion); } return promise.resolve(undefined); }.bind(this); if (arg == null) { var blank = assignment.param.type.getBlank(this.executionContext); return setAssignmentInternal(blank); } if (typeof arg.getStatus === 'function') { // It's not really an arg, it's a conversion already return setAssignmentInternal(arg); } var parsed = assignment.param.type.parse(arg, this.executionContext); return parsed.then(setAssignmentInternal); }; /** * Reset all the assignments to their default values */ Requisition.prototype.setBlankArguments = function() { this.getAssignments().forEach(function(assignment) { var assignPromise = this.setAssignment(assignment, null, { internal: true }); util.synchronize(assignPromise); }, this); }; /** * Complete the argument at <tt>cursor</tt>. * Basically the same as: * assignment = getAssignmentAt(cursor); * assignment.value = assignment.conversion.predictions[0]; * Except it's done safely, and with particular care to where we place the * space, which is complex, and annoying if we get it wrong. * * WARNING: complete() can happen asynchronously. * * @param cursor The cursor configuration. Should have start and end properties * which should be set to start and end of the selection. * @param predictionChoice The index of the prediction that we should choose. * This number is not bounded by the size of the prediction array, we take the * modulus to get it within bounds * @return A promise which completes (with undefined) when any outstanding * completion tasks are done. */ Requisition.prototype.complete = function(cursor, predictionChoice) { var assignment = this.getAssignmentAt(cursor.start); var predictionPromise = assignment.getPredictionAt(predictionChoice); return predictionPromise.then(function(prediction) { var outstanding = []; this.onTextChange.holdFire(); // Note: Since complete is asynchronous we should perhaps have a system to // bail out of making changes if the command line has changed since TAB // was pressed. It's not yet clear if this will be a problem. if (prediction == null) { // No predictions generally means we shouldn't change anything on TAB, // but TAB has the connotation of 'next thing' and when we're at the end // of a thing that implies that we should add a space. i.e. // 'help<TAB>' -> 'help ' // But we should only do this if the thing that we're 'completing' is // valid and doesn't already end in a space. if (assignment.arg.suffix.slice(-1) !== ' ' && assignment.getStatus() === Status.VALID) { outstanding.push(this._addSpace(assignment)); } // Also add a space if we are in the name part of an assignment, however // this time we don't want the 'push the space to the next assignment' // logic, so we don't use addSpace if (assignment.isInName()) { var newArg = assignment.arg.beget({ prefixPostSpace: true }); outstanding.push(this.setAssignment(assignment, newArg)); } } else { // Mutate this argument to hold the completion var arg = assignment.arg.beget({ text: prediction.name, dontQuote: (assignment === this.commandAssignment) }); var assignPromise = this.setAssignment(assignment, arg); if (!prediction.incomplete) { assignPromise = assignPromise.then(function() { // The prediction is complete, add a space to let the user move-on return this._addSpace(assignment).then(function() { // Bug 779443 - Remove or explain the re-parse if (assignment instanceof UnassignedAssignment) { return this.update(this.toString()); } }.bind(this)); }.bind(this)); } outstanding.push(assignPromise); } return promise.all(outstanding).then(function() { this.onTextChange(); this.onTextChange.resumeFire(); return true; }.bind(this)); }.bind(this)); }; /** * A test method to check that all args are assigned in some way */ Requisition.prototype._assertArgsAssigned = function() { this._args.forEach(function(arg) { if (arg.assignment == null) { console.log('No assignment for ' + arg); } }, this); }; /** * Pressing TAB sometimes requires that we add a space to denote that we're on * to the 'next thing'. * @param assignment The assignment to which to append the space */ Requisition.prototype._addSpace = function(assignment) { var arg = assignment.arg.beget({ suffixSpace: true }); if (arg !== assignment.arg) { return this.setAssignment(assignment, arg); } else { return promise.resolve(undefined); } }; /** * Replace the current value with the lower value if such a concept exists. */ Requisition.prototype.decrement = function(assignment) { var replacement = assignment.param.type.decrement(assignment.value, this.executionContext); if (replacement != null) { var str = assignment.param.type.stringify(replacement, this.executionContext); var arg = assignment.arg.beget({ text: str }); var assignPromise = this.setAssignment(assignment, arg); util.synchronize(assignPromise); } }; /** * Replace the current value with the higher value if such a concept exists. */ Requisition.prototype.increment = function(assignment) { var replacement = assignment.param.type.increment(assignment.value, this.executionContext); if (replacement != null) { var str = assignment.param.type.stringify(replacement, this.executionContext); var arg = assignment.arg.beget({ text: str }); var assignPromise = this.setAssignment(assignment, arg); util.synchronize(assignPromise); } }; /** * Extract a canonical version of the input */ Requisition.prototype.toCanonicalString = function() { var line = []; var cmd = this.commandAssignment.value ? this.commandAssignment.value.name : this.commandAssignment.arg.text; line.push(cmd); Object.keys(this._assignments).forEach(function(name) { var assignment = this._assignments[name]; var type = assignment.param.type; // Bug 664377: This will cause problems if there is a non-default value // after a default value. Also we need to decide when to use // named parameters in place of positional params. Both can wait. if (assignment.value !== assignment.param.defaultValue) { line.push(' '); line.push(type.stringify(assignment.value, this.executionContext)); } }, this); // Canonically, if we've opened with a { then we should have a } to close if (cmd === '{') { if (this.getAssignment(0).arg.suffix.indexOf('}') === -1) { line.push(' }'); } } return line.join(''); }; /** * Input trace gives us an array of Argument tracing objects, one for each * character in the typed input, from which we can derive information about how * to display this typed input. It's a bit like toString on steroids. * <p> * The returned object has the following members:<ul> * <li>character: The character to which this arg trace refers. * <li>arg: The Argument to which this character is assigned. * <li>part: One of ['prefix'|'text'|suffix'] - how was this char understood * </ul> * <p> * The Argument objects are as output from tokenize() rather than as applied * to Assignments by _assign() (i.e. they are not instances of NamedArgument, * ArrayArgument, etc). * <p> * To get at the arguments applied to the assignments simply call * <tt>arg.assignment.arg</tt>. If <tt>arg.assignment.arg !== arg</tt> then * the arg applied to the assignment will contain the original arg. * See _assign() for details. */ Requisition.prototype.createInputArgTrace = function() { if (!this._args) { throw new Error('createInputMap requires a command line. See source.'); // If this is a problem then we can fake command line input using // something like the code in #toCanonicalString(). } var args = []; var i; this._args.forEach(function(arg) { for (i = 0; i < arg.prefix.length; i++) { args.push({ arg: arg, character: arg.prefix[i], part: 'prefix' }); } for (i = 0; i < arg.text.length; i++) { args.push({ arg: arg, character: arg.text[i], part: 'text' }); } for (i = 0; i < arg.suffix.length; i++) { args.push({ arg: arg, character: arg.suffix[i], part: 'suffix' }); } }); return args; }; /** * Reconstitute the input from the args */ Requisition.prototype.toString = function() { if (this._args) { return this._args.map(function(arg) { return arg.toString(); }).join(''); } return this.toCanonicalString(); }; /** * If the last character is whitespace then things that we suggest to add to * the end don't need a space prefix. * While this is quite a niche function, it has 2 benefits: * - it's more correct because we can distinguish between final whitespace that * is part of an unclosed string, and parameter separating whitespace. * - also it's faster than toString() the whole thing and checking the end char * @return true iff the last character is interpreted as parameter separating * whitespace */ Requisition.prototype.typedEndsWithSeparator = function() { // This is not as easy as doing (this.toString().slice(-1) === ' ') // See the doc comments above; We're checking for separators, not spaces if (this._args) { var lastArg = this._args.slice(-1)[0]; if (lastArg.suffix.slice(-1) === ' ') { return true; } return lastArg.text === '' && lastArg.suffix === '' && lastArg.prefix.slice(-1) === ' '; } return this.toCanonicalString().slice(-1) === ' '; }; /** * Return an array of Status scores so we can create a marked up * version of the command line input. * @param cursor We only take a status of INCOMPLETE to be INCOMPLETE when the * cursor is actually in the argument. Otherwise it's an error. * @return Array of objects each containing <tt>status</tt> property and a * <tt>string</tt> property containing the characters to which the status * applies. Concatenating the strings in order gives the original input. */ Requisition.prototype.getInputStatusMarkup = function(cursor) { var argTraces = this.createInputArgTrace(); // Generally the 'argument at the cursor' is the argument before the cursor // unless it is before the first char, in which case we take the first. cursor = cursor === 0 ? 0 : cursor - 1; var cTrace = argTraces[cursor]; var markup = []; for (var i = 0; i < argTraces.length; i++) { var argTrace = argTraces[i]; var arg = argTrace.arg; var status = Status.VALID; if (argTrace.part === 'text') { status = arg.assignment.getStatus(arg); // Promote INCOMPLETE to ERROR ... if (status === Status.INCOMPLETE) { // If the cursor is in the prefix or suffix of an argument then we // don't consider it in the argument for the purposes of preventing // the escalation to ERROR. However if this is a NamedArgument, then we // allow the suffix (as space between 2 parts of the argument) to be in. // We use arg.assignment.arg not arg because we're looking at the arg // that got put into the assignment not as returned by tokenize() var isNamed = (cTrace.arg.assignment.arg.type === 'NamedArgument'); var isInside = cTrace.part === 'text' || (isNamed && cTrace.part === 'suffix'); if (arg.assignment !== cTrace.arg.assignment || !isInside) { // And if we're not in the command if (!(arg.assignment instanceof CommandAssignment)) { status = Status.ERROR; } } } } markup.push({ status: status, string: argTrace.character }); } // De-dupe: merge entries where 2 adjacent have same status i = 0; while (i < markup.length - 1) { if (markup[i].status === markup[i + 1].status) { markup[i].string += markup[i + 1].string; markup.splice(i + 1, 1); } else { i++; } } return markup; }; /** * Look through the arguments attached to our assignments for the assignment * at the given position. * @param {number} cursor The cursor position to query */ Requisition.prototype.getAssignmentAt = function(cursor) { if (!this._args) { console.trace(); throw new Error('Missing args'); } // We short circuit this one because we may have no args, or no args with // any size and the alg below only finds arguments with size. if (cursor === 0) { return this.commandAssignment; } var assignForPos = []; var i, j; for (i = 0; i < this._args.length; i++) { var arg = this._args[i]; var assignment = arg.assignment; // prefix and text are clearly part of the argument for (j = 0; j < arg.prefix.length; j++) { assignForPos.push(assignment); } for (j = 0; j < arg.text.length; j++) { assignForPos.push(assignment); } // suffix is part of the argument only if this is a named parameter, // otherwise it looks forwards if (arg.assignment.arg.type === 'NamedArgument') { // leave the argument as it is } else if (this._args.length > i + 1) { // first to the next argument assignment = this._args[i + 1].assignment; } else { // then to the first blank positional parameter, leaving 'as is' if none var nextAssignment = this._getFirstBlankPositionalAssignment(); if (nextAssignment != null) { assignment = nextAssignment; } } for (j = 0; j < arg.suffix.length; j++) { assignForPos.push(assignment); } } // Possible shortcut, we don't really need to go through all the args // to work out the solution to this var reply = assignForPos[cursor - 1]; if (!reply) { throw new Error('Missing assignment.' + ' cursor=' + cursor + ' text=' + this.toString()); } return reply; }; /** * Entry point for keyboard accelerators or anything else that wants to execute * a command. * @param options Object describing how the execution should be handled. * (optional). Contains some of the following properties: * - hidden (boolean, default=false) Should the output be hidden from the * commandOutputManager for this requisition * - command/args A fast shortcut to executing a known command with a known * set of parsed arguments. */ Requisition.prototype.exec = function(options) { var command = null; var args = null; var hidden = false; if (options) { if (options.hidden) { hidden = true; } if (options.command != null) { // Fast track by looking up the command directly since passed args // means there is no command line to parse. command = canon.getCommand(options.command); if (!command) { console.error('Command not found: ' + options.command); } args = options.args; } } if (!command) { command = this.commandAssignment.value; args = this.getArgsObject(); } // Display JavaScript input without the initial { or closing } var typed = this.toString(); if (evalCmd.isCommandRegexp.test(typed)) { typed = typed.replace(evalCmd.isCommandRegexp, ''); // Bug 717763: What if the JavaScript naturally ends with a }? typed = typed.replace(/\s*}\s*$/, ''); } var output = new Output({ command: command, args: args, typed: typed, canonical: this.toCanonicalString(), hidden: hidden }); this.commandOutputManager.onOutput({ output: output }); var onDone = function(data) { output.complete(data, false); return output; }; var onError = function(ex) { if (exports.logErrors) { util.errorHandler(ex); } var data = ex.isTypedData ? ex : { isTypedData: true, data: ex, type: 'error' }; output.complete(data, true); return output; }; if (this.status !== Status.VALID) { var ex = new Error(this.getStatusMessage()); return promise.resolve(onError(ex)).then(function(output) { this.clear(); return output; }); } else { try { var reply = command.exec(args, this.executionContext); return promise.resolve(reply).then(onDone, onError); } catch (ex) { return promise.resolve(onError(ex)); } finally { this.clear(); } } }; /** * A shortcut for calling update, resolving the promise and then exec. * @param input The string to execute * @param options Passed to exec * @return A promise of an output object */ Requisition.prototype.updateExec = function(input, options) { return this.update(input).then(function() { return this.exec(options); }.bind(this)); }; /** * Similar to update('') except that it's guaranteed to execute synchronously */ Requisition.prototype.clear = function() { this.onTextChange.holdFire(); var arg = new Argument('', '', ''); this._args = [ arg ]; var commandType = this.commandAssignment.param.type; var parsePromise = commandType.parse(arg, this.executionContext); this.setAssignment(this.commandAssignment, util.synchronize(parsePromise), { internal: true }); this.onTextChange.resumeFire(); this.onTextChange(); }; /** * Helper to find the 'data-command' attribute, used by |update()| */ function getDataCommandAttribute(element) { var command = element.getAttribute('data-command'); if (!command) { command = element.querySelector('*[data-command]') .getAttribute('data-command'); } return command; } /** * Called by the UI when ever the user interacts with a command line input * @param typed The contents of the input field */ Requisition.prototype.update = function(typed) { if (typeof HTMLElement !== 'undefined' && typed instanceof HTMLElement) { typed = getDataCommandAttribute(typed); } if (typeof Event !== 'undefined' && typed instanceof Event) { typed = getDataCommandAttribute(typed.currentTarget); } var updateId = this._beginChange(); this._args = exports.tokenize(typed); var args = this._args.slice(0); // i.e. clone return this._split(args).then(function() { if (!this._isChangeCurrent(updateId)) { return false; } return this._assign(args).then(function() { if (this._endChangeCheckOrder(updateId)) { this.onTextChange(); return true; } return false; }.bind(this)); }.bind(this)); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Requisition.prototype, '_summaryJson', { get: function() { var summary = { $args: this._args.map(function(arg) { return arg._summaryJson; }), _command: this.commandAssignment._summaryJson, _unassigned: this._unassigned.forEach(function(assignment) { return assignment._summaryJson; }) }; Object.keys(this._assignments).forEach(function(name) { summary[name] = this.getAssignment(name)._summaryJson; }.bind(this)); return summary; }, enumerable: true }); /** * tokenize() is a state machine. These are the states. */ var In = { /** * The last character was ' '. * Typing a ' ' character will not change the mode * Typing one of '"{ will change mode to SINGLE_Q, DOUBLE_Q or SCRIPT. * Anything else goes into SIMPLE mode. */ WHITESPACE: 1, /** * The last character was part of a parameter. * Typing ' ' returns to WHITESPACE mode. Any other character * (including '"{} which are otherwise special) does not change the mode. */ SIMPLE: 2, /** * We're inside single quotes: ' * Typing ' returns to WHITESPACE mode. Other characters do not change mode. */ SINGLE_Q: 3, /** * We're inside double quotes: " * Typing " returns to WHITESPACE mode. Other characters do not change mode. */ DOUBLE_Q: 4, /** * We're inside { and } * Typing } returns to WHITESPACE mode. Other characters do not change mode. * SCRIPT mode is slightly different from other modes in that spaces between * the {/} delimiters and the actual input are not considered significant. * e.g: " x " is a 3 character string, delimited by double quotes, however * { x } is a 1 character JavaScript surrounded by whitespace and {} * delimiters. * In the short term we assume that the JS routines can make sense of the * extra whitespace, however at some stage we may need to move the space into * the Argument prefix/suffix. * Also we don't attempt to handle nested {}. See bug 678961 */ SCRIPT: 5 }; /** * Split up the input taking into account ', " and {. * We don't consider \t or other classical whitespace characters to split * arguments apart. For one thing these characters are hard to type, but also * if the user has gone to the trouble of pasting a TAB character into the * input field (or whatever it takes), they probably mean it. */ exports.tokenize = function(typed) { // For blank input, place a dummy empty argument into the list if (typed == null || typed.length === 0) { return [ new Argument('', '', '') ]; } if (isSimple(typed)) { return [ new Argument(typed, '', '') ]; } var mode = In.WHITESPACE; // First we swap out escaped characters that are special to the tokenizer. // So a backslash followed by any of ['"{} ] is turned into a unicode private // char so we can swap back later typed = typed .replace(/\\\\/g, '\uF000') .replace(/\\ /g, '\uF001') .replace(/\\'/g, '\uF002') .replace(/\\"/g, '\uF003') .replace(/\\{/g, '\uF004') .replace(/\\}/g, '\uF005'); function unescape2(escaped) { return escaped .replace(/\uF000/g, '\\\\') .replace(/\uF001/g, '\\ ') .replace(/\uF002/g, '\\\'') .replace(/\uF003/g, '\\\"') .replace(/\uF004/g, '\\{') .replace(/\uF005/g, '\\}'); } var i = 0; // The index of the current character var start = 0; // Where did this section start? var prefix = ''; // Stuff that comes before the current argument var args = []; // The array that we're creating var blockDepth = 0; // For JS with nested {} // This is just a state machine. We're going through the string char by char // The 'mode' is one of the 'In' states. As we go, we're adding Arguments // to the 'args' array. while (true) { var c = typed[i]; var str; switch (mode) { case In.WHITESPACE: if (c === '\'') { prefix = typed.substring(start, i + 1); mode = In.SINGLE_Q; start = i + 1; } else if (c === '"') { prefix = typed.substring(start, i + 1); mode = In.DOUBLE_Q; start = i + 1; } else if (c === '{') { prefix = typed.substring(start, i + 1); mode = In.SCRIPT; blockDepth++; start = i + 1; } else if (/ /.test(c)) { // Still whitespace, do nothing } else { prefix = typed.substring(start, i); mode = In.SIMPLE; start = i; } break; case In.SIMPLE: // There is an edge case of xx'xx which we are assuming to // be a single parameter (and same with ") if (c === ' ') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, '')); mode = In.WHITESPACE; start = i; prefix = ''; } break; case In.SINGLE_Q: if (c === '\'') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.DOUBLE_Q: if (c === '"') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.SCRIPT: if (c === '{') { blockDepth++; } else if (c === '}') { blockDepth--; if (blockDepth === 0) { str = unescape2(typed.substring(start, i)); args.push(new ScriptArgument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } } break; } i++; if (i >= typed.length) { // There is nothing else to read - tidy up if (mode === In.WHITESPACE) { if (i !== start) { // There's whitespace at the end of the typed string. Add it to the // last argument's suffix, creating an empty argument if needed. var extra = typed.substring(start, i); var lastArg = args[args.length - 1]; if (!lastArg) { args.push(new Argument('', extra, '')); } else { lastArg.suffix += extra; } } } else if (mode === In.SCRIPT) { str = unescape2(typed.substring(start, i + 1)); args.push(new ScriptArgument(str, prefix, '')); } else { str = unescape2(typed.substring(start, i + 1)); args.push(new Argument(str, prefix, '')); } break; } } return args; }; /** * If the input has no spaces, quotes, braces or escapes, * we can take the fast track. */ function isSimple(typed) { for (var i = 0; i < typed.length; i++) { var c = typed.charAt(i); if (c === ' ' || c === '"' || c === '\'' || c === '{' || c === '}' || c === '\\') { return false; } } return true; } /** * Looks in the canon for a command extension that matches what has been * typed at the command line. */ Requisition.prototype._split = function(args) { // We're processing args, so we don't want the assignments that we make to // try to adjust other args assuming this is an external update var noArgUp = { internal: true }; // Handle the special case of the user typing { javascript(); } // We use the hidden 'eval' command directly rather than shift()ing one of // the parameters, and parse()ing it. var conversion; if (args[0].type === 'ScriptArgument') { // Special case: if the user enters { console.log('foo'); } then we need to // use the hidden 'eval' command conversion = new Conversion(getEvalCommand(), new ScriptArgument()); return this.setAssignment(this.commandAssignment, conversion, noArgUp); } var argsUsed = 1; var parsePromise; var commandType = this.commandAssignment.param.type; while (argsUsed <= args.length) { var arg = (argsUsed === 1) ? args[0] : new MergedArgument(args, 0, argsUsed); // Making the commandType.parse() promise as synchronous is OK because we // know that commandType is a synchronous type. if (this.prefix != null && this.prefix !== '') { var prefixArg = new Argument(this.prefix, '', ' '); var prefixedArg = new MergedArgument([ prefixArg, arg ]); parsePromise = commandType.parse(prefixedArg, this.executionContext); conversion = util.synchronize(parsePromise); if (conversion.value == null) { parsePromise = commandType.parse(arg, this.executionContext); conversion = util.synchronize(parsePromise); } } else { parsePromise = commandType.parse(arg, this.executionContext); conversion = util.synchronize(parsePromise); } // We only want to carry on if this command is a parent command, // which means that there is a commandAssignment, but not one with // an exec function. if (!conversion.value || conversion.value.exec) { break; } // Previously we needed a way to hide commands depending context. // We have not resurrected that feature yet, but if we do we should // insert code here to ignore certain commands depending on the // context/environment argsUsed++; } // This could probably be re-written to consume args as we go for (var i = 0; i < argsUsed; i++) { args.shift(); } // Warning: we're returning a promise (from setAssignment) which tells us // when we're done setting the current command, but mutating the args array // as we go, so we're conflicted on when we're done return this.setAssignment(this.commandAssignment, conversion, noArgUp); }; /** * Add all the passed args to the list of unassigned assignments. */ Requisition.prototype._addUnassignedArgs = function(args) { args.forEach(function(arg) { this._unassigned.push(new UnassignedAssignment(this, arg)); }.bind(this)); }; /** * Work out which arguments are applicable to which parameters. */ Requisition.prototype._assign = function(args) { // See comment in _split. Avoid multiple updates var noArgUp = { internal: true }; this._unassigned = []; var outstanding = []; if (!this.commandAssignment.value) { this._addUnassignedArgs(args); return promise.all(outstanding); } if (args.length === 0) { this.setBlankArguments(); return promise.all(outstanding); } // Create an error if the command does not take parameters, but we have // been given them ... if (this.assignmentCount === 0) { this._addUnassignedArgs(args); return promise.all(outstanding); } // Special case: if there is only 1 parameter, and that's of type // text, then we put all the params into the first param if (this.assignmentCount === 1) { var assignment = this.getAssignment(0); if (assignment.param.type.name === 'string') { var arg = (args.length === 1) ? args[0] : new MergedArgument(args); outstanding.push(this.setAssignment(assignment, arg, noArgUp)); return promise.all(outstanding); } } // Positional arguments can still be specified by name, but if they are // then we need to ignore them when working them out positionally var unassignedParams = this.getParameterNames(); // We collect the arguments used in arrays here before assigning var arrayArgs = {}; // Extract all the named parameters this.getAssignments(false).forEach(function(assignment) { // Loop over the arguments // Using while rather than loop because we remove args as we go var i = 0; while (i < args.length) { if (assignment.param.isKnownAs(args[i].text)) { var arg = args.splice(i, 1)[0]; unassignedParams = unassignedParams.filter(function(test) { return test !== assignment.param.name; }); // boolean parameters don't have values, default to false if (assignment.param.type.name === 'boolean') { arg = new TrueNamedArgument(arg); } else { var valueArg = null; if (i + 1 <= args.length) { valueArg = args.splice(i, 1)[0]; } arg = new NamedArgument(arg, valueArg); } if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArgument(arg); } else { outstanding.push(this.setAssignment(assignment, arg, noArgUp)); } } else { // Skip this parameter and handle as a positional parameter i++; } } }, this); // What's left are positional parameters: assign in order unassignedParams.forEach(function(name) { var assignment = this.getAssignment(name); // If not set positionally, and we can't set it non-positionally, // we have to default it to prevent previous values surviving if (!assignment.param.isPositionalAllowed) { outstanding.push(this.setAssignment(assignment, null, noArgUp)); return; } // If this is a positional array argument, then it swallows the // rest of the arguments. if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArguments(args); args = []; // The actual assignment to the array parameter is done below return; } // Set assignment to defaults if there are no more arguments if (args.length === 0) { outstanding.push(this.setAssignment(assignment, null, noArgUp)); return; } var arg = args.splice(0, 1)[0]; // --foo and -f are named parameters, -4 is a number. So '-' is either // the start of a named parameter or a number depending on the context var isIncompleteName = assignment.param.type.name === 'number' ? /-[-a-zA-Z_]/.test(arg.text) : arg.text.charAt(0) === '-'; if (isIncompleteName) { this._unassigned.push(new UnassignedAssignment(this, arg)); } else { outstanding.push(this.setAssignment(assignment, arg, noArgUp)); } }, this); // Now we need to assign the array argument (if any) Object.keys(arrayArgs).forEach(function(name) { var assignment = this.getAssignment(name); outstanding.push(this.setAssignment(assignment, arrayArgs[name], noArgUp)); }, this); // What's left is can't be assigned, but we need to officially unassign them this._addUnassignedArgs(args); return promise.all(outstanding); }; exports.Requisition = Requisition; /** * A simple object to hold information about the output of a command */ function Output(options) { options = options || {}; this.command = options.command || ''; this.args = options.args || {}; this.typed = options.typed || ''; this.canonical = options.canonical || ''; this.hidden = options.hidden === true ? true : false; this.type = undefined; this.data = undefined; this.completed = false; this.error = false; this.start = new Date(); this._deferred = promise.defer(); this.promise = this._deferred.promise; this.onClose = util.createEvent('Output.onClose'); } /** * Called when there is data to display, and the command has finished executing * See changed() for details on parameters. */ Output.prototype.complete = function(data, error) { this.end = new Date(); this.duration = this.end.getTime() - this.start.getTime(); this.completed = true; this.error = error; if (data != null && data.isTypedData) { this.data = data.data; this.type = data.type; } else { this.data = data; this.type = this.command.returnType; if (this.type == null) { this.type = (this.data == null) ? 'undefined' : typeof this.data; } } if (this.type === 'object') { throw new Error('No type from output of ' + this.typed); } this._deferred.resolve(); }; /** * Call converters.convert using the data in this Output object */ Output.prototype.convert = function(type, conversionContext) { return converters.convert(this.data, this.type, type, conversionContext); }; exports.Output = Output; });
lib/gcli/cli.js
/* * Copyright 2012, Mozilla Foundation and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(function(require, exports, module) { 'use strict'; var promise = require('util/promise'); var util = require('util/util'); var l10n = require('util/l10n'); var view = require('gcli/ui/view'); var converters = require('gcli/converters'); var canon = require('gcli/canon'); var CommandOutputManager = require('gcli/canon').CommandOutputManager; var Status = require('gcli/types').Status; var Conversion = require('gcli/types').Conversion; var Argument = require('gcli/argument').Argument; var ArrayArgument = require('gcli/argument').ArrayArgument; var NamedArgument = require('gcli/argument').NamedArgument; var TrueNamedArgument = require('gcli/argument').TrueNamedArgument; var MergedArgument = require('gcli/argument').MergedArgument; var ScriptArgument = require('gcli/argument').ScriptArgument; /** * Some manual intervention is needed in parsing the { command. */ function getEvalCommand() { if (getEvalCommand._cmd == null) { getEvalCommand._cmd = canon.getCommand(evalCmd.name); } return getEvalCommand._cmd; } /** * Assignment is a link between a parameter and the data for that parameter. * The data for the parameter is available as in the preferred type and as * an Argument for the CLI. * <p>We also record validity information where applicable. * <p>For values, null and undefined have distinct definitions. null means * that a value has been provided, undefined means that it has not. * Thus, null is a valid default value, and common because it identifies an * parameter that is optional. undefined means there is no value from * the command line. * @constructor */ function Assignment(param, paramIndex) { // The parameter that we are assigning to this.param = param; this.conversion = undefined; // The index of this parameter in the parent Requisition. paramIndex === -1 // is the command assignment although this should not be relied upon, it is // better to test param instanceof CommandAssignment this.paramIndex = paramIndex; } /** * Easy accessor for conversion.arg. * This is a read-only property because writes to arg should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'arg', { get: function() { return this.conversion.arg; }, enumerable: true }); /** * Easy accessor for conversion.value. * This is a read-only property because writes to value should be done through * the 'conversion' property. */ Object.defineProperty(Assignment.prototype, 'value', { get: function() { return this.conversion.value; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.message */ Object.defineProperty(Assignment.prototype, 'message', { get: function() { return this.conversion.message ? this.conversion.message : ''; }, enumerable: true }); /** * Easy (and safe) accessor for conversion.getPredictions() * @return An array of objects with name and value elements. For example: * [ { name:'bestmatch', value:foo1 }, { name:'next', value:foo2 }, ... ] */ Assignment.prototype.getPredictions = function() { return this.conversion.getPredictions(); }; /** * Accessor for a prediction by index. * This is useful above <tt>getPredictions()[index]</tt> because it normalizes * index to be within the bounds of the predictions, which means that the UI * can maintain an index of which prediction to choose without caring how many * predictions there are. * @param index The index of the prediction to choose */ Assignment.prototype.getPredictionAt = function(index) { if (index == null) { index = 0; } if (this.isInName()) { return promise.resolve(undefined); } return this.getPredictions().then(function(predictions) { if (predictions.length === 0) { return undefined; } index = index % predictions.length; if (index < 0) { index = predictions.length + index; } return predictions[index]; }.bind(this)); }; /** * Some places want to take special action if we are in the name part of a * named argument (i.e. the '--foo' bit). * Currently this does not take actual cursor position into account, it just * assumes that the cursor is at the end. In the future we will probably want * to take this into account. */ Assignment.prototype.isInName = function() { return this.conversion.arg.type === 'NamedArgument' && this.conversion.arg.prefix.slice(-1) !== ' '; }; /** * Work out what the status of the current conversion is which involves looking * not only at the conversion, but also checking if data has been provided * where it should. * @param arg For assignments with multiple args (e.g. array assignments) we * can narrow the search for status to a single argument. */ Assignment.prototype.getStatus = function(arg) { if (this.param.isDataRequired && !this.conversion.isDataProvided()) { return Status.INCOMPLETE; } // Selection/Boolean types with a defined range of values will say that // '' is INCOMPLETE, but the parameter may be optional, so we don't ask // if the user doesn't need to enter something and hasn't done so. if (!this.param.isDataRequired && this.arg.type === 'BlankArgument') { return Status.VALID; } return this.conversion.getStatus(arg); }; /** * Helper when we're rebuilding command lines. */ Assignment.prototype.toString = function() { return this.conversion.toString(); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Assignment.prototype, '_summaryJson', { get: function() { var predictionCount = '<async>'; this.getPredictions().then(function(predictions) { predictionCount = predictions.length; }, console.log); return { param: this.param.name + '/' + this.param.type.name, defaultValue: this.param.defaultValue, arg: this.conversion.arg._summaryJson, value: this.value, message: this.message, status: this.getStatus().toString(), predictionCount: predictionCount }; }, enumerable: true }); exports.Assignment = Assignment; /** * How to dynamically execute JavaScript code */ var customEval = eval; /** * Setup a function to be called in place of 'eval', generally for security * reasons */ exports.setEvalFunction = function(newCustomEval) { customEval = newCustomEval; }; /** * Remove the binding done by setEvalFunction(). * We purposely set customEval to undefined rather than to 'eval' because there * is an implication of setEvalFunction that we're in a security sensitive * situation. What if we can trick GCLI into calling unsetEvalFunction() at the * wrong time? * So to properly undo the effects of setEvalFunction(), you need to call * setEvalFunction(eval) rather than unsetEvalFunction(), however the latter is * preferred in most cases. */ exports.unsetEvalFunction = function() { customEval = undefined; }; /** * 'eval' command */ var evalCmd = { item: 'command', name: '{', params: [ { name: 'javascript', type: 'javascript', description: '' } ], hidden: true, returnType: 'object', description: { key: 'cliEvalJavascript' }, exec: function(args, context) { return customEval(args.javascript); }, isCommandRegexp: /^\s*{\s*/ }; exports.items = [ evalCmd ]; /** * This is a special assignment to reflect the command itself. */ function CommandAssignment() { var commandParamMetadata = { name: '__command', type: { name: 'command', allowNonExec: false } }; // This is a hack so that rather than reply with a generic description of the // command assignment, we reply with the description of the assigned command, // (using a generic term if there is no assigned command) var self = this; Object.defineProperty(commandParamMetadata, 'description', { get: function() { var value = self.value; return value && value.description ? value.description : 'The command to execute'; }, enumerable: true }); this.param = new canon.Parameter(commandParamMetadata); this.paramIndex = -1; } CommandAssignment.prototype = Object.create(Assignment.prototype); CommandAssignment.prototype.getStatus = function(arg) { return Status.combine( Assignment.prototype.getStatus.call(this, arg), this.conversion.value && this.conversion.value.exec ? Status.VALID : Status.INCOMPLETE ); }; exports.CommandAssignment = CommandAssignment; /** * Special assignment used when ignoring parameters that don't have a home */ function UnassignedAssignment(requisition, arg) { this.param = new canon.Parameter({ name: '__unassigned', description: l10n.lookup('cliOptions'), type: { name: 'param', requisition: requisition, isIncompleteName: (arg.text.charAt(0) === '-') } }); this.paramIndex = -1; // synchronize is ok because we can be sure that param type is synchronous var parsed = this.param.type.parse(arg, requisition.executionContext); this.conversion = util.synchronize(parsed); this.conversion.assignment = this; } UnassignedAssignment.prototype = Object.create(Assignment.prototype); UnassignedAssignment.prototype.getStatus = function(arg) { return this.conversion.getStatus(); }; exports.logErrors = true; /** * A Requisition collects the information needed to execute a command. * * (For a definition of the term, see http://en.wikipedia.org/wiki/Requisition) * This term is used because carries the notion of a work-flow, or process to * getting the information to execute a command correct. * There is little point in a requisition for parameter-less commands because * there is no information to collect. A Requisition is a collection of * assignments of values to parameters, each handled by an instance of * Assignment. * * <h2>Events<h2> * <p>Requisition publishes the following events: * <ul> * <li>onTextChange: The text to be mirrored in a command line has changed. * </ul> * * @param environment An optional opaque object passed to commands in the * Execution Context. * @param doc A DOM Document passed to commands using the Execution Context in * order to allow creation of DOM nodes. If missing Requisition will use the * global 'document'. * @param commandOutputManager A custom commandOutputManager to which output * should be sent (optional) * @constructor */ function Requisition(environment, doc, commandOutputManager) { this.environment = environment; this.document = doc; if (this.document == null) { try { this.document = document; } catch (ex) { // Ignore } } this.commandOutputManager = commandOutputManager || new CommandOutputManager(); this.shell = { cwd: '/', // Where we store the current working directory env: {} // Where we store the current environment }; this.onTextChange = util.createEvent('Requisition.onTextChange'); // The command that we are about to execute. // @see setCommandConversion() this.commandAssignment = new CommandAssignment(); var assignPromise = this.setAssignment(this.commandAssignment, null, { internal: true }); util.synchronize(assignPromise); // The object that stores of Assignment objects that we are filling out. // The Assignment objects are stored under their param.name for named // lookup. Note: We make use of the property of Javascript objects that // they are not just hashmaps, but linked-list hashmaps which iterate in // insertion order. // _assignments excludes the commandAssignment. this._assignments = {}; // The count of assignments. Excludes the commandAssignment this.assignmentCount = 0; // Used to store cli arguments in the order entered on the cli this._args = []; // Used to store cli arguments that were not assigned to parameters this._unassigned = []; // Changes can be asynchronous, when one update starts before another // finishes we abandon the former change this._nextUpdateId = 0; // We can set a prefix to typed commands to make it easier to focus on // Allowing us to type "add -a; commit" in place of "git add -a; git commit" this.prefix = ''; } /** * Avoid memory leaks */ Requisition.prototype.destroy = function() { delete this.document; delete this.environment; }; /** * If we're about to make an asynchronous change when other async changes could * overtake this one, then we want to be able to bail out if overtaken. The * value passed back from beginChange should be passed to endChangeCheckOrder * on completion of calculation, before the results are applied in order to * check that the calculation has not been overtaken */ Requisition.prototype._beginChange = function() { this.onTextChange.holdFire(); var updateId = this._nextUpdateId; this._nextUpdateId++; return updateId; }; /** * Check to see if another change has started since updateId started. * This allows us to bail out of an update. * It's hard to make updates atomic because until you've responded to a parse * of the command argument, you don't know how to parse the arguments to that * command. */ Requisition.prototype._isChangeCurrent = function(updateId) { return updateId + 1 === this._nextUpdateId; }; /** * See notes on beginChange */ Requisition.prototype._endChangeCheckOrder = function(updateId) { this.onTextChange.resumeFire(); if (updateId + 1 !== this._nextUpdateId) { // An update that started after we did has already finished, so our // changes are out of date. Abandon further work. return false; } return true; }; var legacy = false; /** * Functions and data related to the execution of a command */ Object.defineProperty(Requisition.prototype, 'executionContext', { get: function() { if (this._executionContext == null) { this._executionContext = { defer: function() { return promise.defer(); }, typedData: function(type, data) { return { isTypedData: true, data: data, type: type }; }, getArgsObject: this.getArgsObject.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._executionContext, 'typed', { get: function() { return requisition.toString(); }, enumerable: true }); Object.defineProperty(this._executionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); Object.defineProperty(this._executionContext, 'shell', { get: function() { return requisition.shell; }, enumerable : true }); /** * This is a temporary property that will change and/or be removed. * Do not use it */ Object.defineProperty(this._executionContext, '__dlhjshfw', { get: function() { return requisition; }, enumerable: false }); if (legacy) { this._executionContext.createView = view.createView; this._executionContext.exec = this.exec.bind(this); this._executionContext.update = this.update.bind(this); this._executionContext.updateExec = this.updateExec.bind(this); Object.defineProperty(this._executionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); } } return this._executionContext; }, enumerable: true }); /** * Functions and data related to the conversion of the output of a command */ Object.defineProperty(Requisition.prototype, 'conversionContext', { get: function() { if (this._conversionContext == null) { this._conversionContext = { defer: function() { return promise.defer(); }, createView: view.createView, exec: this.exec.bind(this), update: this.update.bind(this), updateExec: this.updateExec.bind(this) }; // Alias requisition so we're clear about what's what var requisition = this; Object.defineProperty(this._conversionContext, 'document', { get: function() { return requisition.document; }, enumerable: true }); Object.defineProperty(this._conversionContext, 'environment', { get: function() { return requisition.environment; }, enumerable: true }); /** * This is a temporary property that will change and/or be removed. * Do not use it */ Object.defineProperty(this._conversionContext, '__dlhjshfw', { get: function() { return requisition; }, enumerable: false }); } return this._conversionContext; }, enumerable: true }); /** * Assignments have an order, so we need to store them in an array. * But we also need named access ... * @return The found assignment, or undefined, if no match was found */ Requisition.prototype.getAssignment = function(nameOrNumber) { var name = (typeof nameOrNumber === 'string') ? nameOrNumber : Object.keys(this._assignments)[nameOrNumber]; return this._assignments[name] || undefined; }; /** * There are a few places where we need to know what the 'next thing' is. What * is the user going to be filling out next (assuming they don't enter a named * argument). The next argument is the first in line that is both blank, and * that can be filled in positionally. * @return The next assignment to be used, or null if all the positional * parameters have values. */ Requisition.prototype._getFirstBlankPositionalAssignment = function() { var reply = null; Object.keys(this._assignments).some(function(name) { var assignment = this.getAssignment(name); if (assignment.arg.type === 'BlankArgument' && assignment.param.isPositionalAllowed) { reply = assignment; return true; // i.e. break } return false; }, this); return reply; }; /** * Where parameter name == assignment names - they are the same */ Requisition.prototype.getParameterNames = function() { return Object.keys(this._assignments); }; /** * A *shallow* clone of the assignments. * This is useful for systems that wish to go over all the assignments * finding values one way or another and wish to trim an array as they go. */ Requisition.prototype.cloneAssignments = function() { return Object.keys(this._assignments).map(function(name) { return this._assignments[name]; }, this); }; /** * The overall status is the most severe status. * There is no such thing as an INCOMPLETE overall status because the * definition of INCOMPLETE takes into account the cursor position to say 'this * isn't quite ERROR because the user can fix it by typing', however overall, * this is still an error status. */ Object.defineProperty(Requisition.prototype, 'status', { get : function() { var status = Status.VALID; if (this._unassigned.length !== 0) { var isAllIncomplete = true; this._unassigned.forEach(function(assignment) { if (!assignment.param.type.isIncompleteName) { isAllIncomplete = false; } }); status = isAllIncomplete ? Status.INCOMPLETE : Status.ERROR; } this.getAssignments(true).forEach(function(assignment) { var assignStatus = assignment.getStatus(); if (assignStatus > status) { status = assignStatus; } }, this); if (status === Status.INCOMPLETE) { status = Status.ERROR; } return status; }, enumerable : true }); /** * If ``requisition.status != VALID`` message then return a string which * best describes what is wrong. Generally error messages are delivered by * looking at the error associated with the argument at the cursor, but there * are times when you just want to say 'tell me the worst'. * If ``requisition.status != VALID`` then return ``null``. */ Requisition.prototype.getStatusMessage = function() { if (this.commandAssignment.getStatus() !== Status.VALID) { return l10n.lookup('cliUnknownCommand'); } var assignments = this.getAssignments(); for (var i = 0; i < assignments.length; i++) { if (assignments[i].getStatus() !== Status.VALID) { return assignments[i].message; } } if (this._unassigned.length !== 0) { return l10n.lookup('cliUnusedArg'); } return null; }; /** * Extract the names and values of all the assignments, and return as * an object. */ Requisition.prototype.getArgsObject = function() { var args = {}; this.getAssignments().forEach(function(assignment) { args[assignment.param.name] = assignment.conversion.isDataProvided() ? assignment.value : assignment.param.defaultValue; }, this); return args; }; /** * Access the arguments as an array. * @param includeCommand By default only the parameter arguments are * returned unless (includeCommand === true), in which case the list is * prepended with commandAssignment.arg */ Requisition.prototype.getAssignments = function(includeCommand) { var assignments = []; if (includeCommand === true) { assignments.push(this.commandAssignment); } Object.keys(this._assignments).forEach(function(name) { assignments.push(this.getAssignment(name)); }, this); return assignments; }; /** * When any assignment changes, we might need to update the _args array to * match and inform people of changes to the typed input text. */ Requisition.prototype._setAssignmentInternal = function(assignment, conversion) { var oldConversion = assignment.conversion; assignment.conversion = conversion; assignment.conversion.assignment = assignment; // Do nothing if the value is unchanged if (assignment.conversion.equals(oldConversion) || assignment.conversion.valueEquals(oldConversion)) { return; } // When the command changes, we need to keep a bunch of stuff in sync if (assignment === this.commandAssignment) { this._assignments = {}; var command = this.commandAssignment.value; if (command) { for (var i = 0; i < command.params.length; i++) { var param = command.params[i]; var newAssignment = new Assignment(param, i); var assignPromise = this.setAssignment(newAssignment, null, { internal: true }); util.synchronize(assignPromise); this._assignments[param.name] = newAssignment; } } this.assignmentCount = Object.keys(this._assignments).length; } // For the onTextChange event, we only care about changes to the argument if (!assignment.conversion.argEquals(oldConversion)) { this.onTextChange(); } }; /** * Internal function to alter the given assignment using the given arg. * @param assignment The assignment to alter * @param arg The new value for the assignment. An instance of Argument, or an * instance of Conversion, or null to set the blank value. * @param options There are a number of ways to customize how the assignment * is made, including: * - internal: (default:false) External updates are required to do more work, * including adjusting the args in this requisition to stay in sync. * On the other hand non internal changes use beginChange to back out of * changes when overtaken asynchronously. * Setting internal:true effectively means this is being called as part of * the update process. * - matchPadding: (default:false) Alter the whitespace on the prefix and * suffix of the new argument to match that of the old argument. This only * makes sense with internal=false */ Requisition.prototype.setAssignment = function(assignment, arg, options) { options = options || {}; if (!options.internal) { var originalArgs = assignment.arg.getArgs(); // Update the args array var replacementArgs = arg.getArgs(); var maxLen = Math.max(originalArgs.length, replacementArgs.length); for (var i = 0; i < maxLen; i++) { // If there are no more original args, or if the original arg was blank // (i.e. not typed by the user), we'll just need to add at the end if (i >= originalArgs.length || originalArgs[i].type === 'BlankArgument') { this._args.push(replacementArgs[i]); continue; } var index = this._args.indexOf(originalArgs[i]); if (index === -1) { console.error('Couldn\'t find ', originalArgs[i], ' in ', this._args); throw new Error('Couldn\'t find ' + originalArgs[i]); } // If there are no more replacement args, we just remove the original args // Otherwise swap original args and replacements if (i >= replacementArgs.length) { this._args.splice(index, 1); } else { if (options.matchPadding) { if (replacementArgs[i].prefix.length === 0 && this._args[index].prefix.length !== 0) { replacementArgs[i].prefix = this._args[index].prefix; } if (replacementArgs[i].suffix.length === 0 && this._args[index].suffix.length !== 0) { replacementArgs[i].suffix = this._args[index].suffix; } } this._args[index] = replacementArgs[i]; } } } var updateId = options.internal ? null : this._beginChange(); var setAssignmentInternal = function(conversion) { if (options.internal || this._endChangeCheckOrder(updateId)) { this._setAssignmentInternal(assignment, conversion); } return promise.resolve(undefined); }.bind(this); if (arg == null) { var blank = assignment.param.type.getBlank(this.executionContext); return setAssignmentInternal(blank); } if (typeof arg.getStatus === 'function') { // It's not really an arg, it's a conversion already return setAssignmentInternal(arg); } var parsed = assignment.param.type.parse(arg, this.executionContext); return parsed.then(setAssignmentInternal); }; /** * Reset all the assignments to their default values */ Requisition.prototype.setBlankArguments = function() { this.getAssignments().forEach(function(assignment) { var assignPromise = this.setAssignment(assignment, null, { internal: true }); util.synchronize(assignPromise); }, this); }; /** * Complete the argument at <tt>cursor</tt>. * Basically the same as: * assignment = getAssignmentAt(cursor); * assignment.value = assignment.conversion.predictions[0]; * Except it's done safely, and with particular care to where we place the * space, which is complex, and annoying if we get it wrong. * * WARNING: complete() can happen asynchronously. * * @param cursor The cursor configuration. Should have start and end properties * which should be set to start and end of the selection. * @param predictionChoice The index of the prediction that we should choose. * This number is not bounded by the size of the prediction array, we take the * modulus to get it within bounds * @return A promise which completes (with undefined) when any outstanding * completion tasks are done. */ Requisition.prototype.complete = function(cursor, predictionChoice) { var assignment = this.getAssignmentAt(cursor.start); var predictionPromise = assignment.getPredictionAt(predictionChoice); return predictionPromise.then(function(prediction) { var outstanding = []; this.onTextChange.holdFire(); // Note: Since complete is asynchronous we should perhaps have a system to // bail out of making changes if the command line has changed since TAB // was pressed. It's not yet clear if this will be a problem. if (prediction == null) { // No predictions generally means we shouldn't change anything on TAB, // but TAB has the connotation of 'next thing' and when we're at the end // of a thing that implies that we should add a space. i.e. // 'help<TAB>' -> 'help ' // But we should only do this if the thing that we're 'completing' is // valid and doesn't already end in a space. if (assignment.arg.suffix.slice(-1) !== ' ' && assignment.getStatus() === Status.VALID) { outstanding.push(this._addSpace(assignment)); } // Also add a space if we are in the name part of an assignment, however // this time we don't want the 'push the space to the next assignment' // logic, so we don't use addSpace if (assignment.isInName()) { var newArg = assignment.arg.beget({ prefixPostSpace: true }); outstanding.push(this.setAssignment(assignment, newArg)); } } else { // Mutate this argument to hold the completion var arg = assignment.arg.beget({ text: prediction.name, dontQuote: (assignment === this.commandAssignment) }); var assignPromise = this.setAssignment(assignment, arg); if (!prediction.incomplete) { assignPromise = assignPromise.then(function() { // The prediction is complete, add a space to let the user move-on return this._addSpace(assignment).then(function() { // Bug 779443 - Remove or explain the re-parse if (assignment instanceof UnassignedAssignment) { return this.update(this.toString()); } }.bind(this)); }.bind(this)); } outstanding.push(assignPromise); } return promise.all(outstanding).then(function() { this.onTextChange(); this.onTextChange.resumeFire(); return true; }.bind(this)); }.bind(this)); }; /** * A test method to check that all args are assigned in some way */ Requisition.prototype._assertArgsAssigned = function() { this._args.forEach(function(arg) { if (arg.assignment == null) { console.log('No assignment for ' + arg); } }, this); }; /** * Pressing TAB sometimes requires that we add a space to denote that we're on * to the 'next thing'. * @param assignment The assignment to which to append the space */ Requisition.prototype._addSpace = function(assignment) { var arg = assignment.arg.beget({ suffixSpace: true }); if (arg !== assignment.arg) { return this.setAssignment(assignment, arg); } else { return promise.resolve(undefined); } }; /** * Replace the current value with the lower value if such a concept exists. */ Requisition.prototype.decrement = function(assignment) { var replacement = assignment.param.type.decrement(assignment.value, this.executionContext); if (replacement != null) { var str = assignment.param.type.stringify(replacement, this.executionContext); var arg = assignment.arg.beget({ text: str }); var assignPromise = this.setAssignment(assignment, arg); util.synchronize(assignPromise); } }; /** * Replace the current value with the higher value if such a concept exists. */ Requisition.prototype.increment = function(assignment) { var replacement = assignment.param.type.increment(assignment.value, this.executionContext); if (replacement != null) { var str = assignment.param.type.stringify(replacement, this.executionContext); var arg = assignment.arg.beget({ text: str }); var assignPromise = this.setAssignment(assignment, arg); util.synchronize(assignPromise); } }; /** * Extract a canonical version of the input */ Requisition.prototype.toCanonicalString = function() { var line = []; var cmd = this.commandAssignment.value ? this.commandAssignment.value.name : this.commandAssignment.arg.text; line.push(cmd); Object.keys(this._assignments).forEach(function(name) { var assignment = this._assignments[name]; var type = assignment.param.type; // Bug 664377: This will cause problems if there is a non-default value // after a default value. Also we need to decide when to use // named parameters in place of positional params. Both can wait. if (assignment.value !== assignment.param.defaultValue) { line.push(' '); line.push(type.stringify(assignment.value, this.executionContext)); } }, this); // Canonically, if we've opened with a { then we should have a } to close if (cmd === '{') { if (this.getAssignment(0).arg.suffix.indexOf('}') === -1) { line.push(' }'); } } return line.join(''); }; /** * Input trace gives us an array of Argument tracing objects, one for each * character in the typed input, from which we can derive information about how * to display this typed input. It's a bit like toString on steroids. * <p> * The returned object has the following members:<ul> * <li>character: The character to which this arg trace refers. * <li>arg: The Argument to which this character is assigned. * <li>part: One of ['prefix'|'text'|suffix'] - how was this char understood * </ul> * <p> * The Argument objects are as output from tokenize() rather than as applied * to Assignments by _assign() (i.e. they are not instances of NamedArgument, * ArrayArgument, etc). * <p> * To get at the arguments applied to the assignments simply call * <tt>arg.assignment.arg</tt>. If <tt>arg.assignment.arg !== arg</tt> then * the arg applied to the assignment will contain the original arg. * See _assign() for details. */ Requisition.prototype.createInputArgTrace = function() { if (!this._args) { throw new Error('createInputMap requires a command line. See source.'); // If this is a problem then we can fake command line input using // something like the code in #toCanonicalString(). } var args = []; var i; this._args.forEach(function(arg) { for (i = 0; i < arg.prefix.length; i++) { args.push({ arg: arg, character: arg.prefix[i], part: 'prefix' }); } for (i = 0; i < arg.text.length; i++) { args.push({ arg: arg, character: arg.text[i], part: 'text' }); } for (i = 0; i < arg.suffix.length; i++) { args.push({ arg: arg, character: arg.suffix[i], part: 'suffix' }); } }); return args; }; /** * Reconstitute the input from the args */ Requisition.prototype.toString = function() { if (this._args) { return this._args.map(function(arg) { return arg.toString(); }).join(''); } return this.toCanonicalString(); }; /** * If the last character is whitespace then things that we suggest to add to * the end don't need a space prefix. * While this is quite a niche function, it has 2 benefits: * - it's more correct because we can distinguish between final whitespace that * is part of an unclosed string, and parameter separating whitespace. * - also it's faster than toString() the whole thing and checking the end char * @return true iff the last character is interpreted as parameter separating * whitespace */ Requisition.prototype.typedEndsWithSeparator = function() { // This is not as easy as doing (this.toString().slice(-1) === ' ') // See the doc comments above; We're checking for separators, not spaces if (this._args) { var lastArg = this._args.slice(-1)[0]; if (lastArg.suffix.slice(-1) === ' ') { return true; } return lastArg.text === '' && lastArg.suffix === '' && lastArg.prefix.slice(-1) === ' '; } return this.toCanonicalString().slice(-1) === ' '; }; /** * Return an array of Status scores so we can create a marked up * version of the command line input. * @param cursor We only take a status of INCOMPLETE to be INCOMPLETE when the * cursor is actually in the argument. Otherwise it's an error. * @return Array of objects each containing <tt>status</tt> property and a * <tt>string</tt> property containing the characters to which the status * applies. Concatenating the strings in order gives the original input. */ Requisition.prototype.getInputStatusMarkup = function(cursor) { var argTraces = this.createInputArgTrace(); // Generally the 'argument at the cursor' is the argument before the cursor // unless it is before the first char, in which case we take the first. cursor = cursor === 0 ? 0 : cursor - 1; var cTrace = argTraces[cursor]; var markup = []; for (var i = 0; i < argTraces.length; i++) { var argTrace = argTraces[i]; var arg = argTrace.arg; var status = Status.VALID; if (argTrace.part === 'text') { status = arg.assignment.getStatus(arg); // Promote INCOMPLETE to ERROR ... if (status === Status.INCOMPLETE) { // If the cursor is in the prefix or suffix of an argument then we // don't consider it in the argument for the purposes of preventing // the escalation to ERROR. However if this is a NamedArgument, then we // allow the suffix (as space between 2 parts of the argument) to be in. // We use arg.assignment.arg not arg because we're looking at the arg // that got put into the assignment not as returned by tokenize() var isNamed = (cTrace.arg.assignment.arg.type === 'NamedArgument'); var isInside = cTrace.part === 'text' || (isNamed && cTrace.part === 'suffix'); if (arg.assignment !== cTrace.arg.assignment || !isInside) { // And if we're not in the command if (!(arg.assignment instanceof CommandAssignment)) { status = Status.ERROR; } } } } markup.push({ status: status, string: argTrace.character }); } // De-dupe: merge entries where 2 adjacent have same status i = 0; while (i < markup.length - 1) { if (markup[i].status === markup[i + 1].status) { markup[i].string += markup[i + 1].string; markup.splice(i + 1, 1); } else { i++; } } return markup; }; /** * Look through the arguments attached to our assignments for the assignment * at the given position. * @param {number} cursor The cursor position to query */ Requisition.prototype.getAssignmentAt = function(cursor) { if (!this._args) { console.trace(); throw new Error('Missing args'); } // We short circuit this one because we may have no args, or no args with // any size and the alg below only finds arguments with size. if (cursor === 0) { return this.commandAssignment; } var assignForPos = []; var i, j; for (i = 0; i < this._args.length; i++) { var arg = this._args[i]; var assignment = arg.assignment; // prefix and text are clearly part of the argument for (j = 0; j < arg.prefix.length; j++) { assignForPos.push(assignment); } for (j = 0; j < arg.text.length; j++) { assignForPos.push(assignment); } // suffix is part of the argument only if this is a named parameter, // otherwise it looks forwards if (arg.assignment.arg.type === 'NamedArgument') { // leave the argument as it is } else if (this._args.length > i + 1) { // first to the next argument assignment = this._args[i + 1].assignment; } else { // then to the first blank positional parameter, leaving 'as is' if none var nextAssignment = this._getFirstBlankPositionalAssignment(); if (nextAssignment != null) { assignment = nextAssignment; } } for (j = 0; j < arg.suffix.length; j++) { assignForPos.push(assignment); } } // Possible shortcut, we don't really need to go through all the args // to work out the solution to this var reply = assignForPos[cursor - 1]; if (!reply) { throw new Error('Missing assignment.' + ' cursor=' + cursor + ' text=' + this.toString()); } return reply; }; /** * Entry point for keyboard accelerators or anything else that wants to execute * a command. * @param options Object describing how the execution should be handled. * (optional). Contains some of the following properties: * - hidden (boolean, default=false) Should the output be hidden from the * commandOutputManager for this requisition * - command/args A fast shortcut to executing a known command with a known * set of parsed arguments. */ Requisition.prototype.exec = function(options) { var command = null; var args = null; var hidden = false; if (options) { if (options.hidden) { hidden = true; } if (options.command != null) { // Fast track by looking up the command directly since passed args // means there is no command line to parse. command = canon.getCommand(options.command); if (!command) { console.error('Command not found: ' + options.command); } args = options.args; } } if (!command) { command = this.commandAssignment.value; args = this.getArgsObject(); } // Display JavaScript input without the initial { or closing } var typed = this.toString(); if (evalCmd.isCommandRegexp.test(typed)) { typed = typed.replace(evalCmd.isCommandRegexp, ''); // Bug 717763: What if the JavaScript naturally ends with a }? typed = typed.replace(/\s*}\s*$/, ''); } var output = new Output({ command: command, args: args, typed: typed, canonical: this.toCanonicalString(), hidden: hidden }); this.commandOutputManager.onOutput({ output: output }); var onDone = function(data) { output.complete(data, false); return output; }; var onError = function(ex) { if (exports.logErrors) { util.errorHandler(ex); } var data = ex.isTypedData ? ex : { isTypedData: true, data: ex, type: 'error' }; output.complete(data, true); return output; }; if (this.status !== Status.VALID) { var ex = new Error(this.getStatusMessage()); return promise.resolve(onError(ex)).then(function(output) { this.clear(); return output; }); } else { try { var reply = command.exec(args, this.executionContext); return promise.resolve(reply).then(onDone, onError); } catch (ex) { return promise.resolve(onError(ex)); } finally { this.clear(); } } }; /** * A shortcut for calling update, resolving the promise and then exec. * @param input The string to execute * @param options Passed to exec * @return A promise of an output object */ Requisition.prototype.updateExec = function(input, options) { return this.update(input).then(function() { return this.exec(options); }.bind(this)); }; /** * Similar to update('') except that it's guaranteed to execute synchronously */ Requisition.prototype.clear = function() { this.onTextChange.holdFire(); var arg = new Argument('', '', ''); this._args = [ arg ]; var commandType = this.commandAssignment.param.type; var parsePromise = commandType.parse(arg, this.executionContext); this.setAssignment(this.commandAssignment, util.synchronize(parsePromise), { internal: true }); this.onTextChange.resumeFire(); this.onTextChange(); }; /** * Helper to find the 'data-command' attribute, used by |update()| */ function getDataCommandAttribute(element) { var command = element.getAttribute('data-command'); if (!command) { command = element.querySelector('*[data-command]') .getAttribute('data-command'); } return command; } /** * Called by the UI when ever the user interacts with a command line input * @param typed The contents of the input field */ Requisition.prototype.update = function(typed) { if (typeof HTMLElement !== 'undefined' && typed instanceof HTMLElement) { typed = getDataCommandAttribute(typed); } if (typeof Event !== 'undefined' && typed instanceof Event) { typed = getDataCommandAttribute(typed.currentTarget); } var updateId = this._beginChange(); this._args = exports.tokenize(typed); var args = this._args.slice(0); // i.e. clone return this._split(args).then(function() { if (!this._isChangeCurrent(updateId)) { return false; } return this._assign(args).then(function() { if (this._endChangeCheckOrder(updateId)) { this.onTextChange(); return true; } return false; }.bind(this)); }.bind(this)); }; /** * For test/debug use only. The output from this function is subject to wanton * random change without notice, and should not be relied upon to even exist * at some later date. */ Object.defineProperty(Requisition.prototype, '_summaryJson', { get: function() { var summary = { $args: this._args.map(function(arg) { return arg._summaryJson; }), _command: this.commandAssignment._summaryJson, _unassigned: this._unassigned.forEach(function(assignment) { return assignment._summaryJson; }) }; Object.keys(this._assignments).forEach(function(name) { summary[name] = this.getAssignment(name)._summaryJson; }.bind(this)); return summary; }, enumerable: true }); /** * tokenize() is a state machine. These are the states. */ var In = { /** * The last character was ' '. * Typing a ' ' character will not change the mode * Typing one of '"{ will change mode to SINGLE_Q, DOUBLE_Q or SCRIPT. * Anything else goes into SIMPLE mode. */ WHITESPACE: 1, /** * The last character was part of a parameter. * Typing ' ' returns to WHITESPACE mode. Any other character * (including '"{} which are otherwise special) does not change the mode. */ SIMPLE: 2, /** * We're inside single quotes: ' * Typing ' returns to WHITESPACE mode. Other characters do not change mode. */ SINGLE_Q: 3, /** * We're inside double quotes: " * Typing " returns to WHITESPACE mode. Other characters do not change mode. */ DOUBLE_Q: 4, /** * We're inside { and } * Typing } returns to WHITESPACE mode. Other characters do not change mode. * SCRIPT mode is slightly different from other modes in that spaces between * the {/} delimiters and the actual input are not considered significant. * e.g: " x " is a 3 character string, delimited by double quotes, however * { x } is a 1 character JavaScript surrounded by whitespace and {} * delimiters. * In the short term we assume that the JS routines can make sense of the * extra whitespace, however at some stage we may need to move the space into * the Argument prefix/suffix. * Also we don't attempt to handle nested {}. See bug 678961 */ SCRIPT: 5 }; /** * Split up the input taking into account ', " and {. * We don't consider \t or other classical whitespace characters to split * arguments apart. For one thing these characters are hard to type, but also * if the user has gone to the trouble of pasting a TAB character into the * input field (or whatever it takes), they probably mean it. */ exports.tokenize = function(typed) { // For blank input, place a dummy empty argument into the list if (typed == null || typed.length === 0) { return [ new Argument('', '', '') ]; } if (isSimple(typed)) { return [ new Argument(typed, '', '') ]; } var mode = In.WHITESPACE; // First we swap out escaped characters that are special to the tokenizer. // So a backslash followed by any of ['"{} ] is turned into a unicode private // char so we can swap back later typed = typed .replace(/\\\\/g, '\uF000') .replace(/\\ /g, '\uF001') .replace(/\\'/g, '\uF002') .replace(/\\"/g, '\uF003') .replace(/\\{/g, '\uF004') .replace(/\\}/g, '\uF005'); function unescape2(escaped) { return escaped .replace(/\uF000/g, '\\\\') .replace(/\uF001/g, '\\ ') .replace(/\uF002/g, '\\\'') .replace(/\uF003/g, '\\\"') .replace(/\uF004/g, '\\{') .replace(/\uF005/g, '\\}'); } var i = 0; // The index of the current character var start = 0; // Where did this section start? var prefix = ''; // Stuff that comes before the current argument var args = []; // The array that we're creating var blockDepth = 0; // For JS with nested {} // This is just a state machine. We're going through the string char by char // The 'mode' is one of the 'In' states. As we go, we're adding Arguments // to the 'args' array. while (true) { var c = typed[i]; var str; switch (mode) { case In.WHITESPACE: if (c === '\'') { prefix = typed.substring(start, i + 1); mode = In.SINGLE_Q; start = i + 1; } else if (c === '"') { prefix = typed.substring(start, i + 1); mode = In.DOUBLE_Q; start = i + 1; } else if (c === '{') { prefix = typed.substring(start, i + 1); mode = In.SCRIPT; blockDepth++; start = i + 1; } else if (/ /.test(c)) { // Still whitespace, do nothing } else { prefix = typed.substring(start, i); mode = In.SIMPLE; start = i; } break; case In.SIMPLE: // There is an edge case of xx'xx which we are assuming to // be a single parameter (and same with ") if (c === ' ') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, '')); mode = In.WHITESPACE; start = i; prefix = ''; } break; case In.SINGLE_Q: if (c === '\'') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.DOUBLE_Q: if (c === '"') { str = unescape2(typed.substring(start, i)); args.push(new Argument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } break; case In.SCRIPT: if (c === '{') { blockDepth++; } else if (c === '}') { blockDepth--; if (blockDepth === 0) { str = unescape2(typed.substring(start, i)); args.push(new ScriptArgument(str, prefix, c)); mode = In.WHITESPACE; start = i + 1; prefix = ''; } } break; } i++; if (i >= typed.length) { // There is nothing else to read - tidy up if (mode === In.WHITESPACE) { if (i !== start) { // There's whitespace at the end of the typed string. Add it to the // last argument's suffix, creating an empty argument if needed. var extra = typed.substring(start, i); var lastArg = args[args.length - 1]; if (!lastArg) { args.push(new Argument('', extra, '')); } else { lastArg.suffix += extra; } } } else if (mode === In.SCRIPT) { str = unescape2(typed.substring(start, i + 1)); args.push(new ScriptArgument(str, prefix, '')); } else { str = unescape2(typed.substring(start, i + 1)); args.push(new Argument(str, prefix, '')); } break; } } return args; }; /** * If the input has no spaces, quotes, braces or escapes, * we can take the fast track. */ function isSimple(typed) { for (var i = 0; i < typed.length; i++) { var c = typed.charAt(i); if (c === ' ' || c === '"' || c === '\'' || c === '{' || c === '}' || c === '\\') { return false; } } return true; } /** * Looks in the canon for a command extension that matches what has been * typed at the command line. */ Requisition.prototype._split = function(args) { // We're processing args, so we don't want the assignments that we make to // try to adjust other args assuming this is an external update var noArgUp = { internal: true }; // Handle the special case of the user typing { javascript(); } // We use the hidden 'eval' command directly rather than shift()ing one of // the parameters, and parse()ing it. var conversion; if (args[0].type === 'ScriptArgument') { // Special case: if the user enters { console.log('foo'); } then we need to // use the hidden 'eval' command conversion = new Conversion(getEvalCommand(), new ScriptArgument()); return this.setAssignment(this.commandAssignment, conversion, noArgUp); } var argsUsed = 1; var parsePromise; var commandType = this.commandAssignment.param.type; while (argsUsed <= args.length) { var arg = (argsUsed === 1) ? args[0] : new MergedArgument(args, 0, argsUsed); // Making the commandType.parse() promise as synchronous is OK because we // know that commandType is a synchronous type. if (this.prefix != null && this.prefix !== '') { var prefixArg = new Argument(this.prefix, '', ' '); var prefixedArg = new MergedArgument([ prefixArg, arg ]); parsePromise = commandType.parse(prefixedArg, this.executionContext); conversion = util.synchronize(parsePromise); if (conversion.value == null) { parsePromise = commandType.parse(arg, this.executionContext); conversion = util.synchronize(parsePromise); } } else { parsePromise = commandType.parse(arg, this.executionContext); conversion = util.synchronize(parsePromise); } // We only want to carry on if this command is a parent command, // which means that there is a commandAssignment, but not one with // an exec function. if (!conversion.value || conversion.value.exec) { break; } // Previously we needed a way to hide commands depending context. // We have not resurrected that feature yet, but if we do we should // insert code here to ignore certain commands depending on the // context/environment argsUsed++; } // This could probably be re-written to consume args as we go for (var i = 0; i < argsUsed; i++) { args.shift(); } // Warning: we're returning a promise (from setAssignment) which tells us // when we're done setting the current command, but mutating the args array // as we go, so we're conflicted on when we're done return this.setAssignment(this.commandAssignment, conversion, noArgUp); }; /** * Add all the passed args to the list of unassigned assignments. */ Requisition.prototype._addUnassignedArgs = function(args) { args.forEach(function(arg) { this._unassigned.push(new UnassignedAssignment(this, arg)); }.bind(this)); }; /** * Work out which arguments are applicable to which parameters. */ Requisition.prototype._assign = function(args) { // See comment in _split. Avoid multiple updates var noArgUp = { internal: true }; this._unassigned = []; var outstanding = []; if (!this.commandAssignment.value) { this._addUnassignedArgs(args); return promise.all(outstanding); } if (args.length === 0) { this.setBlankArguments(); return promise.all(outstanding); } // Create an error if the command does not take parameters, but we have // been given them ... if (this.assignmentCount === 0) { this._addUnassignedArgs(args); return promise.all(outstanding); } // Special case: if there is only 1 parameter, and that's of type // text, then we put all the params into the first param if (this.assignmentCount === 1) { var assignment = this.getAssignment(0); if (assignment.param.type.name === 'string') { var arg = (args.length === 1) ? args[0] : new MergedArgument(args); outstanding.push(this.setAssignment(assignment, arg, noArgUp)); return promise.all(outstanding); } } // Positional arguments can still be specified by name, but if they are // then we need to ignore them when working them out positionally var unassignedParams = this.getParameterNames(); // We collect the arguments used in arrays here before assigning var arrayArgs = {}; // Extract all the named parameters this.getAssignments(false).forEach(function(assignment) { // Loop over the arguments // Using while rather than loop because we remove args as we go var i = 0; while (i < args.length) { if (assignment.param.isKnownAs(args[i].text)) { var arg = args.splice(i, 1)[0]; unassignedParams = unassignedParams.filter(function(test) { return test !== assignment.param.name; }); // boolean parameters don't have values, default to false if (assignment.param.type.name === 'boolean') { arg = new TrueNamedArgument(arg); } else { var valueArg = null; if (i + 1 <= args.length) { valueArg = args.splice(i, 1)[0]; } arg = new NamedArgument(arg, valueArg); } if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArgument(arg); } else { outstanding.push(this.setAssignment(assignment, arg, noArgUp)); } } else { // Skip this parameter and handle as a positional parameter i++; } } }, this); // What's left are positional parameters: assign in order unassignedParams.forEach(function(name) { var assignment = this.getAssignment(name); // If not set positionally, and we can't set it non-positionally, // we have to default it to prevent previous values surviving if (!assignment.param.isPositionalAllowed) { outstanding.push(this.setAssignment(assignment, null, noArgUp)); return; } // If this is a positional array argument, then it swallows the // rest of the arguments. if (assignment.param.type.name === 'array') { var arrayArg = arrayArgs[assignment.param.name]; if (!arrayArg) { arrayArg = new ArrayArgument(); arrayArgs[assignment.param.name] = arrayArg; } arrayArg.addArguments(args); args = []; // The actual assignment to the array parameter is done below return; } // Set assignment to defaults if there are no more arguments if (args.length === 0) { outstanding.push(this.setAssignment(assignment, null, noArgUp)); return; } var arg = args.splice(0, 1)[0]; // --foo and -f are named parameters, -4 is a number. So '-' is either // the start of a named parameter or a number depending on the context var isIncompleteName = assignment.param.type.name === 'number' ? /-[-a-zA-Z_]/.test(arg.text) : arg.text.charAt(0) === '-'; if (isIncompleteName) { this._unassigned.push(new UnassignedAssignment(this, arg)); } else { outstanding.push(this.setAssignment(assignment, arg, noArgUp)); } }, this); // Now we need to assign the array argument (if any) Object.keys(arrayArgs).forEach(function(name) { var assignment = this.getAssignment(name); outstanding.push(this.setAssignment(assignment, arrayArgs[name], noArgUp)); }, this); // What's left is can't be assigned, but we need to officially unassign them this._addUnassignedArgs(args); return promise.all(outstanding); }; exports.Requisition = Requisition; /** * A simple object to hold information about the output of a command */ function Output(options) { options = options || {}; this.command = options.command || ''; this.args = options.args || {}; this.typed = options.typed || ''; this.canonical = options.canonical || ''; this.hidden = options.hidden === true ? true : false; this.type = undefined; this.data = undefined; this.completed = false; this.error = false; this.start = new Date(); this._deferred = promise.defer(); this.promise = this._deferred.promise; this.onClose = util.createEvent('Output.onClose'); } /** * Called when there is data to display, and the command has finished executing * See changed() for details on parameters. */ Output.prototype.complete = function(data, error) { this.end = new Date(); this.duration = this.end.getTime() - this.start.getTime(); this.completed = true; this.error = error; if (data != null && data.isTypedData) { this.data = data.data; this.type = data.type; } else { this.data = data; this.type = this.command.returnType; if (this.type == null) { this.type = (this.data == null) ? 'undefined' : typeof this.data; } } if (this.type === 'object') { throw new Error('No type from output of ' + this.typed); } this._deferred.resolve(); }; /** * Call converters.convert using the data in this Output object */ Output.prototype.convert = function(type, conversionContext) { return converters.convert(this.data, this.type, type, conversionContext); }; exports.Output = Output; });
refactor-864370: null protect assignment.conversion assignment.conversion can be null, so check for that before using it. Signed-off-by: Joe Walker <[email protected]>
lib/gcli/cli.js
refactor-864370: null protect assignment.conversion
<ide><path>ib/gcli/cli.js <ide> */ <ide> Object.defineProperty(Assignment.prototype, 'arg', { <ide> get: function() { <del> return this.conversion.arg; <add> return this.conversion == null ? undefined : this.conversion.arg; <ide> }, <ide> enumerable: true <ide> }); <ide> */ <ide> Object.defineProperty(Assignment.prototype, 'value', { <ide> get: function() { <del> return this.conversion.value; <add> return this.conversion == null ? undefined : this.conversion.value; <ide> }, <ide> enumerable: true <ide> }); <ide> */ <ide> Object.defineProperty(Assignment.prototype, 'message', { <ide> get: function() { <del> return this.conversion.message ? this.conversion.message : ''; <add> return this.conversion == null || !this.conversion.message ? <add> '' : this.conversion.message; <ide> }, <ide> enumerable: true <ide> }); <ide> * [ { name:'bestmatch', value:foo1 }, { name:'next', value:foo2 }, ... ] <ide> */ <ide> Assignment.prototype.getPredictions = function() { <del> return this.conversion.getPredictions(); <add> return this.conversion == null ? [] : this.conversion.getPredictions(); <ide> }; <ide> <ide> /**
Java
apache-2.0
dccd32223000b44980772d8f8ba037f4e78c877d
0
ouyangkongtong/Hystrix,Fsero/Hystrix,mickdwyer/Hystrix,hcheung/Hystrix,JayhJung/Hystrix,coopsource/Hystrix,sensaid/Hystrix,dmgcodevil/Hystrix,Siddartha07/Hystrix,sposam/Hystrix,Netflix/Hystrix,reboss/Hystrix,justinjose28/Hystrix,manwithharmonica/Hystrix,sasrin/Hystrix,JayhJung/Hystrix,fabcipriano/Hystrix,daveray/Hystrix,tvaughan77/Hystrix,liyuqi/Hystrix,mauricionr/Hystrix,eunmin/Hystrix,coopsource/Hystrix,Muktesh01/Hystrix,JayhJung/Hystrix,mantofast/Hystrix,davidkarlsen/Hystrix,yshaojie/Hystrix,jordancheah/Hystrix,daveray/Hystrix,ruhkopf/Hystrix,fengshao0907/Hystrix,yshaojie/Hystrix,sensaid/Hystrix,pcssi/Hystrix,mattrjacobs/Hystrix,liyuqi/Hystrix,fredboutin/Hystrix,npccsb/Hystrix,mattrjacobs/Hystrix,eunmin/Hystrix,tvaughan77/Hystrix,dmgcodevil/Hystrix,KoltonAndrus/Hystrix,gorcz/Hystrix,mattrjacobs/Hystrix,sposam/Hystrix,KoltonAndrus/Hystrix,manwithharmonica/Hystrix,loop-jazz/Hystrix,rukor/Hystrix,ruhkopf/Hystrix,davidkarlsen/Hystrix,gorcz/Hystrix,sasrin/Hystrix,Fsero/Hystrix,dmgcodevil/Hystrix,sposam/Hystrix,mebigfatguy/Hystrix,ianynchen/Hystrix,Fsero/Hystrix,agentgt/Hystrix,jordancheah/Hystrix,mebigfatguy/Hystrix,pcssi/Hystrix,thomasandersen77/Hystrix,jordancheah/Hystrix,robertroeser/Hystrix,KoltonAndrus/Hystrix,yshaojie/Hystrix,mickdwyer/Hystrix,Muktesh01/Hystrix,liyuqi/Hystrix,reboss/Hystrix,fengshao0907/Hystrix,jforge/Hystrix,thomasandersen77/Hystrix,robertroeser/Hystrix,Siddartha07/Hystrix,fabcipriano/Hystrix,wangsan/Hystrix,fredboutin/Hystrix,fengshao0907/Hystrix,justinjose28/Hystrix,loop-jazz/Hystrix,reboss/Hystrix,hcheung/Hystrix,justinjose28/Hystrix,wangsan/Hystrix,Siddartha07/Hystrix,npccsb/Hystrix,jforge/Hystrix,manwithharmonica/Hystrix,robertroeser/Hystrix,mauricionr/Hystrix,npccsb/Hystrix,sasrin/Hystrix,mickdwyer/Hystrix,tvaughan77/Hystrix,fredboutin/Hystrix,pcssi/Hystrix,ouyangkongtong/Hystrix,rukor/Hystrix,eunmin/Hystrix,ruhkopf/Hystrix,davidkarlsen/Hystrix,sensaid/Hystrix,thomasandersen77/Hystrix,jforge/Hystrix,agentgt/Hystrix,fabcipriano/Hystrix,rukor/Hystrix,hcheung/Hystrix,mauricionr/Hystrix,gorcz/Hystrix,ouyangkongtong/Hystrix,loop-jazz/Hystrix,wangsan/Hystrix,mantofast/Hystrix,coopsource/Hystrix,mantofast/Hystrix,agentgt/Hystrix,Muktesh01/Hystrix,mebigfatguy/Hystrix
/** * Copyright 2012 Netflix, 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.netflix.hystrix; import static org.junit.Assert.*; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.ThreadSafe; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.Scheduler; import rx.Subscription; import rx.concurrency.Schedulers; import rx.operators.AtomicObservableSubscription; import rx.subjects.ReplaySubject; import rx.subscriptions.Subscriptions; import rx.util.functions.Action0; import rx.util.functions.Func1; import rx.util.functions.Func2; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.HystrixCircuitBreaker.NoOpCircuitBreaker; import com.netflix.hystrix.HystrixCircuitBreaker.TestCircuitBreaker; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault; import com.netflix.hystrix.strategy.concurrency.HystrixContextCallable; import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; import com.netflix.hystrix.util.ExceptionThreadingUtility; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import com.netflix.hystrix.util.HystrixTimer; import com.netflix.hystrix.util.HystrixTimer.TimerListener; /** * Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) * with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. * * @param <R> * the return type */ @ThreadSafe public abstract class HystrixCommand<R> implements HystrixExecutable<R> { private static final Logger logger = LoggerFactory.getLogger(HystrixCommand.class); private final HystrixCircuitBreaker circuitBreaker; private final HystrixThreadPool threadPool; private final HystrixThreadPoolKey threadPoolKey; private final HystrixCommandProperties properties; private final HystrixCommandMetrics metrics; /* result of execution (if this command instance actually gets executed, which may not occur due to request caching) */ private volatile ExecutionResult executionResult = ExecutionResult.EMPTY; /* If this command executed and timed-out */ private final AtomicBoolean isCommandTimedOut = new AtomicBoolean(false); private final AtomicBoolean isExecutionComplete = new AtomicBoolean(false); private final AtomicBoolean isExecutedInThread = new AtomicBoolean(false); private final HystrixCommandKey commandKey; private final HystrixCommandGroupKey commandGroup; /* FALLBACK Semaphore */ private final TryableSemaphore fallbackSemaphoreOverride; /* each circuit has a semaphore to restrict concurrent fallback execution */ private static final ConcurrentHashMap<String, TryableSemaphore> fallbackSemaphorePerCircuit = new ConcurrentHashMap<String, TryableSemaphore>(); /* END FALLBACK Semaphore */ /* EXECUTION Semaphore */ private final TryableSemaphore executionSemaphoreOverride; /* each circuit has a semaphore to restrict concurrent fallback execution */ private static final ConcurrentHashMap<String, TryableSemaphore> executionSemaphorePerCircuit = new ConcurrentHashMap<String, TryableSemaphore>(); /* END EXECUTION Semaphore */ private final AtomicReference<Reference<TimerListener>> timeoutTimer = new AtomicReference<Reference<TimerListener>>(); private AtomicBoolean started = new AtomicBoolean(); private volatile long invocationStartTime = -1; /** * Instance of RequestCache logic */ private final HystrixRequestCache requestCache; /** * Plugin implementations */ private final HystrixEventNotifier eventNotifier; private final HystrixConcurrencyStrategy concurrencyStrategy; private final HystrixCommandExecutionHook executionHook; /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, * common business purpose etc. */ protected HystrixCommand(HystrixCommandGroupKey group) { // use 'null' to specify use the default this(new Setter(group)); } /** * Construct a {@link HystrixCommand} with defined {@link Setter} that allows injecting property and strategy overrides and other optional arguments. * <p> * NOTE: The {@link HystrixCommandKey} is used to associate a {@link HystrixCommand} with {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and other objects. * <p> * Do not create multiple {@link HystrixCommand} implementations with the same {@link HystrixCommandKey} but different injected default properties as the first instantiated will win. * * @param setter * Fluent interface for constructor arguments */ protected HystrixCommand(Setter setter) { // use 'null' to specify use the default this(setter.groupKey, setter.commandKey, setter.threadPoolKey, null, null, setter.commandPropertiesDefaults, setter.threadPoolPropertiesDefaults, null, null, null, null, null); } /** * Allow constructing a {@link HystrixCommand} with injection of most aspects of its functionality. * <p> * Some of these never have a legitimate reason for injection except in unit testing. * <p> * Most of the args will revert to a valid default if 'null' is passed in. */ private HystrixCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { /* * CommandGroup initialization */ if (group == null) { throw new IllegalStateException("HystrixCommandGroup can not be NULL"); } else { this.commandGroup = group; } /* * CommandKey initialization */ if (key == null || key.name().trim().equals("")) { final String keyName = getDefaultNameFromClass(getClass()); this.commandKey = HystrixCommandKey.Factory.asKey(keyName); } else { this.commandKey = key; } /* * Properties initialization */ if (propertiesStrategy == null) { this.properties = HystrixPropertiesFactory.getCommandProperties(this.commandKey, commandPropertiesDefaults); } else { // used for unit testing this.properties = propertiesStrategy.getCommandProperties(this.commandKey, commandPropertiesDefaults); } /* * ThreadPoolKey * * This defines which thread-pool this command should run on. * * It uses the HystrixThreadPoolKey if provided, then defaults to use HystrixCommandGroup. * * It can then be overridden by a property if defined so it can be changed at runtime. */ if (this.properties.executionIsolationThreadPoolKeyOverride().get() == null) { // we don't have a property overriding the value so use either HystrixThreadPoolKey or HystrixCommandGroup if (threadPoolKey == null) { /* use HystrixCommandGroup if HystrixThreadPoolKey is null */ this.threadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name()); } else { this.threadPoolKey = threadPoolKey; } } else { // we have a property defining the thread-pool so use it instead this.threadPoolKey = HystrixThreadPoolKey.Factory.asKey(properties.executionIsolationThreadPoolKeyOverride().get()); } /* strategy: HystrixEventNotifier */ this.eventNotifier = HystrixPlugins.getInstance().getEventNotifier(); /* strategy: HystrixConcurrentStrategy */ this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); /* * Metrics initialization */ if (metrics == null) { this.metrics = HystrixCommandMetrics.getInstance(this.commandKey, this.commandGroup, this.properties); } else { this.metrics = metrics; } /* * CircuitBreaker initialization */ if (this.properties.circuitBreakerEnabled().get()) { if (circuitBreaker == null) { // get the default implementation of HystrixCircuitBreaker this.circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(this.commandKey, this.commandGroup, this.properties, this.metrics); } else { this.circuitBreaker = circuitBreaker; } } else { this.circuitBreaker = new NoOpCircuitBreaker(); } /* strategy: HystrixMetricsPublisherCommand */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(this.commandKey, this.commandGroup, this.metrics, this.circuitBreaker, this.properties); /* strategy: HystrixCommandExecutionHook */ if (executionHook == null) { this.executionHook = HystrixPlugins.getInstance().getCommandExecutionHook(); } else { // used for unit testing this.executionHook = executionHook; } /* * ThreadPool initialization */ if (threadPool == null) { // get the default implementation of HystrixThreadPool this.threadPool = HystrixThreadPool.Factory.getInstance(this.threadPoolKey, threadPoolPropertiesDefaults); } else { this.threadPool = threadPool; } /* fallback semaphore override if applicable */ this.fallbackSemaphoreOverride = fallbackSemaphore; /* execution semaphore override if applicable */ this.executionSemaphoreOverride = executionSemaphore; /* setup the request cache for this instance */ this.requestCache = HystrixRequestCache.getInstance(this.commandKey, this.concurrencyStrategy); } private static String getDefaultNameFromClass(@SuppressWarnings("rawtypes") Class<? extends HystrixCommand> cls) { String fromCache = defaultNameCache.get(cls); if (fromCache != null) { return fromCache; } // generate the default // default HystrixCommandKey to use if the method is not overridden String name = cls.getSimpleName(); if (name.equals("")) { // we don't have a SimpleName (anonymous inner class) so use the full class name name = cls.getName(); name = name.substring(name.lastIndexOf('.') + 1, name.length()); } defaultNameCache.put(cls, name); return name; } // this is a micro-optimization but saves about 1-2microseconds (on 2011 MacBook Pro) // on the repetitive string processing that will occur on the same classes over and over again @SuppressWarnings("rawtypes") private static ConcurrentHashMap<Class<? extends HystrixCommand>, String> defaultNameCache = new ConcurrentHashMap<Class<? extends HystrixCommand>, String>(); /** * Implement this method with code to be executed when {@link #execute()} or {@link #queue()} are invoked. * * @return R response type * @throws Exception * if command execution fails */ protected abstract R run() throws Exception; /** * If {@link #execute()} or {@link #queue()} fails in any way then this method will be invoked to provide an opportunity to return a fallback response. * <p> * This should do work that does not require network transport to produce. * <p> * In other words, this should be a static or cached result that can immediately be returned upon failure. * <p> * If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another {@link HystrixCommand} instance that protects against that network * access and possibly has another level of fallback that does not involve network access. * <p> * DEFAULT BEHAVIOR: It throws UnsupportedOperationException. * * @return R or throw UnsupportedOperationException if not implemented */ protected R getFallback() { throw new UnsupportedOperationException("No fallback available."); } /** * @return {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, * common business purpose etc. */ public HystrixCommandGroupKey getCommandGroup() { return commandGroup; } /** * @return {@link HystrixCommandKey} identifying this command instance for statistics, circuit-breaker, properties, etc. */ public HystrixCommandKey getCommandKey() { return commandKey; } /** * @return {@link HystrixThreadPoolKey} identifying which thread-pool this command uses (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). */ public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } /* package */HystrixCircuitBreaker getCircuitBreaker() { return circuitBreaker; } /** * The {@link HystrixCommandMetrics} associated with this {@link HystrixCommand} instance. * * @return HystrixCommandMetrics */ public HystrixCommandMetrics getMetrics() { return metrics; } /** * The {@link HystrixCommandProperties} associated with this {@link HystrixCommand} instance. * * @return HystrixCommandProperties */ public HystrixCommandProperties getProperties() { return properties; } /** * Allow the Collapser to mark this command instance as being used for a collapsed request and how many requests were collapsed. * * @param sizeOfBatch */ /* package */void markAsCollapsedCommand(int sizeOfBatch) { getMetrics().markCollapsed(sizeOfBatch); executionResult = executionResult.addEvents(HystrixEventType.COLLAPSED); } /** * Used for synchronous execution of command. * * @return R * Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a failure occurs and a fallback cannot be retrieved * @throws HystrixBadRequestException * if invalid arguments or state were used representing a user failure, not a system failure */ public R execute() { try { return queue().get(); } catch (Exception e) { throw decomposeException(e); } } /** * Used for asynchronous execution of command. * <p> * This will queue up the command on the thread pool and return an {@link Future} to get the result once it completes. * <p> * NOTE: If configured to not run in a separate thread, this will have the same effect as {@link #execute()} and will block. * <p> * We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread. * * @return {@code Future<R>} Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Future.get()} in {@link ExecutionException#getCause()} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Future.get()} in {@link ExecutionException#getCause()} if invalid arguments or state were used representing a user failure, not a system failure */ public Future<R> queue() { /* * --- Schedulers.immediate() * * We use the 'immediate' schedule since Future.get() is blocking so we don't want to bother doing the callback to the Future on a separate thread * as we don't need to separate the Hystrix thread from user threads since they are already providing it via the Future.get() call. * * --- performAsyncTimeout: false * * We pass 'false' to tell the Observable we will block on it so it doesn't schedule an async timeout. * * This optimizes for using the calling thread to do the timeout rather than scheduling another thread. * * In a tight-loop of executing commands this optimization saves a few microseconds per execution. * It also just makes no sense to use a separate thread to timeout the command when the calling thread * is going to sit waiting on it. */ final ObservableCommand<R> o = toObservable(Schedulers.immediate(), false); final Future<R> f = o.toBlockingObservable().toFuture(); /* special handling of error states that throw immediately */ if (f.isDone()) { try { f.get(); return f; } catch (Exception e) { RuntimeException re = decomposeException(e); if (re instanceof HystrixRuntimeException) { HystrixRuntimeException hre = (HystrixRuntimeException) re; if (hre.getFailureType() == FailureType.COMMAND_EXCEPTION || hre.getFailureType() == FailureType.TIMEOUT) { // we don't throw these types from queue() only from queue().get() as they are execution errors return f; } else { // these are errors we throw from queue() as they as rejection type errors throw hre; } } else { throw re; } } } return new Future<R>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return f.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return f.isCancelled(); } @Override public boolean isDone() { return f.isDone(); } @Override public R get() throws InterruptedException, ExecutionException { return performBlockingGetWithTimeout(o, f); } /** * --- Non-Blocking Timeout (performAsyncTimeout:true) --- * * When 'toObservable' is done with non-blocking timeout then timeout functionality is provided * by a separate HystrixTimer thread that will "tick" and cancel the underlying async Future inside the Observable. * * This method allows stealing that responsibility and letting the thread that's going to block anyways * do the work to reduce pressure on the HystrixTimer. * * Blocking via queue().get() on a non-blocking timeout will work it's just less efficient * as it involves an extra thread and cancels the scheduled action that does the timeout. * * --- Blocking Timeout (performAsyncTimeout:false) --- * * When blocking timeout is assumed (default behavior for execute/queue flows) then the async * timeout will not have been scheduled and this will wait in a blocking manner and if a timeout occurs * trigger the timeout logic that comes from inside the Observable/Observer. * * * --- Examples * * Stack for timeout with performAsyncTimeout=false (note the calling thread via get): * * at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$1.tick(HystrixCommand.java:788) * at com.netflix.hystrix.HystrixCommand$1.performBlockingGetWithTimeout(HystrixCommand.java:536) * at com.netflix.hystrix.HystrixCommand$1.get(HystrixCommand.java:484) * at com.netflix.hystrix.HystrixCommand.execute(HystrixCommand.java:413) * * * Stack for timeout with performAsyncTimeout=true (note the HystrixTimer involved): * * at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$1.tick(HystrixCommand.java:799) * at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:101) * * * * @param o * @param f * @throws InterruptedException * @throws ExecutionException */ protected R performBlockingGetWithTimeout(final ObservableCommand<R> o, final Future<R> f) throws InterruptedException, ExecutionException { // shortcut if already done if (f.isDone()) { return f.get(); } // it's still working so proceed with blocking/timeout logic HystrixCommand<R> originalCommand = o.getCommand(); /** * One thread will get the timeoutTimer if it's set and clear it then do blocking timeout. * <p> * If non-blocking timeout was scheduled this will unschedule it. If it wasn't scheduled it is basically * a no-op but fits the same interface so blocking and non-blocking flows both work the same. * <p> * This "originalCommand" concept exists because of request caching. We only do the work and timeout logic * on the original, not the cached responses. However, whichever the first thread is that comes in to block * will be the one who performs the timeout logic. * <p> * If request caching is disabled then it will always go into here. */ if (originalCommand != null) { Reference<TimerListener> timer = originalCommand.timeoutTimer.getAndSet(null); if (timer != null) { /** * If an async timeout was scheduled then: * * - We are going to clear the Reference<TimerListener> so the scheduler threads stop managing the timeout * and we'll take over instead since we're going to be blocking on it anyways. * * - Other threads (since we won the race) will just wait on the normal Future which will release * once the Observable is marked as completed (which may come via timeout) * * If an async timeout was not scheduled: * * - We go through the same flow as we receive the same interfaces just the "timer.clear()" will do nothing. */ // get the timer we'll use to perform the timeout TimerListener l = timer.get(); // remove the timer from the scheduler timer.clear(); // determine how long we should wait for, taking into account time since work started // and when this thread came in to block. If invocationTime hasn't been set then assume time remaining is entire timeout value // as this maybe a case of multiple threads trying to run this command in which one thread wins but even before the winning thread is able to set // the starttime another thread going via the Cached command route gets here first. long timeout = originalCommand.properties.executionIsolationThreadTimeoutInMilliseconds().get(); long timeRemaining = timeout; long currTime = System.currentTimeMillis(); if (originalCommand.invocationStartTime != -1) { timeRemaining = (originalCommand.invocationStartTime + originalCommand.properties.executionIsolationThreadTimeoutInMilliseconds().get()) - currTime; } if (timeRemaining > 0) { // we need to block with the calculated timeout try { return f.get(timeRemaining, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { if (l != null) { // this perform the timeout logic on the Observable/Observer l.tick(); } } } else { // this means it should have already timed out so do so if it is not completed if (!f.isDone()) { if (l != null) { l.tick(); } } } } } // other threads will block until the "l.tick" occurs and releases the underlying Future. return f.get(); } @Override public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; } /** * Take an Exception and determine whether to throw it, its cause or a new HystrixRuntimeException. * <p> * This will only throw an HystrixRuntimeException or HystrixBadRequestException * * @param e * @return HystrixRuntimeException or HystrixBadRequestException */ protected RuntimeException decomposeException(Exception e) { if (e instanceof HystrixBadRequestException) { return (HystrixBadRequestException) e; } if (e.getCause() instanceof HystrixBadRequestException) { return (HystrixBadRequestException) e.getCause(); } if (e instanceof HystrixRuntimeException) { return (HystrixRuntimeException) e; } // if we have an exception we know about we'll throw it directly without the wrapper exception if (e.getCause() instanceof HystrixRuntimeException) { return (HystrixRuntimeException) e.getCause(); } // we don't know what kind of exception this is so create a generic message and throw a new HystrixRuntimeException String message = getLogMessagePrefix() + " failed while executing."; logger.debug(message, e); // debug only since we're throwing the exception and someone higher will do something with it return new HystrixRuntimeException(FailureType.COMMAND_EXCEPTION, this.getClass(), message, e, null); } public Observable<R> observe() { // us a ReplaySubject to buffer the eagerly subscribed-to Observable ReplaySubject<R> subject = ReplaySubject.create(); // eagerly kick off subscription toObservable().subscribe(subject); // return the subject that can be subscribed to later while the execution has already started return subject; } public Observable<R> toObservable() { if (properties.executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD)) { return toObservable(Schedulers.threadPoolForComputation()); } else { // semaphore isolation is all blocking, no new threads involved // so we'll use the calling thread return toObservable(Schedulers.immediate()); } } public Observable<R> toObservable(Scheduler observeOn) { return toObservable(observeOn, true); } private ObservableCommand<R> toObservable(Scheduler observeOn, boolean performAsyncTimeout) { /* this is a stateful object so can only be used once */ if (!started.compareAndSet(false, true)) { throw new IllegalStateException("This instance can only be executed once. Please instantiate a new instance."); } /* try from cache first */ if (isRequestCachingEnabled()) { Observable<R> fromCache = requestCache.get(getCacheKey()); if (fromCache != null) { /* mark that we received this response from cache */ metrics.markResponseFromCache(); return new CachedObservableResponse<R>((CachedObservableOriginal<R>) fromCache, this); } } final HystrixCommand<R> _this = this; // create an Observable that will lazily execute when subscribed to Observable<R> o = Observable.create(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(Observer<R> observer) { try { /* used to track userThreadExecutionTime */ invocationStartTime = System.currentTimeMillis(); // mark that we're starting execution on the ExecutionHook executionHook.onStart(_this); /* determine if we're allowed to execute */ if (!circuitBreaker.allowRequest()) { // record that we are returning a short-circuited fallback metrics.markShortCircuited(); // short-circuit and go directly to fallback (or throw an exception if no fallback implemented) try { observer.onNext(getFallbackOrThrowException(HystrixEventType.SHORT_CIRCUITED, FailureType.SHORTCIRCUIT, "short-circuited")); observer.onCompleted(); } catch (Exception e) { observer.onError(e); } return Subscriptions.empty(); } else { /* not short-circuited so proceed with queuing the execution */ try { if (properties.executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD)) { return subscribeWithThreadIsolation(observer); } else { return subscribeWithSemaphoreIsolation(observer); } } catch (RuntimeException e) { observer.onError(e); return Subscriptions.empty(); } } } finally { recordExecutedCommand(); } } }); if (properties.executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD)) { // wrap for timeout support o = new TimeoutObservable<R>(o, _this, performAsyncTimeout); } // error handling o = o.onErrorResumeNext(new Func1<Exception, Observable<R>>() { @Override public Observable<R> call(Exception e) { // count that we are throwing an exception and re-throw it metrics.markExceptionThrown(); return Observable.error(e); } }); // we want to hand off work to a different scheduler so we don't tie up the Hystrix thread o = o.observeOn(observeOn); o = o.finallyDo(new Action0() { @Override public void call() { Reference<TimerListener> tl = timeoutTimer.get(); if (tl != null) { tl.clear(); } } }); // put in cache if (isRequestCachingEnabled()) { // wrap it for caching o = new CachedObservableOriginal<R>(o.cache(), this); Observable<R> fromCache = requestCache.putIfAbsent(getCacheKey(), o); if (fromCache != null) { // another thread beat us so we'll use the cached value instead o = new CachedObservableResponse<R>((CachedObservableOriginal<R>) fromCache, this); } // we just created an ObservableCommand so we cast and return it return (ObservableCommand<R>) o; } else { // no request caching so a simple wrapper just to pass 'this' along with the Observable return new ObservableCommand<R>(o, this); } } /** * Wraps a source Observable and remembers the original HystrixCommand. * <p> * Used for request caching so multiple commands can respond from a single Observable but also get access to the originating HystrixCommand. * * @param <R> */ private static class CachedObservableOriginal<R> extends ObservableCommand<R> { final HystrixCommand<R> originalCommand; CachedObservableOriginal(final Observable<R> actual, HystrixCommand<R> command) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(final Observer<R> observer) { return actual.subscribe(observer); } }, command); this.originalCommand = command; } } private static class ObservableCommand<R> extends Observable<R> { private final HystrixCommand<R> command; ObservableCommand(Func1<Observer<R>, Subscription> func, final HystrixCommand<R> command) { super(func); this.command = command; } public HystrixCommand<R> getCommand() { return command; } ObservableCommand(final Observable<R> originalObservable, final HystrixCommand<R> command) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(Observer<R> observer) { return originalObservable.subscribe(observer); } }); this.command = command; } } /** * Wraps a CachedObservableOriginal as it is being returned from cache. * <p> * As the Observable completes it copies state used for ExecutionResults * and metrics that differentiate between the original and the de-duped "response from cache" command execution. * * @param <R> */ private static class CachedObservableResponse<R> extends ObservableCommand<R> { final CachedObservableOriginal<R> originalObservable; CachedObservableResponse(final CachedObservableOriginal<R> originalObservable, final HystrixCommand<R> commandOfDuplicateCall) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(final Observer<R> observer) { return originalObservable.subscribe(new Observer<R>() { @Override public void onCompleted() { completeCommand(); observer.onCompleted(); } @Override public void onError(Exception e) { completeCommand(); observer.onError(e); } @Override public void onNext(R v) { observer.onNext(v); } private void completeCommand() { // when the observable completes we then update the execution results of the duplicate command // set this instance to the result that is from cache commandOfDuplicateCall.executionResult = originalObservable.originalCommand.executionResult; // add that this came from cache commandOfDuplicateCall.executionResult = commandOfDuplicateCall.executionResult.addEvents(HystrixEventType.RESPONSE_FROM_CACHE); // set the execution time to 0 since we retrieved from cache commandOfDuplicateCall.executionResult = commandOfDuplicateCall.executionResult.setExecutionTime(-1); // record that this command executed commandOfDuplicateCall.recordExecutedCommand(); } }); } }, commandOfDuplicateCall); this.originalObservable = originalObservable; } /* * This is a cached response so we want the command of the observable we're wrapping. */ public HystrixCommand<R> getCommand() { return originalObservable.originalCommand; } } private static class TimeoutObservable<R> extends Observable<R> { public TimeoutObservable(final Observable<R> o, final HystrixCommand<R> originalCommand, final boolean isNonBlocking) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(final Observer<R> observer) { final AtomicObservableSubscription s = new AtomicObservableSubscription(); TimerListener listener = new TimerListener() { @Override public void tick() { if (originalCommand.isCommandTimedOut.compareAndSet(false, true)) { // do fallback logic // report timeout failure originalCommand.metrics.markTimeout(System.currentTimeMillis() - originalCommand.invocationStartTime); // we record execution time because we are returning before originalCommand.recordTotalExecutionTime(originalCommand.invocationStartTime); try { R v = originalCommand.getFallbackOrThrowException(HystrixEventType.TIMEOUT, FailureType.TIMEOUT, "timed-out", new TimeoutException()); observer.onNext(v); observer.onCompleted(); } catch (HystrixRuntimeException re) { observer.onError(re); } } s.unsubscribe(); } @Override public int getIntervalTimeInMilliseconds() { return originalCommand.properties.executionIsolationThreadTimeoutInMilliseconds().get(); } }; Reference<TimerListener> _tl = null; if (isNonBlocking) { /* * Scheduling a separate timer to do timeouts is more expensive * so we'll only do it if we're being used in a non-blocking manner. */ _tl = HystrixTimer.getInstance().addTimerListener(listener); } else { /* * Otherwise we just set the hook that queue().get() can trigger if a timeout occurs. * * This allows the blocking and non-blocking approaches to be coded basically the same way * though it is admittedly awkward if we were just blocking (the use of Reference annoys me for example) */ _tl = new SoftReference<TimerListener>(listener); } final Reference<TimerListener> tl = _tl; // set externally so execute/queue can see this originalCommand.timeoutTimer.set(tl); return s.wrap(o.subscribe(new Observer<R>() { @Override public void onCompleted() { tl.clear(); observer.onCompleted(); } @Override public void onError(Exception e) { tl.clear(); observer.onError(e); } @Override public void onNext(R v) { observer.onNext(v); } })); } }); } } private Subscription subscribeWithSemaphoreIsolation(final Observer<R> observer) { TryableSemaphore executionSemaphore = getExecutionSemaphore(); // acquire a permit if (executionSemaphore.tryAcquire()) { try { try { // store the command that is being run Hystrix.startCurrentThreadExecutingCommand(getCommandKey()); // execute outside of future so that fireAndForget will still work (ie. someone calls queue() but not get()) and so that multiple requests can be deduped through request caching R r = executeCommand(); r = executionHook.onComplete(this, r); observer.onNext(r); /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ recordTotalExecutionTime(invocationStartTime); /* now complete which releases the consumer */ observer.onCompleted(); // empty subscription since we executed synchronously return Subscriptions.empty(); } catch (Exception e) { /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ recordTotalExecutionTime(invocationStartTime); observer.onError(e); // empty subscription since we executed synchronously return Subscriptions.empty(); } finally { // pop the command that is being run Hystrix.endCurrentThreadExecutingCommand(); } } finally { // release the semaphore executionSemaphore.release(); } } else { metrics.markSemaphoreRejection(); logger.debug("HystrixCommand Execution Rejection by Semaphore."); // debug only since we're throwing the exception and someone higher will do something with it // retrieve a fallback or throw an exception if no fallback available observer.onNext(getFallbackOrThrowException(HystrixEventType.SEMAPHORE_REJECTED, FailureType.REJECTED_SEMAPHORE_EXECUTION, "could not acquire a semaphore for execution")); observer.onCompleted(); // empty subscription since we executed synchronously return Subscriptions.empty(); } } private Subscription subscribeWithThreadIsolation(final Observer<R> observer) { // mark that we are executing in a thread (even if we end up being rejected we still were a THREAD execution and not SEMAPHORE) isExecutedInThread.set(true); // final reference to the current calling thread so the child thread can access it if needed final Thread callingThread = Thread.currentThread(); final HystrixCommand<R> _this = this; try { if (!threadPool.isQueueSpaceAvailable()) { // we are at the property defined max so want to throw a RejectedExecutionException to simulate reaching the real max throw new RejectedExecutionException("Rejected command because thread-pool queueSize is at rejection threshold."); } // wrap the synchronous execute() method in a Callable and execute in the threadpool final Future<R> f = threadPool.getExecutor().submit(concurrencyStrategy.wrapCallable(new HystrixContextCallable<R>(new Callable<R>() { @Override public R call() throws Exception { try { // assign 'callingThread' to our NFExceptionThreadingUtility ThreadLocal variable so that if we blow up // anywhere along the way the exception knows who the calling thread is and can include it in the stacktrace ExceptionThreadingUtility.assignCallingThread(callingThread); // execution hook executionHook.onThreadStart(_this); // count the active thread threadPool.markThreadExecution(); try { // store the command that is being run Hystrix.startCurrentThreadExecutingCommand(getCommandKey()); // execute the command R r = executeCommand(); if (isCommandTimedOut.get()) { // state changes before termination preTerminationWork(); return null; } // give the hook an opportunity to modify it r = executionHook.onComplete(_this, r); // pass to the observer observer.onNext(r); // state changes before termination preTerminationWork(); /* now complete which releases the consumer */ observer.onCompleted(); return r; } finally { // pop this off the thread now that it's done Hystrix.endCurrentThreadExecutingCommand(); } } catch (Exception e) { // state changes before termination preTerminationWork(); observer.onError(e); throw e; } } private void preTerminationWork() { /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ recordTotalExecutionTime(invocationStartTime); threadPool.markThreadCompletion(); try { executionHook.onThreadComplete(_this); } catch (Exception e) { logger.warn("ExecutionHook.onThreadComplete threw an exception that will be ignored.", e); } } }))); return new Subscription() { @Override public void unsubscribe() { f.cancel(properties.executionIsolationThreadInterruptOnTimeout().get()); } }; } catch (RejectedExecutionException e) { // mark on counter metrics.markThreadPoolRejection(); // use a fallback instead (or throw exception if not implemented) observer.onNext(getFallbackOrThrowException(HystrixEventType.THREAD_POOL_REJECTED, FailureType.REJECTED_THREAD_EXECUTION, "could not be queued for execution", e)); observer.onCompleted(); return Subscriptions.empty(); } catch (Exception e) { // unknown exception logger.error(getLogMessagePrefix() + ": Unexpected exception while submitting to queue.", e); observer.onNext(getFallbackOrThrowException(HystrixEventType.THREAD_POOL_REJECTED, FailureType.REJECTED_THREAD_EXECUTION, "had unexpected exception while attempting to queue for execution.", e)); observer.onCompleted(); return Subscriptions.empty(); } } /** * Executes the command and marks success/failure on the circuit-breaker and calls <code>getFallback</code> if a failure occurs. * <p> * This does NOT use the circuit-breaker to determine if the command should be executed, use <code>execute()</code> for that. This method will ALWAYS attempt to execute the method. * * @return R */ private R executeCommand() { /** * NOTE: Be very careful about what goes in this method. It gets invoked within another thread in most circumstances. * * The modifications of booleans 'isResponseFromFallback' etc are going across thread-boundaries thus those * variables MUST be volatile otherwise they are not guaranteed to be seen by the user thread when the executing thread modifies them. */ /* capture start time for logging */ long startTime = System.currentTimeMillis(); // allow tracking how many concurrent threads are executing metrics.incrementConcurrentExecutionCount(); try { executionHook.onRunStart(this); R response = executionHook.onRunSuccess(this, run()); long duration = System.currentTimeMillis() - startTime; metrics.addCommandExecutionTime(duration); if (isCommandTimedOut.get()) { // the command timed out in the wrapping thread so we will return immediately // and not increment any of the counters below or other such logic return null; } else { // report success executionResult = executionResult.addEvents(HystrixEventType.SUCCESS); metrics.markSuccess(duration); circuitBreaker.markSuccess(); eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) duration, executionResult.events); return response; } } catch (HystrixBadRequestException e) { try { Exception decorated = executionHook.onRunError(this, e); if (decorated instanceof HystrixBadRequestException) { e = (HystrixBadRequestException) decorated; } else { logger.warn("ExecutionHook.endRunFailure returned an exception that was not an instance of HystrixBadRequestException so will be ignored.", decorated); } throw e; } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.endRunFailure", hookException); } /* * HystrixBadRequestException is treated differently and allowed to propagate without any stats tracking or fallback logic */ throw e; } catch (Exception e) { try { e = executionHook.onRunError(this, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.endRunFailure", hookException); } if (isCommandTimedOut.get()) { // http://jira/browse/API-4905 HystrixCommand: Error/Timeout Double-count if both occur // this means we have already timed out then we don't count this error stat and we just return // as this means the user-thread has already returned, we've already done fallback logic // and we've already counted the timeout stat logger.error("Error executing HystrixCommand.run() [TimedOut]. Proceeding to fallback logic ...", e); return null; } else { logger.error("Error executing HystrixCommand.run(). Proceeding to fallback logic ...", e); } // report failure metrics.markFailure(System.currentTimeMillis() - startTime); // record the exception executionResult = executionResult.setException(e); return getFallbackOrThrowException(HystrixEventType.FAILURE, FailureType.COMMAND_EXCEPTION, "failed", e); } finally { metrics.decrementConcurrentExecutionCount(); // record that we're completed isExecutionComplete.set(true); } } /** * Execute <code>getFallback()</code> within protection of a semaphore that limits number of concurrent executions. * <p> * Fallback implementations shouldn't perform anything that can be blocking, but we protect against it anyways in case someone doesn't abide by the contract. * <p> * If something in the <code>getFallback()</code> implementation is latent (such as a network call) then the semaphore will cause us to start rejecting requests rather than allowing potentially * all threads to pile up and block. * * @return K * @throws UnsupportedOperationException * if getFallback() not implemented * @throws HystrixException * if getFallback() fails (throws an Exception) or is rejected by the semaphore */ private R getFallbackWithProtection() { TryableSemaphore fallbackSemaphore = getFallbackSemaphore(); // acquire a permit if (fallbackSemaphore.tryAcquire()) { try { executionHook.onFallbackStart(this); return executionHook.onFallbackSuccess(this, getFallback()); } catch (RuntimeException e) { Exception decorated = executionHook.onFallbackError(this, e); if (decorated instanceof RuntimeException) { e = (RuntimeException) decorated; } else { logger.warn("ExecutionHook.onFallbackError returned an exception that was not an instance of RuntimeException so will be ignored.", decorated); } // re-throw to calling method throw e; } finally { fallbackSemaphore.release(); } } else { metrics.markFallbackRejection(); logger.debug("HystrixCommand Fallback Rejection."); // debug only since we're throwing the exception and someone higher will do something with it // if we couldn't acquire a permit, we "fail fast" by throwing an exception throw new HystrixRuntimeException(FailureType.REJECTED_SEMAPHORE_FALLBACK, this.getClass(), getLogMessagePrefix() + " fallback execution rejected.", null, null); } } /** * Record the duration of execution as response or exception is being returned to the caller. */ private void recordTotalExecutionTime(long startTime) { long duration = System.currentTimeMillis() - startTime; // the total execution time for the user thread including queuing, thread scheduling, run() execution metrics.addUserThreadExecutionTime(duration); /* * We record the executionTime for command execution. * * If the command is never executed (rejected, short-circuited, etc) then it will be left unset. * * For this metric we include failures and successes as we use it for per-request profiling and debugging * whereas 'metrics.addCommandExecutionTime(duration)' is used by stats across many requests. */ executionResult = executionResult.setExecutionTime((int) duration); } /** * Record that this command was executed in the HystrixRequestLog. * <p> * This can be treated as an async operation as it just adds a references to "this" in the log even if the current command is still executing. */ private void recordExecutedCommand() { if (properties.requestLogEnabled().get()) { // log this command execution regardless of what happened if (concurrencyStrategy instanceof HystrixConcurrencyStrategyDefault) { // if we're using the default we support only optionally using a request context if (HystrixRequestContext.isCurrentThreadInitialized()) { HystrixRequestLog.getCurrentRequest(concurrencyStrategy).addExecutedCommand(this); } } else { // if it's a custom strategy it must ensure the context is initialized if (HystrixRequestLog.getCurrentRequest(concurrencyStrategy) != null) { HystrixRequestLog.getCurrentRequest(concurrencyStrategy).addExecutedCommand(this); } } } } /** * Whether the 'circuit-breaker' is open meaning that <code>execute()</code> will immediately return * the <code>getFallback()</code> response and not attempt a HystrixCommand execution. * * @return boolean */ public boolean isCircuitBreakerOpen() { return circuitBreaker.isOpen(); } /** * If this command has completed execution either successfully, via fallback or failure. * * @return boolean */ public boolean isExecutionComplete() { return isExecutionComplete.get(); } /** * Whether the execution occurred in a separate thread. * <p> * This should be called only once execute()/queue()/fireOrForget() are called otherwise it will always return false. * <p> * This specifies if a thread execution actually occurred, not just if it is configured to be executed in a thread. * * @return boolean */ public boolean isExecutedInThread() { return isExecutedInThread.get(); } /** * Whether the response was returned successfully either by executing <code>run()</code> or from cache. * * @return boolean */ public boolean isSuccessfulExecution() { return executionResult.events.contains(HystrixEventType.SUCCESS); } /** * Whether the <code>run()</code> resulted in a failure (exception). * * @return boolean */ public boolean isFailedExecution() { return executionResult.events.contains(HystrixEventType.FAILURE); } /** * Get the Throwable/Exception thrown that caused the failure. * <p> * If <code>isFailedExecution() == true</code> then this would represent the Exception thrown by the <code>run()</code> method. * <p> * If <code>isFailedExecution() == false</code> then this would return null. * * @return Throwable or null */ public Throwable getFailedExecutionException() { return executionResult.exception; } /** * Whether the response received from was the result of some type of failure * and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseFromFallback() { return executionResult.events.contains(HystrixEventType.FALLBACK_SUCCESS); } /** * Whether the response received was the result of a timeout * and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseTimedOut() { return executionResult.events.contains(HystrixEventType.TIMEOUT); } /** * Whether the response received was a fallback as result of being * short-circuited (meaning <code>isCircuitBreakerOpen() == true</code>) and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseShortCircuited() { return executionResult.events.contains(HystrixEventType.SHORT_CIRCUITED); } /** * Whether the response is from cache and <code>run()</code> was not invoked. * * @return boolean */ public boolean isResponseFromCache() { return executionResult.events.contains(HystrixEventType.RESPONSE_FROM_CACHE); } /** * Whether the response received was a fallback as result of being * rejected (from thread-pool or semaphore) and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseRejected() { return executionResult.events.contains(HystrixEventType.THREAD_POOL_REJECTED) || executionResult.events.contains(HystrixEventType.SEMAPHORE_REJECTED); } /** * List of HystrixCommandEventType enums representing events that occurred during execution. * <p> * Examples of events are SUCCESS, FAILURE, TIMEOUT, and SHORT_CIRCUITED * * @return {@code List<HystrixEventType>} */ public List<HystrixEventType> getExecutionEvents() { return executionResult.events; } /** * The execution time of this command instance in milliseconds, or -1 if not executed. * * @return int */ public int getExecutionTimeInMilliseconds() { return executionResult.executionTime; } /** * Get the TryableSemaphore this HystrixCommand should use if a fallback occurs. * * @param circuitBreaker * @param fallbackSemaphore * @return TryableSemaphore */ private TryableSemaphore getFallbackSemaphore() { if (fallbackSemaphoreOverride == null) { TryableSemaphore _s = fallbackSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup fallbackSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphore(properties.fallbackIsolationSemaphoreMaxConcurrentRequests())); // assign whatever got set (this or another thread) return fallbackSemaphorePerCircuit.get(commandKey.name()); } else { return _s; } } else { return fallbackSemaphoreOverride; } } /** * Get the TryableSemaphore this HystrixCommand should use for execution if not running in a separate thread. * * @param circuitBreaker * @param fallbackSemaphore * @return TryableSemaphore */ private TryableSemaphore getExecutionSemaphore() { if (executionSemaphoreOverride == null) { TryableSemaphore _s = executionSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup executionSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphore(properties.executionIsolationSemaphoreMaxConcurrentRequests())); // assign whatever got set (this or another thread) return executionSemaphorePerCircuit.get(commandKey.name()); } else { return _s; } } else { return executionSemaphoreOverride; } } /** * @throws HystrixRuntimeException */ private R getFallbackOrThrowException(HystrixEventType eventType, FailureType failureType, String message) { return getFallbackOrThrowException(eventType, failureType, message, null); } /** * @throws HystrixRuntimeException */ private R getFallbackOrThrowException(HystrixEventType eventType, FailureType failureType, String message, Exception e) { try { if (properties.fallbackEnabled().get()) { /* fallback behavior is permitted so attempt */ try { // retrieve the fallback R fallback = getFallbackWithProtection(); // mark fallback on counter metrics.markFallbackSuccess(); // record the executionResult executionResult = executionResult.addEvents(eventType, HystrixEventType.FALLBACK_SUCCESS); return executionHook.onComplete(this, fallback); } catch (UnsupportedOperationException fe) { logger.debug("No fallback for HystrixCommand. ", fe); // debug only since we're throwing the exception and someone higher will do something with it // record the executionResult executionResult = executionResult.addEvents(eventType); /* executionHook for all errors */ try { e = executionHook.onError(this, failureType, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.onError", hookException); } throw new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and no fallback available.", e, fe); } catch (Exception fe) { logger.error("Error retrieving fallback for HystrixCommand. ", fe); metrics.markFallbackFailure(); // record the executionResult executionResult = executionResult.addEvents(eventType, HystrixEventType.FALLBACK_FAILURE); /* executionHook for all errors */ try { e = executionHook.onError(this, failureType, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.onError", hookException); } throw new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and failed retrieving fallback.", e, fe); } } else { /* fallback is disabled so throw HystrixRuntimeException */ logger.debug("Fallback disabled for HystrixCommand so will throw HystrixRuntimeException. ", e); // debug only since we're throwing the exception and someone higher will do something with it // record the executionResult executionResult = executionResult.addEvents(eventType); /* executionHook for all errors */ try { e = executionHook.onError(this, failureType, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.onError", hookException); } throw new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and fallback disabled.", e, null); } } finally { // record that we're completed (to handle non-successful events we do it here as well as at the end of executeCommand isExecutionComplete.set(true); } } /* ******************************************************************************** */ /* ******************************************************************************** */ /* Result Status */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Immutable holder class for the status of command execution. * <p> * Contained within a class to simplify the sharing of it across Futures/threads that result from request caching. * <p> * This object can be referenced and "modified" by parent and child threads as well as by different instances of HystrixCommand since * 1 instance could create an ExecutionResult, cache a Future that refers to it, a 2nd instance execution then retrieves a Future * from cache and wants to append RESPONSE_FROM_CACHE to whatever the ExecutionResult was from the first command execution. * <p> * This being immutable forces and ensure thread-safety instead of using AtomicInteger/ConcurrentLinkedQueue and determining * when it's safe to mutate the object directly versus needing to deep-copy clone to a new instance. */ private static class ExecutionResult { private final List<HystrixEventType> events; private final int executionTime; private final Exception exception; private ExecutionResult(HystrixEventType... events) { this(Arrays.asList(events), -1, null); } public ExecutionResult setExecutionTime(int executionTime) { return new ExecutionResult(events, executionTime, exception); } public ExecutionResult setException(Exception e) { return new ExecutionResult(events, executionTime, e); } private ExecutionResult(List<HystrixEventType> events, int executionTime, Exception e) { // we are safe assigning the List reference instead of deep-copying // because we control the original list in 'newEvent' this.events = events; this.executionTime = executionTime; this.exception = e; } // we can return a static version since it's immutable private static ExecutionResult EMPTY = new ExecutionResult(new HystrixEventType[0]); /** * Creates a new ExecutionResult by adding the defined 'events' to the ones on the current instance. * * @param events * @return */ public ExecutionResult addEvents(HystrixEventType... events) { ArrayList<HystrixEventType> newEvents = new ArrayList<HystrixEventType>(); newEvents.addAll(this.events); for (HystrixEventType e : events) { newEvents.add(e); } return new ExecutionResult(Collections.unmodifiableList(newEvents), executionTime, exception); } } /* ******************************************************************************** */ /* ******************************************************************************** */ /* RequestCache */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Key to be used for request caching. * <p> * By default this returns null which means "do not cache". * <p> * To enable caching override this method and return a string key uniquely representing the state of a command instance. * <p> * If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache. * * @return cacheKey */ protected String getCacheKey() { return null; } private boolean isRequestCachingEnabled() { return properties.requestCacheEnabled().get(); } /* ******************************************************************************** */ /* ******************************************************************************** */ /* TryableSemaphore */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Semaphore that only supports tryAcquire and never blocks and that supports a dynamic permit count. * <p> * Using AtomicInteger increment/decrement instead of java.util.concurrent.Semaphore since we don't need blocking and need a custom implementation to get the dynamic permit count and since * AtomicInteger achieves the same behavior and performance without the more complex implementation of the actual Semaphore class using AbstractQueueSynchronizer. */ private static class TryableSemaphore { private final HystrixProperty<Integer> numberOfPermits; private final AtomicInteger count = new AtomicInteger(0); public TryableSemaphore(HystrixProperty<Integer> numberOfPermits) { this.numberOfPermits = numberOfPermits; } /** * Use like this: * <p> * * <pre> * if (s.tryAcquire()) { * try { * // do work that is protected by 's' * } finally { * s.release(); * } * } * </pre> * * @return boolean */ public boolean tryAcquire() { int currentCount = count.incrementAndGet(); if (currentCount > numberOfPermits.get()) { count.decrementAndGet(); return false; } else { return true; } } /** * ONLY call release if tryAcquire returned true. * <p> * * <pre> * if (s.tryAcquire()) { * try { * // do work that is protected by 's' * } finally { * s.release(); * } * } * </pre> */ public void release() { count.decrementAndGet(); } public int getNumberOfPermitsUsed() { return count.get(); } } private String getLogMessagePrefix() { return getCommandKey().name(); } /** * Fluent interface for arguments to the {@link HystrixCommand} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName")) .andCommandKey(HystrixCommandKey.Factory.asKey("CommandName")) .andEventNotifier(notifier); * } </pre> */ @NotThreadSafe public static class Setter { private final HystrixCommandGroupKey groupKey; private HystrixCommandKey commandKey; private HystrixThreadPoolKey threadPoolKey; private HystrixCommandProperties.Setter commandPropertiesDefaults; private HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults; /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ private Setter(HystrixCommandGroupKey groupKey) { this.groupKey = groupKey; } /** * Setter factory method with required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ public static Setter withGroupKey(HystrixCommandGroupKey groupKey) { return new Setter(groupKey); } /** * @param commandKey * {@link HystrixCommandKey} used to identify a {@link HystrixCommand} instance for statistics, circuit-breaker, properties, etc. * <p> * By default this will be derived from the instance class name. * <p> * NOTE: Every unique {@link HystrixCommandKey} will result in new instances of {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and {@link HystrixCommandProperties}. * Thus, * the number of variants should be kept to a finite and reasonable number to avoid high-memory usage or memory leacks. * <p> * Hundreds of keys is fine, tens of thousands is probably not. * @return Setter for fluent interface via method chaining */ public Setter andCommandKey(HystrixCommandKey commandKey) { this.commandKey = commandKey; return this; } /** * @param threadPoolKey * {@link HystrixThreadPoolKey} used to define which thread-pool this command should run in (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). * <p> * By default this is derived from the {@link HystrixCommandGroupKey} but if injected this allows multiple commands to have the same {@link HystrixCommandGroupKey} but different * thread-pools. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolKey(HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; return this; } /** * Optional * * @param commandPropertiesDefaults * {@link HystrixCommandProperties.Setter} with property overrides for this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = commandPropertiesDefaults; return this; } /** * Optional * * @param threadPoolPropertiesDefaults * {@link HystrixThreadPoolProperties.Setter} with property overrides for the {@link HystrixThreadPool} used by this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults; return this; } } public static class UnitTest { @Before public void prepareForTest() { /* we must call this to simulate a new request lifecycle running and clearing caches */ HystrixRequestContext.initializeContext(); } @After public void cleanup() { // instead of storing the reference from initialize we'll just get the current state and shutdown if (HystrixRequestContext.getContextForCurrentThread() != null) { // it could have been set NULL by the test HystrixRequestContext.getContextForCurrentThread().shutdown(); } // force properties to be clean as well ConfigurationManager.getConfigInstance().clear(); } /** * Test a successful command execution. */ @Test public void testExecutionSuccess() { try { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.execute()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(null, command.getFailedExecutionException()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test that a command can not be executed multiple times. */ @Test public void testExecutionMultipleTimes() { SuccessfulTestCommand command = new SuccessfulTestCommand(); assertFalse(command.isExecutionComplete()); // first should succeed assertEquals(true, command.execute()); assertTrue(command.isExecutionComplete()); assertTrue(command.isExecutedInThread()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); try { // second should fail command.execute(); fail("we should not allow this ... it breaks the state of request logs"); } catch (Exception e) { e.printStackTrace(); // we want to get here } try { // queue should also fail command.queue(); fail("we should not allow this ... it breaks the state of request logs"); } catch (Exception e) { e.printStackTrace(); // we want to get here } } /** * Test a command execution that throws an HystrixException and didn't implement getFallback. */ @Test public void testExecutionKnownFailureWithNoFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { command.execute(); fail("we shouldn't get here"); } catch (HystrixRuntimeException e) { e.printStackTrace(); assertNotNull(e.getFallbackException()); assertNotNull(e.getImplementingClass()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); } catch (Exception e) { e.printStackTrace(); fail("We should always get an HystrixRuntimeException when an error occurs."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution that throws an unknown exception (not HystrixException) and didn't implement getFallback. */ @Test public void testExecutionUnknownFailureWithNoFallback() { TestHystrixCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(); try { command.execute(); fail("we shouldn't get here"); } catch (HystrixRuntimeException e) { e.printStackTrace(); assertNotNull(e.getFallbackException()); assertNotNull(e.getImplementingClass()); } catch (Exception e) { e.printStackTrace(); fail("We should always get an HystrixRuntimeException when an error occurs."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution that fails but has a fallback. */ @Test public void testExecutionFailureWithFallback() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); try { assertEquals(false, command.execute()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals("we failed with a simulated issue", command.getFailedExecutionException().getMessage()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution that fails, has getFallback implemented but that fails as well. */ @Test public void testExecutionFailureWithFallbackFailure() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(); try { command.execute(); fail("we shouldn't get here"); } catch (HystrixRuntimeException e) { System.out.println("------------------------------------------------"); e.printStackTrace(); System.out.println("------------------------------------------------"); assertNotNull(e.getFallbackException()); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a successful command execution (asynchronously). */ @Test public void testQueueSuccess() { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); try { Future<Boolean> future = command.queue(); assertEquals(true, future.get()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that throws an HystrixException and didn't implement getFallback. */ @Test public void testQueueKnownFailureWithNoFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertNotNull(de.getImplementingClass()); } else { fail("the cause should be HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that throws an unknown exception (not HystrixException) and didn't implement getFallback. */ @Test public void testQueueUnknownFailureWithNoFallback() { TestHystrixCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertNotNull(de.getImplementingClass()); } else { fail("the cause should be HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that fails but has a fallback. */ @Test public void testQueueFailureWithFallback() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); try { Future<Boolean> future = command.queue(); assertEquals(false, future.get()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that fails, has getFallback implemented but that fails as well. */ @Test public void testQueueFailureWithFallbackFailure() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { if (e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); e.printStackTrace(); assertNotNull(de.getFallbackException()); } else { fail("the cause should be HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a successful command execution. */ @Test public void testObserveSuccess() { try { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.observe().toBlockingObservable().single()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(null, command.getFailedExecutionException()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test a successful command execution. */ @Test public void testObserveOnScheduler() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder()) { @Override protected Boolean run() { commandThread.set(Thread.currentThread()); return true; } }; final CountDownLatch latch = new CountDownLatch(1); Scheduler customScheduler = new Scheduler() { private final Scheduler self = this; @Override public <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action) { return schedule(state, action, 0, TimeUnit.MILLISECONDS); } @Override public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action, long delayTime, TimeUnit unit) { new Thread("RxScheduledThread") { @Override public void run() { action.call(self, state); } }.start(); // not testing unsubscribe behavior return Subscriptions.empty(); } }; command.toObservable(customScheduler).subscribe(new Observer<Boolean>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Exception e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Boolean args) { subscribeThread.set(Thread.currentThread()); } }); if (!latch.await(2000, TimeUnit.MILLISECONDS)) { fail("timed out"); } assertNotNull(commandThread.get()); assertNotNull(subscribeThread.get()); System.out.println("Command Thread: " + commandThread.get()); System.out.println("Subscribe Thread: " + subscribeThread.get()); assertTrue(commandThread.get().getName().startsWith("hystrix-")); assertTrue(subscribeThread.get().getName().equals("RxScheduledThread")); } /** * Test a successful command execution. */ @Test public void testObserveOnComputationSchedulerByDefaultForThreadIsolation() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder()) { @Override protected Boolean run() { commandThread.set(Thread.currentThread()); return true; } }; final CountDownLatch latch = new CountDownLatch(1); command.toObservable().subscribe(new Observer<Boolean>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Exception e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Boolean args) { subscribeThread.set(Thread.currentThread()); } }); if (!latch.await(2000, TimeUnit.MILLISECONDS)) { fail("timed out"); } assertNotNull(commandThread.get()); assertNotNull(subscribeThread.get()); System.out.println("Command Thread: " + commandThread.get()); System.out.println("Subscribe Thread: " + subscribeThread.get()); assertTrue(commandThread.get().getName().startsWith("hystrix-")); assertTrue(subscribeThread.get().getName().startsWith("RxComputationThreadPool")); } /** * Test a successful command execution. */ @Test public void testObserveOnImmediateSchedulerByDefaultForSemaphoreIsolation() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder() .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))) { @Override protected Boolean run() { commandThread.set(Thread.currentThread()); return true; } }; final CountDownLatch latch = new CountDownLatch(1); command.toObservable().subscribe(new Observer<Boolean>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Exception e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Boolean args) { subscribeThread.set(Thread.currentThread()); } }); if (!latch.await(2000, TimeUnit.MILLISECONDS)) { fail("timed out"); } assertNotNull(commandThread.get()); assertNotNull(subscribeThread.get()); System.out.println("Command Thread: " + commandThread.get()); System.out.println("Subscribe Thread: " + subscribeThread.get()); String mainThreadName = Thread.currentThread().getName(); // semaphore should be on the calling thread assertTrue(commandThread.get().getName().equals(mainThreadName)); assertTrue(subscribeThread.get().getName().equals(mainThreadName)); } /** * Test that the circuit-breaker will 'trip' and prevent command execution on subsequent calls. */ @Test public void testCircuitBreakerTripsAfterFailures() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); /* fail 3 times and then it should trip the circuit and stop executing */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt1.execute(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt2.execute(); assertTrue(attempt2.isResponseFromFallback()); assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt3.execute(); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should now be 'open' and prevent further executions assertTrue(attempt3.isCircuitBreakerOpen()); // attempt 4 KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt4.execute(); assertTrue(attempt4.isResponseFromFallback()); // this should now be true as the response will be short-circuited assertTrue(attempt4.isResponseShortCircuited()); // this should remain open assertTrue(attempt4.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker will 'trip' and prevent command execution on subsequent calls. */ @Test public void testCircuitBreakerTripsAfterFailuresViaQueue() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { /* fail 3 times and then it should trip the circuit and stop executing */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt1.queue().get(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt2.queue().get(); assertTrue(attempt2.isResponseFromFallback()); assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt3.queue().get(); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should now be 'open' and prevent further executions assertTrue(attempt3.isCircuitBreakerOpen()); // attempt 4 KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt4.queue().get(); assertTrue(attempt4.isResponseFromFallback()); // this should now be true as the response will be short-circuited assertTrue(attempt4.isResponseShortCircuited()); // this should remain open assertTrue(attempt4.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } catch (Exception e) { e.printStackTrace(); fail("We should have received fallbacks."); } } /** * Test that the circuit-breaker is shared across HystrixCommand objects with the same CommandKey. * <p> * This will test HystrixCommand objects with a single circuit-breaker (as if each injected with same CommandKey) * <p> * Multiple HystrixCommand objects with the same dependency use the same circuit-breaker. */ @Test public void testCircuitBreakerAcrossMultipleCommandsButSameCircuitBreaker() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); /* fail 3 times and then it should trip the circuit and stop executing */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt1.execute(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 with a different command, same circuit breaker KnownFailureTestCommandWithoutFallback attempt2 = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { attempt2.execute(); } catch (Exception e) { // ignore ... this doesn't have a fallback so will throw an exception } assertTrue(attempt2.isFailedExecution()); assertFalse(attempt2.isResponseFromFallback()); // false because no fallback assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 of the Hystrix, 2nd for this particular HystrixCommand KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt3.execute(); assertTrue(attempt2.isFailedExecution()); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should now be 'open' and prevent further executions // after having 3 failures on the Hystrix that these 2 different HystrixCommand objects are for assertTrue(attempt3.isCircuitBreakerOpen()); // attempt 4 KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt4.execute(); assertTrue(attempt4.isResponseFromFallback()); // this should now be true as the response will be short-circuited assertTrue(attempt4.isResponseShortCircuited()); // this should remain open assertTrue(attempt4.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker is different between HystrixCommand objects with a different Hystrix. */ @Test public void testCircuitBreakerAcrossMultipleCommandsAndDifferentDependency() { TestCircuitBreaker circuitBreaker_one = new TestCircuitBreaker(); TestCircuitBreaker circuitBreaker_two = new TestCircuitBreaker(); /* fail 3 times, twice on one Hystrix, once on a different Hystrix ... circuit-breaker should NOT open */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker_one); attempt1.execute(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 with a different HystrixCommand implementation and different Hystrix KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker_two); attempt2.execute(); assertTrue(attempt2.isResponseFromFallback()); assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 but only 2nd of the Hystrix.ONE KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker_one); attempt3.execute(); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should remain 'closed' since we have only had 2 failures on Hystrix.ONE assertFalse(attempt3.isCircuitBreakerOpen()); // this one should also remain closed as it only had 1 failure for Hystrix.TWO assertFalse(attempt2.isCircuitBreakerOpen()); // attempt 4 (3rd attempt for Hystrix.ONE) KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker_one); attempt4.execute(); // this should NOW flip to true as this is the 3rd failure for Hystrix.ONE assertTrue(attempt3.isCircuitBreakerOpen()); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // Hystrix.TWO should still remain closed assertFalse(attempt2.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(3, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker_one.metrics.getHealthCounts().getErrorPercentage()); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker_two.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker being disabled doesn't wreak havoc. */ @Test public void testExecutionSuccessWithCircuitBreakerDisabled() { TestHystrixCommand<Boolean> command = new TestCommandWithoutCircuitBreaker(); try { assertEquals(true, command.execute()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } // we'll still get metrics ... just not the circuit breaker opening/closing assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution timeout where the command didn't implement getFallback. */ @Test public void testExecutionTimeoutWithNoFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.execute(); fail("we shouldn't get here"); } catch (Exception e) { // e.printStackTrace(); if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be HystrixRuntimeException"); } } // the time should be 50+ since we timeout at 50ms assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50); assertTrue(command.isResponseTimedOut()); assertFalse(command.isResponseFromFallback()); assertFalse(command.isResponseRejected()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution timeout where the command implemented getFallback. */ @Test public void testExecutionTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(false, command.execute()); // the time should be 50+ since we timeout at 50ms assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50); assertTrue(command.isResponseTimedOut()); assertTrue(command.isResponseFromFallback()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution timeout where the command implemented getFallback but it fails. */ @Test public void testExecutionTimeoutFallbackFailure() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_FAILURE); try { command.execute(); fail("we shouldn't get here"); } catch (Exception e) { if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be HystrixRuntimeException"); } } // the time should be 50+ since we timeout at 50ms assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker counts a command execution timeout as a 'timeout' and not just failure. */ @Test public void testCircuitBreakerOnExecutionTimeout() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); command.execute(); assertTrue(command.isResponseFromFallback()); assertFalse(command.isCircuitBreakerOpen()); assertFalse(command.isResponseShortCircuited()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the command finishing AFTER a timeout (because thread continues in background) does not register a SUCCESS */ @Test public void testCountersOnExecutionTimeout() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { command.execute(); /* wait long enough for the command to have finished */ Thread.sleep(200); /* response should still be the same as 'testCircuitBreakerOnExecutionTimeout' */ assertTrue(command.isResponseFromFallback()); assertFalse(command.isCircuitBreakerOpen()); assertFalse(command.isResponseShortCircuited()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertFalse(command.isSuccessfulExecution()); /* failure and timeout count should be the same as 'testCircuitBreakerOnExecutionTimeout' */ assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); /* we should NOT have a 'success' counter */ assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command didn't implement getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testQueuedExecutionTimeoutWithNoFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e instanceof ExecutionException && e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testQueuedExecutionTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(false, command.queue().get()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback but it fails. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testQueuedExecutionTimeoutFallbackFailure() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_FAILURE); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { if (e instanceof ExecutionException && e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command didn't implement getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testObservedExecutionTimeoutWithNoFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.observe().toBlockingObservable().single(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testObservedExecutionTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(false, command.observe().toBlockingObservable().single()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback but it fails. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testObservedExecutionTimeoutFallbackFailure() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_FAILURE); try { command.observe().toBlockingObservable().single(); fail("we shouldn't get here"); } catch (Exception e) { if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker counts a command execution timeout as a 'timeout' and not just failure. */ @Test public void testShortCircuitFallbackCounter() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true); try { new KnownFailureTestCommandWithFallback(circuitBreaker).execute(); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); KnownFailureTestCommandWithFallback command = new KnownFailureTestCommandWithFallback(circuitBreaker); command.execute(); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); // will be -1 because it never attempted execution assertTrue(command.getExecutionTimeInMilliseconds() == -1); assertTrue(command.isResponseShortCircuited()); assertFalse(command.isResponseTimedOut()); // because it was short-circuited to a fallback we don't count an error assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test when a command fails to get queued up in the threadpool where the command didn't implement getFallback. * <p> * We specifically want to protect against developers getting random thread exceptions and instead just correctly receiving HystrixRuntimeException when no fallback exists. */ @Test public void testRejectedThreadWithNoFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); // fill up the queue pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); Future<Boolean> f = null; TestCommandRejection command = null; try { f = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED).queue(); command = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED); command.queue(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); // will be -1 because it never attempted execution assertTrue(command.getExecutionTimeInMilliseconds() == -1); assertTrue(command.isResponseRejected()); assertFalse(command.isResponseShortCircuited()); assertFalse(command.isResponseTimedOut()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof RejectedExecutionException); } else { fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException"); } } try { f.get(); } catch (Exception e) { e.printStackTrace(); fail("The first one should succeed."); } assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(50, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test when a command fails to get queued up in the threadpool where the command implemented getFallback. * <p> * We specifically want to protect against developers getting random thread exceptions and instead just correctly receives a fallback. */ @Test public void testRejectedThreadWithFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); // fill up the queue pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { TestCommandRejection command1 = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); command1.queue(); TestCommandRejection command2 = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); assertEquals(false, command2.queue().get()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertFalse(command1.isResponseRejected()); assertFalse(command1.isResponseFromFallback()); assertTrue(command2.isResponseRejected()); assertTrue(command2.isResponseFromFallback()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test when a command fails to get queued up in the threadpool where the command implemented getFallback but it fails. * <p> * We specifically want to protect against developers getting random thread exceptions and instead just correctly receives an HystrixRuntimeException. */ @Test public void testRejectedThreadWithFallbackFailure() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); // fill up the queue pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_FAILURE).queue(); assertEquals(false, new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_FAILURE).queue().get()); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof RejectedExecutionException); } else { fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException"); } } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that we can reject a thread using isQueueSpaceAvailable() instead of just when the pool rejects. * <p> * For example, we have queue size set to 100 but want to reject when we hit 10. * <p> * This allows us to use FastProperties to control our rejection point whereas we can't resize a queue after it's created. */ @Test public void testRejectedThreadUsingQueueSize() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(10, 1); // put 1 item in the queue // the thread pool won't pick it up because we're bypassing the pool and adding to the queue directly so this will keep the queue full pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); TestCommandRejection command = null; try { // this should fail as we already have 1 in the queue command = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED); command.queue(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); // will be -1 because it never attempted execution assertTrue(command.getExecutionTimeInMilliseconds() == -1); assertTrue(command.isResponseRejected()); assertFalse(command.isResponseShortCircuited()); assertFalse(command.isResponseTimedOut()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof RejectedExecutionException); } else { fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException"); } } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testTimedOutCommandDoesNotExecute() { SingleThreadedPool pool = new SingleThreadedPool(5); TestCircuitBreaker s1 = new TestCircuitBreaker(); TestCircuitBreaker s2 = new TestCircuitBreaker(); // execution will take 100ms, thread pool has a 600ms timeout CommandWithCustomThreadPool c1 = new CommandWithCustomThreadPool(s1, pool, 100, HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(600)); // execution will take 200ms, thread pool has a 20ms timeout CommandWithCustomThreadPool c2 = new CommandWithCustomThreadPool(s2, pool, 200, HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(20)); // queue up c1 first Future<Boolean> c1f = c1.queue(); // now queue up c2 and wait on it boolean receivedException = false; try { c2.queue().get(); } catch (Exception e) { // we expect to get an exception here receivedException = true; } if (!receivedException) { fail("We expect to receive an exception for c2 as it's supposed to timeout."); } // c1 will complete after 100ms try { c1f.get(); } catch (Exception e1) { e1.printStackTrace(); fail("we should not have failed while getting c1"); } assertTrue("c1 is expected to executed but didn't", c1.didExecute); // c2 will timeout after 20 ms ... we'll wait longer than the 200ms time to make sure // the thread doesn't keep running in the background and execute try { Thread.sleep(400); } catch (Exception e) { throw new RuntimeException("Failed to sleep"); } assertFalse("c2 is not expected to execute, but did", c2.didExecute); assertEquals(1, s1.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, s1.metrics.getHealthCounts().getErrorPercentage()); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, s2.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, s2.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, s2.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testFallbackSemaphore() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // single thread should work try { boolean result = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 200).queue().get(); assertTrue(result); } catch (Exception e) { // we shouldn't fail on this one throw new RuntimeException(e); } // 2 threads, the second should be rejected by the fallback semaphore boolean exceptionReceived = false; Future<Boolean> result = null; try { result = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 400).queue(); // make sure that thread gets a chance to run before queuing the next one Thread.sleep(50); Future<Boolean> result2 = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 200).queue(); result2.get(); } catch (Exception e) { e.printStackTrace(); exceptionReceived = true; } try { assertTrue(result.get()); } catch (Exception e) { throw new RuntimeException(e); } if (!exceptionReceived) { fail("We expected an exception on the 2nd get"); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); // TestSemaphoreCommandWithSlowFallback always fails so all 3 should show failure assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); // the 1st thread executes single-threaded and gets a fallback, the next 2 are concurrent so only 1 of them is permitted by the fallback semaphore so 1 is rejected assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); // whenever a fallback_rejection occurs it is also a fallback_failure assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); // we should not have rejected any via the "execution semaphore" but instead via the "fallback semaphore" assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testExecutionSemaphoreWithQueue() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // single thread should work try { boolean result = new TestSemaphoreCommand(circuitBreaker, 1, 200).queue().get(); assertTrue(result); } catch (Exception e) { // we shouldn't fail on this one throw new RuntimeException(e); } final AtomicBoolean exceptionReceived = new AtomicBoolean(); final TryableSemaphore semaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(1)); Runnable r = new HystrixContextRunnable(new Runnable() { @Override public void run() { try { new TestSemaphoreCommand(circuitBreaker, semaphore, 200).queue().get(); } catch (Exception e) { e.printStackTrace(); exceptionReceived.set(true); } } }); // 2 threads, the second should be rejected by the semaphore Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } if (!exceptionReceived.get()) { fail("We expected an exception on the 2nd get"); } assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); // we don't have a fallback so threw an exception when rejected assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); // not a failure as the command never executed so can't fail assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); // no fallback failure as there isn't a fallback implemented assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); // we should have rejected via semaphore assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testExecutionSemaphoreWithExecution() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // single thread should work try { TestSemaphoreCommand command = new TestSemaphoreCommand(circuitBreaker, 1, 200); boolean result = command.execute(); assertFalse(command.isExecutedInThread()); assertTrue(result); } catch (Exception e) { // we shouldn't fail on this one throw new RuntimeException(e); } final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2); final AtomicBoolean exceptionReceived = new AtomicBoolean(); final TryableSemaphore semaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(1)); Runnable r = new HystrixContextRunnable(new Runnable() { @Override public void run() { try { results.add(new TestSemaphoreCommand(circuitBreaker, semaphore, 200).execute()); } catch (Exception e) { e.printStackTrace(); exceptionReceived.set(true); } } }); // 2 threads, the second should be rejected by the semaphore Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } if (!exceptionReceived.get()) { fail("We expected an exception on the 2nd get"); } // only 1 value is expected as the other should have thrown an exception assertEquals(1, results.size()); // should contain only a true result assertTrue(results.contains(Boolean.TRUE)); assertFalse(results.contains(Boolean.FALSE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); // no failure ... we throw an exception because of rejection but the command does not fail execution assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); // there is no fallback implemented so no failure can occur on it assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); // we rejected via semaphore assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testRejectedExecutionSemaphoreWithFallback() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2); final AtomicBoolean exceptionReceived = new AtomicBoolean(); Runnable r = new HystrixContextRunnable(new Runnable() { @Override public void run() { try { results.add(new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false).execute()); } catch (Exception e) { e.printStackTrace(); exceptionReceived.set(true); } } }); // 2 threads, the second should be rejected by the semaphore and return fallback Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } if (exceptionReceived.get()) { fail("We should have received a fallback response"); } // both threads should have returned values assertEquals(2, results.size()); // should contain both a true and false result assertTrue(results.contains(Boolean.TRUE)); assertTrue(results.contains(Boolean.FALSE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); System.out.println("**** DONE"); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Tests that semaphores are counted separately for commands with unique keys */ @Test public void testSemaphorePermitsInUse() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // this semaphore will be shared across multiple command instances final TryableSemaphore sharedSemaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(3)); // used to wait until all commands have started final CountDownLatch startLatch = new CountDownLatch(sharedSemaphore.numberOfPermits.get() + 1); // used to signal that all command can finish final CountDownLatch sharedLatch = new CountDownLatch(1); final Runnable sharedSemaphoreRunnable = new HystrixContextRunnable(new Runnable() { public void run() { try { new LatchedSemaphoreCommand(circuitBreaker, sharedSemaphore, startLatch, sharedLatch).execute(); } catch (Exception e) { e.printStackTrace(); } } }); // creates group of threads each using command sharing a single semaphore // I create extra threads and commands so that I can verify that some of them fail to obtain a semaphore final int sharedThreadCount = sharedSemaphore.numberOfPermits.get() * 2; final Thread[] sharedSemaphoreThreads = new Thread[sharedThreadCount]; for (int i = 0; i < sharedThreadCount; i++) { sharedSemaphoreThreads[i] = new Thread(sharedSemaphoreRunnable); } // creates thread using isolated semaphore final TryableSemaphore isolatedSemaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(1)); final CountDownLatch isolatedLatch = new CountDownLatch(1); // tracks failures to obtain semaphores final AtomicInteger failureCount = new AtomicInteger(); final Thread isolatedThread = new Thread(new HystrixContextRunnable(new Runnable() { public void run() { try { new LatchedSemaphoreCommand(circuitBreaker, isolatedSemaphore, startLatch, isolatedLatch).execute(); } catch (Exception e) { e.printStackTrace(); failureCount.incrementAndGet(); } } })); // verifies no permits in use before starting threads assertEquals("wrong number of permits for shared semaphore", 0, sharedSemaphore.getNumberOfPermitsUsed()); assertEquals("wrong number of permits for isolated semaphore", 0, isolatedSemaphore.getNumberOfPermitsUsed()); for (int i = 0; i < sharedThreadCount; i++) { sharedSemaphoreThreads[i].start(); } isolatedThread.start(); // waits until all commands have started try { startLatch.await(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } // verifies that all semaphores are in use assertEquals("wrong number of permits for shared semaphore", sharedSemaphore.numberOfPermits.get().longValue(), sharedSemaphore.getNumberOfPermitsUsed()); assertEquals("wrong number of permits for isolated semaphore", isolatedSemaphore.numberOfPermits.get().longValue(), isolatedSemaphore.getNumberOfPermitsUsed()); // signals commands to finish sharedLatch.countDown(); isolatedLatch.countDown(); try { for (int i = 0; i < sharedThreadCount; i++) { sharedSemaphoreThreads[i].join(); } isolatedThread.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } // verifies no permits in use after finishing threads assertEquals("wrong number of permits for shared semaphore", 0, sharedSemaphore.getNumberOfPermitsUsed()); assertEquals("wrong number of permits for isolated semaphore", 0, isolatedSemaphore.getNumberOfPermitsUsed()); // verifies that some executions failed final int expectedFailures = sharedSemaphore.getNumberOfPermitsUsed(); assertEquals("failures expected but did not happen", expectedFailures, failureCount.get()); } /** * Test that HystrixOwner can be passed in dynamically. */ @Test public void testDynamicOwner() { try { TestHystrixCommand<Boolean> command = new DynamicOwnerTestCommand(CommandGroupForUnitTest.OWNER_ONE); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.execute()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test a successful command execution. */ @Test public void testDynamicOwnerFails() { try { TestHystrixCommand<Boolean> command = new DynamicOwnerTestCommand(null); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.execute()); fail("we should have thrown an exception as we need an owner"); } catch (Exception e) { // success if we get here } } /** * Test that HystrixCommandKey can be passed in dynamically. */ @Test public void testDynamicKey() { try { DynamicOwnerAndKeyTestCommand command1 = new DynamicOwnerAndKeyTestCommand(CommandGroupForUnitTest.OWNER_ONE, CommandKeyForUnitTest.KEY_ONE); assertEquals(true, command1.execute()); DynamicOwnerAndKeyTestCommand command2 = new DynamicOwnerAndKeyTestCommand(CommandGroupForUnitTest.OWNER_ONE, CommandKeyForUnitTest.KEY_TWO); assertEquals(true, command2.execute()); // 2 different circuit breakers should be created assertNotSame(command1.getCircuitBreaker(), command2.getCircuitBreaker()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future */ @Test public void testRequestCache1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); try { assertEquals("A", f1.get()); assertEquals("A", f2.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // the second one should not have executed as it should have received the cached value instead assertFalse(command2.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command1.getExecutionTimeInMilliseconds() > -1); assertFalse(command1.isResponseFromCache()); // the execution log for command2 should show it came from cache assertEquals(2, command2.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command2.getExecutionTimeInMilliseconds() == -1); assertTrue(command2.isResponseFromCache()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching doesn't prevent different ones from executing */ @Test public void testRequestCache2() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "B"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command2.getExecutionTimeInMilliseconds() > -1); assertFalse(command2.isResponseFromCache()); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testRequestCache3() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "B"); SuccessfulCacheableCommand command3 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // but the 3rd should come from cache assertFalse(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show it came from cache assertEquals(2, command3.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command3.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command3.getExecutionTimeInMilliseconds() == -1); assertTrue(command3.isResponseFromCache()); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future */ @Test public void testRequestCacheWithSlowExecution() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SlowCacheableCommand command1 = new SlowCacheableCommand(circuitBreaker, "A", 200); SlowCacheableCommand command2 = new SlowCacheableCommand(circuitBreaker, "A", 100); SlowCacheableCommand command3 = new SlowCacheableCommand(circuitBreaker, "A", 100); SlowCacheableCommand command4 = new SlowCacheableCommand(circuitBreaker, "A", 100); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); Future<String> f4 = command4.queue(); try { assertEquals("A", f2.get()); assertEquals("A", f3.get()); assertEquals("A", f4.get()); assertEquals("A", f1.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // the second one should not have executed as it should have received the cached value instead assertFalse(command2.executed); assertFalse(command3.executed); assertFalse(command4.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command1.getExecutionTimeInMilliseconds() > -1); assertFalse(command1.isResponseFromCache()); // the execution log for command2 should show it came from cache assertEquals(2, command2.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command2.getExecutionTimeInMilliseconds() == -1); assertTrue(command2.isResponseFromCache()); assertTrue(command3.isResponseFromCache()); assertTrue(command3.getExecutionTimeInMilliseconds() == -1); assertTrue(command4.isResponseFromCache()); assertTrue(command4.getExecutionTimeInMilliseconds() == -1); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); System.out.println("HystrixRequestLog: " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testNoRequestCache3() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, false, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, false, "B"); SuccessfulCacheableCommand command3 = new SuccessfulCacheableCommand(circuitBreaker, false, "A"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // this should also execute since we disabled the cache assertTrue(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show a SUCCESS assertEquals(1, command3.getExecutionEvents().size()); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testRequestCacheViaQueueSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); assertFalse(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // but the 3rd should come from cache assertFalse(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show it comes from cache assertEquals(2, command3.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command3.isResponseFromCache()); assertTrue(command3.getExecutionTimeInMilliseconds() == -1); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testNoRequestCacheViaQueueSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); assertFalse(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // this should also execute because caching is disabled assertTrue(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show a SUCCESS assertEquals(1, command3.getExecutionEvents().size()); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testRequestCacheViaExecuteSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); assertFalse(command1.isCommandRunningInThread()); String f1 = command1.execute(); String f2 = command2.execute(); String f3 = command3.execute(); assertEquals("A", f1); assertEquals("B", f2); assertEquals("A", f3); assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // but the 3rd should come from cache assertFalse(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show it comes from cache assertEquals(2, command3.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command3.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testNoRequestCacheViaExecuteSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); assertFalse(command1.isCommandRunningInThread()); String f1 = command1.execute(); String f2 = command2.execute(); String f3 = command3.execute(); assertEquals("A", f1); assertEquals("B", f2); assertEquals("A", f3); assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // this should also execute because caching is disabled assertTrue(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show a SUCCESS assertEquals(1, command3.getExecutionEvents().size()); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testNoRequestCacheOnTimeoutThrowsException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); NoRequestCacheTimeoutWithoutFallback r1 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); try { System.out.println("r1 value: " + r1.execute()); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r1.isResponseTimedOut()); // what we want } NoRequestCacheTimeoutWithoutFallback r2 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); try { r2.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r2.isResponseTimedOut()); // what we want } NoRequestCacheTimeoutWithoutFallback r3 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); Future<Boolean> f3 = r3.queue(); try { f3.get(); // we should have thrown an exception fail("expected a timeout"); } catch (ExecutionException e) { e.printStackTrace(); assertTrue(r3.isResponseTimedOut()); // what we want } Thread.sleep(500); // timeout on command is set to 200ms NoRequestCacheTimeoutWithoutFallback r4 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); try { r4.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r4.isResponseTimedOut()); assertFalse(r4.isResponseFromFallback()); // what we want } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testRequestCacheOnTimeoutCausesNullPointerException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // Expect it to time out - all results should be false assertFalse(new RequestCacheNullPointerExceptionCase(circuitBreaker).execute()); assertFalse(new RequestCacheNullPointerExceptionCase(circuitBreaker).execute()); // return from cache #1 assertFalse(new RequestCacheNullPointerExceptionCase(circuitBreaker).execute()); // return from cache #2 Thread.sleep(500); // timeout on command is set to 200ms Boolean value = new RequestCacheNullPointerExceptionCase(circuitBreaker).execute(); // return from cache #3 assertFalse(value); RequestCacheNullPointerExceptionCase c = new RequestCacheNullPointerExceptionCase(circuitBreaker); Future<Boolean> f = c.queue(); // return from cache #4 // the bug is that we're getting a null Future back, rather than a Future that returns false assertNotNull(f); assertFalse(f.get()); assertTrue(c.isResponseFromFallback()); assertTrue(c.isResponseTimedOut()); assertFalse(c.isFailedExecution()); assertFalse(c.isResponseShortCircuited()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(5, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); HystrixCommand<?>[] executeCommands = HystrixRequestLog.getCurrentRequest().getExecutedCommands().toArray(new HystrixCommand<?>[] {}); System.out.println(":executeCommands[0].getExecutionEvents()" + executeCommands[0].getExecutionEvents()); assertEquals(2, executeCommands[0].getExecutionEvents().size()); assertTrue(executeCommands[0].getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS)); assertTrue(executeCommands[0].getExecutionEvents().contains(HystrixEventType.TIMEOUT)); assertTrue(executeCommands[0].getExecutionTimeInMilliseconds() > -1); assertTrue(executeCommands[0].isResponseTimedOut()); assertTrue(executeCommands[0].isResponseFromFallback()); assertFalse(executeCommands[0].isResponseFromCache()); assertEquals(3, executeCommands[1].getExecutionEvents().size()); // it will include FALLBACK_SUCCESS/TIMEOUT + RESPONSE_FROM_CACHE assertTrue(executeCommands[1].getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(executeCommands[1].getExecutionTimeInMilliseconds() == -1); assertTrue(executeCommands[1].isResponseFromCache()); assertTrue(executeCommands[1].isResponseTimedOut()); assertTrue(executeCommands[1].isResponseFromFallback()); } @Test public void testRequestCacheOnTimeoutThrowsException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); RequestCacheTimeoutWithoutFallback r1 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); try { System.out.println("r1 value: " + r1.execute()); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r1.isResponseTimedOut()); // what we want } RequestCacheTimeoutWithoutFallback r2 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); try { r2.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r2.isResponseTimedOut()); // what we want } RequestCacheTimeoutWithoutFallback r3 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); Future<Boolean> f3 = r3.queue(); try { f3.get(); // we should have thrown an exception fail("expected a timeout"); } catch (ExecutionException e) { e.printStackTrace(); assertTrue(r3.isResponseTimedOut()); // what we want } Thread.sleep(500); // timeout on command is set to 200ms RequestCacheTimeoutWithoutFallback r4 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); try { r4.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r4.isResponseTimedOut()); assertFalse(r4.isResponseFromFallback()); // what we want } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testRequestCacheOnThreadRejectionThrowsException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); CountDownLatch completionLatch = new CountDownLatch(1); RequestCacheThreadRejectionWithoutFallback r1 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("r1: " + r1.execute()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { assertTrue(r1.isResponseRejected()); // what we want } RequestCacheThreadRejectionWithoutFallback r2 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("r2: " + r2.execute()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { // e.printStackTrace(); assertTrue(r2.isResponseRejected()); // what we want } RequestCacheThreadRejectionWithoutFallback r3 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("f3: " + r3.queue().get()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { // e.printStackTrace(); assertTrue(r3.isResponseRejected()); // what we want } // let the command finish (only 1 should actually be blocked on this due to the response cache) completionLatch.countDown(); // then another after the command has completed RequestCacheThreadRejectionWithoutFallback r4 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("r4: " + r4.execute()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { // e.printStackTrace(); assertTrue(r4.isResponseRejected()); assertFalse(r4.isResponseFromFallback()); // what we want } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that we can do basic execution without a RequestVariable being initialized. */ @Test public void testBasicExecutionWorksWithoutRequestVariable() { try { /* force the RequestVariable to not be initialized */ HystrixRequestContext.setContextOnCurrentThread(null); TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); assertEquals(true, command.execute()); TestHystrixCommand<Boolean> command2 = new SuccessfulTestCommand(); assertEquals(true, command2.queue().get()); // we should be able to execute without a RequestVariable if ... // 1) We don't have a cacheKey // 2) We don't ask for the RequestLog // 3) We don't do collapsing } catch (Exception e) { e.printStackTrace(); fail("We received an exception => " + e.getMessage()); } } /** * Test that if we try and execute a command with a cacheKey without initializing RequestVariable that it gives an error. */ @Test public void testCacheKeyExecutionRequiresRequestVariable() { try { /* force the RequestVariable to not be initialized */ HystrixRequestContext.setContextOnCurrentThread(null); TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command = new SuccessfulCacheableCommand(circuitBreaker, true, "one"); assertEquals(true, command.execute()); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "two"); assertEquals(true, command2.queue().get()); fail("We expect an exception because cacheKey requires RequestVariable."); } catch (Exception e) { e.printStackTrace(); } } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaExecuteInThread() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD).execute(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (HystrixBadRequestException e) { // success e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaQueueInThread() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD).queue().get(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (ExecutionException e) { e.printStackTrace(); if (e.getCause() instanceof HystrixBadRequestException) { // success } else { fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } } catch (Exception e) { e.printStackTrace(); fail(); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaExecuteInSemaphore() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE).execute(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (HystrixBadRequestException e) { // success e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaQueueInSemaphore() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE).queue().get(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (HystrixBadRequestException e) { // success e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test a checked Exception being thrown */ @Test public void testCheckedException() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker); try { command.execute(); fail("we expect to receive a " + Exception.class.getSimpleName()); } catch (Exception e) { assertEquals("simulated checked exception message", e.getCause().getMessage()); } assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); } /** * Execution hook on successful execution */ @Test public void testExecutionHookSuccessfulCommand() { /* test with execute() */ TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); command.execute(); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from execute() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new SuccessfulTestCommand(); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException(e); } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with "fire and forget" approach */ @Test public void testExecutionHookSuccessfulCommandViaFireAndForget() { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); try { // do not block on "get()" ... fire this asynchronously command.queue(); } catch (Exception e) { throw new RuntimeException(e); } // wait for command to execute without calling get on the future while (!command.isExecutionComplete()) { try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException("interrupted"); } } /* * All the hooks should still work even though we didn't call get() on the future */ // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with multiple get() calls to Future */ @Test public void testExecutionHookSuccessfulCommandWithMultipleGetsOnFuture() { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); try { Future<Boolean> f = command.queue(); f.get(); f.get(); f.get(); f.get(); } catch (Exception e) { throw new RuntimeException(e); } /* * Despite multiple calls to get() we should only have 1 call to the hooks. */ // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on failed execution without a fallback */ @Test public void testExecutionHookRunFailureWithoutFallback() { /* test with execute() */ TestHystrixCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(); try { command.execute(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback is not implemented assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's not implemented and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response from execute() since we do not have a fallback and run() failed assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new UnknownFailureTestCommandWithoutFallback(); try { command.queue().get(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback is not implemented assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's not implemented and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response from queue() since we do not have a fallback and run() failed assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on failed execution with a fallback */ @Test public void testExecutionHookRunFailureWithFallback() { /* test with execute() */ TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); command.execute(); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response from run since run() failed assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // a response since fallback is implemented assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since it's implemented and succeeds assertNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from execute() since we expect a fallback despite failure of run() assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because we expect a fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException(e); } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response from run since run() failed assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // a response since fallback is implemented assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since it's implemented and succeeds assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since we expect a fallback despite failure of run() assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because we expect a fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on failed execution with a fallback failure */ @Test public void testExecutionHookRunFailureWithFallbackFailure() { /* test with execute() */ TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(); try { command.execute(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback fails assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's implemented but fails assertNotNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new KnownFailureTestCommandWithFallbackFailure(); try { command.queue().get(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback fails assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's implemented but fails assertNotNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on timeout without a fallback */ @Test public void testExecutionHookTimeoutWithoutFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.queue().get(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because of timeout and no fallback assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because run() didn't fail, it timed out assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to timeout assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since no fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since no fallback implementation assertNotNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because of timeout and no fallback assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception because of timeout and no fallback assertNotNull(command.builder.executionHook.endExecuteFailureException); // timeout failure assertEquals(FailureType.TIMEOUT, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); // we need to wait for the thread to complete before the onThreadComplete hook will be called try { Thread.sleep(400); } catch (InterruptedException e) { // ignore } assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on timeout with a fallback */ @Test public void testExecutionHookTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException("not expecting", e); } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because of timeout assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because run() didn't fail, it timed out assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to timeout assertEquals(1, command.builder.executionHook.startFallback.get()); // response since we have a fallback assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since fallback succeeds assertNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response because of fallback assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because of fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); // we need to wait for the thread to complete before the onThreadComplete hook will be called try { Thread.sleep(400); } catch (InterruptedException e) { // ignore } assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on rejected with a fallback */ @Test public void testExecutionHookRejectedWithFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); try { // fill the queue new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS).queue(); new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS).queue(); } catch (Exception e) { // ignore } TestCommandRejection command = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); try { // now execute one that will be rejected command.queue().get(); } catch (Exception e) { throw new RuntimeException("not expecting", e); } assertTrue(command.isResponseRejected()); // the run() method should not run as we're rejected assertEquals(0, command.builder.executionHook.startRun.get()); // we should not have a response because of rejection assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because we didn't run assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // response since we have a fallback assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since fallback succeeds assertNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response because of fallback assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because of fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on short-circuit with a fallback */ @Test public void testExecutionHookShortCircuitedWithFallbackViaQueue() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true); KnownFailureTestCommandWithoutFallback command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { // now execute one that will be short-circuited command.queue().get(); fail("we expect an error as there is no fallback"); } catch (Exception e) { // expecting } assertTrue(command.isResponseShortCircuited()); // the run() method should not run as we're rejected assertEquals(0, command.builder.executionHook.startRun.get()); // we should not have a response because of rejection assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because we didn't run assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since we don't have a fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since fallback fails and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because fallback fails assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we won't have an exception because short-circuit doesn't have one assertNull(command.builder.executionHook.endExecuteFailureException); // but we do expect to receive a onError call with FailureType.SHORTCIRCUIT assertEquals(FailureType.SHORTCIRCUIT, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on short-circuit with a fallback */ @Test public void testExecutionHookShortCircuitedWithFallbackViaExecute() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true); KnownFailureTestCommandWithoutFallback command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { // now execute one that will be short-circuited command.execute(); fail("we expect an error as there is no fallback"); } catch (Exception e) { // expecting } assertTrue(command.isResponseShortCircuited()); // the run() method should not run as we're rejected assertEquals(0, command.builder.executionHook.startRun.get()); // we should not have a response because of rejection assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because we didn't run assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since we don't have a fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since fallback fails and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because fallback fails assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we won't have an exception because short-circuit doesn't have one assertNull(command.builder.executionHook.endExecuteFailureException); // but we do expect to receive a onError call with FailureType.SHORTCIRCUIT assertEquals(FailureType.SHORTCIRCUIT, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with semaphore isolation */ @Test public void testExecutionHookSuccessfulCommandWithSemaphoreIsolation() { /* test with execute() */ TestSemaphoreCommand command = new TestSemaphoreCommand(new TestCircuitBreaker(), 1, 10); command.execute(); assertFalse(command.isExecutedInThread()); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from execute() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new TestSemaphoreCommand(new TestCircuitBreaker(), 1, 10); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException(e); } assertFalse(command.isExecutedInThread()); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with semaphore isolation */ @Test public void testExecutionHookFailureWithSemaphoreIsolation() { /* test with execute() */ final TryableSemaphore semaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(0)); TestSemaphoreCommand command = new TestSemaphoreCommand(new TestCircuitBreaker(), semaphore, 200); try { command.execute(); fail("we expect a failure"); } catch (Exception e) { // expected } assertFalse(command.isExecutedInThread()); assertTrue(command.isResponseRejected()); // the run() method should not run as we are rejected assertEquals(0, command.builder.executionHook.startRun.get()); // null as run() does not get invoked assertNull(command.builder.executionHook.runSuccessResponse); // null as run() does not get invoked assertNull(command.builder.executionHook.runFailureException); // the fallback() method should run because of rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // null since there is no fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since the fallback is not implemented assertNotNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response since fallback has nothing assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we won't have an exception because rejection doesn't have one assertNull(command.builder.executionHook.endExecuteFailureException); // but we do expect to receive a onError call with FailureType.SHORTCIRCUIT assertEquals(FailureType.REJECTED_SEMAPHORE_EXECUTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Test a command execution that fails but has a fallback. */ @Test public void testExecutionFailureWithFallbackImplementedButDisabled() { TestHystrixCommand<Boolean> commandEnabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), true); try { assertEquals(false, commandEnabled.execute()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } TestHystrixCommand<Boolean> commandDisabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), false); try { assertEquals(false, commandDisabled.execute()); fail("expect exception thrown"); } catch (Exception e) { // expected } assertEquals("we failed with a simulated issue", commandDisabled.getFailedExecutionException().getMessage()); assertTrue(commandDisabled.isFailedExecution()); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, commandDisabled.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /* ******************************************************************************** */ /* ******************************************************************************** */ /* private HystrixCommand class implementations for unit testing */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Used by UnitTest command implementations to provide base defaults for constructor and a builder pattern for the arguments being passed in. */ /* package */static abstract class TestHystrixCommand<K> extends HystrixCommand<K> { final TestCommandBuilder builder; TestHystrixCommand(TestCommandBuilder builder) { super(builder.owner, builder.dependencyKey, builder.threadPoolKey, builder.circuitBreaker, builder.threadPool, builder.commandPropertiesDefaults, builder.threadPoolPropertiesDefaults, builder.metrics, builder.fallbackSemaphore, builder.executionSemaphore, TEST_PROPERTIES_FACTORY, builder.executionHook); this.builder = builder; } static TestCommandBuilder testPropsBuilder() { return new TestCommandBuilder(); } static class TestCommandBuilder { TestCircuitBreaker _cb = new TestCircuitBreaker(); HystrixCommandGroupKey owner = CommandGroupForUnitTest.OWNER_ONE; HystrixCommandKey dependencyKey = null; HystrixThreadPoolKey threadPoolKey = null; HystrixCircuitBreaker circuitBreaker = _cb; HystrixThreadPool threadPool = null; HystrixCommandProperties.Setter commandPropertiesDefaults = HystrixCommandProperties.Setter.getUnitTestPropertiesSetter(); HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults = HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder(); HystrixCommandMetrics metrics = _cb.metrics; TryableSemaphore fallbackSemaphore = null; TryableSemaphore executionSemaphore = null; TestExecutionHook executionHook = new TestExecutionHook(); TestCommandBuilder setOwner(HystrixCommandGroupKey owner) { this.owner = owner; return this; } TestCommandBuilder setCommandKey(HystrixCommandKey dependencyKey) { this.dependencyKey = dependencyKey; return this; } TestCommandBuilder setThreadPoolKey(HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; return this; } TestCommandBuilder setCircuitBreaker(HystrixCircuitBreaker circuitBreaker) { this.circuitBreaker = circuitBreaker; return this; } TestCommandBuilder setThreadPool(HystrixThreadPool threadPool) { this.threadPool = threadPool; return this; } TestCommandBuilder setCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = commandPropertiesDefaults; return this; } TestCommandBuilder setThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults; return this; } TestCommandBuilder setMetrics(HystrixCommandMetrics metrics) { this.metrics = metrics; return this; } TestCommandBuilder setFallbackSemaphore(TryableSemaphore fallbackSemaphore) { this.fallbackSemaphore = fallbackSemaphore; return this; } TestCommandBuilder setExecutionSemaphore(TryableSemaphore executionSemaphore) { this.executionSemaphore = executionSemaphore; return this; } } } /** * Successful execution - no fallback implementation. */ private static class SuccessfulTestCommand extends TestHystrixCommand<Boolean> { public SuccessfulTestCommand() { this(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter()); } public SuccessfulTestCommand(HystrixCommandProperties.Setter properties) { super(testPropsBuilder().setCommandPropertiesDefaults(properties)); } @Override protected Boolean run() { return true; } } /** * Successful execution - no fallback implementation. */ private static class DynamicOwnerTestCommand extends TestHystrixCommand<Boolean> { public DynamicOwnerTestCommand(HystrixCommandGroupKey owner) { super(testPropsBuilder().setOwner(owner)); } @Override protected Boolean run() { System.out.println("successfully executed"); return true; } } /** * Successful execution - no fallback implementation. */ private static class DynamicOwnerAndKeyTestCommand extends TestHystrixCommand<Boolean> { public DynamicOwnerAndKeyTestCommand(HystrixCommandGroupKey owner, HystrixCommandKey key) { super(testPropsBuilder().setOwner(owner).setCommandKey(key).setCircuitBreaker(null).setMetrics(null)); // we specifically are NOT passing in a circuit breaker here so we test that it creates a new one correctly based on the dynamic key } @Override protected Boolean run() { System.out.println("successfully executed"); return true; } } /** * Failed execution with unknown exception (not HystrixException) - no fallback implementation. */ private static class UnknownFailureTestCommandWithoutFallback extends TestHystrixCommand<Boolean> { private UnknownFailureTestCommandWithoutFallback() { super(testPropsBuilder()); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with an unknown issue"); } } /** * Failed execution with known exception (HystrixException) - no fallback implementation. */ private static class KnownFailureTestCommandWithoutFallback extends TestHystrixCommand<Boolean> { private KnownFailureTestCommandWithoutFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with a simulated issue"); } } /** * Failed execution - fallback implementation successfully returns value. */ private static class KnownFailureTestCommandWithFallback extends TestHystrixCommand<Boolean> { public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); } public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker, boolean fallbackEnabled) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withFallbackEnabled(fallbackEnabled))); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with a simulated issue"); } @Override protected Boolean getFallback() { return false; } } /** * Failed execution - fallback implementation throws exception. */ private static class KnownFailureTestCommandWithFallbackFailure extends TestHystrixCommand<Boolean> { private KnownFailureTestCommandWithFallbackFailure() { super(testPropsBuilder()); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with a simulated issue"); } @Override protected Boolean getFallback() { throw new RuntimeException("failed while getting fallback"); } } /** * A Command implementation that supports caching. */ private static class SuccessfulCacheableCommand extends TestHystrixCommand<String> { private final boolean cacheEnabled; private volatile boolean executed = false; private final String value; public SuccessfulCacheableCommand(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, String value) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); this.value = value; this.cacheEnabled = cacheEnabled; } @Override protected String run() { executed = true; System.out.println("successfully executed"); return value; } public boolean isCommandRunningInThread() { return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD); } @Override public String getCacheKey() { if (cacheEnabled) return value; else return null; } } /** * A Command implementation that supports caching. */ private static class SuccessfulCacheableCommandViaSemaphore extends TestHystrixCommand<String> { private final boolean cacheEnabled; private volatile boolean executed = false; private final String value; public SuccessfulCacheableCommandViaSemaphore(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, String value) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))); this.value = value; this.cacheEnabled = cacheEnabled; } @Override protected String run() { executed = true; System.out.println("successfully executed"); return value; } public boolean isCommandRunningInThread() { return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD); } @Override public String getCacheKey() { if (cacheEnabled) return value; else return null; } } /** * A Command implementation that supports caching and execution takes a while. * <p> * Used to test scenario where Futures are returned with a backing call still executing. */ private static class SlowCacheableCommand extends TestHystrixCommand<String> { private final String value; private final int duration; private volatile boolean executed = false; public SlowCacheableCommand(TestCircuitBreaker circuitBreaker, String value, int duration) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); this.value = value; this.duration = duration; } @Override protected String run() { executed = true; try { Thread.sleep(duration); } catch (Exception e) { e.printStackTrace(); } System.out.println("successfully executed"); return value; } @Override public String getCacheKey() { return value; } } /** * Successful execution - no fallback implementation, circuit-breaker disabled. */ private static class TestCommandWithoutCircuitBreaker extends TestHystrixCommand<Boolean> { private TestCommandWithoutCircuitBreaker() { super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withCircuitBreakerEnabled(false))); } @Override protected Boolean run() { System.out.println("successfully executed"); return true; } } /** * This should timeout. */ private static class TestCommandWithTimeout extends TestHystrixCommand<Boolean> { private final long timeout; private final static int FALLBACK_NOT_IMPLEMENTED = 1; private final static int FALLBACK_SUCCESS = 2; private final static int FALLBACK_FAILURE = 3; private final int fallbackBehavior; private TestCommandWithTimeout(long timeout, int fallbackBehavior) { super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds((int) timeout))); this.timeout = timeout; this.fallbackBehavior = fallbackBehavior; } @Override protected Boolean run() { System.out.println("***** running"); try { Thread.sleep(timeout * 10); } catch (InterruptedException e) { e.printStackTrace(); // ignore and sleep some more to simulate a dependency that doesn't obey interrupts try { Thread.sleep(timeout * 2); } catch (Exception e2) { // ignore } System.out.println("after interruption with extra sleep"); } return true; } @Override protected Boolean getFallback() { if (fallbackBehavior == FALLBACK_SUCCESS) { return false; } else if (fallbackBehavior == FALLBACK_FAILURE) { throw new RuntimeException("failed on fallback"); } else { // FALLBACK_NOT_IMPLEMENTED return super.getFallback(); } } } /** * Threadpool with 1 thread, queue of size 1 */ private static class SingleThreadedPool implements HystrixThreadPool { final LinkedBlockingQueue<Runnable> queue; final ThreadPoolExecutor pool; private final int rejectionQueueSizeThreshold; public SingleThreadedPool(int queueSize) { this(queueSize, 100); } public SingleThreadedPool(int queueSize, int rejectionQueueSizeThreshold) { queue = new LinkedBlockingQueue<Runnable>(queueSize); pool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, queue); this.rejectionQueueSizeThreshold = rejectionQueueSizeThreshold; } @Override public ThreadPoolExecutor getExecutor() { return pool; } @Override public void markThreadExecution() { // not used for this test } @Override public void markThreadCompletion() { // not used for this test } @Override public boolean isQueueSpaceAvailable() { return queue.size() < rejectionQueueSizeThreshold; } } /** * This has a ThreadPool that has a single thread and queueSize of 1. */ private static class TestCommandRejection extends TestHystrixCommand<Boolean> { private final static int FALLBACK_NOT_IMPLEMENTED = 1; private final static int FALLBACK_SUCCESS = 2; private final static int FALLBACK_FAILURE = 3; private final int fallbackBehavior; private final int sleepTime; private TestCommandRejection(TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int sleepTime, int timeout, int fallbackBehavior) { super(testPropsBuilder().setThreadPool(threadPool).setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(timeout))); this.fallbackBehavior = fallbackBehavior; this.sleepTime = sleepTime; } @Override protected Boolean run() { System.out.println(">>> TestCommandRejection running"); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected Boolean getFallback() { if (fallbackBehavior == FALLBACK_SUCCESS) { return false; } else if (fallbackBehavior == FALLBACK_FAILURE) { throw new RuntimeException("failed on fallback"); } else { // FALLBACK_NOT_IMPLEMENTED return super.getFallback(); } } } /** * Command that receives a custom thread-pool, sleepTime, timeout */ private static class CommandWithCustomThreadPool extends TestHystrixCommand<Boolean> { public boolean didExecute = false; private final int sleepTime; private CommandWithCustomThreadPool(TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int sleepTime, HystrixCommandProperties.Setter properties) { super(testPropsBuilder().setThreadPool(threadPool).setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics).setCommandPropertiesDefaults(properties)); this.sleepTime = sleepTime; } @Override protected Boolean run() { System.out.println("**** Executing CommandWithCustomThreadPool. Execution => " + sleepTime); didExecute = true; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } return true; } } /** * The run() will fail and getFallback() take a long time. */ private static class TestSemaphoreCommandWithSlowFallback extends TestHystrixCommand<Boolean> { private final long fallbackSleep; private TestSemaphoreCommandWithSlowFallback(TestCircuitBreaker circuitBreaker, int fallbackSemaphoreExecutionCount, long fallbackSleep) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withFallbackIsolationSemaphoreMaxConcurrentRequests(fallbackSemaphoreExecutionCount))); this.fallbackSleep = fallbackSleep; } @Override protected Boolean run() { throw new RuntimeException("run fails"); } @Override protected Boolean getFallback() { try { Thread.sleep(fallbackSleep); } catch (InterruptedException e) { e.printStackTrace(); } return true; } } private static class NoRequestCacheTimeoutWithoutFallback extends TestHystrixCommand<Boolean> { public NoRequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(200))); // we want it to timeout } @Override protected Boolean run() { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(">>>> Sleep Interrupted: " + e.getMessage()); // e.printStackTrace(); } return true; } @Override public String getCacheKey() { return null; } } /** * The run() will take time. No fallback implementation. */ private static class TestSemaphoreCommand extends TestHystrixCommand<Boolean> { private final long executionSleep; private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter() .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE) .withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount))); this.executionSleep = executionSleep; } private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, long executionSleep) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter() .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)) .setExecutionSemaphore(semaphore)); this.executionSleep = executionSleep; } @Override protected Boolean run() { try { Thread.sleep(executionSleep); } catch (InterruptedException e) { e.printStackTrace(); } return true; } } /** * Semaphore based command that allows caller to use latches to know when it has started and signal when it * would like the command to finish */ private static class LatchedSemaphoreCommand extends TestHystrixCommand<Boolean> { private final CountDownLatch startLatch, waitLatch; /** * * @param circuitBreaker * @param semaphore * @param startLatch * this command calls {@link java.util.concurrent.CountDownLatch#countDown()} immediately * upon running * @param waitLatch * this command calls {@link java.util.concurrent.CountDownLatch#await()} once it starts * to run. The caller can use the latch to signal the command to finish */ private LatchedSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, CountDownLatch startLatch, CountDownLatch waitLatch) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)) .setExecutionSemaphore(semaphore)); this.startLatch = startLatch; this.waitLatch = waitLatch; } @Override protected Boolean run() { // signals caller that run has started this.startLatch.countDown(); try { // waits for caller to countDown latch this.waitLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); return false; } return true; } } /** * The run() will take time. Contains fallback. */ private static class TestSemaphoreCommandWithFallback extends TestHystrixCommand<Boolean> { private final long executionSleep; private final Boolean fallback; private TestSemaphoreCommandWithFallback(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep, Boolean fallback) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount))); this.executionSleep = executionSleep; this.fallback = fallback; } @Override protected Boolean run() { try { Thread.sleep(executionSleep); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected Boolean getFallback() { return fallback; } } private static class RequestCacheNullPointerExceptionCase extends TestHystrixCommand<Boolean> { public RequestCacheNullPointerExceptionCase(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(200))); // we want it to timeout } @Override protected Boolean run() { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected Boolean getFallback() { return false; } @Override public String getCacheKey() { return "A"; } } private static class RequestCacheTimeoutWithoutFallback extends TestHystrixCommand<Boolean> { public RequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(200))); // we want it to timeout } @Override protected Boolean run() { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(">>>> Sleep Interrupted: " + e.getMessage()); // e.printStackTrace(); } return true; } @Override public String getCacheKey() { return "A"; } } private static class RequestCacheThreadRejectionWithoutFallback extends TestHystrixCommand<Boolean> { final CountDownLatch completionLatch; public RequestCacheThreadRejectionWithoutFallback(TestCircuitBreaker circuitBreaker, CountDownLatch completionLatch) { super(testPropsBuilder() .setCircuitBreaker(circuitBreaker) .setMetrics(circuitBreaker.metrics) .setThreadPool(new HystrixThreadPool() { @Override public ThreadPoolExecutor getExecutor() { return null; } @Override public void markThreadExecution() { } @Override public void markThreadCompletion() { } @Override public boolean isQueueSpaceAvailable() { // always return false so we reject everything return false; } })); this.completionLatch = completionLatch; } @Override protected Boolean run() { try { if (completionLatch.await(1000, TimeUnit.MILLISECONDS)) { throw new RuntimeException("timed out waiting on completionLatch"); } } catch (InterruptedException e) { throw new RuntimeException(e); } return true; } @Override public String getCacheKey() { return "A"; } } private static class BadRequestCommand extends TestHystrixCommand<Boolean> { public BadRequestCommand(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationType) { super(testPropsBuilder() .setCircuitBreaker(circuitBreaker) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationType))); } @Override protected Boolean run() { throw new HystrixBadRequestException("Message to developer that they passed in bad data or something like that."); } @Override protected Boolean getFallback() { return false; } } private static class CommandWithCheckedException extends TestHystrixCommand<Boolean> { public CommandWithCheckedException(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder() .setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); } @Override protected Boolean run() throws Exception { throw new IOException("simulated checked exception message"); } } enum CommandKeyForUnitTest implements HystrixCommandKey { KEY_ONE, KEY_TWO; } enum CommandGroupForUnitTest implements HystrixCommandGroupKey { OWNER_ONE, OWNER_TWO; } enum ThreadPoolKeyForUnitTest implements HystrixThreadPoolKey { THREAD_POOL_ONE, THREAD_POOL_TWO; } private static HystrixPropertiesStrategy TEST_PROPERTIES_FACTORY = new TestPropertiesFactory(); private static class TestPropertiesFactory extends HystrixPropertiesStrategy { @Override public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) { if (builder == null) { builder = HystrixCommandProperties.Setter.getUnitTestPropertiesSetter(); } return HystrixCommandProperties.Setter.asMock(builder); } @Override public HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter builder) { if (builder == null) { builder = HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder(); } return HystrixThreadPoolProperties.Setter.asMock(builder); } @Override public HystrixCollapserProperties getCollapserProperties(HystrixCollapserKey collapserKey, HystrixCollapserProperties.Setter builder) { throw new IllegalStateException("not expecting collapser properties"); } @Override public String getCommandPropertiesCacheKey(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) { return null; } @Override public String getThreadPoolPropertiesCacheKey(HystrixThreadPoolKey threadPoolKey, com.netflix.hystrix.HystrixThreadPoolProperties.Setter builder) { return null; } @Override public String getCollapserPropertiesCacheKey(HystrixCollapserKey collapserKey, com.netflix.hystrix.HystrixCollapserProperties.Setter builder) { return null; } } private static class TestExecutionHook extends HystrixCommandExecutionHook { AtomicInteger startExecute = new AtomicInteger(); @Override public <T> void onStart(HystrixCommand<T> commandInstance) { super.onStart(commandInstance); startExecute.incrementAndGet(); } Object endExecuteSuccessResponse = null; @Override public <T> T onComplete(HystrixCommand<T> commandInstance, T response) { endExecuteSuccessResponse = response; return super.onComplete(commandInstance, response); } Exception endExecuteFailureException = null; FailureType endExecuteFailureType = null; @Override public <T> Exception onError(HystrixCommand<T> commandInstance, FailureType failureType, Exception e) { endExecuteFailureException = e; endExecuteFailureType = failureType; return super.onError(commandInstance, failureType, e); } AtomicInteger startRun = new AtomicInteger(); @Override public <T> void onRunStart(HystrixCommand<T> commandInstance) { super.onRunStart(commandInstance); startRun.incrementAndGet(); } Object runSuccessResponse = null; @Override public <T> T onRunSuccess(HystrixCommand<T> commandInstance, T response) { runSuccessResponse = response; return super.onRunSuccess(commandInstance, response); } Exception runFailureException = null; @Override public <T> Exception onRunError(HystrixCommand<T> commandInstance, Exception e) { runFailureException = e; return super.onRunError(commandInstance, e); } AtomicInteger startFallback = new AtomicInteger(); @Override public <T> void onFallbackStart(HystrixCommand<T> commandInstance) { super.onFallbackStart(commandInstance); startFallback.incrementAndGet(); } Object fallbackSuccessResponse = null; @Override public <T> T onFallbackSuccess(HystrixCommand<T> commandInstance, T response) { fallbackSuccessResponse = response; return super.onFallbackSuccess(commandInstance, response); } Exception fallbackFailureException = null; @Override public <T> Exception onFallbackError(HystrixCommand<T> commandInstance, Exception e) { fallbackFailureException = e; return super.onFallbackError(commandInstance, e); } AtomicInteger threadStart = new AtomicInteger(); @Override public <T> void onThreadStart(HystrixCommand<T> commandInstance) { super.onThreadStart(commandInstance); threadStart.incrementAndGet(); } AtomicInteger threadComplete = new AtomicInteger(); @Override public <T> void onThreadComplete(HystrixCommand<T> commandInstance) { super.onThreadComplete(commandInstance); threadComplete.incrementAndGet(); } } } }
hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommand.java
/** * Copyright 2012 Netflix, 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.netflix.hystrix; import static org.junit.Assert.*; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.ThreadSafe; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observer; import rx.Scheduler; import rx.Subscription; import rx.concurrency.Schedulers; import rx.operators.AtomicObservableSubscription; import rx.subjects.ReplaySubject; import rx.subscriptions.Subscriptions; import rx.util.functions.Action0; import rx.util.functions.Func1; import rx.util.functions.Func2; import com.netflix.config.ConfigurationManager; import com.netflix.hystrix.HystrixCircuitBreaker.NoOpCircuitBreaker; import com.netflix.hystrix.HystrixCircuitBreaker.TestCircuitBreaker; import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault; import com.netflix.hystrix.strategy.concurrency.HystrixContextCallable; import com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisherFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; import com.netflix.hystrix.strategy.properties.HystrixProperty; import com.netflix.hystrix.util.ExceptionThreadingUtility; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import com.netflix.hystrix.util.HystrixTimer; import com.netflix.hystrix.util.HystrixTimer.TimerListener; /** * Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) * with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. * * @param <R> * the return type */ @ThreadSafe public abstract class HystrixCommand<R> implements HystrixExecutable<R> { private static final Logger logger = LoggerFactory.getLogger(HystrixCommand.class); private final HystrixCircuitBreaker circuitBreaker; private final HystrixThreadPool threadPool; private final HystrixThreadPoolKey threadPoolKey; private final HystrixCommandProperties properties; private final HystrixCommandMetrics metrics; /* result of execution (if this command instance actually gets executed, which may not occur due to request caching) */ private volatile ExecutionResult executionResult = ExecutionResult.EMPTY; /* If this command executed and timed-out */ private final AtomicBoolean isCommandTimedOut = new AtomicBoolean(false); private final AtomicBoolean isExecutionComplete = new AtomicBoolean(false); private final AtomicBoolean isExecutedInThread = new AtomicBoolean(false); private final HystrixCommandKey commandKey; private final HystrixCommandGroupKey commandGroup; /* FALLBACK Semaphore */ private final TryableSemaphore fallbackSemaphoreOverride; /* each circuit has a semaphore to restrict concurrent fallback execution */ private static final ConcurrentHashMap<String, TryableSemaphore> fallbackSemaphorePerCircuit = new ConcurrentHashMap<String, TryableSemaphore>(); /* END FALLBACK Semaphore */ /* EXECUTION Semaphore */ private final TryableSemaphore executionSemaphoreOverride; /* each circuit has a semaphore to restrict concurrent fallback execution */ private static final ConcurrentHashMap<String, TryableSemaphore> executionSemaphorePerCircuit = new ConcurrentHashMap<String, TryableSemaphore>(); /* END EXECUTION Semaphore */ private final AtomicReference<Reference<TimerListener>> timeoutTimer = new AtomicReference<Reference<TimerListener>>(); private AtomicBoolean started = new AtomicBoolean(); private volatile long invocationStartTime = -1; /** * Instance of RequestCache logic */ private final HystrixRequestCache requestCache; /** * Plugin implementations */ private final HystrixEventNotifier eventNotifier; private final HystrixConcurrencyStrategy concurrencyStrategy; private final HystrixCommandExecutionHook executionHook; /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, * common business purpose etc. */ protected HystrixCommand(HystrixCommandGroupKey group) { // use 'null' to specify use the default this(new Setter(group)); } /** * Construct a {@link HystrixCommand} with defined {@link Setter} that allows injecting property and strategy overrides and other optional arguments. * <p> * NOTE: The {@link HystrixCommandKey} is used to associate a {@link HystrixCommand} with {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and other objects. * <p> * Do not create multiple {@link HystrixCommand} implementations with the same {@link HystrixCommandKey} but different injected default properties as the first instantiated will win. * * @param setter * Fluent interface for constructor arguments */ protected HystrixCommand(Setter setter) { // use 'null' to specify use the default this(setter.groupKey, setter.commandKey, setter.threadPoolKey, null, null, setter.commandPropertiesDefaults, setter.threadPoolPropertiesDefaults, null, null, null, null, null); } /** * Allow constructing a {@link HystrixCommand} with injection of most aspects of its functionality. * <p> * Some of these never have a legitimate reason for injection except in unit testing. * <p> * Most of the args will revert to a valid default if 'null' is passed in. */ private HystrixCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { /* * CommandGroup initialization */ if (group == null) { throw new IllegalStateException("HystrixCommandGroup can not be NULL"); } else { this.commandGroup = group; } /* * CommandKey initialization */ if (key == null || key.name().trim().equals("")) { final String keyName = getDefaultNameFromClass(getClass()); this.commandKey = HystrixCommandKey.Factory.asKey(keyName); } else { this.commandKey = key; } /* * Properties initialization */ if (propertiesStrategy == null) { this.properties = HystrixPropertiesFactory.getCommandProperties(this.commandKey, commandPropertiesDefaults); } else { // used for unit testing this.properties = propertiesStrategy.getCommandProperties(this.commandKey, commandPropertiesDefaults); } /* * ThreadPoolKey * * This defines which thread-pool this command should run on. * * It uses the HystrixThreadPoolKey if provided, then defaults to use HystrixCommandGroup. * * It can then be overridden by a property if defined so it can be changed at runtime. */ if (this.properties.executionIsolationThreadPoolKeyOverride().get() == null) { // we don't have a property overriding the value so use either HystrixThreadPoolKey or HystrixCommandGroup if (threadPoolKey == null) { /* use HystrixCommandGroup if HystrixThreadPoolKey is null */ this.threadPoolKey = HystrixThreadPoolKey.Factory.asKey(commandGroup.name()); } else { this.threadPoolKey = threadPoolKey; } } else { // we have a property defining the thread-pool so use it instead this.threadPoolKey = HystrixThreadPoolKey.Factory.asKey(properties.executionIsolationThreadPoolKeyOverride().get()); } /* strategy: HystrixEventNotifier */ this.eventNotifier = HystrixPlugins.getInstance().getEventNotifier(); /* strategy: HystrixConcurrentStrategy */ this.concurrencyStrategy = HystrixPlugins.getInstance().getConcurrencyStrategy(); /* * Metrics initialization */ if (metrics == null) { this.metrics = HystrixCommandMetrics.getInstance(this.commandKey, this.commandGroup, this.properties); } else { this.metrics = metrics; } /* * CircuitBreaker initialization */ if (this.properties.circuitBreakerEnabled().get()) { if (circuitBreaker == null) { // get the default implementation of HystrixCircuitBreaker this.circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(this.commandKey, this.commandGroup, this.properties, this.metrics); } else { this.circuitBreaker = circuitBreaker; } } else { this.circuitBreaker = new NoOpCircuitBreaker(); } /* strategy: HystrixMetricsPublisherCommand */ HystrixMetricsPublisherFactory.createOrRetrievePublisherForCommand(this.commandKey, this.commandGroup, this.metrics, this.circuitBreaker, this.properties); /* strategy: HystrixCommandExecutionHook */ if (executionHook == null) { this.executionHook = HystrixPlugins.getInstance().getCommandExecutionHook(); } else { // used for unit testing this.executionHook = executionHook; } /* * ThreadPool initialization */ if (threadPool == null) { // get the default implementation of HystrixThreadPool this.threadPool = HystrixThreadPool.Factory.getInstance(this.threadPoolKey, threadPoolPropertiesDefaults); } else { this.threadPool = threadPool; } /* fallback semaphore override if applicable */ this.fallbackSemaphoreOverride = fallbackSemaphore; /* execution semaphore override if applicable */ this.executionSemaphoreOverride = executionSemaphore; /* setup the request cache for this instance */ this.requestCache = HystrixRequestCache.getInstance(this.commandKey, this.concurrencyStrategy); } private static String getDefaultNameFromClass(@SuppressWarnings("rawtypes") Class<? extends HystrixCommand> cls) { String fromCache = defaultNameCache.get(cls); if (fromCache != null) { return fromCache; } // generate the default // default HystrixCommandKey to use if the method is not overridden String name = cls.getSimpleName(); if (name.equals("")) { // we don't have a SimpleName (anonymous inner class) so use the full class name name = cls.getName(); name = name.substring(name.lastIndexOf('.') + 1, name.length()); } defaultNameCache.put(cls, name); return name; } // this is a micro-optimization but saves about 1-2microseconds (on 2011 MacBook Pro) // on the repetitive string processing that will occur on the same classes over and over again @SuppressWarnings("rawtypes") private static ConcurrentHashMap<Class<? extends HystrixCommand>, String> defaultNameCache = new ConcurrentHashMap<Class<? extends HystrixCommand>, String>(); /** * Implement this method with code to be executed when {@link #execute()} or {@link #queue()} are invoked. * * @return R response type * @throws Exception * if command execution fails */ protected abstract R run() throws Exception; /** * If {@link #execute()} or {@link #queue()} fails in any way then this method will be invoked to provide an opportunity to return a fallback response. * <p> * This should do work that does not require network transport to produce. * <p> * In other words, this should be a static or cached result that can immediately be returned upon failure. * <p> * If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another {@link HystrixCommand} instance that protects against that network * access and possibly has another level of fallback that does not involve network access. * <p> * DEFAULT BEHAVIOR: It throws UnsupportedOperationException. * * @return R or throw UnsupportedOperationException if not implemented */ protected R getFallback() { throw new UnsupportedOperationException("No fallback available."); } /** * @return {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, * common business purpose etc. */ public HystrixCommandGroupKey getCommandGroup() { return commandGroup; } /** * @return {@link HystrixCommandKey} identifying this command instance for statistics, circuit-breaker, properties, etc. */ public HystrixCommandKey getCommandKey() { return commandKey; } /** * @return {@link HystrixThreadPoolKey} identifying which thread-pool this command uses (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). */ public HystrixThreadPoolKey getThreadPoolKey() { return threadPoolKey; } /* package */HystrixCircuitBreaker getCircuitBreaker() { return circuitBreaker; } /** * The {@link HystrixCommandMetrics} associated with this {@link HystrixCommand} instance. * * @return HystrixCommandMetrics */ public HystrixCommandMetrics getMetrics() { return metrics; } /** * The {@link HystrixCommandProperties} associated with this {@link HystrixCommand} instance. * * @return HystrixCommandProperties */ public HystrixCommandProperties getProperties() { return properties; } /** * Allow the Collapser to mark this command instance as being used for a collapsed request and how many requests were collapsed. * * @param sizeOfBatch */ /* package */void markAsCollapsedCommand(int sizeOfBatch) { getMetrics().markCollapsed(sizeOfBatch); executionResult = executionResult.addEvents(HystrixEventType.COLLAPSED); } /** * Used for synchronous execution of command. * * @return R * Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a failure occurs and a fallback cannot be retrieved * @throws HystrixBadRequestException * if invalid arguments or state were used representing a user failure, not a system failure */ public R execute() { try { return queue().get(); } catch (Exception e) { throw decomposeException(e); } } /** * Used for asynchronous execution of command. * <p> * This will queue up the command on the thread pool and return an {@link Future} to get the result once it completes. * <p> * NOTE: If configured to not run in a separate thread, this will have the same effect as {@link #execute()} and will block. * <p> * We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread. * * @return {@code Future<R>} Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Future.get()} in {@link ExecutionException#getCause()} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Future.get()} in {@link ExecutionException#getCause()} if invalid arguments or state were used representing a user failure, not a system failure */ public Future<R> queue() { /* * --- Schedulers.immediate() * * We use the 'immediate' schedule since Future.get() is blocking so we don't want to bother doing the callback to the Future on a separate thread * as we don't need to separate the Hystrix thread from user threads since they are already providing it via the Future.get() call. * * --- performAsyncTimeout: false * * We pass 'false' to tell the Observable we will block on it so it doesn't schedule an async timeout. * * This optimizes for using the calling thread to do the timeout rather than scheduling another thread. * * In a tight-loop of executing commands this optimization saves a few microseconds per execution. * It also just makes no sense to use a separate thread to timeout the command when the calling thread * is going to sit waiting on it. */ final ObservableCommand<R> o = toObservable(Schedulers.immediate(), false); final Future<R> f = o.toBlockingObservable().toFuture(); /* special handling of error states that throw immediately */ if (f.isDone()) { try { f.get(); return f; } catch (Exception e) { RuntimeException re = decomposeException(e); if (re instanceof HystrixRuntimeException) { HystrixRuntimeException hre = (HystrixRuntimeException) re; if (hre.getFailureType() == FailureType.COMMAND_EXCEPTION || hre.getFailureType() == FailureType.TIMEOUT) { // we don't throw these types from queue() only from queue().get() as they are execution errors return f; } else { // these are errors we throw from queue() as they as rejection type errors throw hre; } } else { throw re; } } } return new Future<R>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return f.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return f.isCancelled(); } @Override public boolean isDone() { return f.isDone(); } @Override public R get() throws InterruptedException, ExecutionException { return performBlockingGetWithTimeout(o, f); } /** * --- Non-Blocking Timeout (performAsyncTimeout:true) --- * * When 'toObservable' is done with non-blocking timeout then timeout functionality is provided * by a separate HystrixTimer thread that will "tick" and cancel the underlying async Future inside the Observable. * * This method allows stealing that responsibility and letting the thread that's going to block anyways * do the work to reduce pressure on the HystrixTimer. * * Blocking via queue().get() on a non-blocking timeout will work it's just less efficient * as it involves an extra thread and cancels the scheduled action that does the timeout. * * --- Blocking Timeout (performAsyncTimeout:false) --- * * When blocking timeout is assumed (default behavior for execute/queue flows) then the async * timeout will not have been scheduled and this will wait in a blocking manner and if a timeout occurs * trigger the timeout logic that comes from inside the Observable/Observer. * * * --- Examples * * Stack for timeout with performAsyncTimeout=false (note the calling thread via get): * * at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$1.tick(HystrixCommand.java:788) * at com.netflix.hystrix.HystrixCommand$1.performBlockingGetWithTimeout(HystrixCommand.java:536) * at com.netflix.hystrix.HystrixCommand$1.get(HystrixCommand.java:484) * at com.netflix.hystrix.HystrixCommand.execute(HystrixCommand.java:413) * * * Stack for timeout with performAsyncTimeout=true (note the HystrixTimer involved): * * at com.netflix.hystrix.HystrixCommand$TimeoutObservable$1$1.tick(HystrixCommand.java:799) * at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:101) * * * * @param o * @param f * @throws InterruptedException * @throws ExecutionException */ protected R performBlockingGetWithTimeout(final ObservableCommand<R> o, final Future<R> f) throws InterruptedException, ExecutionException { // shortcut if already done if (f.isDone()) { return f.get(); } // it's still working so proceed with blocking/timeout logic HystrixCommand<R> originalCommand = o.getCommand(); /** * One thread will get the timeoutTimer if it's set and clear it then do blocking timeout. * <p> * If non-blocking timeout was scheduled this will unschedule it. If it wasn't scheduled it is basically * a no-op but fits the same interface so blocking and non-blocking flows both work the same. * <p> * This "originalCommand" concept exists because of request caching. We only do the work and timeout logic * on the original, not the cached responses. However, whichever the first thread is that comes in to block * will be the one who performs the timeout logic. * <p> * If request caching is disabled then it will always go into here. */ if (originalCommand != null) { Reference<TimerListener> timer = originalCommand.timeoutTimer.getAndSet(null); if (timer != null) { /** * If an async timeout was scheduled then: * * - We are going to clear the Reference<TimerListener> so the scheduler threads stop managing the timeout * and we'll take over instead since we're going to be blocking on it anyways. * * - Other threads (since we won the race) will just wait on the normal Future which will release * once the Observable is marked as completed (which may come via timeout) * * If an async timeout was not scheduled: * * - We go through the same flow as we receive the same interfaces just the "timer.clear()" will do nothing. */ // get the timer we'll use to perform the timeout TimerListener l = timer.get(); // remove the timer from the scheduler timer.clear(); // determine how long we should wait for, taking into account time since work started // and when this thread came in to block. If invocationTime hasn't been set then assume time remaining is entire timeout value // as this maybe a case of multiple threads trying to run this command in which one thread wins but even before the winning thread is able to set // the starttime another thread going via the Cached command route gets here first. long timeout = originalCommand.properties.executionIsolationThreadTimeoutInMilliseconds().get(); long timeRemaining = timeout; long currTime = System.currentTimeMillis(); if (originalCommand.invocationStartTime != -1) { timeRemaining = (originalCommand.invocationStartTime + originalCommand.properties.executionIsolationThreadTimeoutInMilliseconds().get()) - currTime; } if (timeRemaining > 0) { // we need to block with the calculated timeout try { return f.get(timeRemaining, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { if (l != null) { // this perform the timeout logic on the Observable/Observer l.tick(); } } } else { // this means it should have already timed out so do so if it is not completed if (!f.isDone()) { if (l != null) { l.tick(); } } } } } // other threads will block until the "l.tick" occurs and releases the underlying Future. return f.get(); } @Override public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; } /** * Take an Exception and determine whether to throw it, its cause or a new HystrixRuntimeException. * <p> * This will only throw an HystrixRuntimeException or HystrixBadRequestException * * @param e * @return HystrixRuntimeException or HystrixBadRequestException */ protected RuntimeException decomposeException(Exception e) { if (e instanceof HystrixBadRequestException) { return (HystrixBadRequestException) e; } if (e.getCause() instanceof HystrixBadRequestException) { return (HystrixBadRequestException) e.getCause(); } if (e instanceof HystrixRuntimeException) { return (HystrixRuntimeException) e; } // if we have an exception we know about we'll throw it directly without the wrapper exception if (e.getCause() instanceof HystrixRuntimeException) { return (HystrixRuntimeException) e.getCause(); } // we don't know what kind of exception this is so create a generic message and throw a new HystrixRuntimeException String message = getLogMessagePrefix() + " failed while executing."; logger.debug(message, e); // debug only since we're throwing the exception and someone higher will do something with it return new HystrixRuntimeException(FailureType.COMMAND_EXCEPTION, this.getClass(), message, e, null); } public Observable<R> observe() { // us a ReplaySubject to buffer the eagerly subscribed-to Observable ReplaySubject<R> subject = ReplaySubject.create(); // eagerly kick off subscription toObservable().subscribe(subject); // return the subject that can be subscribed to later while the execution has already started return subject; } public Observable<R> toObservable() { if (properties.executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD)) { return toObservable(Schedulers.threadPoolForComputation()); } else { // semaphore isolation is all blocking, no new threads involved return toObservable(Schedulers.immediate()); } } public Observable<R> toObservable(Scheduler observeOn) { return toObservable(observeOn, true); } private ObservableCommand<R> toObservable(Scheduler observeOn, boolean performAsyncTimeout) { /* this is a stateful object so can only be used once */ if (!started.compareAndSet(false, true)) { throw new IllegalStateException("This instance can only be executed once. Please instantiate a new instance."); } /* try from cache first */ if (isRequestCachingEnabled()) { Observable<R> fromCache = requestCache.get(getCacheKey()); if (fromCache != null) { /* mark that we received this response from cache */ metrics.markResponseFromCache(); return new CachedObservableResponse<R>((CachedObservableOriginal<R>) fromCache, this); } } final HystrixCommand<R> _this = this; // create an Observable that will lazily execute when subscribed to Observable<R> o = Observable.create(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(Observer<R> observer) { try { /* used to track userThreadExecutionTime */ invocationStartTime = System.currentTimeMillis(); // mark that we're starting execution on the ExecutionHook executionHook.onStart(_this); /* determine if we're allowed to execute */ if (!circuitBreaker.allowRequest()) { // record that we are returning a short-circuited fallback metrics.markShortCircuited(); // short-circuit and go directly to fallback (or throw an exception if no fallback implemented) try { observer.onNext(getFallbackOrThrowException(HystrixEventType.SHORT_CIRCUITED, FailureType.SHORTCIRCUIT, "short-circuited")); observer.onCompleted(); } catch (Exception e) { observer.onError(e); } return Subscriptions.empty(); } else { /* not short-circuited so proceed with queuing the execution */ try { if (properties.executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD)) { return subscribeWithThreadIsolation(observer); } else { return subscribeWithSemaphoreIsolation(observer); } } catch (RuntimeException e) { observer.onError(e); return Subscriptions.empty(); } } } finally { recordExecutedCommand(); } } }); if (properties.executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD)) { // wrap for timeout support o = new TimeoutObservable<R>(o, _this, performAsyncTimeout); } // error handling o = o.onErrorResumeNext(new Func1<Exception, Observable<R>>() { @Override public Observable<R> call(Exception e) { // count that we are throwing an exception and re-throw it metrics.markExceptionThrown(); return Observable.error(e); } }); // we want to hand off work to a different scheduler so we don't tie up the Hystrix thread o = o.observeOn(observeOn); o = o.finallyDo(new Action0() { @Override public void call() { Reference<TimerListener> tl = timeoutTimer.get(); if (tl != null) { tl.clear(); } } }); // put in cache if (isRequestCachingEnabled()) { // wrap it for caching o = new CachedObservableOriginal<R>(o.cache(), this); Observable<R> fromCache = requestCache.putIfAbsent(getCacheKey(), o); if (fromCache != null) { // another thread beat us so we'll use the cached value instead o = new CachedObservableResponse<R>((CachedObservableOriginal<R>) fromCache, this); } // we just created an ObservableCommand so we cast and return it return (ObservableCommand<R>) o; } else { // no request caching so a simple wrapper just to pass 'this' along with the Observable return new ObservableCommand<R>(o, this); } } /** * Wraps a source Observable and remembers the original HystrixCommand. * <p> * Used for request caching so multiple commands can respond from a single Observable but also get access to the originating HystrixCommand. * * @param <R> */ private static class CachedObservableOriginal<R> extends ObservableCommand<R> { final HystrixCommand<R> originalCommand; CachedObservableOriginal(final Observable<R> actual, HystrixCommand<R> command) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(final Observer<R> observer) { return actual.subscribe(observer); } }, command); this.originalCommand = command; } } private static class ObservableCommand<R> extends Observable<R> { private final HystrixCommand<R> command; ObservableCommand(Func1<Observer<R>, Subscription> func, final HystrixCommand<R> command) { super(func); this.command = command; } public HystrixCommand<R> getCommand() { return command; } ObservableCommand(final Observable<R> originalObservable, final HystrixCommand<R> command) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(Observer<R> observer) { return originalObservable.subscribe(observer); } }); this.command = command; } } /** * Wraps a CachedObservableOriginal as it is being returned from cache. * <p> * As the Observable completes it copies state used for ExecutionResults * and metrics that differentiate between the original and the de-duped "response from cache" command execution. * * @param <R> */ private static class CachedObservableResponse<R> extends ObservableCommand<R> { final CachedObservableOriginal<R> originalObservable; CachedObservableResponse(final CachedObservableOriginal<R> originalObservable, final HystrixCommand<R> commandOfDuplicateCall) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(final Observer<R> observer) { return originalObservable.subscribe(new Observer<R>() { @Override public void onCompleted() { completeCommand(); observer.onCompleted(); } @Override public void onError(Exception e) { completeCommand(); observer.onError(e); } @Override public void onNext(R v) { observer.onNext(v); } private void completeCommand() { // when the observable completes we then update the execution results of the duplicate command // set this instance to the result that is from cache commandOfDuplicateCall.executionResult = originalObservable.originalCommand.executionResult; // add that this came from cache commandOfDuplicateCall.executionResult = commandOfDuplicateCall.executionResult.addEvents(HystrixEventType.RESPONSE_FROM_CACHE); // set the execution time to 0 since we retrieved from cache commandOfDuplicateCall.executionResult = commandOfDuplicateCall.executionResult.setExecutionTime(-1); // record that this command executed commandOfDuplicateCall.recordExecutedCommand(); } }); } }, commandOfDuplicateCall); this.originalObservable = originalObservable; } /* * This is a cached response so we want the command of the observable we're wrapping. */ public HystrixCommand<R> getCommand() { return originalObservable.originalCommand; } } private static class TimeoutObservable<R> extends Observable<R> { public TimeoutObservable(final Observable<R> o, final HystrixCommand<R> originalCommand, final boolean isNonBlocking) { super(new Func1<Observer<R>, Subscription>() { @Override public Subscription call(final Observer<R> observer) { final AtomicObservableSubscription s = new AtomicObservableSubscription(); TimerListener listener = new TimerListener() { @Override public void tick() { if (originalCommand.isCommandTimedOut.compareAndSet(false, true)) { // do fallback logic // report timeout failure originalCommand.metrics.markTimeout(System.currentTimeMillis() - originalCommand.invocationStartTime); // we record execution time because we are returning before originalCommand.recordTotalExecutionTime(originalCommand.invocationStartTime); try { R v = originalCommand.getFallbackOrThrowException(HystrixEventType.TIMEOUT, FailureType.TIMEOUT, "timed-out", new TimeoutException()); observer.onNext(v); observer.onCompleted(); } catch (HystrixRuntimeException re) { observer.onError(re); } } s.unsubscribe(); } @Override public int getIntervalTimeInMilliseconds() { return originalCommand.properties.executionIsolationThreadTimeoutInMilliseconds().get(); } }; Reference<TimerListener> _tl = null; if (isNonBlocking) { /* * Scheduling a separate timer to do timeouts is more expensive * so we'll only do it if we're being used in a non-blocking manner. */ _tl = HystrixTimer.getInstance().addTimerListener(listener); } else { /* * Otherwise we just set the hook that queue().get() can trigger if a timeout occurs. * * This allows the blocking and non-blocking approaches to be coded basically the same way * though it is admittedly awkward if we were just blocking (the use of Reference annoys me for example) */ _tl = new SoftReference<TimerListener>(listener); } final Reference<TimerListener> tl = _tl; // set externally so execute/queue can see this originalCommand.timeoutTimer.set(tl); return s.wrap(o.subscribe(new Observer<R>() { @Override public void onCompleted() { tl.clear(); observer.onCompleted(); } @Override public void onError(Exception e) { tl.clear(); observer.onError(e); } @Override public void onNext(R v) { observer.onNext(v); } })); } }); } } private Subscription subscribeWithSemaphoreIsolation(final Observer<R> observer) { TryableSemaphore executionSemaphore = getExecutionSemaphore(); // acquire a permit if (executionSemaphore.tryAcquire()) { try { try { // store the command that is being run Hystrix.startCurrentThreadExecutingCommand(getCommandKey()); // execute outside of future so that fireAndForget will still work (ie. someone calls queue() but not get()) and so that multiple requests can be deduped through request caching R r = executeCommand(); r = executionHook.onComplete(this, r); observer.onNext(r); /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ recordTotalExecutionTime(invocationStartTime); /* now complete which releases the consumer */ observer.onCompleted(); // empty subscription since we executed synchronously return Subscriptions.empty(); } catch (Exception e) { /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ recordTotalExecutionTime(invocationStartTime); observer.onError(e); // empty subscription since we executed synchronously return Subscriptions.empty(); } finally { // pop the command that is being run Hystrix.endCurrentThreadExecutingCommand(); } } finally { // release the semaphore executionSemaphore.release(); } } else { metrics.markSemaphoreRejection(); logger.debug("HystrixCommand Execution Rejection by Semaphore."); // debug only since we're throwing the exception and someone higher will do something with it // retrieve a fallback or throw an exception if no fallback available observer.onNext(getFallbackOrThrowException(HystrixEventType.SEMAPHORE_REJECTED, FailureType.REJECTED_SEMAPHORE_EXECUTION, "could not acquire a semaphore for execution")); observer.onCompleted(); // empty subscription since we executed synchronously return Subscriptions.empty(); } } private Subscription subscribeWithThreadIsolation(final Observer<R> observer) { // mark that we are executing in a thread (even if we end up being rejected we still were a THREAD execution and not SEMAPHORE) isExecutedInThread.set(true); // final reference to the current calling thread so the child thread can access it if needed final Thread callingThread = Thread.currentThread(); final HystrixCommand<R> _this = this; try { if (!threadPool.isQueueSpaceAvailable()) { // we are at the property defined max so want to throw a RejectedExecutionException to simulate reaching the real max throw new RejectedExecutionException("Rejected command because thread-pool queueSize is at rejection threshold."); } // wrap the synchronous execute() method in a Callable and execute in the threadpool final Future<R> f = threadPool.getExecutor().submit(concurrencyStrategy.wrapCallable(new HystrixContextCallable<R>(new Callable<R>() { @Override public R call() throws Exception { try { // assign 'callingThread' to our NFExceptionThreadingUtility ThreadLocal variable so that if we blow up // anywhere along the way the exception knows who the calling thread is and can include it in the stacktrace ExceptionThreadingUtility.assignCallingThread(callingThread); // execution hook executionHook.onThreadStart(_this); // count the active thread threadPool.markThreadExecution(); try { // store the command that is being run Hystrix.startCurrentThreadExecutingCommand(getCommandKey()); // execute the command R r = executeCommand(); if (isCommandTimedOut.get()) { // state changes before termination preTerminationWork(); return null; } // give the hook an opportunity to modify it r = executionHook.onComplete(_this, r); // pass to the observer observer.onNext(r); // state changes before termination preTerminationWork(); /* now complete which releases the consumer */ observer.onCompleted(); return r; } finally { // pop this off the thread now that it's done Hystrix.endCurrentThreadExecutingCommand(); } } catch (Exception e) { // state changes before termination preTerminationWork(); observer.onError(e); throw e; } } private void preTerminationWork() { /* execution time (must occur before terminal state otherwise a race condition can occur if requested by client) */ recordTotalExecutionTime(invocationStartTime); threadPool.markThreadCompletion(); try { executionHook.onThreadComplete(_this); } catch (Exception e) { logger.warn("ExecutionHook.onThreadComplete threw an exception that will be ignored.", e); } } }))); return new Subscription() { @Override public void unsubscribe() { f.cancel(properties.executionIsolationThreadInterruptOnTimeout().get()); } }; } catch (RejectedExecutionException e) { // mark on counter metrics.markThreadPoolRejection(); // use a fallback instead (or throw exception if not implemented) observer.onNext(getFallbackOrThrowException(HystrixEventType.THREAD_POOL_REJECTED, FailureType.REJECTED_THREAD_EXECUTION, "could not be queued for execution", e)); observer.onCompleted(); return Subscriptions.empty(); } catch (Exception e) { // unknown exception logger.error(getLogMessagePrefix() + ": Unexpected exception while submitting to queue.", e); observer.onNext(getFallbackOrThrowException(HystrixEventType.THREAD_POOL_REJECTED, FailureType.REJECTED_THREAD_EXECUTION, "had unexpected exception while attempting to queue for execution.", e)); observer.onCompleted(); return Subscriptions.empty(); } } /** * Executes the command and marks success/failure on the circuit-breaker and calls <code>getFallback</code> if a failure occurs. * <p> * This does NOT use the circuit-breaker to determine if the command should be executed, use <code>execute()</code> for that. This method will ALWAYS attempt to execute the method. * * @return R */ private R executeCommand() { /** * NOTE: Be very careful about what goes in this method. It gets invoked within another thread in most circumstances. * * The modifications of booleans 'isResponseFromFallback' etc are going across thread-boundaries thus those * variables MUST be volatile otherwise they are not guaranteed to be seen by the user thread when the executing thread modifies them. */ /* capture start time for logging */ long startTime = System.currentTimeMillis(); // allow tracking how many concurrent threads are executing metrics.incrementConcurrentExecutionCount(); try { executionHook.onRunStart(this); R response = executionHook.onRunSuccess(this, run()); long duration = System.currentTimeMillis() - startTime; metrics.addCommandExecutionTime(duration); if (isCommandTimedOut.get()) { // the command timed out in the wrapping thread so we will return immediately // and not increment any of the counters below or other such logic return null; } else { // report success executionResult = executionResult.addEvents(HystrixEventType.SUCCESS); metrics.markSuccess(duration); circuitBreaker.markSuccess(); eventNotifier.markCommandExecution(getCommandKey(), properties.executionIsolationStrategy().get(), (int) duration, executionResult.events); return response; } } catch (HystrixBadRequestException e) { try { Exception decorated = executionHook.onRunError(this, e); if (decorated instanceof HystrixBadRequestException) { e = (HystrixBadRequestException) decorated; } else { logger.warn("ExecutionHook.endRunFailure returned an exception that was not an instance of HystrixBadRequestException so will be ignored.", decorated); } throw e; } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.endRunFailure", hookException); } /* * HystrixBadRequestException is treated differently and allowed to propagate without any stats tracking or fallback logic */ throw e; } catch (Exception e) { try { e = executionHook.onRunError(this, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.endRunFailure", hookException); } if (isCommandTimedOut.get()) { // http://jira/browse/API-4905 HystrixCommand: Error/Timeout Double-count if both occur // this means we have already timed out then we don't count this error stat and we just return // as this means the user-thread has already returned, we've already done fallback logic // and we've already counted the timeout stat logger.error("Error executing HystrixCommand.run() [TimedOut]. Proceeding to fallback logic ...", e); return null; } else { logger.error("Error executing HystrixCommand.run(). Proceeding to fallback logic ...", e); } // report failure metrics.markFailure(System.currentTimeMillis() - startTime); // record the exception executionResult = executionResult.setException(e); return getFallbackOrThrowException(HystrixEventType.FAILURE, FailureType.COMMAND_EXCEPTION, "failed", e); } finally { metrics.decrementConcurrentExecutionCount(); // record that we're completed isExecutionComplete.set(true); } } /** * Execute <code>getFallback()</code> within protection of a semaphore that limits number of concurrent executions. * <p> * Fallback implementations shouldn't perform anything that can be blocking, but we protect against it anyways in case someone doesn't abide by the contract. * <p> * If something in the <code>getFallback()</code> implementation is latent (such as a network call) then the semaphore will cause us to start rejecting requests rather than allowing potentially * all threads to pile up and block. * * @return K * @throws UnsupportedOperationException * if getFallback() not implemented * @throws HystrixException * if getFallback() fails (throws an Exception) or is rejected by the semaphore */ private R getFallbackWithProtection() { TryableSemaphore fallbackSemaphore = getFallbackSemaphore(); // acquire a permit if (fallbackSemaphore.tryAcquire()) { try { executionHook.onFallbackStart(this); return executionHook.onFallbackSuccess(this, getFallback()); } catch (RuntimeException e) { Exception decorated = executionHook.onFallbackError(this, e); if (decorated instanceof RuntimeException) { e = (RuntimeException) decorated; } else { logger.warn("ExecutionHook.onFallbackError returned an exception that was not an instance of RuntimeException so will be ignored.", decorated); } // re-throw to calling method throw e; } finally { fallbackSemaphore.release(); } } else { metrics.markFallbackRejection(); logger.debug("HystrixCommand Fallback Rejection."); // debug only since we're throwing the exception and someone higher will do something with it // if we couldn't acquire a permit, we "fail fast" by throwing an exception throw new HystrixRuntimeException(FailureType.REJECTED_SEMAPHORE_FALLBACK, this.getClass(), getLogMessagePrefix() + " fallback execution rejected.", null, null); } } /** * Record the duration of execution as response or exception is being returned to the caller. */ private void recordTotalExecutionTime(long startTime) { long duration = System.currentTimeMillis() - startTime; // the total execution time for the user thread including queuing, thread scheduling, run() execution metrics.addUserThreadExecutionTime(duration); /* * We record the executionTime for command execution. * * If the command is never executed (rejected, short-circuited, etc) then it will be left unset. * * For this metric we include failures and successes as we use it for per-request profiling and debugging * whereas 'metrics.addCommandExecutionTime(duration)' is used by stats across many requests. */ executionResult = executionResult.setExecutionTime((int) duration); } /** * Record that this command was executed in the HystrixRequestLog. * <p> * This can be treated as an async operation as it just adds a references to "this" in the log even if the current command is still executing. */ private void recordExecutedCommand() { if (properties.requestLogEnabled().get()) { // log this command execution regardless of what happened if (concurrencyStrategy instanceof HystrixConcurrencyStrategyDefault) { // if we're using the default we support only optionally using a request context if (HystrixRequestContext.isCurrentThreadInitialized()) { HystrixRequestLog.getCurrentRequest(concurrencyStrategy).addExecutedCommand(this); } } else { // if it's a custom strategy it must ensure the context is initialized if (HystrixRequestLog.getCurrentRequest(concurrencyStrategy) != null) { HystrixRequestLog.getCurrentRequest(concurrencyStrategy).addExecutedCommand(this); } } } } /** * Whether the 'circuit-breaker' is open meaning that <code>execute()</code> will immediately return * the <code>getFallback()</code> response and not attempt a HystrixCommand execution. * * @return boolean */ public boolean isCircuitBreakerOpen() { return circuitBreaker.isOpen(); } /** * If this command has completed execution either successfully, via fallback or failure. * * @return boolean */ public boolean isExecutionComplete() { return isExecutionComplete.get(); } /** * Whether the execution occurred in a separate thread. * <p> * This should be called only once execute()/queue()/fireOrForget() are called otherwise it will always return false. * <p> * This specifies if a thread execution actually occurred, not just if it is configured to be executed in a thread. * * @return boolean */ public boolean isExecutedInThread() { return isExecutedInThread.get(); } /** * Whether the response was returned successfully either by executing <code>run()</code> or from cache. * * @return boolean */ public boolean isSuccessfulExecution() { return executionResult.events.contains(HystrixEventType.SUCCESS); } /** * Whether the <code>run()</code> resulted in a failure (exception). * * @return boolean */ public boolean isFailedExecution() { return executionResult.events.contains(HystrixEventType.FAILURE); } /** * Get the Throwable/Exception thrown that caused the failure. * <p> * If <code>isFailedExecution() == true</code> then this would represent the Exception thrown by the <code>run()</code> method. * <p> * If <code>isFailedExecution() == false</code> then this would return null. * * @return Throwable or null */ public Throwable getFailedExecutionException() { return executionResult.exception; } /** * Whether the response received from was the result of some type of failure * and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseFromFallback() { return executionResult.events.contains(HystrixEventType.FALLBACK_SUCCESS); } /** * Whether the response received was the result of a timeout * and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseTimedOut() { return executionResult.events.contains(HystrixEventType.TIMEOUT); } /** * Whether the response received was a fallback as result of being * short-circuited (meaning <code>isCircuitBreakerOpen() == true</code>) and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseShortCircuited() { return executionResult.events.contains(HystrixEventType.SHORT_CIRCUITED); } /** * Whether the response is from cache and <code>run()</code> was not invoked. * * @return boolean */ public boolean isResponseFromCache() { return executionResult.events.contains(HystrixEventType.RESPONSE_FROM_CACHE); } /** * Whether the response received was a fallback as result of being * rejected (from thread-pool or semaphore) and <code>getFallback()</code> being called. * * @return boolean */ public boolean isResponseRejected() { return executionResult.events.contains(HystrixEventType.THREAD_POOL_REJECTED) || executionResult.events.contains(HystrixEventType.SEMAPHORE_REJECTED); } /** * List of HystrixCommandEventType enums representing events that occurred during execution. * <p> * Examples of events are SUCCESS, FAILURE, TIMEOUT, and SHORT_CIRCUITED * * @return {@code List<HystrixEventType>} */ public List<HystrixEventType> getExecutionEvents() { return executionResult.events; } /** * The execution time of this command instance in milliseconds, or -1 if not executed. * * @return int */ public int getExecutionTimeInMilliseconds() { return executionResult.executionTime; } /** * Get the TryableSemaphore this HystrixCommand should use if a fallback occurs. * * @param circuitBreaker * @param fallbackSemaphore * @return TryableSemaphore */ private TryableSemaphore getFallbackSemaphore() { if (fallbackSemaphoreOverride == null) { TryableSemaphore _s = fallbackSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup fallbackSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphore(properties.fallbackIsolationSemaphoreMaxConcurrentRequests())); // assign whatever got set (this or another thread) return fallbackSemaphorePerCircuit.get(commandKey.name()); } else { return _s; } } else { return fallbackSemaphoreOverride; } } /** * Get the TryableSemaphore this HystrixCommand should use for execution if not running in a separate thread. * * @param circuitBreaker * @param fallbackSemaphore * @return TryableSemaphore */ private TryableSemaphore getExecutionSemaphore() { if (executionSemaphoreOverride == null) { TryableSemaphore _s = executionSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup executionSemaphorePerCircuit.putIfAbsent(commandKey.name(), new TryableSemaphore(properties.executionIsolationSemaphoreMaxConcurrentRequests())); // assign whatever got set (this or another thread) return executionSemaphorePerCircuit.get(commandKey.name()); } else { return _s; } } else { return executionSemaphoreOverride; } } /** * @throws HystrixRuntimeException */ private R getFallbackOrThrowException(HystrixEventType eventType, FailureType failureType, String message) { return getFallbackOrThrowException(eventType, failureType, message, null); } /** * @throws HystrixRuntimeException */ private R getFallbackOrThrowException(HystrixEventType eventType, FailureType failureType, String message, Exception e) { try { if (properties.fallbackEnabled().get()) { /* fallback behavior is permitted so attempt */ try { // retrieve the fallback R fallback = getFallbackWithProtection(); // mark fallback on counter metrics.markFallbackSuccess(); // record the executionResult executionResult = executionResult.addEvents(eventType, HystrixEventType.FALLBACK_SUCCESS); return executionHook.onComplete(this, fallback); } catch (UnsupportedOperationException fe) { logger.debug("No fallback for HystrixCommand. ", fe); // debug only since we're throwing the exception and someone higher will do something with it // record the executionResult executionResult = executionResult.addEvents(eventType); /* executionHook for all errors */ try { e = executionHook.onError(this, failureType, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.onError", hookException); } throw new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and no fallback available.", e, fe); } catch (Exception fe) { logger.error("Error retrieving fallback for HystrixCommand. ", fe); metrics.markFallbackFailure(); // record the executionResult executionResult = executionResult.addEvents(eventType, HystrixEventType.FALLBACK_FAILURE); /* executionHook for all errors */ try { e = executionHook.onError(this, failureType, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.onError", hookException); } throw new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and failed retrieving fallback.", e, fe); } } else { /* fallback is disabled so throw HystrixRuntimeException */ logger.debug("Fallback disabled for HystrixCommand so will throw HystrixRuntimeException. ", e); // debug only since we're throwing the exception and someone higher will do something with it // record the executionResult executionResult = executionResult.addEvents(eventType); /* executionHook for all errors */ try { e = executionHook.onError(this, failureType, e); } catch (Exception hookException) { logger.warn("Error calling ExecutionHook.onError", hookException); } throw new HystrixRuntimeException(failureType, this.getClass(), getLogMessagePrefix() + " " + message + " and fallback disabled.", e, null); } } finally { // record that we're completed (to handle non-successful events we do it here as well as at the end of executeCommand isExecutionComplete.set(true); } } /* ******************************************************************************** */ /* ******************************************************************************** */ /* Result Status */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Immutable holder class for the status of command execution. * <p> * Contained within a class to simplify the sharing of it across Futures/threads that result from request caching. * <p> * This object can be referenced and "modified" by parent and child threads as well as by different instances of HystrixCommand since * 1 instance could create an ExecutionResult, cache a Future that refers to it, a 2nd instance execution then retrieves a Future * from cache and wants to append RESPONSE_FROM_CACHE to whatever the ExecutionResult was from the first command execution. * <p> * This being immutable forces and ensure thread-safety instead of using AtomicInteger/ConcurrentLinkedQueue and determining * when it's safe to mutate the object directly versus needing to deep-copy clone to a new instance. */ private static class ExecutionResult { private final List<HystrixEventType> events; private final int executionTime; private final Exception exception; private ExecutionResult(HystrixEventType... events) { this(Arrays.asList(events), -1, null); } public ExecutionResult setExecutionTime(int executionTime) { return new ExecutionResult(events, executionTime, exception); } public ExecutionResult setException(Exception e) { return new ExecutionResult(events, executionTime, e); } private ExecutionResult(List<HystrixEventType> events, int executionTime, Exception e) { // we are safe assigning the List reference instead of deep-copying // because we control the original list in 'newEvent' this.events = events; this.executionTime = executionTime; this.exception = e; } // we can return a static version since it's immutable private static ExecutionResult EMPTY = new ExecutionResult(new HystrixEventType[0]); /** * Creates a new ExecutionResult by adding the defined 'events' to the ones on the current instance. * * @param events * @return */ public ExecutionResult addEvents(HystrixEventType... events) { ArrayList<HystrixEventType> newEvents = new ArrayList<HystrixEventType>(); newEvents.addAll(this.events); for (HystrixEventType e : events) { newEvents.add(e); } return new ExecutionResult(Collections.unmodifiableList(newEvents), executionTime, exception); } } /* ******************************************************************************** */ /* ******************************************************************************** */ /* RequestCache */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Key to be used for request caching. * <p> * By default this returns null which means "do not cache". * <p> * To enable caching override this method and return a string key uniquely representing the state of a command instance. * <p> * If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache. * * @return cacheKey */ protected String getCacheKey() { return null; } private boolean isRequestCachingEnabled() { return properties.requestCacheEnabled().get(); } /* ******************************************************************************** */ /* ******************************************************************************** */ /* TryableSemaphore */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Semaphore that only supports tryAcquire and never blocks and that supports a dynamic permit count. * <p> * Using AtomicInteger increment/decrement instead of java.util.concurrent.Semaphore since we don't need blocking and need a custom implementation to get the dynamic permit count and since * AtomicInteger achieves the same behavior and performance without the more complex implementation of the actual Semaphore class using AbstractQueueSynchronizer. */ private static class TryableSemaphore { private final HystrixProperty<Integer> numberOfPermits; private final AtomicInteger count = new AtomicInteger(0); public TryableSemaphore(HystrixProperty<Integer> numberOfPermits) { this.numberOfPermits = numberOfPermits; } /** * Use like this: * <p> * * <pre> * if (s.tryAcquire()) { * try { * // do work that is protected by 's' * } finally { * s.release(); * } * } * </pre> * * @return boolean */ public boolean tryAcquire() { int currentCount = count.incrementAndGet(); if (currentCount > numberOfPermits.get()) { count.decrementAndGet(); return false; } else { return true; } } /** * ONLY call release if tryAcquire returned true. * <p> * * <pre> * if (s.tryAcquire()) { * try { * // do work that is protected by 's' * } finally { * s.release(); * } * } * </pre> */ public void release() { count.decrementAndGet(); } public int getNumberOfPermitsUsed() { return count.get(); } } private String getLogMessagePrefix() { return getCommandKey().name(); } /** * Fluent interface for arguments to the {@link HystrixCommand} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName")) .andCommandKey(HystrixCommandKey.Factory.asKey("CommandName")) .andEventNotifier(notifier); * } </pre> */ @NotThreadSafe public static class Setter { private final HystrixCommandGroupKey groupKey; private HystrixCommandKey commandKey; private HystrixThreadPoolKey threadPoolKey; private HystrixCommandProperties.Setter commandPropertiesDefaults; private HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults; /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ private Setter(HystrixCommandGroupKey groupKey) { this.groupKey = groupKey; } /** * Setter factory method with required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ public static Setter withGroupKey(HystrixCommandGroupKey groupKey) { return new Setter(groupKey); } /** * @param commandKey * {@link HystrixCommandKey} used to identify a {@link HystrixCommand} instance for statistics, circuit-breaker, properties, etc. * <p> * By default this will be derived from the instance class name. * <p> * NOTE: Every unique {@link HystrixCommandKey} will result in new instances of {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and {@link HystrixCommandProperties}. * Thus, * the number of variants should be kept to a finite and reasonable number to avoid high-memory usage or memory leacks. * <p> * Hundreds of keys is fine, tens of thousands is probably not. * @return Setter for fluent interface via method chaining */ public Setter andCommandKey(HystrixCommandKey commandKey) { this.commandKey = commandKey; return this; } /** * @param threadPoolKey * {@link HystrixThreadPoolKey} used to define which thread-pool this command should run in (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). * <p> * By default this is derived from the {@link HystrixCommandGroupKey} but if injected this allows multiple commands to have the same {@link HystrixCommandGroupKey} but different * thread-pools. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolKey(HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; return this; } /** * Optional * * @param commandPropertiesDefaults * {@link HystrixCommandProperties.Setter} with property overrides for this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = commandPropertiesDefaults; return this; } /** * Optional * * @param threadPoolPropertiesDefaults * {@link HystrixThreadPoolProperties.Setter} with property overrides for the {@link HystrixThreadPool} used by this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults; return this; } } public static class UnitTest { @Before public void prepareForTest() { /* we must call this to simulate a new request lifecycle running and clearing caches */ HystrixRequestContext.initializeContext(); } @After public void cleanup() { // instead of storing the reference from initialize we'll just get the current state and shutdown if (HystrixRequestContext.getContextForCurrentThread() != null) { // it could have been set NULL by the test HystrixRequestContext.getContextForCurrentThread().shutdown(); } // force properties to be clean as well ConfigurationManager.getConfigInstance().clear(); } /** * Test a successful command execution. */ @Test public void testExecutionSuccess() { try { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.execute()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(null, command.getFailedExecutionException()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test that a command can not be executed multiple times. */ @Test public void testExecutionMultipleTimes() { SuccessfulTestCommand command = new SuccessfulTestCommand(); assertFalse(command.isExecutionComplete()); // first should succeed assertEquals(true, command.execute()); assertTrue(command.isExecutionComplete()); assertTrue(command.isExecutedInThread()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); try { // second should fail command.execute(); fail("we should not allow this ... it breaks the state of request logs"); } catch (Exception e) { e.printStackTrace(); // we want to get here } try { // queue should also fail command.queue(); fail("we should not allow this ... it breaks the state of request logs"); } catch (Exception e) { e.printStackTrace(); // we want to get here } } /** * Test a command execution that throws an HystrixException and didn't implement getFallback. */ @Test public void testExecutionKnownFailureWithNoFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { command.execute(); fail("we shouldn't get here"); } catch (HystrixRuntimeException e) { e.printStackTrace(); assertNotNull(e.getFallbackException()); assertNotNull(e.getImplementingClass()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); } catch (Exception e) { e.printStackTrace(); fail("We should always get an HystrixRuntimeException when an error occurs."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution that throws an unknown exception (not HystrixException) and didn't implement getFallback. */ @Test public void testExecutionUnknownFailureWithNoFallback() { TestHystrixCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(); try { command.execute(); fail("we shouldn't get here"); } catch (HystrixRuntimeException e) { e.printStackTrace(); assertNotNull(e.getFallbackException()); assertNotNull(e.getImplementingClass()); } catch (Exception e) { e.printStackTrace(); fail("We should always get an HystrixRuntimeException when an error occurs."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution that fails but has a fallback. */ @Test public void testExecutionFailureWithFallback() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); try { assertEquals(false, command.execute()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals("we failed with a simulated issue", command.getFailedExecutionException().getMessage()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution that fails, has getFallback implemented but that fails as well. */ @Test public void testExecutionFailureWithFallbackFailure() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(); try { command.execute(); fail("we shouldn't get here"); } catch (HystrixRuntimeException e) { System.out.println("------------------------------------------------"); e.printStackTrace(); System.out.println("------------------------------------------------"); assertNotNull(e.getFallbackException()); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a successful command execution (asynchronously). */ @Test public void testQueueSuccess() { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); try { Future<Boolean> future = command.queue(); assertEquals(true, future.get()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that throws an HystrixException and didn't implement getFallback. */ @Test public void testQueueKnownFailureWithNoFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertNotNull(de.getImplementingClass()); } else { fail("the cause should be HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that throws an unknown exception (not HystrixException) and didn't implement getFallback. */ @Test public void testQueueUnknownFailureWithNoFallback() { TestHystrixCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertNotNull(de.getImplementingClass()); } else { fail("the cause should be HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that fails but has a fallback. */ @Test public void testQueueFailureWithFallback() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); try { Future<Boolean> future = command.queue(); assertEquals(false, future.get()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution (asynchronously) that fails, has getFallback implemented but that fails as well. */ @Test public void testQueueFailureWithFallbackFailure() { TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { if (e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); e.printStackTrace(); assertNotNull(de.getFallbackException()); } else { fail("the cause should be HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a successful command execution. */ @Test public void testObserveSuccess() { try { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.observe().toBlockingObservable().single()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(null, command.getFailedExecutionException()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isSuccessfulExecution()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test a successful command execution. */ @Test public void testObserveOnScheduler() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder()) { @Override protected Boolean run() { commandThread.set(Thread.currentThread()); return true; } }; final CountDownLatch latch = new CountDownLatch(1); Scheduler customScheduler = new Scheduler() { private final Scheduler self = this; @Override public <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action) { return schedule(state, action, 0, TimeUnit.MILLISECONDS); } @Override public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action, long delayTime, TimeUnit unit) { new Thread("RxScheduledThread") { @Override public void run() { action.call(self, state); } }.start(); // not testing unsubscribe behavior return Subscriptions.empty(); } }; command.toObservable(customScheduler).subscribe(new Observer<Boolean>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Exception e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Boolean args) { subscribeThread.set(Thread.currentThread()); } }); if (!latch.await(2000, TimeUnit.MILLISECONDS)) { fail("timed out"); } assertNotNull(commandThread.get()); assertNotNull(subscribeThread.get()); System.out.println("Command Thread: " + commandThread.get()); System.out.println("Subscribe Thread: " + subscribeThread.get()); assertTrue(commandThread.get().getName().startsWith("hystrix-")); assertTrue(subscribeThread.get().getName().equals("RxScheduledThread")); } /** * Test a successful command execution. */ @Test public void testObserveOnComputationSchedulerByDefaultForThreadIsolation() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder()) { @Override protected Boolean run() { commandThread.set(Thread.currentThread()); return true; } }; final CountDownLatch latch = new CountDownLatch(1); command.toObservable().subscribe(new Observer<Boolean>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Exception e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Boolean args) { subscribeThread.set(Thread.currentThread()); } }); if (!latch.await(2000, TimeUnit.MILLISECONDS)) { fail("timed out"); } assertNotNull(commandThread.get()); assertNotNull(subscribeThread.get()); System.out.println("Command Thread: " + commandThread.get()); System.out.println("Subscribe Thread: " + subscribeThread.get()); assertTrue(commandThread.get().getName().startsWith("hystrix-")); assertTrue(subscribeThread.get().getName().startsWith("RxComputationThreadPool")); } /** * Test a successful command execution. */ @Test public void testObserveOnImmediateSchedulerByDefaultForSemaphoreIsolation() throws Exception { final AtomicReference<Thread> commandThread = new AtomicReference<Thread>(); final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); TestHystrixCommand<Boolean> command = new TestHystrixCommand<Boolean>(TestHystrixCommand.testPropsBuilder() .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))) { @Override protected Boolean run() { commandThread.set(Thread.currentThread()); return true; } }; final CountDownLatch latch = new CountDownLatch(1); command.toObservable().subscribe(new Observer<Boolean>() { @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Exception e) { latch.countDown(); e.printStackTrace(); } @Override public void onNext(Boolean args) { subscribeThread.set(Thread.currentThread()); } }); if (!latch.await(2000, TimeUnit.MILLISECONDS)) { fail("timed out"); } assertNotNull(commandThread.get()); assertNotNull(subscribeThread.get()); System.out.println("Command Thread: " + commandThread.get()); System.out.println("Subscribe Thread: " + subscribeThread.get()); String mainThreadName = Thread.currentThread().getName(); // semaphore should be on the calling thread assertTrue(commandThread.get().getName().equals(mainThreadName)); assertTrue(subscribeThread.get().getName().equals(mainThreadName)); } /** * Test that the circuit-breaker will 'trip' and prevent command execution on subsequent calls. */ @Test public void testCircuitBreakerTripsAfterFailures() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); /* fail 3 times and then it should trip the circuit and stop executing */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt1.execute(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt2.execute(); assertTrue(attempt2.isResponseFromFallback()); assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt3.execute(); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should now be 'open' and prevent further executions assertTrue(attempt3.isCircuitBreakerOpen()); // attempt 4 KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt4.execute(); assertTrue(attempt4.isResponseFromFallback()); // this should now be true as the response will be short-circuited assertTrue(attempt4.isResponseShortCircuited()); // this should remain open assertTrue(attempt4.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker will 'trip' and prevent command execution on subsequent calls. */ @Test public void testCircuitBreakerTripsAfterFailuresViaQueue() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { /* fail 3 times and then it should trip the circuit and stop executing */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt1.queue().get(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt2.queue().get(); assertTrue(attempt2.isResponseFromFallback()); assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt3.queue().get(); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should now be 'open' and prevent further executions assertTrue(attempt3.isCircuitBreakerOpen()); // attempt 4 KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt4.queue().get(); assertTrue(attempt4.isResponseFromFallback()); // this should now be true as the response will be short-circuited assertTrue(attempt4.isResponseShortCircuited()); // this should remain open assertTrue(attempt4.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } catch (Exception e) { e.printStackTrace(); fail("We should have received fallbacks."); } } /** * Test that the circuit-breaker is shared across HystrixCommand objects with the same CommandKey. * <p> * This will test HystrixCommand objects with a single circuit-breaker (as if each injected with same CommandKey) * <p> * Multiple HystrixCommand objects with the same dependency use the same circuit-breaker. */ @Test public void testCircuitBreakerAcrossMultipleCommandsButSameCircuitBreaker() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); /* fail 3 times and then it should trip the circuit and stop executing */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt1.execute(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 with a different command, same circuit breaker KnownFailureTestCommandWithoutFallback attempt2 = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { attempt2.execute(); } catch (Exception e) { // ignore ... this doesn't have a fallback so will throw an exception } assertTrue(attempt2.isFailedExecution()); assertFalse(attempt2.isResponseFromFallback()); // false because no fallback assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 of the Hystrix, 2nd for this particular HystrixCommand KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt3.execute(); assertTrue(attempt2.isFailedExecution()); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should now be 'open' and prevent further executions // after having 3 failures on the Hystrix that these 2 different HystrixCommand objects are for assertTrue(attempt3.isCircuitBreakerOpen()); // attempt 4 KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker); attempt4.execute(); assertTrue(attempt4.isResponseFromFallback()); // this should now be true as the response will be short-circuited assertTrue(attempt4.isResponseShortCircuited()); // this should remain open assertTrue(attempt4.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker is different between HystrixCommand objects with a different Hystrix. */ @Test public void testCircuitBreakerAcrossMultipleCommandsAndDifferentDependency() { TestCircuitBreaker circuitBreaker_one = new TestCircuitBreaker(); TestCircuitBreaker circuitBreaker_two = new TestCircuitBreaker(); /* fail 3 times, twice on one Hystrix, once on a different Hystrix ... circuit-breaker should NOT open */ // failure 1 KnownFailureTestCommandWithFallback attempt1 = new KnownFailureTestCommandWithFallback(circuitBreaker_one); attempt1.execute(); assertTrue(attempt1.isResponseFromFallback()); assertFalse(attempt1.isCircuitBreakerOpen()); assertFalse(attempt1.isResponseShortCircuited()); // failure 2 with a different HystrixCommand implementation and different Hystrix KnownFailureTestCommandWithFallback attempt2 = new KnownFailureTestCommandWithFallback(circuitBreaker_two); attempt2.execute(); assertTrue(attempt2.isResponseFromFallback()); assertFalse(attempt2.isCircuitBreakerOpen()); assertFalse(attempt2.isResponseShortCircuited()); // failure 3 but only 2nd of the Hystrix.ONE KnownFailureTestCommandWithFallback attempt3 = new KnownFailureTestCommandWithFallback(circuitBreaker_one); attempt3.execute(); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // it should remain 'closed' since we have only had 2 failures on Hystrix.ONE assertFalse(attempt3.isCircuitBreakerOpen()); // this one should also remain closed as it only had 1 failure for Hystrix.TWO assertFalse(attempt2.isCircuitBreakerOpen()); // attempt 4 (3rd attempt for Hystrix.ONE) KnownFailureTestCommandWithFallback attempt4 = new KnownFailureTestCommandWithFallback(circuitBreaker_one); attempt4.execute(); // this should NOW flip to true as this is the 3rd failure for Hystrix.ONE assertTrue(attempt3.isCircuitBreakerOpen()); assertTrue(attempt3.isResponseFromFallback()); assertFalse(attempt3.isResponseShortCircuited()); // Hystrix.TWO should still remain closed assertFalse(attempt2.isCircuitBreakerOpen()); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(3, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(3, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker_one.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker_one.metrics.getHealthCounts().getErrorPercentage()); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker_two.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker_two.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker being disabled doesn't wreak havoc. */ @Test public void testExecutionSuccessWithCircuitBreakerDisabled() { TestHystrixCommand<Boolean> command = new TestCommandWithoutCircuitBreaker(); try { assertEquals(true, command.execute()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } // we'll still get metrics ... just not the circuit breaker opening/closing assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution timeout where the command didn't implement getFallback. */ @Test public void testExecutionTimeoutWithNoFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.execute(); fail("we shouldn't get here"); } catch (Exception e) { // e.printStackTrace(); if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be HystrixRuntimeException"); } } // the time should be 50+ since we timeout at 50ms assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50); assertTrue(command.isResponseTimedOut()); assertFalse(command.isResponseFromFallback()); assertFalse(command.isResponseRejected()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution timeout where the command implemented getFallback. */ @Test public void testExecutionTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(false, command.execute()); // the time should be 50+ since we timeout at 50ms assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50); assertTrue(command.isResponseTimedOut()); assertTrue(command.isResponseFromFallback()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a command execution timeout where the command implemented getFallback but it fails. */ @Test public void testExecutionTimeoutFallbackFailure() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_FAILURE); try { command.execute(); fail("we shouldn't get here"); } catch (Exception e) { if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be HystrixRuntimeException"); } } // the time should be 50+ since we timeout at 50ms assertTrue("Execution Time is: " + command.getExecutionTimeInMilliseconds(), command.getExecutionTimeInMilliseconds() >= 50); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker counts a command execution timeout as a 'timeout' and not just failure. */ @Test public void testCircuitBreakerOnExecutionTimeout() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); command.execute(); assertTrue(command.isResponseFromFallback()); assertFalse(command.isCircuitBreakerOpen()); assertFalse(command.isResponseShortCircuited()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the command finishing AFTER a timeout (because thread continues in background) does not register a SUCCESS */ @Test public void testCountersOnExecutionTimeout() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { command.execute(); /* wait long enough for the command to have finished */ Thread.sleep(200); /* response should still be the same as 'testCircuitBreakerOnExecutionTimeout' */ assertTrue(command.isResponseFromFallback()); assertFalse(command.isCircuitBreakerOpen()); assertFalse(command.isResponseShortCircuited()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertFalse(command.isSuccessfulExecution()); /* failure and timeout count should be the same as 'testCircuitBreakerOnExecutionTimeout' */ assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); /* we should NOT have a 'success' counter */ assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command didn't implement getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testQueuedExecutionTimeoutWithNoFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e instanceof ExecutionException && e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testQueuedExecutionTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(false, command.queue().get()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback but it fails. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testQueuedExecutionTimeoutFallbackFailure() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_FAILURE); try { command.queue().get(); fail("we shouldn't get here"); } catch (Exception e) { if (e instanceof ExecutionException && e.getCause() instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e.getCause(); assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command didn't implement getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testObservedExecutionTimeoutWithNoFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.observe().toBlockingObservable().single(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isResponseTimedOut()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testObservedExecutionTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { assertEquals(false, command.observe().toBlockingObservable().single()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test a queued command execution timeout where the command implemented getFallback but it fails. * <p> * We specifically want to protect against developers queuing commands and using queue().get() without a timeout (such as queue().get(3000, TimeUnit.Milliseconds)) and ending up blocking * indefinitely by skipping the timeout protection of the execute() command. */ @Test public void testObservedExecutionTimeoutFallbackFailure() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_FAILURE); try { command.observe().toBlockingObservable().single(); fail("we shouldn't get here"); } catch (Exception e) { if (e instanceof HystrixRuntimeException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof TimeoutException); } else { fail("the exception should be ExecutionException with cause as HystrixRuntimeException"); } } assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, command.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that the circuit-breaker counts a command execution timeout as a 'timeout' and not just failure. */ @Test public void testShortCircuitFallbackCounter() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true); try { new KnownFailureTestCommandWithFallback(circuitBreaker).execute(); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); KnownFailureTestCommandWithFallback command = new KnownFailureTestCommandWithFallback(circuitBreaker); command.execute(); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); // will be -1 because it never attempted execution assertTrue(command.getExecutionTimeInMilliseconds() == -1); assertTrue(command.isResponseShortCircuited()); assertFalse(command.isResponseTimedOut()); // because it was short-circuited to a fallback we don't count an error assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test when a command fails to get queued up in the threadpool where the command didn't implement getFallback. * <p> * We specifically want to protect against developers getting random thread exceptions and instead just correctly receiving HystrixRuntimeException when no fallback exists. */ @Test public void testRejectedThreadWithNoFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); // fill up the queue pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); Future<Boolean> f = null; TestCommandRejection command = null; try { f = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED).queue(); command = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED); command.queue(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); // will be -1 because it never attempted execution assertTrue(command.getExecutionTimeInMilliseconds() == -1); assertTrue(command.isResponseRejected()); assertFalse(command.isResponseShortCircuited()); assertFalse(command.isResponseTimedOut()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof RejectedExecutionException); } else { fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException"); } } try { f.get(); } catch (Exception e) { e.printStackTrace(); fail("The first one should succeed."); } assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(50, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test when a command fails to get queued up in the threadpool where the command implemented getFallback. * <p> * We specifically want to protect against developers getting random thread exceptions and instead just correctly receives a fallback. */ @Test public void testRejectedThreadWithFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); // fill up the queue pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { TestCommandRejection command1 = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); command1.queue(); TestCommandRejection command2 = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); assertEquals(false, command2.queue().get()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertFalse(command1.isResponseRejected()); assertFalse(command1.isResponseFromFallback()); assertTrue(command2.isResponseRejected()); assertTrue(command2.isResponseFromFallback()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test when a command fails to get queued up in the threadpool where the command implemented getFallback but it fails. * <p> * We specifically want to protect against developers getting random thread exceptions and instead just correctly receives an HystrixRuntimeException. */ @Test public void testRejectedThreadWithFallbackFailure() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); // fill up the queue pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_FAILURE).queue(); assertEquals(false, new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_FAILURE).queue().get()); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertFalse(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof RejectedExecutionException); } else { fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException"); } } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that we can reject a thread using isQueueSpaceAvailable() instead of just when the pool rejects. * <p> * For example, we have queue size set to 100 but want to reject when we hit 10. * <p> * This allows us to use FastProperties to control our rejection point whereas we can't resize a queue after it's created. */ @Test public void testRejectedThreadUsingQueueSize() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(10, 1); // put 1 item in the queue // the thread pool won't pick it up because we're bypassing the pool and adding to the queue directly so this will keep the queue full pool.queue.add(new Runnable() { @Override public void run() { System.out.println("**** queue filler1 ****"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }); TestCommandRejection command = null; try { // this should fail as we already have 1 in the queue command = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_NOT_IMPLEMENTED); command.queue(); fail("we shouldn't get here"); } catch (Exception e) { e.printStackTrace(); // will be -1 because it never attempted execution assertTrue(command.getExecutionTimeInMilliseconds() == -1); assertTrue(command.isResponseRejected()); assertFalse(command.isResponseShortCircuited()); assertFalse(command.isResponseTimedOut()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); if (e instanceof HystrixRuntimeException && e.getCause() instanceof RejectedExecutionException) { HystrixRuntimeException de = (HystrixRuntimeException) e; assertNotNull(de.getFallbackException()); assertTrue(de.getFallbackException() instanceof UnsupportedOperationException); assertNotNull(de.getImplementingClass()); assertNotNull(de.getCause()); assertTrue(de.getCause() instanceof RejectedExecutionException); } else { fail("the exception should be HystrixRuntimeException with cause as RejectedExecutionException"); } } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(1, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testTimedOutCommandDoesNotExecute() { SingleThreadedPool pool = new SingleThreadedPool(5); TestCircuitBreaker s1 = new TestCircuitBreaker(); TestCircuitBreaker s2 = new TestCircuitBreaker(); // execution will take 100ms, thread pool has a 600ms timeout CommandWithCustomThreadPool c1 = new CommandWithCustomThreadPool(s1, pool, 100, HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(600)); // execution will take 200ms, thread pool has a 20ms timeout CommandWithCustomThreadPool c2 = new CommandWithCustomThreadPool(s2, pool, 200, HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(20)); // queue up c1 first Future<Boolean> c1f = c1.queue(); // now queue up c2 and wait on it boolean receivedException = false; try { c2.queue().get(); } catch (Exception e) { // we expect to get an exception here receivedException = true; } if (!receivedException) { fail("We expect to receive an exception for c2 as it's supposed to timeout."); } // c1 will complete after 100ms try { c1f.get(); } catch (Exception e1) { e1.printStackTrace(); fail("we should not have failed while getting c1"); } assertTrue("c1 is expected to executed but didn't", c1.didExecute); // c2 will timeout after 20 ms ... we'll wait longer than the 200ms time to make sure // the thread doesn't keep running in the background and execute try { Thread.sleep(400); } catch (Exception e) { throw new RuntimeException("Failed to sleep"); } assertFalse("c2 is not expected to execute, but did", c2.didExecute); assertEquals(1, s1.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, s1.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, s1.metrics.getHealthCounts().getErrorPercentage()); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, s2.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, s2.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, s2.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, s2.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testFallbackSemaphore() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // single thread should work try { boolean result = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 200).queue().get(); assertTrue(result); } catch (Exception e) { // we shouldn't fail on this one throw new RuntimeException(e); } // 2 threads, the second should be rejected by the fallback semaphore boolean exceptionReceived = false; Future<Boolean> result = null; try { result = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 400).queue(); // make sure that thread gets a chance to run before queuing the next one Thread.sleep(50); Future<Boolean> result2 = new TestSemaphoreCommandWithSlowFallback(circuitBreaker, 1, 200).queue(); result2.get(); } catch (Exception e) { e.printStackTrace(); exceptionReceived = true; } try { assertTrue(result.get()); } catch (Exception e) { throw new RuntimeException(e); } if (!exceptionReceived) { fail("We expected an exception on the 2nd get"); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); // TestSemaphoreCommandWithSlowFallback always fails so all 3 should show failure assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); // the 1st thread executes single-threaded and gets a fallback, the next 2 are concurrent so only 1 of them is permitted by the fallback semaphore so 1 is rejected assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); // whenever a fallback_rejection occurs it is also a fallback_failure assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); // we should not have rejected any via the "execution semaphore" but instead via the "fallback semaphore" assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testExecutionSemaphoreWithQueue() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // single thread should work try { boolean result = new TestSemaphoreCommand(circuitBreaker, 1, 200).queue().get(); assertTrue(result); } catch (Exception e) { // we shouldn't fail on this one throw new RuntimeException(e); } final AtomicBoolean exceptionReceived = new AtomicBoolean(); final TryableSemaphore semaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(1)); Runnable r = new HystrixContextRunnable(new Runnable() { @Override public void run() { try { new TestSemaphoreCommand(circuitBreaker, semaphore, 200).queue().get(); } catch (Exception e) { e.printStackTrace(); exceptionReceived.set(true); } } }); // 2 threads, the second should be rejected by the semaphore Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } if (!exceptionReceived.get()) { fail("We expected an exception on the 2nd get"); } assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); // we don't have a fallback so threw an exception when rejected assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); // not a failure as the command never executed so can't fail assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); // no fallback failure as there isn't a fallback implemented assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); // we should have rejected via semaphore assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testExecutionSemaphoreWithExecution() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // single thread should work try { TestSemaphoreCommand command = new TestSemaphoreCommand(circuitBreaker, 1, 200); boolean result = command.execute(); assertFalse(command.isExecutedInThread()); assertTrue(result); } catch (Exception e) { // we shouldn't fail on this one throw new RuntimeException(e); } final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2); final AtomicBoolean exceptionReceived = new AtomicBoolean(); final TryableSemaphore semaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(1)); Runnable r = new HystrixContextRunnable(new Runnable() { @Override public void run() { try { results.add(new TestSemaphoreCommand(circuitBreaker, semaphore, 200).execute()); } catch (Exception e) { e.printStackTrace(); exceptionReceived.set(true); } } }); // 2 threads, the second should be rejected by the semaphore Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } if (!exceptionReceived.get()) { fail("We expected an exception on the 2nd get"); } // only 1 value is expected as the other should have thrown an exception assertEquals(1, results.size()); // should contain only a true result assertTrue(results.contains(Boolean.TRUE)); assertFalse(results.contains(Boolean.FALSE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); // no failure ... we throw an exception because of rejection but the command does not fail execution assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); // there is no fallback implemented so no failure can occur on it assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); // we rejected via semaphore assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testRejectedExecutionSemaphoreWithFallback() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); final ArrayBlockingQueue<Boolean> results = new ArrayBlockingQueue<Boolean>(2); final AtomicBoolean exceptionReceived = new AtomicBoolean(); Runnable r = new HystrixContextRunnable(new Runnable() { @Override public void run() { try { results.add(new TestSemaphoreCommandWithFallback(circuitBreaker, 1, 200, false).execute()); } catch (Exception e) { e.printStackTrace(); exceptionReceived.set(true); } } }); // 2 threads, the second should be rejected by the semaphore and return fallback Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } if (exceptionReceived.get()) { fail("We should have received a fallback response"); } // both threads should have returned values assertEquals(2, results.size()); // should contain both a true and false result assertTrue(results.contains(Boolean.TRUE)); assertTrue(results.contains(Boolean.FALSE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); // the rest should not be involved in this test assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); System.out.println("**** DONE"); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Tests that semaphores are counted separately for commands with unique keys */ @Test public void testSemaphorePermitsInUse() { final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // this semaphore will be shared across multiple command instances final TryableSemaphore sharedSemaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(3)); // used to wait until all commands have started final CountDownLatch startLatch = new CountDownLatch(sharedSemaphore.numberOfPermits.get() + 1); // used to signal that all command can finish final CountDownLatch sharedLatch = new CountDownLatch(1); final Runnable sharedSemaphoreRunnable = new HystrixContextRunnable(new Runnable() { public void run() { try { new LatchedSemaphoreCommand(circuitBreaker, sharedSemaphore, startLatch, sharedLatch).execute(); } catch (Exception e) { e.printStackTrace(); } } }); // creates group of threads each using command sharing a single semaphore // I create extra threads and commands so that I can verify that some of them fail to obtain a semaphore final int sharedThreadCount = sharedSemaphore.numberOfPermits.get() * 2; final Thread[] sharedSemaphoreThreads = new Thread[sharedThreadCount]; for (int i = 0; i < sharedThreadCount; i++) { sharedSemaphoreThreads[i] = new Thread(sharedSemaphoreRunnable); } // creates thread using isolated semaphore final TryableSemaphore isolatedSemaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(1)); final CountDownLatch isolatedLatch = new CountDownLatch(1); // tracks failures to obtain semaphores final AtomicInteger failureCount = new AtomicInteger(); final Thread isolatedThread = new Thread(new HystrixContextRunnable(new Runnable() { public void run() { try { new LatchedSemaphoreCommand(circuitBreaker, isolatedSemaphore, startLatch, isolatedLatch).execute(); } catch (Exception e) { e.printStackTrace(); failureCount.incrementAndGet(); } } })); // verifies no permits in use before starting threads assertEquals("wrong number of permits for shared semaphore", 0, sharedSemaphore.getNumberOfPermitsUsed()); assertEquals("wrong number of permits for isolated semaphore", 0, isolatedSemaphore.getNumberOfPermitsUsed()); for (int i = 0; i < sharedThreadCount; i++) { sharedSemaphoreThreads[i].start(); } isolatedThread.start(); // waits until all commands have started try { startLatch.await(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } // verifies that all semaphores are in use assertEquals("wrong number of permits for shared semaphore", sharedSemaphore.numberOfPermits.get().longValue(), sharedSemaphore.getNumberOfPermitsUsed()); assertEquals("wrong number of permits for isolated semaphore", isolatedSemaphore.numberOfPermits.get().longValue(), isolatedSemaphore.getNumberOfPermitsUsed()); // signals commands to finish sharedLatch.countDown(); isolatedLatch.countDown(); try { for (int i = 0; i < sharedThreadCount; i++) { sharedSemaphoreThreads[i].join(); } isolatedThread.join(); } catch (Exception e) { e.printStackTrace(); fail("failed waiting on threads"); } // verifies no permits in use after finishing threads assertEquals("wrong number of permits for shared semaphore", 0, sharedSemaphore.getNumberOfPermitsUsed()); assertEquals("wrong number of permits for isolated semaphore", 0, isolatedSemaphore.getNumberOfPermitsUsed()); // verifies that some executions failed final int expectedFailures = sharedSemaphore.getNumberOfPermitsUsed(); assertEquals("failures expected but did not happen", expectedFailures, failureCount.get()); } /** * Test that HystrixOwner can be passed in dynamically. */ @Test public void testDynamicOwner() { try { TestHystrixCommand<Boolean> command = new DynamicOwnerTestCommand(CommandGroupForUnitTest.OWNER_ONE); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.execute()); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test a successful command execution. */ @Test public void testDynamicOwnerFails() { try { TestHystrixCommand<Boolean> command = new DynamicOwnerTestCommand(null); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, command.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(true, command.execute()); fail("we should have thrown an exception as we need an owner"); } catch (Exception e) { // success if we get here } } /** * Test that HystrixCommandKey can be passed in dynamically. */ @Test public void testDynamicKey() { try { DynamicOwnerAndKeyTestCommand command1 = new DynamicOwnerAndKeyTestCommand(CommandGroupForUnitTest.OWNER_ONE, CommandKeyForUnitTest.KEY_ONE); assertEquals(true, command1.execute()); DynamicOwnerAndKeyTestCommand command2 = new DynamicOwnerAndKeyTestCommand(CommandGroupForUnitTest.OWNER_ONE, CommandKeyForUnitTest.KEY_TWO); assertEquals(true, command2.execute()); // 2 different circuit breakers should be created assertNotSame(command1.getCircuitBreaker(), command2.getCircuitBreaker()); } catch (Exception e) { e.printStackTrace(); fail("We received an exception."); } } /** * Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future */ @Test public void testRequestCache1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); try { assertEquals("A", f1.get()); assertEquals("A", f2.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // the second one should not have executed as it should have received the cached value instead assertFalse(command2.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command1.getExecutionTimeInMilliseconds() > -1); assertFalse(command1.isResponseFromCache()); // the execution log for command2 should show it came from cache assertEquals(2, command2.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command2.getExecutionTimeInMilliseconds() == -1); assertTrue(command2.isResponseFromCache()); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching doesn't prevent different ones from executing */ @Test public void testRequestCache2() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "B"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command2.getExecutionTimeInMilliseconds() > -1); assertFalse(command2.isResponseFromCache()); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testRequestCache3() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "B"); SuccessfulCacheableCommand command3 = new SuccessfulCacheableCommand(circuitBreaker, true, "A"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // but the 3rd should come from cache assertFalse(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show it came from cache assertEquals(2, command3.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command3.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command3.getExecutionTimeInMilliseconds() == -1); assertTrue(command3.isResponseFromCache()); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching of commands so that a 2nd duplicate call doesn't execute but returns the previous Future */ @Test public void testRequestCacheWithSlowExecution() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SlowCacheableCommand command1 = new SlowCacheableCommand(circuitBreaker, "A", 200); SlowCacheableCommand command2 = new SlowCacheableCommand(circuitBreaker, "A", 100); SlowCacheableCommand command3 = new SlowCacheableCommand(circuitBreaker, "A", 100); SlowCacheableCommand command4 = new SlowCacheableCommand(circuitBreaker, "A", 100); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); Future<String> f4 = command4.queue(); try { assertEquals("A", f2.get()); assertEquals("A", f3.get()); assertEquals("A", f4.get()); assertEquals("A", f1.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // the second one should not have executed as it should have received the cached value instead assertFalse(command2.executed); assertFalse(command3.executed); assertFalse(command4.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command1.getExecutionTimeInMilliseconds() > -1); assertFalse(command1.isResponseFromCache()); // the execution log for command2 should show it came from cache assertEquals(2, command2.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command2.getExecutionTimeInMilliseconds() == -1); assertTrue(command2.isResponseFromCache()); assertTrue(command3.isResponseFromCache()); assertTrue(command3.getExecutionTimeInMilliseconds() == -1); assertTrue(command4.isResponseFromCache()); assertTrue(command4.getExecutionTimeInMilliseconds() == -1); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); System.out.println("HystrixRequestLog: " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testNoRequestCache3() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command1 = new SuccessfulCacheableCommand(circuitBreaker, false, "A"); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, false, "B"); SuccessfulCacheableCommand command3 = new SuccessfulCacheableCommand(circuitBreaker, false, "A"); assertTrue(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // this should also execute since we disabled the cache assertTrue(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show a SUCCESS assertEquals(1, command3.getExecutionEvents().size()); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testRequestCacheViaQueueSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); assertFalse(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // but the 3rd should come from cache assertFalse(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show it comes from cache assertEquals(2, command3.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(command3.isResponseFromCache()); assertTrue(command3.getExecutionTimeInMilliseconds() == -1); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testNoRequestCacheViaQueueSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); assertFalse(command1.isCommandRunningInThread()); Future<String> f1 = command1.queue(); Future<String> f2 = command2.queue(); Future<String> f3 = command3.queue(); try { assertEquals("A", f1.get()); assertEquals("B", f2.get()); assertEquals("A", f3.get()); } catch (Exception e) { throw new RuntimeException(e); } assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // this should also execute because caching is disabled assertTrue(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show a SUCCESS assertEquals(1, command3.getExecutionEvents().size()); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testRequestCacheViaExecuteSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, true, "A"); assertFalse(command1.isCommandRunningInThread()); String f1 = command1.execute(); String f2 = command2.execute(); String f3 = command3.execute(); assertEquals("A", f1); assertEquals("B", f2); assertEquals("A", f3); assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // but the 3rd should come from cache assertFalse(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show it comes from cache assertEquals(2, command3.getExecutionEvents().size()); // it will include the SUCCESS + RESPONSE_FROM_CACHE assertTrue(command3.getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertEquals(2, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test Request scoped caching with a mixture of commands */ @Test public void testNoRequestCacheViaExecuteSemaphore1() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommandViaSemaphore command1 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); SuccessfulCacheableCommandViaSemaphore command2 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "B"); SuccessfulCacheableCommandViaSemaphore command3 = new SuccessfulCacheableCommandViaSemaphore(circuitBreaker, false, "A"); assertFalse(command1.isCommandRunningInThread()); String f1 = command1.execute(); String f2 = command2.execute(); String f3 = command3.execute(); assertEquals("A", f1); assertEquals("B", f2); assertEquals("A", f3); assertTrue(command1.executed); // both should execute as they are different assertTrue(command2.executed); // this should also execute because caching is disabled assertTrue(command3.executed); // the execution log for command1 should show a SUCCESS assertEquals(1, command1.getExecutionEvents().size()); assertTrue(command1.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command2 should show a SUCCESS assertEquals(1, command2.getExecutionEvents().size()); assertTrue(command2.getExecutionEvents().contains(HystrixEventType.SUCCESS)); // the execution log for command3 should show a SUCCESS assertEquals(1, command3.getExecutionEvents().size()); assertTrue(command3.getExecutionEvents().contains(HystrixEventType.SUCCESS)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(0, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(3, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testNoRequestCacheOnTimeoutThrowsException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); NoRequestCacheTimeoutWithoutFallback r1 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); try { System.out.println("r1 value: " + r1.execute()); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r1.isResponseTimedOut()); // what we want } NoRequestCacheTimeoutWithoutFallback r2 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); try { r2.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r2.isResponseTimedOut()); // what we want } NoRequestCacheTimeoutWithoutFallback r3 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); Future<Boolean> f3 = r3.queue(); try { f3.get(); // we should have thrown an exception fail("expected a timeout"); } catch (ExecutionException e) { e.printStackTrace(); assertTrue(r3.isResponseTimedOut()); // what we want } Thread.sleep(500); // timeout on command is set to 200ms NoRequestCacheTimeoutWithoutFallback r4 = new NoRequestCacheTimeoutWithoutFallback(circuitBreaker); try { r4.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r4.isResponseTimedOut()); assertFalse(r4.isResponseFromFallback()); // what we want } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testRequestCacheOnTimeoutCausesNullPointerException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); // Expect it to time out - all results should be false assertFalse(new RequestCacheNullPointerExceptionCase(circuitBreaker).execute()); assertFalse(new RequestCacheNullPointerExceptionCase(circuitBreaker).execute()); // return from cache #1 assertFalse(new RequestCacheNullPointerExceptionCase(circuitBreaker).execute()); // return from cache #2 Thread.sleep(500); // timeout on command is set to 200ms Boolean value = new RequestCacheNullPointerExceptionCase(circuitBreaker).execute(); // return from cache #3 assertFalse(value); RequestCacheNullPointerExceptionCase c = new RequestCacheNullPointerExceptionCase(circuitBreaker); Future<Boolean> f = c.queue(); // return from cache #4 // the bug is that we're getting a null Future back, rather than a Future that returns false assertNotNull(f); assertFalse(f.get()); assertTrue(c.isResponseFromFallback()); assertTrue(c.isResponseTimedOut()); assertFalse(c.isFailedExecution()); assertFalse(c.isResponseShortCircuited()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(4, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(5, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); HystrixCommand<?>[] executeCommands = HystrixRequestLog.getCurrentRequest().getExecutedCommands().toArray(new HystrixCommand<?>[] {}); System.out.println(":executeCommands[0].getExecutionEvents()" + executeCommands[0].getExecutionEvents()); assertEquals(2, executeCommands[0].getExecutionEvents().size()); assertTrue(executeCommands[0].getExecutionEvents().contains(HystrixEventType.FALLBACK_SUCCESS)); assertTrue(executeCommands[0].getExecutionEvents().contains(HystrixEventType.TIMEOUT)); assertTrue(executeCommands[0].getExecutionTimeInMilliseconds() > -1); assertTrue(executeCommands[0].isResponseTimedOut()); assertTrue(executeCommands[0].isResponseFromFallback()); assertFalse(executeCommands[0].isResponseFromCache()); assertEquals(3, executeCommands[1].getExecutionEvents().size()); // it will include FALLBACK_SUCCESS/TIMEOUT + RESPONSE_FROM_CACHE assertTrue(executeCommands[1].getExecutionEvents().contains(HystrixEventType.RESPONSE_FROM_CACHE)); assertTrue(executeCommands[1].getExecutionTimeInMilliseconds() == -1); assertTrue(executeCommands[1].isResponseFromCache()); assertTrue(executeCommands[1].isResponseTimedOut()); assertTrue(executeCommands[1].isResponseFromFallback()); } @Test public void testRequestCacheOnTimeoutThrowsException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); RequestCacheTimeoutWithoutFallback r1 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); try { System.out.println("r1 value: " + r1.execute()); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r1.isResponseTimedOut()); // what we want } RequestCacheTimeoutWithoutFallback r2 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); try { r2.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r2.isResponseTimedOut()); // what we want } RequestCacheTimeoutWithoutFallback r3 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); Future<Boolean> f3 = r3.queue(); try { f3.get(); // we should have thrown an exception fail("expected a timeout"); } catch (ExecutionException e) { e.printStackTrace(); assertTrue(r3.isResponseTimedOut()); // what we want } Thread.sleep(500); // timeout on command is set to 200ms RequestCacheTimeoutWithoutFallback r4 = new RequestCacheTimeoutWithoutFallback(circuitBreaker); try { r4.execute(); // we should have thrown an exception fail("expected a timeout"); } catch (HystrixRuntimeException e) { assertTrue(r4.isResponseTimedOut()); assertFalse(r4.isResponseFromFallback()); // what we want } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } @Test public void testRequestCacheOnThreadRejectionThrowsException() throws Exception { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); CountDownLatch completionLatch = new CountDownLatch(1); RequestCacheThreadRejectionWithoutFallback r1 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("r1: " + r1.execute()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { assertTrue(r1.isResponseRejected()); // what we want } RequestCacheThreadRejectionWithoutFallback r2 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("r2: " + r2.execute()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { // e.printStackTrace(); assertTrue(r2.isResponseRejected()); // what we want } RequestCacheThreadRejectionWithoutFallback r3 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("f3: " + r3.queue().get()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { // e.printStackTrace(); assertTrue(r3.isResponseRejected()); // what we want } // let the command finish (only 1 should actually be blocked on this due to the response cache) completionLatch.countDown(); // then another after the command has completed RequestCacheThreadRejectionWithoutFallback r4 = new RequestCacheThreadRejectionWithoutFallback(circuitBreaker, completionLatch); try { System.out.println("r4: " + r4.execute()); // we should have thrown an exception fail("expected a rejection"); } catch (HystrixRuntimeException e) { // e.printStackTrace(); assertTrue(r4.isResponseRejected()); assertFalse(r4.isResponseFromFallback()); // what we want } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(3, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, circuitBreaker.metrics.getHealthCounts().getErrorPercentage()); assertEquals(4, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /** * Test that we can do basic execution without a RequestVariable being initialized. */ @Test public void testBasicExecutionWorksWithoutRequestVariable() { try { /* force the RequestVariable to not be initialized */ HystrixRequestContext.setContextOnCurrentThread(null); TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); assertEquals(true, command.execute()); TestHystrixCommand<Boolean> command2 = new SuccessfulTestCommand(); assertEquals(true, command2.queue().get()); // we should be able to execute without a RequestVariable if ... // 1) We don't have a cacheKey // 2) We don't ask for the RequestLog // 3) We don't do collapsing } catch (Exception e) { e.printStackTrace(); fail("We received an exception => " + e.getMessage()); } } /** * Test that if we try and execute a command with a cacheKey without initializing RequestVariable that it gives an error. */ @Test public void testCacheKeyExecutionRequiresRequestVariable() { try { /* force the RequestVariable to not be initialized */ HystrixRequestContext.setContextOnCurrentThread(null); TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SuccessfulCacheableCommand command = new SuccessfulCacheableCommand(circuitBreaker, true, "one"); assertEquals(true, command.execute()); SuccessfulCacheableCommand command2 = new SuccessfulCacheableCommand(circuitBreaker, true, "two"); assertEquals(true, command2.queue().get()); fail("We expect an exception because cacheKey requires RequestVariable."); } catch (Exception e) { e.printStackTrace(); } } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaExecuteInThread() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD).execute(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (HystrixBadRequestException e) { // success e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaQueueInThread() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.THREAD).queue().get(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (ExecutionException e) { e.printStackTrace(); if (e.getCause() instanceof HystrixBadRequestException) { // success } else { fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } } catch (Exception e) { e.printStackTrace(); fail(); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaExecuteInSemaphore() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE).execute(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (HystrixBadRequestException e) { // success e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test that a BadRequestException can be thrown and not count towards errors and bypasses fallback. */ @Test public void testBadRequestExceptionViaQueueInSemaphore() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); try { new BadRequestCommand(circuitBreaker, ExecutionIsolationStrategy.SEMAPHORE).queue().get(); fail("we expect to receive a " + HystrixBadRequestException.class.getSimpleName()); } catch (HystrixBadRequestException e) { // success e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fail("We expect a " + HystrixBadRequestException.class.getSimpleName() + " but got a " + e.getClass().getSimpleName()); } assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); } /** * Test a checked Exception being thrown */ @Test public void testCheckedException() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); CommandWithCheckedException command = new CommandWithCheckedException(circuitBreaker); try { command.execute(); fail("we expect to receive a " + Exception.class.getSimpleName()); } catch (Exception e) { assertEquals("simulated checked exception message", e.getCause().getMessage()); } assertEquals("simulated checked exception message", command.getFailedExecutionException().getMessage()); assertTrue(command.getExecutionTimeInMilliseconds() > -1); assertTrue(command.isFailedExecution()); assertEquals(0, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(1, circuitBreaker.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); } /** * Execution hook on successful execution */ @Test public void testExecutionHookSuccessfulCommand() { /* test with execute() */ TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); command.execute(); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from execute() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new SuccessfulTestCommand(); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException(e); } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with "fire and forget" approach */ @Test public void testExecutionHookSuccessfulCommandViaFireAndForget() { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); try { // do not block on "get()" ... fire this asynchronously command.queue(); } catch (Exception e) { throw new RuntimeException(e); } // wait for command to execute without calling get on the future while (!command.isExecutionComplete()) { try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException("interrupted"); } } /* * All the hooks should still work even though we didn't call get() on the future */ // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with multiple get() calls to Future */ @Test public void testExecutionHookSuccessfulCommandWithMultipleGetsOnFuture() { TestHystrixCommand<Boolean> command = new SuccessfulTestCommand(); try { Future<Boolean> f = command.queue(); f.get(); f.get(); f.get(); f.get(); } catch (Exception e) { throw new RuntimeException(e); } /* * Despite multiple calls to get() we should only have 1 call to the hooks. */ // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on failed execution without a fallback */ @Test public void testExecutionHookRunFailureWithoutFallback() { /* test with execute() */ TestHystrixCommand<Boolean> command = new UnknownFailureTestCommandWithoutFallback(); try { command.execute(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback is not implemented assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's not implemented and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response from execute() since we do not have a fallback and run() failed assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new UnknownFailureTestCommandWithoutFallback(); try { command.queue().get(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback is not implemented assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's not implemented and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response from queue() since we do not have a fallback and run() failed assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on failed execution with a fallback */ @Test public void testExecutionHookRunFailureWithFallback() { /* test with execute() */ TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); command.execute(); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response from run since run() failed assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // a response since fallback is implemented assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since it's implemented and succeeds assertNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from execute() since we expect a fallback despite failure of run() assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because we expect a fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker()); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException(e); } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response from run since run() failed assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception since run() failed assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // a response since fallback is implemented assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since it's implemented and succeeds assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since we expect a fallback despite failure of run() assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because we expect a fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on failed execution with a fallback failure */ @Test public void testExecutionHookRunFailureWithFallbackFailure() { /* test with execute() */ TestHystrixCommand<Boolean> command = new KnownFailureTestCommandWithFallbackFailure(); try { command.execute(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback fails assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's implemented but fails assertNotNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new KnownFailureTestCommandWithFallbackFailure(); try { command.queue().get(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.runSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.runFailureException); // the fallback() method should be run since run() failed assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since fallback fails assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since it's implemented but fails assertNotNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because run() and fallback fail assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception because run() and fallback fail assertNotNull(command.builder.executionHook.endExecuteFailureException); // run() failure assertEquals(FailureType.COMMAND_EXCEPTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on timeout without a fallback */ @Test public void testExecutionHookTimeoutWithoutFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_NOT_IMPLEMENTED); try { command.queue().get(); fail("Expecting exception"); } catch (Exception e) { // ignore } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because of timeout and no fallback assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because run() didn't fail, it timed out assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to timeout assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since no fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since no fallback implementation assertNotNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because of timeout and no fallback assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we should have an exception because of timeout and no fallback assertNotNull(command.builder.executionHook.endExecuteFailureException); // timeout failure assertEquals(FailureType.TIMEOUT, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); // we need to wait for the thread to complete before the onThreadComplete hook will be called try { Thread.sleep(400); } catch (InterruptedException e) { // ignore } assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on timeout with a fallback */ @Test public void testExecutionHookTimeoutWithFallback() { TestHystrixCommand<Boolean> command = new TestCommandWithTimeout(50, TestCommandWithTimeout.FALLBACK_SUCCESS); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException("not expecting", e); } // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we should not have a response because of timeout assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because run() didn't fail, it timed out assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to timeout assertEquals(1, command.builder.executionHook.startFallback.get()); // response since we have a fallback assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since fallback succeeds assertNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response because of fallback assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because of fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(1, command.builder.executionHook.threadStart.get()); // we need to wait for the thread to complete before the onThreadComplete hook will be called try { Thread.sleep(400); } catch (InterruptedException e) { // ignore } assertEquals(1, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on rejected with a fallback */ @Test public void testExecutionHookRejectedWithFallback() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker(); SingleThreadedPool pool = new SingleThreadedPool(1); try { // fill the queue new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS).queue(); new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS).queue(); } catch (Exception e) { // ignore } TestCommandRejection command = new TestCommandRejection(circuitBreaker, pool, 500, 600, TestCommandRejection.FALLBACK_SUCCESS); try { // now execute one that will be rejected command.queue().get(); } catch (Exception e) { throw new RuntimeException("not expecting", e); } assertTrue(command.isResponseRejected()); // the run() method should not run as we're rejected assertEquals(0, command.builder.executionHook.startRun.get()); // we should not have a response because of rejection assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because we didn't run assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // response since we have a fallback assertNotNull(command.builder.executionHook.fallbackSuccessResponse); // null since fallback succeeds assertNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response because of fallback assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception because of fallback assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on short-circuit with a fallback */ @Test public void testExecutionHookShortCircuitedWithFallbackViaQueue() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true); KnownFailureTestCommandWithoutFallback command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { // now execute one that will be short-circuited command.queue().get(); fail("we expect an error as there is no fallback"); } catch (Exception e) { // expecting } assertTrue(command.isResponseShortCircuited()); // the run() method should not run as we're rejected assertEquals(0, command.builder.executionHook.startRun.get()); // we should not have a response because of rejection assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because we didn't run assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since we don't have a fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since fallback fails and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because fallback fails assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we won't have an exception because short-circuit doesn't have one assertNull(command.builder.executionHook.endExecuteFailureException); // but we do expect to receive a onError call with FailureType.SHORTCIRCUIT assertEquals(FailureType.SHORTCIRCUIT, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on short-circuit with a fallback */ @Test public void testExecutionHookShortCircuitedWithFallbackViaExecute() { TestCircuitBreaker circuitBreaker = new TestCircuitBreaker().setForceShortCircuit(true); KnownFailureTestCommandWithoutFallback command = new KnownFailureTestCommandWithoutFallback(circuitBreaker); try { // now execute one that will be short-circuited command.execute(); fail("we expect an error as there is no fallback"); } catch (Exception e) { // expecting } assertTrue(command.isResponseShortCircuited()); // the run() method should not run as we're rejected assertEquals(0, command.builder.executionHook.startRun.get()); // we should not have a response because of rejection assertNull(command.builder.executionHook.runSuccessResponse); // we should not have an exception because we didn't run assertNull(command.builder.executionHook.runFailureException); // the fallback() method should be run due to rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // no response since we don't have a fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since fallback fails and throws an exception assertNotNull(command.builder.executionHook.fallbackFailureException); // execution occurred assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response because fallback fails assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we won't have an exception because short-circuit doesn't have one assertNull(command.builder.executionHook.endExecuteFailureException); // but we do expect to receive a onError call with FailureType.SHORTCIRCUIT assertEquals(FailureType.SHORTCIRCUIT, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with semaphore isolation */ @Test public void testExecutionHookSuccessfulCommandWithSemaphoreIsolation() { /* test with execute() */ TestSemaphoreCommand command = new TestSemaphoreCommand(new TestCircuitBreaker(), 1, 10); command.execute(); assertFalse(command.isExecutedInThread()); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from execute() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); /* test with queue() */ command = new TestSemaphoreCommand(new TestCircuitBreaker(), 1, 10); try { command.queue().get(); } catch (Exception e) { throw new RuntimeException(e); } assertFalse(command.isExecutedInThread()); // the run() method should run as we're not short-circuited or rejected assertEquals(1, command.builder.executionHook.startRun.get()); // we expect a successful response from run() assertNotNull(command.builder.executionHook.runSuccessResponse); // we do not expect an exception assertNull(command.builder.executionHook.runFailureException); // the fallback() method should not be run as we were successful assertEquals(0, command.builder.executionHook.startFallback.get()); // null since it didn't run assertNull(command.builder.executionHook.fallbackSuccessResponse); // null since it didn't run assertNull(command.builder.executionHook.fallbackFailureException); // the queue() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should have a response from queue() since run() succeeded assertNotNull(command.builder.executionHook.endExecuteSuccessResponse); // we should not have an exception since run() succeeded assertNull(command.builder.executionHook.endExecuteFailureException); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Execution hook on successful execution with semaphore isolation */ @Test public void testExecutionHookFailureWithSemaphoreIsolation() { /* test with execute() */ final TryableSemaphore semaphore = new TryableSemaphore(HystrixProperty.Factory.asProperty(0)); TestSemaphoreCommand command = new TestSemaphoreCommand(new TestCircuitBreaker(), semaphore, 200); try { command.execute(); fail("we expect a failure"); } catch (Exception e) { // expected } assertFalse(command.isExecutedInThread()); assertTrue(command.isResponseRejected()); // the run() method should not run as we are rejected assertEquals(0, command.builder.executionHook.startRun.get()); // null as run() does not get invoked assertNull(command.builder.executionHook.runSuccessResponse); // null as run() does not get invoked assertNull(command.builder.executionHook.runFailureException); // the fallback() method should run because of rejection assertEquals(1, command.builder.executionHook.startFallback.get()); // null since there is no fallback assertNull(command.builder.executionHook.fallbackSuccessResponse); // not null since the fallback is not implemented assertNotNull(command.builder.executionHook.fallbackFailureException); // the execute() method was used assertEquals(1, command.builder.executionHook.startExecute.get()); // we should not have a response since fallback has nothing assertNull(command.builder.executionHook.endExecuteSuccessResponse); // we won't have an exception because rejection doesn't have one assertNull(command.builder.executionHook.endExecuteFailureException); // but we do expect to receive a onError call with FailureType.SHORTCIRCUIT assertEquals(FailureType.REJECTED_SEMAPHORE_EXECUTION, command.builder.executionHook.endExecuteFailureType); // thread execution assertEquals(0, command.builder.executionHook.threadStart.get()); assertEquals(0, command.builder.executionHook.threadComplete.get()); } /** * Test a command execution that fails but has a fallback. */ @Test public void testExecutionFailureWithFallbackImplementedButDisabled() { TestHystrixCommand<Boolean> commandEnabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), true); try { assertEquals(false, commandEnabled.execute()); } catch (Exception e) { e.printStackTrace(); fail("We should have received a response from the fallback."); } TestHystrixCommand<Boolean> commandDisabled = new KnownFailureTestCommandWithFallback(new TestCircuitBreaker(), false); try { assertEquals(false, commandDisabled.execute()); fail("expect exception thrown"); } catch (Exception e) { // expected } assertEquals("we failed with a simulated issue", commandDisabled.getFailedExecutionException().getMessage()); assertTrue(commandDisabled.isFailedExecution()); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS)); assertEquals(1, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN)); assertEquals(1, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FAILURE)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT)); assertEquals(0, commandDisabled.builder.metrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE)); assertEquals(100, commandDisabled.builder.metrics.getHealthCounts().getErrorPercentage()); assertEquals(2, HystrixRequestLog.getCurrentRequest().getExecutedCommands().size()); } /* ******************************************************************************** */ /* ******************************************************************************** */ /* private HystrixCommand class implementations for unit testing */ /* ******************************************************************************** */ /* ******************************************************************************** */ /** * Used by UnitTest command implementations to provide base defaults for constructor and a builder pattern for the arguments being passed in. */ /* package */static abstract class TestHystrixCommand<K> extends HystrixCommand<K> { final TestCommandBuilder builder; TestHystrixCommand(TestCommandBuilder builder) { super(builder.owner, builder.dependencyKey, builder.threadPoolKey, builder.circuitBreaker, builder.threadPool, builder.commandPropertiesDefaults, builder.threadPoolPropertiesDefaults, builder.metrics, builder.fallbackSemaphore, builder.executionSemaphore, TEST_PROPERTIES_FACTORY, builder.executionHook); this.builder = builder; } static TestCommandBuilder testPropsBuilder() { return new TestCommandBuilder(); } static class TestCommandBuilder { TestCircuitBreaker _cb = new TestCircuitBreaker(); HystrixCommandGroupKey owner = CommandGroupForUnitTest.OWNER_ONE; HystrixCommandKey dependencyKey = null; HystrixThreadPoolKey threadPoolKey = null; HystrixCircuitBreaker circuitBreaker = _cb; HystrixThreadPool threadPool = null; HystrixCommandProperties.Setter commandPropertiesDefaults = HystrixCommandProperties.Setter.getUnitTestPropertiesSetter(); HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults = HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder(); HystrixCommandMetrics metrics = _cb.metrics; TryableSemaphore fallbackSemaphore = null; TryableSemaphore executionSemaphore = null; TestExecutionHook executionHook = new TestExecutionHook(); TestCommandBuilder setOwner(HystrixCommandGroupKey owner) { this.owner = owner; return this; } TestCommandBuilder setCommandKey(HystrixCommandKey dependencyKey) { this.dependencyKey = dependencyKey; return this; } TestCommandBuilder setThreadPoolKey(HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; return this; } TestCommandBuilder setCircuitBreaker(HystrixCircuitBreaker circuitBreaker) { this.circuitBreaker = circuitBreaker; return this; } TestCommandBuilder setThreadPool(HystrixThreadPool threadPool) { this.threadPool = threadPool; return this; } TestCommandBuilder setCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = commandPropertiesDefaults; return this; } TestCommandBuilder setThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults; return this; } TestCommandBuilder setMetrics(HystrixCommandMetrics metrics) { this.metrics = metrics; return this; } TestCommandBuilder setFallbackSemaphore(TryableSemaphore fallbackSemaphore) { this.fallbackSemaphore = fallbackSemaphore; return this; } TestCommandBuilder setExecutionSemaphore(TryableSemaphore executionSemaphore) { this.executionSemaphore = executionSemaphore; return this; } } } /** * Successful execution - no fallback implementation. */ private static class SuccessfulTestCommand extends TestHystrixCommand<Boolean> { public SuccessfulTestCommand() { this(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter()); } public SuccessfulTestCommand(HystrixCommandProperties.Setter properties) { super(testPropsBuilder().setCommandPropertiesDefaults(properties)); } @Override protected Boolean run() { return true; } } /** * Successful execution - no fallback implementation. */ private static class DynamicOwnerTestCommand extends TestHystrixCommand<Boolean> { public DynamicOwnerTestCommand(HystrixCommandGroupKey owner) { super(testPropsBuilder().setOwner(owner)); } @Override protected Boolean run() { System.out.println("successfully executed"); return true; } } /** * Successful execution - no fallback implementation. */ private static class DynamicOwnerAndKeyTestCommand extends TestHystrixCommand<Boolean> { public DynamicOwnerAndKeyTestCommand(HystrixCommandGroupKey owner, HystrixCommandKey key) { super(testPropsBuilder().setOwner(owner).setCommandKey(key).setCircuitBreaker(null).setMetrics(null)); // we specifically are NOT passing in a circuit breaker here so we test that it creates a new one correctly based on the dynamic key } @Override protected Boolean run() { System.out.println("successfully executed"); return true; } } /** * Failed execution with unknown exception (not HystrixException) - no fallback implementation. */ private static class UnknownFailureTestCommandWithoutFallback extends TestHystrixCommand<Boolean> { private UnknownFailureTestCommandWithoutFallback() { super(testPropsBuilder()); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with an unknown issue"); } } /** * Failed execution with known exception (HystrixException) - no fallback implementation. */ private static class KnownFailureTestCommandWithoutFallback extends TestHystrixCommand<Boolean> { private KnownFailureTestCommandWithoutFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with a simulated issue"); } } /** * Failed execution - fallback implementation successfully returns value. */ private static class KnownFailureTestCommandWithFallback extends TestHystrixCommand<Boolean> { public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); } public KnownFailureTestCommandWithFallback(TestCircuitBreaker circuitBreaker, boolean fallbackEnabled) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withFallbackEnabled(fallbackEnabled))); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with a simulated issue"); } @Override protected Boolean getFallback() { return false; } } /** * Failed execution - fallback implementation throws exception. */ private static class KnownFailureTestCommandWithFallbackFailure extends TestHystrixCommand<Boolean> { private KnownFailureTestCommandWithFallbackFailure() { super(testPropsBuilder()); } @Override protected Boolean run() { System.out.println("*** simulated failed execution ***"); throw new RuntimeException("we failed with a simulated issue"); } @Override protected Boolean getFallback() { throw new RuntimeException("failed while getting fallback"); } } /** * A Command implementation that supports caching. */ private static class SuccessfulCacheableCommand extends TestHystrixCommand<String> { private final boolean cacheEnabled; private volatile boolean executed = false; private final String value; public SuccessfulCacheableCommand(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, String value) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); this.value = value; this.cacheEnabled = cacheEnabled; } @Override protected String run() { executed = true; System.out.println("successfully executed"); return value; } public boolean isCommandRunningInThread() { return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD); } @Override public String getCacheKey() { if (cacheEnabled) return value; else return null; } } /** * A Command implementation that supports caching. */ private static class SuccessfulCacheableCommandViaSemaphore extends TestHystrixCommand<String> { private final boolean cacheEnabled; private volatile boolean executed = false; private final String value; public SuccessfulCacheableCommandViaSemaphore(TestCircuitBreaker circuitBreaker, boolean cacheEnabled, String value) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE))); this.value = value; this.cacheEnabled = cacheEnabled; } @Override protected String run() { executed = true; System.out.println("successfully executed"); return value; } public boolean isCommandRunningInThread() { return super.getProperties().executionIsolationStrategy().get().equals(ExecutionIsolationStrategy.THREAD); } @Override public String getCacheKey() { if (cacheEnabled) return value; else return null; } } /** * A Command implementation that supports caching and execution takes a while. * <p> * Used to test scenario where Futures are returned with a backing call still executing. */ private static class SlowCacheableCommand extends TestHystrixCommand<String> { private final String value; private final int duration; private volatile boolean executed = false; public SlowCacheableCommand(TestCircuitBreaker circuitBreaker, String value, int duration) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); this.value = value; this.duration = duration; } @Override protected String run() { executed = true; try { Thread.sleep(duration); } catch (Exception e) { e.printStackTrace(); } System.out.println("successfully executed"); return value; } @Override public String getCacheKey() { return value; } } /** * Successful execution - no fallback implementation, circuit-breaker disabled. */ private static class TestCommandWithoutCircuitBreaker extends TestHystrixCommand<Boolean> { private TestCommandWithoutCircuitBreaker() { super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withCircuitBreakerEnabled(false))); } @Override protected Boolean run() { System.out.println("successfully executed"); return true; } } /** * This should timeout. */ private static class TestCommandWithTimeout extends TestHystrixCommand<Boolean> { private final long timeout; private final static int FALLBACK_NOT_IMPLEMENTED = 1; private final static int FALLBACK_SUCCESS = 2; private final static int FALLBACK_FAILURE = 3; private final int fallbackBehavior; private TestCommandWithTimeout(long timeout, int fallbackBehavior) { super(testPropsBuilder().setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds((int) timeout))); this.timeout = timeout; this.fallbackBehavior = fallbackBehavior; } @Override protected Boolean run() { System.out.println("***** running"); try { Thread.sleep(timeout * 10); } catch (InterruptedException e) { e.printStackTrace(); // ignore and sleep some more to simulate a dependency that doesn't obey interrupts try { Thread.sleep(timeout * 2); } catch (Exception e2) { // ignore } System.out.println("after interruption with extra sleep"); } return true; } @Override protected Boolean getFallback() { if (fallbackBehavior == FALLBACK_SUCCESS) { return false; } else if (fallbackBehavior == FALLBACK_FAILURE) { throw new RuntimeException("failed on fallback"); } else { // FALLBACK_NOT_IMPLEMENTED return super.getFallback(); } } } /** * Threadpool with 1 thread, queue of size 1 */ private static class SingleThreadedPool implements HystrixThreadPool { final LinkedBlockingQueue<Runnable> queue; final ThreadPoolExecutor pool; private final int rejectionQueueSizeThreshold; public SingleThreadedPool(int queueSize) { this(queueSize, 100); } public SingleThreadedPool(int queueSize, int rejectionQueueSizeThreshold) { queue = new LinkedBlockingQueue<Runnable>(queueSize); pool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.MINUTES, queue); this.rejectionQueueSizeThreshold = rejectionQueueSizeThreshold; } @Override public ThreadPoolExecutor getExecutor() { return pool; } @Override public void markThreadExecution() { // not used for this test } @Override public void markThreadCompletion() { // not used for this test } @Override public boolean isQueueSpaceAvailable() { return queue.size() < rejectionQueueSizeThreshold; } } /** * This has a ThreadPool that has a single thread and queueSize of 1. */ private static class TestCommandRejection extends TestHystrixCommand<Boolean> { private final static int FALLBACK_NOT_IMPLEMENTED = 1; private final static int FALLBACK_SUCCESS = 2; private final static int FALLBACK_FAILURE = 3; private final int fallbackBehavior; private final int sleepTime; private TestCommandRejection(TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int sleepTime, int timeout, int fallbackBehavior) { super(testPropsBuilder().setThreadPool(threadPool).setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(timeout))); this.fallbackBehavior = fallbackBehavior; this.sleepTime = sleepTime; } @Override protected Boolean run() { System.out.println(">>> TestCommandRejection running"); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected Boolean getFallback() { if (fallbackBehavior == FALLBACK_SUCCESS) { return false; } else if (fallbackBehavior == FALLBACK_FAILURE) { throw new RuntimeException("failed on fallback"); } else { // FALLBACK_NOT_IMPLEMENTED return super.getFallback(); } } } /** * Command that receives a custom thread-pool, sleepTime, timeout */ private static class CommandWithCustomThreadPool extends TestHystrixCommand<Boolean> { public boolean didExecute = false; private final int sleepTime; private CommandWithCustomThreadPool(TestCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, int sleepTime, HystrixCommandProperties.Setter properties) { super(testPropsBuilder().setThreadPool(threadPool).setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics).setCommandPropertiesDefaults(properties)); this.sleepTime = sleepTime; } @Override protected Boolean run() { System.out.println("**** Executing CommandWithCustomThreadPool. Execution => " + sleepTime); didExecute = true; try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } return true; } } /** * The run() will fail and getFallback() take a long time. */ private static class TestSemaphoreCommandWithSlowFallback extends TestHystrixCommand<Boolean> { private final long fallbackSleep; private TestSemaphoreCommandWithSlowFallback(TestCircuitBreaker circuitBreaker, int fallbackSemaphoreExecutionCount, long fallbackSleep) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withFallbackIsolationSemaphoreMaxConcurrentRequests(fallbackSemaphoreExecutionCount))); this.fallbackSleep = fallbackSleep; } @Override protected Boolean run() { throw new RuntimeException("run fails"); } @Override protected Boolean getFallback() { try { Thread.sleep(fallbackSleep); } catch (InterruptedException e) { e.printStackTrace(); } return true; } } private static class NoRequestCacheTimeoutWithoutFallback extends TestHystrixCommand<Boolean> { public NoRequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(200))); // we want it to timeout } @Override protected Boolean run() { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(">>>> Sleep Interrupted: " + e.getMessage()); // e.printStackTrace(); } return true; } @Override public String getCacheKey() { return null; } } /** * The run() will take time. No fallback implementation. */ private static class TestSemaphoreCommand extends TestHystrixCommand<Boolean> { private final long executionSleep; private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter() .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE) .withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount))); this.executionSleep = executionSleep; } private TestSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, long executionSleep) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter() .withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)) .setExecutionSemaphore(semaphore)); this.executionSleep = executionSleep; } @Override protected Boolean run() { try { Thread.sleep(executionSleep); } catch (InterruptedException e) { e.printStackTrace(); } return true; } } /** * Semaphore based command that allows caller to use latches to know when it has started and signal when it * would like the command to finish */ private static class LatchedSemaphoreCommand extends TestHystrixCommand<Boolean> { private final CountDownLatch startLatch, waitLatch; /** * * @param circuitBreaker * @param semaphore * @param startLatch * this command calls {@link java.util.concurrent.CountDownLatch#countDown()} immediately * upon running * @param waitLatch * this command calls {@link java.util.concurrent.CountDownLatch#await()} once it starts * to run. The caller can use the latch to signal the command to finish */ private LatchedSemaphoreCommand(TestCircuitBreaker circuitBreaker, TryableSemaphore semaphore, CountDownLatch startLatch, CountDownLatch waitLatch) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)) .setExecutionSemaphore(semaphore)); this.startLatch = startLatch; this.waitLatch = waitLatch; } @Override protected Boolean run() { // signals caller that run has started this.startLatch.countDown(); try { // waits for caller to countDown latch this.waitLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); return false; } return true; } } /** * The run() will take time. Contains fallback. */ private static class TestSemaphoreCommandWithFallback extends TestHystrixCommand<Boolean> { private final long executionSleep; private final Boolean fallback; private TestSemaphoreCommandWithFallback(TestCircuitBreaker circuitBreaker, int executionSemaphoreCount, long executionSleep, Boolean fallback) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE).withExecutionIsolationSemaphoreMaxConcurrentRequests(executionSemaphoreCount))); this.executionSleep = executionSleep; this.fallback = fallback; } @Override protected Boolean run() { try { Thread.sleep(executionSleep); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected Boolean getFallback() { return fallback; } } private static class RequestCacheNullPointerExceptionCase extends TestHystrixCommand<Boolean> { public RequestCacheNullPointerExceptionCase(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(200))); // we want it to timeout } @Override protected Boolean run() { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } return true; } @Override protected Boolean getFallback() { return false; } @Override public String getCacheKey() { return "A"; } } private static class RequestCacheTimeoutWithoutFallback extends TestHystrixCommand<Boolean> { public RequestCacheTimeoutWithoutFallback(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder().setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationThreadTimeoutInMilliseconds(200))); // we want it to timeout } @Override protected Boolean run() { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(">>>> Sleep Interrupted: " + e.getMessage()); // e.printStackTrace(); } return true; } @Override public String getCacheKey() { return "A"; } } private static class RequestCacheThreadRejectionWithoutFallback extends TestHystrixCommand<Boolean> { final CountDownLatch completionLatch; public RequestCacheThreadRejectionWithoutFallback(TestCircuitBreaker circuitBreaker, CountDownLatch completionLatch) { super(testPropsBuilder() .setCircuitBreaker(circuitBreaker) .setMetrics(circuitBreaker.metrics) .setThreadPool(new HystrixThreadPool() { @Override public ThreadPoolExecutor getExecutor() { return null; } @Override public void markThreadExecution() { } @Override public void markThreadCompletion() { } @Override public boolean isQueueSpaceAvailable() { // always return false so we reject everything return false; } })); this.completionLatch = completionLatch; } @Override protected Boolean run() { try { if (completionLatch.await(1000, TimeUnit.MILLISECONDS)) { throw new RuntimeException("timed out waiting on completionLatch"); } } catch (InterruptedException e) { throw new RuntimeException(e); } return true; } @Override public String getCacheKey() { return "A"; } } private static class BadRequestCommand extends TestHystrixCommand<Boolean> { public BadRequestCommand(TestCircuitBreaker circuitBreaker, ExecutionIsolationStrategy isolationType) { super(testPropsBuilder() .setCircuitBreaker(circuitBreaker) .setCommandPropertiesDefaults(HystrixCommandProperties.Setter.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolationType))); } @Override protected Boolean run() { throw new HystrixBadRequestException("Message to developer that they passed in bad data or something like that."); } @Override protected Boolean getFallback() { return false; } } private static class CommandWithCheckedException extends TestHystrixCommand<Boolean> { public CommandWithCheckedException(TestCircuitBreaker circuitBreaker) { super(testPropsBuilder() .setCircuitBreaker(circuitBreaker).setMetrics(circuitBreaker.metrics)); } @Override protected Boolean run() throws Exception { throw new IOException("simulated checked exception message"); } } enum CommandKeyForUnitTest implements HystrixCommandKey { KEY_ONE, KEY_TWO; } enum CommandGroupForUnitTest implements HystrixCommandGroupKey { OWNER_ONE, OWNER_TWO; } enum ThreadPoolKeyForUnitTest implements HystrixThreadPoolKey { THREAD_POOL_ONE, THREAD_POOL_TWO; } private static HystrixPropertiesStrategy TEST_PROPERTIES_FACTORY = new TestPropertiesFactory(); private static class TestPropertiesFactory extends HystrixPropertiesStrategy { @Override public HystrixCommandProperties getCommandProperties(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) { if (builder == null) { builder = HystrixCommandProperties.Setter.getUnitTestPropertiesSetter(); } return HystrixCommandProperties.Setter.asMock(builder); } @Override public HystrixThreadPoolProperties getThreadPoolProperties(HystrixThreadPoolKey threadPoolKey, HystrixThreadPoolProperties.Setter builder) { if (builder == null) { builder = HystrixThreadPoolProperties.Setter.getUnitTestPropertiesBuilder(); } return HystrixThreadPoolProperties.Setter.asMock(builder); } @Override public HystrixCollapserProperties getCollapserProperties(HystrixCollapserKey collapserKey, HystrixCollapserProperties.Setter builder) { throw new IllegalStateException("not expecting collapser properties"); } @Override public String getCommandPropertiesCacheKey(HystrixCommandKey commandKey, HystrixCommandProperties.Setter builder) { return null; } @Override public String getThreadPoolPropertiesCacheKey(HystrixThreadPoolKey threadPoolKey, com.netflix.hystrix.HystrixThreadPoolProperties.Setter builder) { return null; } @Override public String getCollapserPropertiesCacheKey(HystrixCollapserKey collapserKey, com.netflix.hystrix.HystrixCollapserProperties.Setter builder) { return null; } } private static class TestExecutionHook extends HystrixCommandExecutionHook { AtomicInteger startExecute = new AtomicInteger(); @Override public <T> void onStart(HystrixCommand<T> commandInstance) { super.onStart(commandInstance); startExecute.incrementAndGet(); } Object endExecuteSuccessResponse = null; @Override public <T> T onComplete(HystrixCommand<T> commandInstance, T response) { endExecuteSuccessResponse = response; return super.onComplete(commandInstance, response); } Exception endExecuteFailureException = null; FailureType endExecuteFailureType = null; @Override public <T> Exception onError(HystrixCommand<T> commandInstance, FailureType failureType, Exception e) { endExecuteFailureException = e; endExecuteFailureType = failureType; return super.onError(commandInstance, failureType, e); } AtomicInteger startRun = new AtomicInteger(); @Override public <T> void onRunStart(HystrixCommand<T> commandInstance) { super.onRunStart(commandInstance); startRun.incrementAndGet(); } Object runSuccessResponse = null; @Override public <T> T onRunSuccess(HystrixCommand<T> commandInstance, T response) { runSuccessResponse = response; return super.onRunSuccess(commandInstance, response); } Exception runFailureException = null; @Override public <T> Exception onRunError(HystrixCommand<T> commandInstance, Exception e) { runFailureException = e; return super.onRunError(commandInstance, e); } AtomicInteger startFallback = new AtomicInteger(); @Override public <T> void onFallbackStart(HystrixCommand<T> commandInstance) { super.onFallbackStart(commandInstance); startFallback.incrementAndGet(); } Object fallbackSuccessResponse = null; @Override public <T> T onFallbackSuccess(HystrixCommand<T> commandInstance, T response) { fallbackSuccessResponse = response; return super.onFallbackSuccess(commandInstance, response); } Exception fallbackFailureException = null; @Override public <T> Exception onFallbackError(HystrixCommand<T> commandInstance, Exception e) { fallbackFailureException = e; return super.onFallbackError(commandInstance, e); } AtomicInteger threadStart = new AtomicInteger(); @Override public <T> void onThreadStart(HystrixCommand<T> commandInstance) { super.onThreadStart(commandInstance); threadStart.incrementAndGet(); } AtomicInteger threadComplete = new AtomicInteger(); @Override public <T> void onThreadComplete(HystrixCommand<T> commandInstance) { super.onThreadComplete(commandInstance); threadComplete.incrementAndGet(); } } } }
add a clarifying comment
hystrix-core/src/main/java/com/netflix/hystrix/HystrixCommand.java
add a clarifying comment
<ide><path>ystrix-core/src/main/java/com/netflix/hystrix/HystrixCommand.java <ide> return toObservable(Schedulers.threadPoolForComputation()); <ide> } else { <ide> // semaphore isolation is all blocking, no new threads involved <add> // so we'll use the calling thread <ide> return toObservable(Schedulers.immediate()); <ide> } <ide> }
Java
apache-2.0
cede69d7000662ce8ab45bba44b107429ae5b985
0
osmmosques/osm-mosques,osmmosques/osm-mosques,osmmosques/osm-mosques,osmmosques/osm-mosques
package com.gurkensalat.osm.mosques.entity; import com.gurkensalat.osm.entity.Address; import com.gurkensalat.osm.entity.Contact; import com.gurkensalat.osm.entity.OsmNode; import com.gurkensalat.osm.entity.OsmPlaceBase; import com.gurkensalat.osm.entity.OsmWay; import com.gurkensalat.osm.entity.PlaceType; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "MOSQUE_PLACES") public class OsmMosquePlace extends OsmPlaceBase { // Adapted from osmconvert, see // http://wiki.openstreetmap.org/wiki/Osmconvert#Dispose_of_Ways_and_Relations_and_Convert_them_to_Nodes private transient static final long WAY_OFFSET = (long) Math.pow(10, 15); @Column(name = "ADDR_COUNTRY_DATAFILE", length = 80) private String countryFromDatafile; @Column(name = "ADDR_POSTCODE_DATAFILE", length = 10) private String postcodeFromDatafile; @Column(name = "ADDR_CITY_DATAFILE", length = 80) private String cityFromDatafile; @Column(name = "ADDR_COUNTRY_OSM", length = 80) private String countryFromOSM; @Column(name = "ADDR_POSTCODE_OSM", length = 10) private String postcodeFromOSM; @Column(name = "ADDR_CITY_OSM", length = 80) private String cityFromOSM; @Column(name = "ADDR_COUNTRY_GEOCODING", length = 80) private String countryFromGeocoding; @Column(name = "ADDR_POSTCODE_GEOCODING", length = 10) private String postcodeFromGeocoding; @Column(name = "ADDR_CITY_GEOCODING", length = 80) private String cityFromGeocoding; @Column(name = "LAST_GEOCODE_ATTEMPT") @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime lastGeocodeAttempt; @Transient private String humanReadableLastGeocodeAttempt; @Column(name = "QA_SCORE") private double qaScore; protected OsmMosquePlace() { } public OsmMosquePlace(String name, PlaceType type) { super(name, type); } public OsmMosquePlace(OsmNode node) { super(node); } public OsmMosquePlace(OsmWay way) { super(way); } public static long getWayOffset() { return WAY_OFFSET; } public boolean isOsmNode() { return ((getId() != null) && (WAY_OFFSET > getId())); } public boolean isOsmWay() { return ((getId() != null) && (WAY_OFFSET < getId())); } public String getCountryFromDatafile() { return countryFromDatafile; } public void setCountryFromDatafile(String countryFromDatafile) { this.countryFromDatafile = countryFromDatafile; } public String getPostcodeFromDatafile() { return postcodeFromDatafile; } public void setPostcodeFromDatafile(String postcodeFromDatafile) { this.postcodeFromDatafile = postcodeFromDatafile; } public String getCityFromDatafile() { return cityFromDatafile; } public void setCityFromDatafile(String cityFromDatafile) { this.cityFromDatafile = cityFromDatafile; } public String getCountryFromOSM() { return countryFromOSM; } public void setCountryFromOSM(String countryFromOSM) { this.countryFromOSM = countryFromOSM; } public String getPostcodeFromOSM() { return postcodeFromOSM; } public void setPostcodeFromOSM(String postcodeFromOSM) { this.postcodeFromOSM = postcodeFromOSM; } public String getCityFromOSM() { return cityFromOSM; } public void setCityFromOSM(String cityFromOSM) { this.cityFromOSM = cityFromOSM; } public String getCountryFromGeocoding() { return countryFromGeocoding; } public void setCountryFromGeocoding(String countryFromGeocoding) { this.countryFromGeocoding = countryFromGeocoding; } public String getPostcodeFromGeocoding() { return postcodeFromGeocoding; } public void setPostcodeFromGeocoding(String postcodeFromGeocoding) { this.postcodeFromGeocoding = postcodeFromGeocoding; } public String getCityFromGeocoding() { return cityFromGeocoding; } public void setCityFromGeocoding(String cityFromGeocoding) { this.cityFromGeocoding = cityFromGeocoding; } public DateTime getLastGeocodeAttempt() { return lastGeocodeAttempt; } public void setLastGeocodeAttempt(DateTime lastGeocodeAttempt) { this.lastGeocodeAttempt = lastGeocodeAttempt; } public String getHumanReadableLastGeocodeAttempt() { return humanReadableLastGeocodeAttempt; } public void setHumanReadableLastGeocodeAttempt(String humanReadableLastGeocodeAttempt) { this.humanReadableLastGeocodeAttempt = humanReadableLastGeocodeAttempt; } public double getQaScore() { return qaScore; } public void setQaScore(double qaScore) { this.qaScore = qaScore; } public void copyTo(OsmMosquePlace other) { other.setLon(getLon()); other.setLat(getLat()); other.setName(getName()); other.setType(getType()); other.setKey(getKey()); other.setValid(isValid()); other.setCountryFromDatafile(getCountryFromDatafile()); other.setPostcodeFromDatafile(getPostcodeFromDatafile()); other.setCityFromDatafile(getCityFromDatafile()); other.setCountryFromGeocoding(getCountryFromGeocoding()); other.setPostcodeFromGeocoding(getPostcodeFromGeocoding()); other.setCityFromGeocoding(getCityFromGeocoding()); other.setCountryFromOSM(getCountryFromOSM()); other.setPostcodeFromOSM(getPostcodeFromOSM()); other.setCityFromOSM(getCityFromOSM()); other.setLastGeocodeAttempt(getLastGeocodeAttempt()); other.setHumanReadableLastGeocodeAttempt(getHumanReadableLastGeocodeAttempt()); other.setQaScore(getQaScore()); if (getAddress() == null) { setAddress(new Address()); } if (other.getAddress() == null) { other.setAddress(new Address()); } getAddress().copyTo(other.getAddress()); if (getContact() == null) { setContact(new Contact()); } if (other.getContact() == null) { other.setContact(new Contact()); } getContact().copyTo(other.getContact()); } }
osm-mosque-persistence/src/main/java/com/gurkensalat/osm/mosques/entity/OsmMosquePlace.java
package com.gurkensalat.osm.mosques.entity; import com.gurkensalat.osm.entity.Address; import com.gurkensalat.osm.entity.Contact; import com.gurkensalat.osm.entity.OsmNode; import com.gurkensalat.osm.entity.OsmPlaceBase; import com.gurkensalat.osm.entity.OsmWay; import com.gurkensalat.osm.entity.PlaceType; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "MOSQUE_PLACES") public class OsmMosquePlace extends OsmPlaceBase { // Adapted from osmconvert, see // http://wiki.openstreetmap.org/wiki/Osmconvert#Dispose_of_Ways_and_Relations_and_Convert_them_to_Nodes private transient static final long WAY_OFFSET = (long) Math.pow(10, 15); @Column(name = "ADDR_COUNTRY_DATAFILE", length = 80) private String countryFromDatafile; @Column(name = "ADDR_COUNTRY_OSM", length = 80) private String countryFromOSM; @Column(name = "ADDR_COUNTRY_GEOCODING", length = 80) private String countryFromGeocoding; @Column(name = "ADDR_CITY_DATAFILE", length = 80) private String cityFromDatafile; @Column(name = "ADDR_CITY_OSM", length = 80) private String cityFromOSM; @Column(name = "ADDR_CITY_GEOCODING", length = 80) private String cityFromGeocoding; @Column(name = "LAST_GEOCODE_ATTEMPT") @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime lastGeocodeAttempt; @Transient private String humanReadableLastGeocodeAttempt; @Column(name = "QA_SCORE") private double qaScore; protected OsmMosquePlace() { } public OsmMosquePlace(String name, PlaceType type) { super(name, type); } public OsmMosquePlace(OsmNode node) { super(node); } public OsmMosquePlace(OsmWay way) { super(way); } public static long getWayOffset() { return WAY_OFFSET; } public boolean isOsmNode() { return ((getId() != null) && (WAY_OFFSET > getId())); } public boolean isOsmWay() { return ((getId() != null) && (WAY_OFFSET < getId())); } public String getCountryFromDatafile() { return countryFromDatafile; } public void setCountryFromDatafile(String countryFromDatafile) { this.countryFromDatafile = countryFromDatafile; } public String getCountryFromOSM() { return countryFromOSM; } public void setCountryFromOSM(String countryFromOSM) { this.countryFromOSM = countryFromOSM; } public String getCountryFromGeocoding() { return countryFromGeocoding; } public void setCountryFromGeocoding(String countryFromGeocoding) { this.countryFromGeocoding = countryFromGeocoding; } public String getCityFromDatafile() { return cityFromDatafile; } public void setCityFromDatafile(String cityFromDatafile) { this.cityFromDatafile = cityFromDatafile; } public String getCityFromOSM() { return cityFromOSM; } public void setCityFromOSM(String cityFromOSM) { this.cityFromOSM = cityFromOSM; } public String getCityFromGeocoding() { return cityFromGeocoding; } public void setCityFromGeocoding(String cityFromGeocoding) { this.cityFromGeocoding = cityFromGeocoding; } public DateTime getLastGeocodeAttempt() { return lastGeocodeAttempt; } public void setLastGeocodeAttempt(DateTime lastGeocodeAttempt) { this.lastGeocodeAttempt = lastGeocodeAttempt; } public String getHumanReadableLastGeocodeAttempt() { return humanReadableLastGeocodeAttempt; } public void setHumanReadableLastGeocodeAttempt(String humanReadableLastGeocodeAttempt) { this.humanReadableLastGeocodeAttempt = humanReadableLastGeocodeAttempt; } public double getQaScore() { return qaScore; } public void setQaScore(double qaScore) { this.qaScore = qaScore; } public void copyTo(OsmMosquePlace other) { other.setLon(getLon()); other.setLat(getLat()); other.setName(getName()); other.setType(getType()); other.setKey(getKey()); other.setValid(isValid()); other.setCountryFromDatafile(getCountryFromDatafile()); other.setCountryFromGeocoding(getCountryFromGeocoding()); other.setCountryFromOSM(getCountryFromOSM()); other.setCityFromDatafile(getCityFromDatafile()); other.setCityFromGeocoding(getCityFromGeocoding()); other.setCityFromOSM(getCityFromOSM()); other.setLastGeocodeAttempt(getLastGeocodeAttempt()); other.setHumanReadableLastGeocodeAttempt(getHumanReadableLastGeocodeAttempt()); other.setQaScore(getQaScore()); if (getAddress() == null) { setAddress(new Address()); } if (other.getAddress() == null) { other.setAddress(new Address()); } getAddress().copyTo(other.getAddress()); if (getContact() == null) { setContact(new Contact()); } if (other.getContact() == null) { other.setContact(new Contact()); } getContact().copyTo(other.getContact()); } }
Support in entity for reverse geocoding cities
osm-mosque-persistence/src/main/java/com/gurkensalat/osm/mosques/entity/OsmMosquePlace.java
Support in entity for reverse geocoding cities
<ide><path>sm-mosque-persistence/src/main/java/com/gurkensalat/osm/mosques/entity/OsmMosquePlace.java <ide> @Column(name = "ADDR_COUNTRY_DATAFILE", length = 80) <ide> private String countryFromDatafile; <ide> <add> @Column(name = "ADDR_POSTCODE_DATAFILE", length = 10) <add> private String postcodeFromDatafile; <add> <add> @Column(name = "ADDR_CITY_DATAFILE", length = 80) <add> private String cityFromDatafile; <add> <ide> @Column(name = "ADDR_COUNTRY_OSM", length = 80) <ide> private String countryFromOSM; <ide> <add> @Column(name = "ADDR_POSTCODE_OSM", length = 10) <add> private String postcodeFromOSM; <add> <add> @Column(name = "ADDR_CITY_OSM", length = 80) <add> private String cityFromOSM; <add> <ide> @Column(name = "ADDR_COUNTRY_GEOCODING", length = 80) <ide> private String countryFromGeocoding; <ide> <del> @Column(name = "ADDR_CITY_DATAFILE", length = 80) <del> private String cityFromDatafile; <del> <del> @Column(name = "ADDR_CITY_OSM", length = 80) <del> private String cityFromOSM; <add> @Column(name = "ADDR_POSTCODE_GEOCODING", length = 10) <add> private String postcodeFromGeocoding; <ide> <ide> @Column(name = "ADDR_CITY_GEOCODING", length = 80) <ide> private String cityFromGeocoding; <ide> this.countryFromDatafile = countryFromDatafile; <ide> } <ide> <add> public String getPostcodeFromDatafile() <add> { <add> return postcodeFromDatafile; <add> } <add> <add> public void setPostcodeFromDatafile(String postcodeFromDatafile) <add> { <add> this.postcodeFromDatafile = postcodeFromDatafile; <add> } <add> <add> public String getCityFromDatafile() <add> { <add> return cityFromDatafile; <add> } <add> <add> public void setCityFromDatafile(String cityFromDatafile) <add> { <add> this.cityFromDatafile = cityFromDatafile; <add> } <add> <ide> public String getCountryFromOSM() <ide> { <ide> return countryFromOSM; <ide> this.countryFromOSM = countryFromOSM; <ide> } <ide> <add> public String getPostcodeFromOSM() <add> { <add> return postcodeFromOSM; <add> } <add> <add> public void setPostcodeFromOSM(String postcodeFromOSM) <add> { <add> this.postcodeFromOSM = postcodeFromOSM; <add> } <add> <add> public String getCityFromOSM() <add> { <add> return cityFromOSM; <add> } <add> <add> public void setCityFromOSM(String cityFromOSM) <add> { <add> this.cityFromOSM = cityFromOSM; <add> } <add> <ide> public String getCountryFromGeocoding() <ide> { <ide> return countryFromGeocoding; <ide> this.countryFromGeocoding = countryFromGeocoding; <ide> } <ide> <del> public String getCityFromDatafile() <del> { <del> return cityFromDatafile; <del> } <del> <del> public void setCityFromDatafile(String cityFromDatafile) <del> { <del> this.cityFromDatafile = cityFromDatafile; <del> } <del> <del> public String getCityFromOSM() <del> { <del> return cityFromOSM; <del> } <del> <del> public void setCityFromOSM(String cityFromOSM) <del> { <del> this.cityFromOSM = cityFromOSM; <add> public String getPostcodeFromGeocoding() <add> { <add> return postcodeFromGeocoding; <add> } <add> <add> public void setPostcodeFromGeocoding(String postcodeFromGeocoding) <add> { <add> this.postcodeFromGeocoding = postcodeFromGeocoding; <ide> } <ide> <ide> public String getCityFromGeocoding() <ide> other.setValid(isValid()); <ide> <ide> other.setCountryFromDatafile(getCountryFromDatafile()); <add> other.setPostcodeFromDatafile(getPostcodeFromDatafile()); <add> other.setCityFromDatafile(getCityFromDatafile()); <add> <ide> other.setCountryFromGeocoding(getCountryFromGeocoding()); <add> other.setPostcodeFromGeocoding(getPostcodeFromGeocoding()); <add> other.setCityFromGeocoding(getCityFromGeocoding()); <add> <ide> other.setCountryFromOSM(getCountryFromOSM()); <del> <del> other.setCityFromDatafile(getCityFromDatafile()); <del> other.setCityFromGeocoding(getCityFromGeocoding()); <add> other.setPostcodeFromOSM(getPostcodeFromOSM()); <ide> other.setCityFromOSM(getCityFromOSM()); <ide> <ide> other.setLastGeocodeAttempt(getLastGeocodeAttempt());
JavaScript
mit
07bbd5708064dee05c72ae0b515be8a638c0c099
0
IrregularShed/nodal,rlugojr/nodal,IrregularShed/nodal,abossard/nodal,nsipplswezey/nodal,nsipplswezey/nodal,abossard/nodal,keithwhor/nodal,nsipplswezey/nodal
#!/usr/bin/env node "use strict"; (function() { const colors = require('colors/safe'); const fs = require('fs'); const path = require('path'); let command = process.argv.slice(2, 3).pop(); command = command ? command : ''; // Make sure we are in a project directory if ((command !== 'new') && (command !== 'help') && (!fs.existsSync(process.cwd() + '/.nodal'))) { console.error(colors.red.bold('Error: ') + 'No Nodal project found here. Use `nodal new` to initialize a project.'); console.error(colors.green('Help: ') + 'Type `nodal help` to get more information about what Nodal can do for you.'); process.exit(1); } let args = []; let flags = {}; // Parse arguments & flags from argv process.argv.slice(3).forEach(function(v) { let values = v.split(':'); if (v.substr(0, 2) === '--') { values[0] = values[0].substr(2); flags[values[0]] = values[1]; } else { args.push(values); } }); // A Map that stores all commands let commandMap = new Map(); // Command Definition class Command { constructor(cmd, options, fn, def, prefix) { this._cmd = cmd; this._name = cmd.split(' ')[0]; this._prefix = prefix; this._options = options || {}; this._ext = (this._options.ext || []); this._ext.unshift(cmd.split(' ').splice(1).join(' ')); this._def = def; this._fn = fn; this._order = (this._name === 'help')?-1:Math.abs(this._options.order || 100); commandMap.set(this.index(), this); } index() { return ((this._prefix)?(this._prefix + ':'):'') + this._name; } full() { return ((this._prefix)?(this._prefix + ':'):'') + this._cmd; } ext(n) { return this._ext[n || 0]; } extLength() { return this._ext.length; } isHidden() { return (this._options.hidden === true); } getDefinition() { return this._def; } exec(args, flags, callback) { if(typeof this._fn !== 'function') return callback(new Error("Method not implemented yet.")); // Prevent throws (overhead is not important in CLI) try { this._fn(args, flags, callback); }catch(e) { callback(e); } } } // Internally implemented commands (require access to Set) // // Define `nodal help` command new Command("help", null, (args, flags, callback) => { let repeatChar = (char, r) => { // Repeats a character to create a string // Useful for logging var str = ''; for (var i = 0; i < Math.ceil(r); i++) str += char; return str; }; console.log(''); console.log(' Nodal commands'); console.log(''); let highPad = 0; // Find the longest length (deep search to include ext) commandMap.forEach((command) => { if(command.full().length > highPad) highPad = command.full().length; // Start at 1 to skip above for(let i = 1; i < command.extLength(); i++) { if(command.ext(i).length > highPad) highPad = command.ext(i).split('#')[0].length + command.full().split(' ')[0].length; } }); // Sort Command map let commandsList = []; // We use commandsList to store all the keys for(var key of commandMap.keys()) { commandsList.push(key); } // Sort the keys based on Class options commandsList.sort((a, b) => { return commandMap.get(a)._order - commandMap.get(b)._order; }); // Go through the sorted keys commandsList.forEach((key) => { // Get the actual class let command = commandMap.get(key); // If command is hidden continue (return in case of forEach) if(command.isHidden()) return; // Extract base command (e.g. `g:model`) let fullCommand = command.full(); let padding = ''; // Add padding to the end if(fullCommand.length < highPad) padding = repeatChar(' ', highPad - fullCommand.length); // Parse Command to colorize let splitCommand = fullCommand.split(' '); let baseCommand = splitCommand.shift(); let tags = splitCommand.join(' '); let definition = command.getDefinition(); console.log(colors.yellow.bold(' nodal ' + baseCommand.toLowerCase()), (tags)?colors.gray(tags):'', padding, '\t' + definition); // SubCommand we start at 1 to skip the original (printed above) for(let i = 1; i < command.extLength(); i++) { let localDef = command.ext(i).split('#'); let localCommand = localDef.shift(); let localPad = repeatChar(' ', (highPad - baseCommand.length - localCommand.length)); console.log(colors.yellow.bold(' nodal ' + baseCommand.toLowerCase()), colors.gray(localCommand.toLowerCase()), localPad, '\t' + localDef.join('')); } // Line under console.log(colors.gray(repeatChar('-', highPad + 7))); }); callback(); }, "Help and information on all Nodal CLI commands"); // Recursive Importer let commandDir = path.resolve(__dirname, 'commands'); let commandFiles = fs.readdirSync(commandDir); for(let i = 0; i < commandFiles.length; i++) { // Make sure task is a .js file if(!path.extname(commandFiles[i])) continue; // Require command file & pass Command class to it require(path.resolve(commandDir, commandFiles[i]))(Command); } // Check if our constructed Map has the command if(commandMap.has(command)) { commandMap.get(command).exec(args, flags, function(error) { if(error) { console.error(colors.red.bold('Error: ') + error.message); // Append help to all errors console.log(colors.green('Help: ') + 'Type `nodal help` to get more information about what Nodal can do for you.'); } process.exit((error)?1:0); }); }else{ console.error(colors.red.bold('Error: ') + 'Command "' + command + '" not found'); console.log(colors.green('Help: ') + 'Type `nodal help` to get more information about what Nodal can do for you.'); } })();
cli/cli.js
#!/usr/bin/env node "use strict"; (function() { const colors = require('colors/safe'); const fs = require('fs'); const path = require('path'); let command = process.argv.slice(2, 3).pop(); command = command ? command : '_base_'; // Make sure we are in a project directory if ((command !== 'new') && (command !== 'help') && (!fs.existsSync(process.cwd() + '/.nodal'))) { console.error(colors.red.bold('Error: ') + 'No Nodal project found here. Use `nodal new` to initialize a project.'); console.error(colors.green('Help: ') + 'Type `nodal help` to get more information about what Nodal can do for you.'); process.exit(1); } let args = []; let flags = {}; // Parse arguments & flags from argv process.argv.slice(3).forEach(function(v) { let values = v.split(':'); if (v.substr(0, 2) === '--') { values[0] = values[0].substr(2); flags[values[0]] = values[1]; } else { args.push(values); } }); // A Map that stores all commands let commandMap = new Map(); // Command Definition class Command { constructor(cmd, options, fn, def, prefix) { this._cmd = cmd; this._name = cmd.split(' ')[0]; this._prefix = prefix; this._options = options || {}; this._ext = (this._options.ext || []); this._ext.unshift(cmd.split(' ').splice(1).join(' ')); this._def = def; this._fn = fn; this._order = (this._name === 'help')?-1:Math.abs(this._options.order || 100); commandMap.set(this.index(), this); } index() { return ((this._prefix)?(this._prefix + ':'):'') + this._name; } full() { return ((this._prefix)?(this._prefix + ':'):'') + this._cmd; } ext(n) { return this._ext[n || 0]; } extLength() { return this._ext.length; } isHidden() { return (this._options.hidden === true); } getDefinition() { return this._def; } exec(args, flags, callback) { if(typeof this._fn !== 'function') return callback(new Error("Method not implemented yet.")); // Prevent throws (overhead is not important in CLI) try { this._fn(args, flags, callback); }catch(e) { callback(e); } } } // Internally implemented commands (require access to Set) // // Define `nodal help` command new Command("help", null, (args, flags, callback) => { let repeatChar = (char, r) => { // Repeats a character to create a string // Useful for logging var str = ''; for (var i = 0; i < Math.ceil(r); i++) str += char; return str; }; console.log(''); console.log(' Nodal commands'); console.log(''); let highPad = 0; // Find the longest length (deep search to include ext) commandMap.forEach((command) => { if(command.full().length > highPad) highPad = command.full().length; // Start at 1 to skip above for(let i = 1; i < command.extLength(); i++) { if(command.ext(i).length > highPad) highPad = command.ext(i).split('#')[0].length + command.full().split(' ')[0].length; } }); // Sort Command map let commandsList = []; // We use commandsList to store all the keys for(var key of commandMap.keys()) { commandsList.push(key); } // Sort the keys based on Class options commandsList.sort((a, b) => { return commandMap.get(a)._order - commandMap.get(b)._order; }); // Go through the sorted keys commandsList.forEach((key) => { // Get the actual class let command = commandMap.get(key); // If command is hidden continue (return in case of forEach) if(command.isHidden()) return; // Extract base command (e.g. `g:model`) let fullCommand = command.full(); let padding = ''; // Add padding to the end if(fullCommand.length < highPad) padding = repeatChar(' ', highPad - fullCommand.length); // Parse Command to colorize let splitCommand = fullCommand.split(' '); let baseCommand = splitCommand.shift(); let tags = splitCommand.join(' '); let definition = command.getDefinition(); console.log(colors.yellow.bold(' nodal ' + baseCommand.toLowerCase()), (tags)?colors.gray(tags):'', padding, '\t' + definition); // SubCommand we start at 1 to skip the original (printed above) for(let i = 1; i < command.extLength(); i++) { let localDef = command.ext(i).split('#'); let localCommand = localDef.shift(); let localPad = repeatChar(' ', (highPad - baseCommand.length - localCommand.length)); console.log(colors.yellow.bold(' nodal ' + baseCommand.toLowerCase()), colors.gray(localCommand.toLowerCase()), localPad, '\t' + localDef.join('')); } // Line under console.log(colors.gray(repeatChar('-', highPad + 7))); }); callback(); }, "Help and information on all Nodal CLI commands"); // Recursive Importer let commandDir = path.resolve(__dirname, 'commands'); let commandFiles = fs.readdirSync(commandDir); for(let i = 0; i < commandFiles.length; i++) { // Make sure task is a .js file if(!path.extname(commandFiles[i])) continue; // Require command file & pass Command class to it require(path.resolve(commandDir, commandFiles[i]))(Command); } // Check if our constructed Map has the command if(commandMap.has(command)) { commandMap.get(command).exec(args, flags, function(error) { if(error) { console.error(colors.red.bold('Error: ') + error.message); // Append help to all errors console.log(colors.green('Help: ') + 'Type `nodal help` to get more information about what Nodal can do for you.'); } process.exit((error)?1:0); }); }else{ console.error(colors.red.bold('Error: ') + 'Command "' + command + '" not found'); console.log(colors.green('Help: ') + 'Type `nodal help` to get more information about what Nodal can do for you.'); } })();
_base_ is no longer a thing
cli/cli.js
_base_ is no longer a thing
<ide><path>li/cli.js <ide> <ide> let command = process.argv.slice(2, 3).pop(); <ide> <del> command = command ? command : '_base_'; <add> command = command ? command : ''; <ide> <ide> // Make sure we are in a project directory <ide> if ((command !== 'new') && (command !== 'help') && (!fs.existsSync(process.cwd() + '/.nodal'))) {
Java
apache-2.0
8f96cf727033a53dc1c87a3cf6e23564abf13965
0
masaki-yamakawa/geode,pdxrunner/geode,jdeppe-pivotal/geode,charliemblack/geode,pivotal-amurmann/geode,smgoller/geode,davinash/geode,shankarh/geode,pdxrunner/geode,davinash/geode,prasi-in/geode,smanvi-pivotal/geode,PurelyApplied/geode,PurelyApplied/geode,jdeppe-pivotal/geode,pivotal-amurmann/geode,PurelyApplied/geode,prasi-in/geode,sshcherbakov/incubator-geode,smanvi-pivotal/geode,deepakddixit/incubator-geode,deepakddixit/incubator-geode,smgoller/geode,jdeppe-pivotal/geode,PurelyApplied/geode,PurelyApplied/geode,davebarnes97/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,masaki-yamakawa/geode,davebarnes97/geode,davinash/geode,PurelyApplied/geode,jdeppe-pivotal/geode,charliemblack/geode,shankarh/geode,smgoller/geode,davebarnes97/geode,masaki-yamakawa/geode,deepakddixit/incubator-geode,prasi-in/geode,pivotal-amurmann/geode,davinash/geode,jdeppe-pivotal/geode,davebarnes97/geode,charliemblack/geode,jdeppe-pivotal/geode,davebarnes97/geode,smgoller/geode,smgoller/geode,PurelyApplied/geode,pivotal-amurmann/geode,pivotal-amurmann/geode,sshcherbakov/incubator-geode,sshcherbakov/incubator-geode,deepakddixit/incubator-geode,davinash/geode,pdxrunner/geode,davinash/geode,deepakddixit/incubator-geode,charliemblack/geode,smgoller/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,smanvi-pivotal/geode,pdxrunner/geode,pdxrunner/geode,smanvi-pivotal/geode,shankarh/geode,smgoller/geode,masaki-yamakawa/geode,davebarnes97/geode,shankarh/geode,pdxrunner/geode,prasi-in/geode,smanvi-pivotal/geode,sshcherbakov/incubator-geode,davebarnes97/geode,shankarh/geode,jdeppe-pivotal/geode,prasi-in/geode,davinash/geode,deepakddixit/incubator-geode,pdxrunner/geode,charliemblack/geode
/* * 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.gemstone.gemfire.management.internal.beans; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.management.JMRuntimeException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.logging.log4j.Logger; import com.gemstone.gemfire.Statistics; import com.gemstone.gemfire.StatisticsType; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.DiskStore; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.execute.FunctionService; import com.gemstone.gemfire.cache.hdfs.internal.HDFSStoreImpl; import com.gemstone.gemfire.cache.persistence.PersistentID; import com.gemstone.gemfire.cache.wan.GatewayReceiver; import com.gemstone.gemfire.cache.wan.GatewaySender; import com.gemstone.gemfire.distributed.Locator; import com.gemstone.gemfire.distributed.LocatorLauncher; import com.gemstone.gemfire.distributed.ServerLauncher; import com.gemstone.gemfire.distributed.internal.DM; import com.gemstone.gemfire.distributed.internal.DistributionConfig; import com.gemstone.gemfire.distributed.internal.DistributionManager; import com.gemstone.gemfire.distributed.internal.DistributionStats; import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; import com.gemstone.gemfire.distributed.internal.locks.DLockService; import com.gemstone.gemfire.distributed.internal.locks.DLockStats; import com.gemstone.gemfire.internal.Assert; import com.gemstone.gemfire.internal.GemFireStatSampler; import com.gemstone.gemfire.internal.GemFireVersion; import com.gemstone.gemfire.internal.HostStatHelper; import com.gemstone.gemfire.internal.LinuxSystemStats; import com.gemstone.gemfire.internal.ProcessStats; import com.gemstone.gemfire.internal.PureJavaMode; import com.gemstone.gemfire.internal.SocketCreator; import com.gemstone.gemfire.internal.SolarisSystemStats; import com.gemstone.gemfire.internal.StatSamplerStats; import com.gemstone.gemfire.internal.VMStatsContract; import com.gemstone.gemfire.internal.WindowsSystemStats; import com.gemstone.gemfire.internal.cache.CachePerfStats; import com.gemstone.gemfire.internal.cache.CacheServerLauncher; import com.gemstone.gemfire.internal.cache.DirectoryHolder; import com.gemstone.gemfire.internal.cache.DiskDirectoryStats; import com.gemstone.gemfire.internal.cache.DiskRegion; import com.gemstone.gemfire.internal.cache.DiskStoreImpl; import com.gemstone.gemfire.internal.cache.DiskStoreStats; import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; import com.gemstone.gemfire.internal.cache.LocalRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegionStats; import com.gemstone.gemfire.internal.cache.control.ResourceManagerStats; import com.gemstone.gemfire.internal.cache.execute.FunctionServiceStats; import com.gemstone.gemfire.internal.cache.lru.LRUStatistics; import com.gemstone.gemfire.internal.cache.persistence.BackupManager; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gemfire.internal.logging.LogService; import com.gemstone.gemfire.internal.logging.ManagerLogWriter; import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage; import com.gemstone.gemfire.internal.logging.log4j.LogMarker; import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppender; import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppenders; import com.gemstone.gemfire.internal.offheap.MemoryAllocator; import com.gemstone.gemfire.internal.offheap.OffHeapMemoryStats; import com.gemstone.gemfire.internal.process.PidUnavailableException; import com.gemstone.gemfire.internal.process.ProcessUtils; import com.gemstone.gemfire.internal.stats50.VMStats50; import com.gemstone.gemfire.internal.tcp.ConnectionTable; import com.gemstone.gemfire.management.DependenciesNotFoundException; import com.gemstone.gemfire.management.DiskBackupResult; import com.gemstone.gemfire.management.GemFireProperties; import com.gemstone.gemfire.management.JVMMetrics; import com.gemstone.gemfire.management.ManagementException; import com.gemstone.gemfire.management.OSMetrics; import com.gemstone.gemfire.management.cli.CommandService; import com.gemstone.gemfire.management.cli.CommandServiceException; import com.gemstone.gemfire.management.cli.Result; import com.gemstone.gemfire.management.internal.ManagementConstants; import com.gemstone.gemfire.management.internal.ManagementStrings; import com.gemstone.gemfire.management.internal.SystemManagementService; import com.gemstone.gemfire.management.internal.beans.stats.AggregateRegionStatsMonitor; import com.gemstone.gemfire.management.internal.beans.stats.GCStatsMonitor; import com.gemstone.gemfire.management.internal.beans.stats.MBeanStatsMonitor; import com.gemstone.gemfire.management.internal.beans.stats.MemberLevelDiskMonitor; import com.gemstone.gemfire.management.internal.beans.stats.StatType; import com.gemstone.gemfire.management.internal.beans.stats.StatsAverageLatency; import com.gemstone.gemfire.management.internal.beans.stats.StatsKey; import com.gemstone.gemfire.management.internal.beans.stats.StatsLatency; import com.gemstone.gemfire.management.internal.beans.stats.StatsRate; import com.gemstone.gemfire.management.internal.beans.stats.VMStatsMonitor; import com.gemstone.gemfire.management.internal.cli.CommandResponseBuilder; import com.gemstone.gemfire.management.internal.cli.remote.CommandExecutionContext; import com.gemstone.gemfire.management.internal.cli.remote.MemberCommandService; import com.gemstone.gemfire.management.internal.cli.result.CommandResult; import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder; import com.gemstone.gemfire.management.internal.cli.shell.Gfsh; /** * This class acts as an Bridge between MemberMBean and GemFire Cache and * Distributed System * * @author rishim * */ public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ public static MBeanServer mbeanServer = ManagementFactory .getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; private static TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private GemFireCacheImpl cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DM dm; /** * Command Service */ private CommandService commandService; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(GemFireCacheImpl cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if(dm instanceof DistributionManager){ DistributionManager distManager = (DistributionManager)system.getDistributionManager(); this.redundancyZone = distManager.getRedundancyZone(cache.getDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandService = CommandService.createLocalCommandService(cache); } catch (CacheClosedException e) { commandServiceInitError = e.getMessage(); // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage(), e); } catch (CommandServiceException e) { commandServiceInitError = e.getMessage(); // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage(), e); } catch (DependenciesNotFoundException e) { commandServiceInitError = e.getMessage(); if (CacheServerLauncher.isDedicatedCacheServer) { // log as error for dedicated cache server - launched through script // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage()); } else { // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage()); } } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ex) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); //Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor(ManagementStrings.MEMBER_CACHE_MONITOR .toLocalizedString()); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor(ManagementStrings.GC_STATS_MONITOR .toLocalizedString()); this.vmStatsMonitor = new VMStatsMonitor(ManagementStrings.VM_STATS_MONITOR .toLocalizedString()); this.systemStatsMonitor = new MBeanStatsMonitor(ManagementStrings.SYSTEM_STATS_MONITOR .toLocalizedString()); //Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getResourceManager().getStats(); } public MemberMBeanBridge(){ this.monitor = new MBeanStatsMonitor(ManagementStrings.MEMBER_CACHE_MONITOR .toLocalizedString()); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor(ManagementStrings.GC_STATS_MONITOR .toLocalizedString()); this.vmStatsMonitor = new VMStatsMonitor(ManagementStrings.VM_STATS_MONITOR .toLocalizedString()); this.systemStatsMonitor = new MBeanStatsMonitor(ManagementStrings.SYSTEM_STATS_MONITOR .toLocalizedString()); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = ((GemFireCacheImpl) cache) .getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system .getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;//@TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = ((GemFireCacheImpl) cache).getOffHeapStore(); if((null != allocator) ) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if(null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats){ diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats){ diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region ){ if(region.getAttributes().getPartitionAttributes() != null){ addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; if(l.getEvictionController() != null){ LRUStatistics stats = l.getEvictionController().getLRUHelper().getStats(); if (stats != null) { addLRUStats(stats); } } DiskRegion dr = l.getDiskRegion(); if(dr != null){ for(DirectoryHolder dh:dr.getDirectories()){ addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats){ regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(LRUStatistics lruStats){ regionMonitor.addStatisticsToMonitor(lruStats.getStats()); } public void addDirectoryStats(DiskDirectoryStats diskDirStats){ regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region ){ if(region.getAttributes().getPartitionAttributes() != null){ removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; if(l.getEvictionController() != null){ LRUStatistics stats = l.getEvictionController().getLRUHelper().getStats(); if (stats != null) { removeLRUStats(stats); } } DiskRegion dr = l.getDiskRegion(); if(dr != null){ for(DirectoryHolder dh:dr.getDirectories()){ removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(LRUStatistics lruStats) { regionMonitor.removeLRUStatistics(lruStats.getStats()); } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock){ if(!lockStatsAdded){ DLockStats stats = (DLockStats)lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats){ monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if(samplerStats != null){ systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats(){ VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50){ VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } //vmStatsMonitor.addStatisticsToMonitor(vm50.getVMNonHeapStats()); StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0){ for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor(){ monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats(){ createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate( StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate( StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate( StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate( StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate( StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate( StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate( StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency( StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency( StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency( StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency( StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency( StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency( StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency( StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency( StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency( StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency( StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency( StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency( StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate( StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate( StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate( StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS) .longValue(); long gcTimeMillis = getGCStatistic( StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); //Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS) .intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in * java.lang.management.OperatingSystemMXBean It has to be cast to * com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic * call so that Java platform will take care of the details in a native * manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic( StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME) .longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception e) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute( osObjectName, "CommittedVirtualMemorySize"); } catch (Exception e) { committedVirtualMemorySize = -1; } //If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get( StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception e) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get( StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception e) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get( StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception e) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get( StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception e) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if(logger.isTraceEnabled()){ logger.trace(ex.getMessage(), ex); } } return metrics; } /** * * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk * stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache; List<String> compactedStores = new ArrayList<String>(); if (cache != null && !cache.isClosed()) { for (DiskStoreImpl store : cacheImpl.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(store.getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned * indicates whether to show the disk belonging to any particular * region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache; String[] retStr = null; Collection<DiskStoreImpl> diskCollection = null; if (includeRegionOwned) { diskCollection = cacheImpl.listDiskStoresIncludingRegionOwned(); } else { diskCollection = cacheImpl.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator<DiskStoreImpl> it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return list all the HDFSStore's name at cache level */ public String[] getHDFSStores() { GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache; String[] retStr = null; Collection<HDFSStoreImpl> hdfsStoreCollection = null; hdfsStoreCollection = cacheImpl.getHDFSStores(); if (hdfsStoreCollection != null && hdfsStoreCollection.size() > 0) { retStr = new String[hdfsStoreCollection.size()]; Iterator<HDFSStoreImpl> it = hdfsStoreCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * * @return log of the member. */ public String fetchLog(int numLines){ if(numLines > ManagementConstants.MAX_SHOW_LOG_LINES){ numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if(numLines == 0 || numLines < 0){ numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; LogWriterAppender lwa = LogWriterAppenders.getAppender(LogWriterAppenders.Identifier.MAIN); if (lwa != null) { childTail = BeanUtilFuncs.tailSystemLog(lwa.getChildLogFile(),numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = LocalizedStrings.TailLogResponse_NO_LOG_FILE_WAS_SPECIFIED_IN_THE_CONFIGURATION_MESSAGES_WILL_BE_DIRECTED_TO_STDOUT .toLocalizedString(); } } else { Assert .assertTrue(false, "TailLogRequest/Response processed in application vm with shared logging."); } } catch (IOException e) { logger.warn(LocalizedMessage.create(LocalizedStrings.TailLogResponse_ERROR_OCCURRED_WHILE_READING_SYSTEM_LOG__0, e)); mainTail = ""; } if (childTail == null && mainTail == null) { return LocalizedStrings.SystemMemberImpl_NO_LOG_FILE_CONFIGURED_LOG_MESSAGES_WILL_BE_DIRECTED_TO_STDOUT .toLocalizedString(); } else { StringBuffer result = new StringBuffer(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append("\n" + LocalizedStrings.SystemMemberImpl_TAIL_OF_CHILD_LOG .toLocalizedString() + "\n"); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by * FunctionService. Might cause problems in cleaning up function related * resources. Aggregate bean DistributedSystemMBean will have to depend on * GemFire messages to decide whether all the members have been shutdown or * not before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new Thread(new Runnable() { public void run() { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException e) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } } }); t.setDaemon(false); t.start(); } } /** * backs up all the disk to the targeted directory * * @param targetDirPath * path of the directory where back up is to be taken * @return array of DiskBackup results which might get aggregated at Managing * node * * Check the validity of this mbean call. When does it make sense to backup a single member of a gemfire system * in isolation of the other members? */ public DiskBackupResult[] backupMember(String targetDirPath) { GemFireCacheImpl cache = GemFireCacheImpl.getInstance(); if (cache != null) { Collection<DiskStoreImpl> diskStores = cache .listDiskStoresIncludingRegionOwned(); for (DiskStoreImpl store : diskStores) { store.flush(); } } DiskBackupResult[] diskBackUpResult = null; File targetDir = new File(targetDirPath); if (cache == null) { return null; } else { try { BackupManager manager = cache.startBackup(cache.getDistributedSystem() .getDistributedMember()); Set<PersistentID> existingDataStores = manager.prepareBackup(); Set<PersistentID> successfulDataStores = manager .finishBackup(targetDir, null/* TODO rishi */); diskBackUpResult = new DiskBackupResult[existingDataStores.size()]; int j = 0; for (PersistentID id : existingDataStores) { if (successfulDataStores.contains(id)) { diskBackUpResult[j] = new DiskBackupResult(id.getDirectory(), false); } else { diskBackUpResult[j] = new DiskBackupResult(id.getDirectory(), true); } j++; } } catch (IOException e) { throw new ManagementException(e); } } return diskBackUpResult; } /** * * @return The name for this member. */ public String getName() { return name; } /** * * @return The ID for this member. */ public String getId() { return id; } /** * * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List<String> groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set<GatewayReceiver> receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set<GatewaySender> senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not limited to: Locators, * Managers, Cache Servers and so on. * </p> * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { //if (isLocator()) { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } //else if (isServer()) { else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); long bytesUsed = memHeap.getUsed(); return bytesUsed; } /** * * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList<String> thrdStr = new ArrayList<String>(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * * @return list of regions */ public String[] getListOfRegions() { Set<LocalRegion> listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (LocalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * * @return root region names */ public String[] getRootRegionNames() { Set<LocalRegion> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionStr = new String[listOfRootRegions.size()]; int j = 0; for (LocalRegion rg : listOfRootRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * * @return true if member contains one locator. From 7.0 only locator can be * hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * * @return true if the Federating Manager Thread is running */ public boolean isManager() { GemFireCacheImpl existingCache = GemFireCacheImpl.getInstance(); if (existingCache == null || existingCache.isClosed()) { return false; } try{ boolean isManager = service.isManager(); return isManager; }catch(Exception e){ return false; } } /** * Returns true if the manager has been created. * Note it does not need to be running so this * method can return true when isManager returns false. * @return true if the manager has been created. */ public boolean isManagerCreated() { GemFireCacheImpl existingCache = GemFireCacheImpl.getInstance(); if (existingCache == null || existingCache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch(Exception e) { return false; } } /** * * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } /** Statistics Related Attributes **/ /*********************************************************************************************************/ public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED) .intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgres() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS) .intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME) .longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING) .intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic( StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information * if it's non-empty. Result returned is in a JSON format. * * @param commandString * command string to be processed * @param env * environment information to be used for processing the command * @return result of the processing the given command string. */ public String processCommand(String commandString, Map<String, String> env) { if (commandService == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: "+commandServiceInitError); } boolean isGfshRequest = isGfshRequest(env); if (isGfshRequest) { CommandExecutionContext.setShellRequest(); } // System.out.println("isGfshRequest :: "+isGfshRequest); Result result = ((MemberCommandService)commandService).processCommand(commandString, env); if (!(result instanceof CommandResult)) {// TODO - Abhishek - Shouldn't be needed while (result.hasNextLine()) { result = ResultBuilder.createInfoResult(result.nextLine()); } } if (isGfshRequest) { String responseJson = CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); // System.out.println("responseJson :: "+responseJson); return responseJson; } else { return ResultBuilder.resultAsString(result); } } private boolean isGfshRequest(Map<String, String> env) { String appName = null; if (env != null) { appName = env.get(Gfsh.ENV_APP_NAME); } // System.out.println("appName :: "+appName); return Gfsh.GFSH_APP_NAME.equals(appName); } public long getTotalDiskUsage() { long diskSpaceUsage = regionMonitor.getDiskSpace(); return diskSpaceUsage; } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception e) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if(!osName.startsWith(ManagementConstants.LINUX_SYSTEM)){ return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { objects = stats.getObjects(); } return objects; } @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { compactionTime = stats.getCompactionTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if(null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } }
gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.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.gemstone.gemfire.management.internal.beans; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.management.JMRuntimeException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.logging.log4j.Logger; import com.gemstone.gemfire.Statistics; import com.gemstone.gemfire.StatisticsType; import com.gemstone.gemfire.cache.CacheClosedException; import com.gemstone.gemfire.cache.DiskStore; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.execute.FunctionService; import com.gemstone.gemfire.cache.hdfs.internal.HDFSStoreImpl; import com.gemstone.gemfire.cache.persistence.PersistentID; import com.gemstone.gemfire.cache.wan.GatewayReceiver; import com.gemstone.gemfire.cache.wan.GatewaySender; import com.gemstone.gemfire.distributed.Locator; import com.gemstone.gemfire.distributed.LocatorLauncher; import com.gemstone.gemfire.distributed.ServerLauncher; import com.gemstone.gemfire.distributed.internal.DM; import com.gemstone.gemfire.distributed.internal.DistributionConfig; import com.gemstone.gemfire.distributed.internal.DistributionManager; import com.gemstone.gemfire.distributed.internal.DistributionStats; import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem; import com.gemstone.gemfire.distributed.internal.locks.DLockService; import com.gemstone.gemfire.distributed.internal.locks.DLockStats; import com.gemstone.gemfire.internal.Assert; import com.gemstone.gemfire.internal.GemFireStatSampler; import com.gemstone.gemfire.internal.GemFireVersion; import com.gemstone.gemfire.internal.HostStatHelper; import com.gemstone.gemfire.internal.LinuxSystemStats; import com.gemstone.gemfire.internal.ProcessStats; import com.gemstone.gemfire.internal.PureJavaMode; import com.gemstone.gemfire.internal.SocketCreator; import com.gemstone.gemfire.internal.SolarisSystemStats; import com.gemstone.gemfire.internal.StatSamplerStats; import com.gemstone.gemfire.internal.VMStatsContract; import com.gemstone.gemfire.internal.WindowsSystemStats; import com.gemstone.gemfire.internal.cache.CachePerfStats; import com.gemstone.gemfire.internal.cache.CacheServerLauncher; import com.gemstone.gemfire.internal.cache.DirectoryHolder; import com.gemstone.gemfire.internal.cache.DiskDirectoryStats; import com.gemstone.gemfire.internal.cache.DiskRegion; import com.gemstone.gemfire.internal.cache.DiskStoreImpl; import com.gemstone.gemfire.internal.cache.DiskStoreStats; import com.gemstone.gemfire.internal.cache.GemFireCacheImpl; import com.gemstone.gemfire.internal.cache.LocalRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegion; import com.gemstone.gemfire.internal.cache.PartitionedRegionStats; import com.gemstone.gemfire.internal.cache.control.ResourceManagerStats; import com.gemstone.gemfire.internal.cache.execute.FunctionServiceStats; import com.gemstone.gemfire.internal.cache.lru.LRUStatistics; import com.gemstone.gemfire.internal.cache.persistence.BackupManager; import com.gemstone.gemfire.internal.i18n.LocalizedStrings; import com.gemstone.gemfire.internal.logging.LogService; import com.gemstone.gemfire.internal.logging.ManagerLogWriter; import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage; import com.gemstone.gemfire.internal.logging.log4j.LogMarker; import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppender; import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppenders; import com.gemstone.gemfire.internal.offheap.MemoryAllocator; import com.gemstone.gemfire.internal.offheap.OffHeapMemoryStats; import com.gemstone.gemfire.internal.process.PidUnavailableException; import com.gemstone.gemfire.internal.process.ProcessUtils; import com.gemstone.gemfire.internal.stats50.VMStats50; import com.gemstone.gemfire.internal.tcp.ConnectionTable; import com.gemstone.gemfire.management.DependenciesNotFoundException; import com.gemstone.gemfire.management.DiskBackupResult; import com.gemstone.gemfire.management.GemFireProperties; import com.gemstone.gemfire.management.JVMMetrics; import com.gemstone.gemfire.management.ManagementException; import com.gemstone.gemfire.management.OSMetrics; import com.gemstone.gemfire.management.cli.CommandService; import com.gemstone.gemfire.management.cli.CommandServiceException; import com.gemstone.gemfire.management.cli.Result; import com.gemstone.gemfire.management.internal.ManagementConstants; import com.gemstone.gemfire.management.internal.ManagementStrings; import com.gemstone.gemfire.management.internal.SystemManagementService; import com.gemstone.gemfire.management.internal.beans.stats.AggregateRegionStatsMonitor; import com.gemstone.gemfire.management.internal.beans.stats.GCStatsMonitor; import com.gemstone.gemfire.management.internal.beans.stats.MBeanStatsMonitor; import com.gemstone.gemfire.management.internal.beans.stats.MemberLevelDiskMonitor; import com.gemstone.gemfire.management.internal.beans.stats.StatType; import com.gemstone.gemfire.management.internal.beans.stats.StatsAverageLatency; import com.gemstone.gemfire.management.internal.beans.stats.StatsKey; import com.gemstone.gemfire.management.internal.beans.stats.StatsLatency; import com.gemstone.gemfire.management.internal.beans.stats.StatsRate; import com.gemstone.gemfire.management.internal.beans.stats.VMStatsMonitor; import com.gemstone.gemfire.management.internal.cli.CommandResponseBuilder; import com.gemstone.gemfire.management.internal.cli.remote.CommandExecutionContext; import com.gemstone.gemfire.management.internal.cli.remote.MemberCommandService; import com.gemstone.gemfire.management.internal.cli.result.CommandResult; import com.gemstone.gemfire.management.internal.cli.result.ResultBuilder; import com.gemstone.gemfire.management.internal.cli.shell.Gfsh; /** * This class acts as an Bridge between MemberMBean and GemFire Cache and * Distributed System * * @author rishim * */ public class MemberMBeanBridge { private static final Logger logger = LogService.getLogger(); /** * Static reference to the Platform MBean server */ public static MBeanServer mbeanServer = ManagementFactory .getPlatformMBeanServer(); /** * Factor converting bytes to MBØØ */ private static final long MBFactor = 1024 * 1024; private static TimeUnit nanoSeconds = TimeUnit.NANOSECONDS; /** Cache Instance **/ private GemFireCacheImpl cache; /** Distribution Config **/ private DistributionConfig config; /** Composite type **/ private GemFireProperties gemFirePropertyData; /** * Internal distributed system */ private InternalDistributedSystem system; /** * Distribution manager */ private DM dm; /** * Command Service */ private CommandService commandService; private String commandServiceInitError; /** * Reference to JDK bean MemoryMXBean */ private MemoryMXBean memoryMXBean; /** * Reference to JDK bean ThreadMXBean */ private ThreadMXBean threadMXBean; /** * Reference to JDK bean RuntimeMXBean */ private RuntimeMXBean runtimeMXBean; /** * Reference to JDK bean OperatingSystemMXBean */ private OperatingSystemMXBean osBean; /** * Host name of the member */ private String hostname; /** * The member's process id (pid) */ private int processId; /** * OS MBean Object name */ private ObjectName osObjectName; /** * Last CPU usage calculation time */ private long lastSystemTime = 0; /** * Last ProcessCPU time */ private long lastProcessCpuTime = 0; private MBeanStatsMonitor monitor; private volatile boolean lockStatsAdded = false; private SystemManagementService service; private MemberLevelDiskMonitor diskMonitor; private AggregateRegionStatsMonitor regionMonitor; private StatsRate createsRate; private StatsRate bytesReceivedRate; private StatsRate bytesSentRate; private StatsRate destroysRate; private StatsRate functionExecutionRate; private StatsRate getsRate; private StatsRate putAllRate; private StatsRate putsRate; private StatsRate transactionCommitsRate; private StatsRate diskReadsRate; private StatsRate diskWritesRate; private StatsAverageLatency listenerCallsAvgLatency; private StatsAverageLatency writerCallsAvgLatency; private StatsAverageLatency putsAvgLatency; private StatsAverageLatency getsAvgLatency; private StatsAverageLatency putAllAvgLatency; private StatsAverageLatency loadsAverageLatency; private StatsAverageLatency netLoadsAverageLatency; private StatsAverageLatency netSearchAverageLatency; private StatsAverageLatency transactionCommitsAvgLatency; private StatsAverageLatency diskFlushAvgLatency; private StatsAverageLatency deserializationAvgLatency; private StatsLatency deserializationLatency; private StatsRate deserializationRate; private StatsAverageLatency serializationAvgLatency; private StatsLatency serializationLatency; private StatsRate serializationRate; private StatsAverageLatency pdxDeserializationAvgLatency; private StatsRate pdxDeserializationRate; private StatsRate lruDestroyRate; private StatsRate lruEvictionRate; private String gemFireVersion; private String classPath; private String name; private String id; private String osName = System.getProperty("os.name", "unknown"); private GCStatsMonitor gcMonitor; private VMStatsMonitor vmStatsMonitor; private MBeanStatsMonitor systemStatsMonitor; private float instCreatesRate = 0; private float instGetsRate = 0; private float instPutsRate = 0; private float instPutAllRate = 0; private GemFireStatSampler sampler; private Statistics systemStat; private static final String MEMBER_LEVEL_DISK_MONITOR = "MemberLevelDiskMonitor"; private static final String MEMBER_LEVEL_REGION_MONITOR = "MemberLevelRegionMonitor"; private boolean cacheServer = false; private String redundancyZone = ""; private ResourceManagerStats resourceManagerStats; public MemberMBeanBridge(GemFireCacheImpl cache, SystemManagementService service) { this.cache = cache; this.service = service; this.system = (InternalDistributedSystem) cache.getDistributedSystem(); this.dm = system.getDistributionManager(); if(dm instanceof DistributionManager){ DistributionManager distManager = (DistributionManager)system.getDistributionManager(); this.redundancyZone = distManager.getRedundancyZone(cache.getDistributedSystem().getDistributedMember()); } this.sampler = system.getStatSampler(); this.config = system.getConfig(); try { this.commandService = CommandService.createLocalCommandService(cache); } catch (CacheClosedException e) { commandServiceInitError = e.getMessage(); // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage(), e); } catch (CommandServiceException e) { commandServiceInitError = e.getMessage(); // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage(), e); } catch (DependenciesNotFoundException e) { commandServiceInitError = e.getMessage(); if (CacheServerLauncher.isDedicatedCacheServer) { // log as error for dedicated cache server - launched through script // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage()); } else { // LOG:CONFIG: logger.info(LogMarker.CONFIG, "Command Service could not be initialized. {}", e.getMessage()); } } intitGemfireProperties(); try { InetAddress addr = SocketCreator.getLocalHost(); this.hostname = addr.getHostName(); } catch (UnknownHostException ex) { this.hostname = ManagementConstants.DEFAULT_HOST_NAME; } try { this.osObjectName = new ObjectName("java.lang:type=OperatingSystem"); } catch (MalformedObjectNameException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } catch (NullPointerException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } this.memoryMXBean = ManagementFactory.getMemoryMXBean(); this.threadMXBean = ManagementFactory.getThreadMXBean(); this.runtimeMXBean = ManagementFactory.getRuntimeMXBean(); this.osBean = ManagementFactory.getOperatingSystemMXBean(); //Initialize all the Stats Monitors this.monitor = new MBeanStatsMonitor(ManagementStrings.MEMBER_CACHE_MONITOR .toLocalizedString()); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor(ManagementStrings.GC_STATS_MONITOR .toLocalizedString()); this.vmStatsMonitor = new VMStatsMonitor(ManagementStrings.VM_STATS_MONITOR .toLocalizedString()); this.systemStatsMonitor = new MBeanStatsMonitor(ManagementStrings.SYSTEM_STATS_MONITOR .toLocalizedString()); //Initialize Proecess related informations this.gemFireVersion = GemFireVersion.asString(); this.classPath = runtimeMXBean.getClassPath(); this.name = cache.getDistributedSystem().getDistributedMember().getName(); this.id = cache.getDistributedSystem().getDistributedMember().getId(); try { this.processId = ProcessUtils.identifyPid(); } catch (PidUnavailableException ex) { if (logger.isDebugEnabled()) { logger.debug(ex.getMessage(), ex); } } QueryDataFunction qDataFunction = new QueryDataFunction(); FunctionService.registerFunction(qDataFunction); this.resourceManagerStats = cache.getResourceManager().getStats(); } public MemberMBeanBridge(){ this.monitor = new MBeanStatsMonitor(ManagementStrings.MEMBER_CACHE_MONITOR .toLocalizedString()); this.diskMonitor = new MemberLevelDiskMonitor(MEMBER_LEVEL_DISK_MONITOR); this.regionMonitor = new AggregateRegionStatsMonitor(MEMBER_LEVEL_REGION_MONITOR); this.gcMonitor = new GCStatsMonitor(ManagementStrings.GC_STATS_MONITOR .toLocalizedString()); this.vmStatsMonitor = new VMStatsMonitor(ManagementStrings.VM_STATS_MONITOR .toLocalizedString()); this.systemStatsMonitor = new MBeanStatsMonitor(ManagementStrings.SYSTEM_STATS_MONITOR .toLocalizedString()); this.system = InternalDistributedSystem.getConnectedInstance(); initializeStats(); } public MemberMBeanBridge init() { CachePerfStats cachePerfStats = ((GemFireCacheImpl) cache) .getCachePerfStats(); addCacheStats(cachePerfStats); addFunctionStats(system.getFunctionServiceStats()); if (system.getDistributionManager().getStats() instanceof DistributionStats) { DistributionStats distributionStats = (DistributionStats) system .getDistributionManager().getStats(); addDistributionStats(distributionStats); } if (PureJavaMode.osStatsAreAvailable()) { Statistics[] systemStats = null; if (HostStatHelper.isSolaris()) { systemStats = system.findStatisticsByType(SolarisSystemStats.getType()); } else if (HostStatHelper.isLinux()) { systemStats = system.findStatisticsByType(LinuxSystemStats.getType()); } else if (HostStatHelper.isOSX()) { systemStats = null;//@TODO once OSX stats are implemented } else if (HostStatHelper.isWindows()) { systemStats = system.findStatisticsByType(WindowsSystemStats.getType()); } if (systemStats != null) { systemStat = systemStats[0]; } } MemoryAllocator allocator = ((GemFireCacheImpl) cache).getOffHeapStore(); if((null != allocator) ) { OffHeapMemoryStats offHeapStats = allocator.getStats(); if(null != offHeapStats) { addOffHeapStats(offHeapStats); } } addSystemStats(); addVMStats(); initializeStats(); return this; } public void addOffHeapStats(OffHeapMemoryStats offHeapStats) { Statistics offHeapMemoryStatistics = offHeapStats.getStats(); monitor.addStatisticsToMonitor(offHeapMemoryStatistics); } public void addCacheStats(CachePerfStats cachePerfStats) { Statistics cachePerfStatistics = cachePerfStats.getStats(); monitor.addStatisticsToMonitor(cachePerfStatistics); } public void addFunctionStats(FunctionServiceStats functionServiceStats) { Statistics functionStatistics = functionServiceStats.getStats(); monitor.addStatisticsToMonitor(functionStatistics); } public void addDistributionStats(DistributionStats distributionStats) { Statistics dsStats = distributionStats.getStats(); monitor.addStatisticsToMonitor(dsStats); } public void addDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; addDiskStoreStats(impl.getStats()); } public void addDiskStoreStats(DiskStoreStats stats){ diskMonitor.addStatisticsToMonitor(stats.getStats()); } public void removeDiskStore(DiskStore dsi) { DiskStoreImpl impl = (DiskStoreImpl) dsi; removeDiskStoreStats(impl.getStats()); } public void removeDiskStoreStats(DiskStoreStats stats){ diskMonitor.removeStatisticsFromMonitor(stats.getStats()); } public void addRegion(Region region ){ if(region.getAttributes().getPartitionAttributes() != null){ addPartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; if(l.getEvictionController() != null){ LRUStatistics stats = l.getEvictionController().getLRUHelper().getStats(); if (stats != null) { addLRUStats(stats); } } DiskRegion dr = l.getDiskRegion(); if(dr != null){ for(DirectoryHolder dh:dr.getDirectories()){ addDirectoryStats(dh.getDiskDirectoryStats()); } } } public void addPartionRegionStats(PartitionedRegionStats parStats){ regionMonitor.addStatisticsToMonitor(parStats.getStats()); } public void addLRUStats(LRUStatistics lruStats){ regionMonitor.addStatisticsToMonitor(lruStats.getStats()); } public void addDirectoryStats(DiskDirectoryStats diskDirStats){ regionMonitor.addStatisticsToMonitor(diskDirStats.getStats()); } public void removeRegion(Region region ){ if(region.getAttributes().getPartitionAttributes() != null){ removePartionRegionStats(((PartitionedRegion) region).getPrStats()); } LocalRegion l = (LocalRegion) region; if(l.getEvictionController() != null){ LRUStatistics stats = l.getEvictionController().getLRUHelper().getStats(); if (stats != null) { removeLRUStats(stats); } } DiskRegion dr = l.getDiskRegion(); if(dr != null){ for(DirectoryHolder dh:dr.getDirectories()){ removeDirectoryStats(dh.getDiskDirectoryStats()); } } } public void removePartionRegionStats(PartitionedRegionStats parStats) { regionMonitor.removePartitionStatistics(parStats.getStats()); } public void removeLRUStats(LRUStatistics lruStats) { regionMonitor.removeLRUStatistics(lruStats.getStats()); } public void removeDirectoryStats(DiskDirectoryStats diskDirStats) { regionMonitor.removeDirectoryStatistics(diskDirStats.getStats()); } public void addLockServiceStats(DLockService lock){ if(!lockStatsAdded){ DLockStats stats = (DLockStats)lock.getStats(); addLockServiceStats(stats); lockStatsAdded = true; } } public void addLockServiceStats(DLockStats stats){ monitor.addStatisticsToMonitor(stats.getStats()); } public void addSystemStats() { GemFireStatSampler sampler = system.getStatSampler(); ProcessStats processStats = sampler.getProcessStats(); StatSamplerStats samplerStats = sampler.getStatSamplerStats(); if (processStats != null) { systemStatsMonitor.addStatisticsToMonitor(processStats.getStatistics()); } if(samplerStats != null){ systemStatsMonitor.addStatisticsToMonitor(samplerStats.getStats()); } } public void addVMStats(){ VMStatsContract vmStatsContract = system.getStatSampler().getVMStats(); if (vmStatsContract != null && vmStatsContract instanceof VMStats50){ VMStats50 vmStats50 = (VMStats50) vmStatsContract; Statistics vmStats = vmStats50.getVMStats(); if (vmStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmStats); } Statistics vmHeapStats = vmStats50.getVMHeapStats(); if (vmHeapStats != null) { vmStatsMonitor.addStatisticsToMonitor(vmHeapStats); } //vmStatsMonitor.addStatisticsToMonitor(vm50.getVMNonHeapStats()); StatisticsType gcType = VMStats50.getGCType(); if (gcType != null) { Statistics[] gcStats = system.findStatisticsByType(gcType); if (gcStats != null && gcStats.length > 0){ for (Statistics gcStat : gcStats) { if (gcStat != null) { gcMonitor.addStatisticsToMonitor(gcStat); } } } } } } public Number getMemberLevelStatistic(String statName) { return monitor.getStatistic(statName); } public Number getVMStatistic(String statName) { return vmStatsMonitor.getStatistic(statName); } public Number getGCStatistic(String statName) { return gcMonitor.getStatistic(statName); } public Number getSystemStatistic(String statName) { return systemStatsMonitor.getStatistic(statName); } public void stopMonitor(){ monitor.stopListener(); regionMonitor.stopListener(); gcMonitor.stopListener(); systemStatsMonitor.stopListener(); vmStatsMonitor.stopListener(); } private void initializeStats(){ createsRate = new StatsRate(StatsKey.CREATES, StatType.INT_TYPE, monitor); bytesReceivedRate = new StatsRate(StatsKey.RECEIVED_BYTES, StatType.LONG_TYPE, monitor); bytesSentRate = new StatsRate(StatsKey.SENT_BYTES, StatType.LONG_TYPE, monitor); destroysRate = new StatsRate(StatsKey.DESTROYS, StatType.INT_TYPE, monitor); functionExecutionRate = new StatsRate( StatsKey.FUNCTION_EXECUTIONS_COMPLETED, StatType.INT_TYPE, monitor); getsRate = new StatsRate( StatsKey.GETS, StatType.INT_TYPE, monitor); putAllRate = new StatsRate( StatsKey.PUT_ALLS, StatType.INT_TYPE, monitor); putsRate = new StatsRate( StatsKey.PUTS, StatType.INT_TYPE, monitor); transactionCommitsRate = new StatsRate( StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, monitor); diskReadsRate = new StatsRate( StatsKey.DISK_READ_BYTES, StatType.LONG_TYPE, diskMonitor); diskWritesRate = new StatsRate( StatsKey.DISK_WRITEN_BYTES, StatType.LONG_TYPE, diskMonitor); listenerCallsAvgLatency = new StatsAverageLatency( StatsKey.CACHE_LISTENER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_LISTENR_CALL_TIME, monitor); writerCallsAvgLatency = new StatsAverageLatency( StatsKey.CACHE_WRITER_CALLS_COMPLETED, StatType.INT_TYPE, StatsKey.CACHE_WRITER_CALL_TIME, monitor); getsAvgLatency = new StatsAverageLatency( StatsKey.GETS, StatType.INT_TYPE, StatsKey.GET_TIME, monitor); putAllAvgLatency = new StatsAverageLatency( StatsKey.PUT_ALLS, StatType.INT_TYPE, StatsKey.PUT_ALL_TIME, monitor); putsAvgLatency = new StatsAverageLatency( StatsKey.PUTS, StatType.INT_TYPE, StatsKey.PUT_TIME, monitor); loadsAverageLatency = new StatsAverageLatency( StatsKey.LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.LOADS_TIME, monitor); netLoadsAverageLatency = new StatsAverageLatency( StatsKey.NET_LOADS_COMPLETED, StatType.INT_TYPE, StatsKey.NET_LOADS_TIME, monitor); netSearchAverageLatency = new StatsAverageLatency( StatsKey.NET_SEARCH_COMPLETED, StatType.INT_TYPE, StatsKey.NET_SEARCH_TIME, monitor); transactionCommitsAvgLatency = new StatsAverageLatency( StatsKey.TRANSACTION_COMMITS, StatType.INT_TYPE, StatsKey.TRANSACTION_COMMIT_TIME, monitor); diskFlushAvgLatency = new StatsAverageLatency( StatsKey.NUM_FLUSHES, StatType.INT_TYPE, StatsKey.TOTAL_FLUSH_TIME, diskMonitor); deserializationAvgLatency = new StatsAverageLatency( StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationLatency = new StatsLatency(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.DESERIALIZATION_TIME, monitor); deserializationRate = new StatsRate(StatsKey.DESERIALIZATIONS, StatType.INT_TYPE, monitor); serializationAvgLatency = new StatsAverageLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationLatency = new StatsLatency(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, StatsKey.SERIALIZATION_TIME, monitor); serializationRate = new StatsRate(StatsKey.SERIALIZATIONS, StatType.INT_TYPE, monitor); pdxDeserializationAvgLatency = new StatsAverageLatency( StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, StatsKey.PDX_INSTANCE_DESERIALIZATION_TIME, monitor); pdxDeserializationRate = new StatsRate( StatsKey.PDX_INSTANCE_DESERIALIZATIONS, StatType.INT_TYPE, monitor); lruDestroyRate = new StatsRate( StatsKey.LRU_DESTROYS, StatType.LONG_TYPE, regionMonitor); lruEvictionRate = new StatsRate( StatsKey.LRU_EVICTIONS, StatType.LONG_TYPE, regionMonitor); } private void intitGemfireProperties() { if (gemFirePropertyData == null) { this.gemFirePropertyData = BeanUtilFuncs.initGemfireProperties(config); } } /** * @return Some basic JVM metrics at the particular instance */ public JVMMetrics fetchJVMMetrics() { long gcCount = getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS) .longValue(); long gcTimeMillis = getGCStatistic( StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); //Fixed values might not be updated back by Stats monitor. Hence getting it directly long initMemory = memoryMXBean.getHeapMemoryUsage().getInit(); long committedMemory = memoryMXBean.getHeapMemoryUsage().getCommitted(); long usedMemory = getVMStatistic(StatsKey.VM_USED_MEMORY).longValue(); long maxMemory = memoryMXBean.getHeapMemoryUsage().getMax(); int totalThreads = getVMStatistic(StatsKey.VM_STATS_NUM_THREADS) .intValue(); return new JVMMetrics(gcCount, gcTimeMillis, initMemory, committedMemory, usedMemory, maxMemory, totalThreads); } /** * All OS metrics are not present in * java.lang.management.OperatingSystemMXBean It has to be cast to * com.sun.management.OperatingSystemMXBean. To avoid the cast using dynamic * call so that Java platform will take care of the details in a native * manner; * * @return Some basic OS metrics at the particular instance */ public OSMetrics fetchOSMetrics() { OSMetrics metrics = null; try { long maxFileDescriptorCount = 0; long openFileDescriptorCount = 0; long processCpuTime = 0; long committedVirtualMemorySize = 0; long totalPhysicalMemorySize = 0; long freePhysicalMemorySize = 0; long totalSwapSpaceSize = 0; long freeSwapSpaceSize = 0; String name = osBean.getName(); String version = osBean.getVersion(); String arch = osBean.getArch(); int availableProcessors = osBean.getAvailableProcessors(); double systemLoadAverage = osBean.getSystemLoadAverage(); openFileDescriptorCount = getVMStatistic( StatsKey.VM_STATS_OPEN_FDS).longValue(); processCpuTime = getVMStatistic(StatsKey.VM_PROCESS_CPU_TIME) .longValue(); try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception e) { maxFileDescriptorCount = -1; } try { committedVirtualMemorySize = (Long) mbeanServer.getAttribute( osObjectName, "CommittedVirtualMemorySize"); } catch (Exception e) { committedVirtualMemorySize = -1; } //If Linux System type exists if (PureJavaMode.osStatsAreAvailable() && HostStatHelper.isLinux() && systemStat != null) { try { totalPhysicalMemorySize = systemStat.get( StatsKey.LINUX_SYSTEM_PHYSICAL_MEMORY).longValue(); } catch (Exception e) { totalPhysicalMemorySize = -1; } try { freePhysicalMemorySize = systemStat.get( StatsKey.LINUX_SYSTEM_FREE_MEMORY).longValue(); } catch (Exception e) { freePhysicalMemorySize = -1; } try { totalSwapSpaceSize = systemStat.get( StatsKey.LINUX_SYSTEM_TOTAL_SWAP_SIZE).longValue(); } catch (Exception e) { totalSwapSpaceSize = -1; } try { freeSwapSpaceSize = systemStat.get( StatsKey.LINUX_SYSTEM_FREE_SWAP_SIZE).longValue(); } catch (Exception e) { freeSwapSpaceSize = -1; } } else { totalPhysicalMemorySize = -1; freePhysicalMemorySize = -1; totalSwapSpaceSize = -1; freeSwapSpaceSize = -1; } metrics = new OSMetrics(maxFileDescriptorCount, openFileDescriptorCount, processCpuTime, committedVirtualMemorySize, totalPhysicalMemorySize, freePhysicalMemorySize, totalSwapSpaceSize, freeSwapSpaceSize, name, version, arch, availableProcessors, systemLoadAverage); } catch (Exception ex) { if(logger.isTraceEnabled()){ logger.trace(ex.getMessage(), ex); } } return metrics; } /** * * @return GemFire Properties */ public GemFireProperties getGemFireProperty() { return gemFirePropertyData; } /** * Creates a Manager * @return successful or not */ public boolean createManager() { if (service.isManager()) { return false; } return service.createManager(); } /** * An instruction to members with cache that they should compact their disk * stores. * * @return a list of compacted Disk stores */ public String[] compactAllDiskStores() { GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache; List<String> compactedStores = new ArrayList<String>(); if (cache != null && !cache.isClosed()) { for (DiskStoreImpl store : cacheImpl.listDiskStoresIncludingRegionOwned()) { if (store.forceCompaction()) { compactedStores.add(store.getPersistentID().getDirectory()); } } } String[] compactedStoresAr = new String[compactedStores.size()]; return compactedStores.toArray(compactedStoresAr); } /** * List all the disk Stores at member level * * @param includeRegionOwned * indicates whether to show the disk belonging to any particular * region * @return list all the disk Stores name at cache level */ public String[] listDiskStores(boolean includeRegionOwned) { GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache; String[] retStr = null; Collection<DiskStoreImpl> diskCollection = null; if (includeRegionOwned) { diskCollection = cacheImpl.listDiskStoresIncludingRegionOwned(); } else { diskCollection = cacheImpl.listDiskStores(); } if (diskCollection != null && diskCollection.size() > 0) { retStr = new String[diskCollection.size()]; Iterator<DiskStoreImpl> it = diskCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * * @return list of disk stores which defaults includeRegionOwned = true; */ public String[] getDiskStores() { return listDiskStores(true); } /** * @return list all the HDFSStore's name at cache level */ public String[] getHDFSStores() { GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache; String[] retStr = null; Collection<HDFSStoreImpl> hdfsStoreCollection = null; hdfsStoreCollection = cacheImpl.getHDFSStores(); if (hdfsStoreCollection != null && hdfsStoreCollection.size() > 0) { retStr = new String[hdfsStoreCollection.size()]; Iterator<HDFSStoreImpl> it = hdfsStoreCollection.iterator(); int i = 0; while (it.hasNext()) { retStr[i] = it.next().getName(); i++; } } return retStr; } /** * * @return log of the member. */ public String fetchLog(int numLines){ if(numLines > ManagementConstants.MAX_SHOW_LOG_LINES){ numLines = ManagementConstants.MAX_SHOW_LOG_LINES; } if(numLines == 0 || numLines < 0){ numLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES; } String childTail = null; String mainTail = null; try { InternalDistributedSystem sys = system; LogWriterAppender lwa = LogWriterAppenders.getAppender(LogWriterAppenders.Identifier.MAIN); if (lwa != null) { childTail = BeanUtilFuncs.tailSystemLog(lwa.getChildLogFile(),numLines); mainTail = BeanUtilFuncs.tailSystemLog(sys.getConfig(), numLines); if (mainTail == null) { mainTail = LocalizedStrings.TailLogResponse_NO_LOG_FILE_WAS_SPECIFIED_IN_THE_CONFIGURATION_MESSAGES_WILL_BE_DIRECTED_TO_STDOUT .toLocalizedString(); } } else { Assert .assertTrue(false, "TailLogRequest/Response processed in application vm with shared logging."); } } catch (IOException e) { logger.warn(LocalizedMessage.create(LocalizedStrings.TailLogResponse_ERROR_OCCURRED_WHILE_READING_SYSTEM_LOG__0, e)); mainTail = ""; } if (childTail == null && mainTail == null) { return LocalizedStrings.SystemMemberImpl_NO_LOG_FILE_CONFIGURED_LOG_MESSAGES_WILL_BE_DIRECTED_TO_STDOUT .toLocalizedString(); } else { StringBuffer result = new StringBuffer(); if (mainTail != null) { result.append(mainTail); } if (childTail != null) { result.append("\n" + LocalizedStrings.SystemMemberImpl_TAIL_OF_CHILD_LOG .toLocalizedString() + "\n"); result.append(childTail); } return result.toString(); } } /** * Using async thread. As remote operation will be executed by * FunctionService. Might cause problems in cleaning up function related * resources. Aggregate bean DistributedSystemMBean will have to depend on * GemFire messages to decide whether all the members have been shutdown or * not before deciding to shut itself down */ public void shutDownMember() { final InternalDistributedSystem ids = dm.getSystem(); if (ids.isConnected()) { Thread t = new Thread(new Runnable() { public void run() { try { // Allow the Function call to exit Thread.sleep(1000); } catch (InterruptedException e) { } ConnectionTable.threadWantsSharedResources(); if (ids.isConnected()) { ids.disconnect(); } } }); t.start(); } } /** * backs up all the disk to the targeted directory * * @param targetDirPath * path of the directory where back up is to be taken * @return array of DiskBackup results which might get aggregated at Managing * node * * Check the validity of this mbean call. When does it make sense to backup a single member of a gemfire system * in isolation of the other members? */ public DiskBackupResult[] backupMember(String targetDirPath) { GemFireCacheImpl cache = GemFireCacheImpl.getInstance(); if (cache != null) { Collection<DiskStoreImpl> diskStores = cache .listDiskStoresIncludingRegionOwned(); for (DiskStoreImpl store : diskStores) { store.flush(); } } DiskBackupResult[] diskBackUpResult = null; File targetDir = new File(targetDirPath); if (cache == null) { return null; } else { try { BackupManager manager = cache.startBackup(cache.getDistributedSystem() .getDistributedMember()); Set<PersistentID> existingDataStores = manager.prepareBackup(); Set<PersistentID> successfulDataStores = manager .finishBackup(targetDir, null/* TODO rishi */); diskBackUpResult = new DiskBackupResult[existingDataStores.size()]; int j = 0; for (PersistentID id : existingDataStores) { if (successfulDataStores.contains(id)) { diskBackUpResult[j] = new DiskBackupResult(id.getDirectory(), false); } else { diskBackUpResult[j] = new DiskBackupResult(id.getDirectory(), true); } j++; } } catch (IOException e) { throw new ManagementException(e); } } return diskBackUpResult; } /** * * @return The name for this member. */ public String getName() { return name; } /** * * @return The ID for this member. */ public String getId() { return id; } /** * * @return The name of the member if it's been set, otherwise the ID of the member */ public String getMember() { if (name != null && !name.isEmpty()) { return name; } return id; } public String[] getGroups() { List<String> groups = cache.getDistributedSystem().getDistributedMember().getGroups(); String[] groupsArray = new String[groups.size()]; groupsArray = groups.toArray(groupsArray); return groupsArray; } /** * * @return classPath of the VM */ public String getClassPath() { return classPath; } /** * * @return Connected gateway receivers */ public String[] listConnectedGatewayReceivers() { if ((cache != null && cache.getGatewayReceivers().size() > 0)) { Set<GatewayReceiver> receivers = cache.getGatewayReceivers(); String[] arr = new String[receivers.size()]; int j = 0; for (GatewayReceiver recv : receivers) { arr[j] = recv.getBindAddress(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return Connected gateway senders */ public String[] listConnectedGatewaySenders() { if ((cache != null && cache.getGatewaySenders().size() > 0)) { Set<GatewaySender> senders = cache.getGatewaySenders(); String[] arr = new String[senders.size()]; int j = 0; for (GatewaySender sender : senders) { arr[j] = sender.getId(); j++; } return arr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return approximate usage of CPUs */ public float getCpuUsage() { return vmStatsMonitor.getCpuUsage(); } /** * * @return current time of the system */ public long getCurrentTime() { return System.currentTimeMillis(); } public String getHost() { return hostname; } /** * @return the member's process id (pid) */ public int getProcessId() { return processId; } /** * Gets a String describing the GemFire member's status. A GemFire member includes, but is not limited to: Locators, * Managers, Cache Servers and so on. * </p> * @return String description of the GemFire member's status. * @see #isLocator() * @see #isServer() */ public String status() { //if (isLocator()) { if (LocatorLauncher.getInstance() != null) { return LocatorLauncher.getLocatorState().toJson(); } //else if (isServer()) { else if (ServerLauncher.getInstance() != null) { return ServerLauncher.getServerState().toJson(); } // TODO implement for non-launcher processes and other GemFire processes (Managers, etc)... return null; } /** * * @return total heap usage in bytes */ public long getTotalBytesInUse() { MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); long bytesUsed = memHeap.getUsed(); return bytesUsed; } /** * * @return Number of availabe CPUs */ public int getAvailableCpus() { Runtime runtime = Runtime.getRuntime(); return runtime.availableProcessors(); } /** * * @return JVM thread list */ public String[] fetchJvmThreads() { long threadIds[] = threadMXBean.getAllThreadIds(); ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadIds, 0); if (threadInfos == null || threadInfos.length < 1) { return ManagementConstants.NO_DATA_STRING; } ArrayList<String> thrdStr = new ArrayList<String>(threadInfos.length); for (ThreadInfo thInfo : threadInfos) { if (thInfo != null) { thrdStr.add(thInfo.getThreadName()); } } String[] result = new String[thrdStr.size()]; return thrdStr.toArray(result); } /** * * @return list of regions */ public String[] getListOfRegions() { Set<LocalRegion> listOfAppRegions = cache.getApplicationRegions(); if (listOfAppRegions != null && listOfAppRegions.size() > 0) { String[] regionStr = new String[listOfAppRegions.size()]; int j = 0; for (LocalRegion rg : listOfAppRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return configuration data lock lease */ public long getLockLease() { return cache.getLockLease(); } /** * * @return configuration data lock time out */ public long getLockTimeout() { return cache.getLockTimeout(); } /** * * @return the duration for which the member is up */ public long getMemberUpTime() { return cache.getUpTime(); } /** * * @return root region names */ public String[] getRootRegionNames() { Set<LocalRegion> listOfRootRegions = cache.rootRegions(); if (listOfRootRegions != null && listOfRootRegions.size() > 0) { String[] regionStr = new String[listOfRootRegions.size()]; int j = 0; for (LocalRegion rg : listOfRootRegions) { regionStr[j] = rg.getFullPath(); j++; } return regionStr; } return ManagementConstants.NO_DATA_STRING; } /** * * @return Current GemFire version */ public String getVersion() { return gemFireVersion; } /** * * @return true if this members has a gateway receiver */ public boolean hasGatewayReceiver() { return (cache != null && cache.getGatewayReceivers().size() > 0); } /** * * @return true if member has Gateway senders */ public boolean hasGatewaySender() { return (cache != null && cache.getAllGatewaySenders().size() > 0); } /** * * @return true if member contains one locator. From 7.0 only locator can be * hosted in a JVM */ public boolean isLocator() { return Locator.hasLocator(); } /** * * @return true if the Federating Manager Thread is running */ public boolean isManager() { GemFireCacheImpl existingCache = GemFireCacheImpl.getInstance(); if (existingCache == null || existingCache.isClosed()) { return false; } try{ boolean isManager = service.isManager(); return isManager; }catch(Exception e){ return false; } } /** * Returns true if the manager has been created. * Note it does not need to be running so this * method can return true when isManager returns false. * @return true if the manager has been created. */ public boolean isManagerCreated() { GemFireCacheImpl existingCache = GemFireCacheImpl.getInstance(); if (existingCache == null || existingCache.isClosed()) { return false; } try { return service.isManagerCreated(); } catch(Exception e) { return false; } } /** * * @return true if member has a server */ public boolean isServer() { return cache.isServer(); } /** Statistics Related Attributes **/ /*********************************************************************************************************/ public int getInitialImageKeysReceived() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_KEYS_RECEIVED) .intValue(); } public long getInitialImageTime() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGE_TIME).longValue(); } public int getInitialImagesInProgres() { return getMemberLevelStatistic(StatsKey.GET_INITIAL_IMAGES_INPROGRESS) .intValue(); } public long getTotalIndexMaintenanceTime() { return getMemberLevelStatistic(StatsKey.TOTAL_INDEX_UPDATE_TIME) .longValue(); } public float getBytesReceivedRate() { return bytesReceivedRate.getRate(); } public float getBytesSentRate() { return bytesSentRate.getRate(); } public long getCacheListenerCallsAvgLatency() { return listenerCallsAvgLatency.getAverageLatency(); } public long getCacheWriterCallsAvgLatency() { return writerCallsAvgLatency.getAverageLatency(); } public float getCreatesRate() { this.instCreatesRate = createsRate.getRate(); return instCreatesRate; } public float getDestroysRate() { return destroysRate.getRate(); } public float getDiskReadsRate() { return diskReadsRate.getRate(); } public float getDiskWritesRate() { return diskWritesRate.getRate(); } public int getTotalBackupInProgress() { return diskMonitor.getBackupsInProgress(); } public int getTotalBackupCompleted() { return diskMonitor.getBackupsCompleted(); } public long getDiskFlushAvgLatency() { return diskFlushAvgLatency.getAverageLatency(); } public float getFunctionExecutionRate() { return functionExecutionRate.getRate(); } public long getGetsAvgLatency() { return getsAvgLatency.getAverageLatency(); } public float getGetsRate() { this.instGetsRate = getsRate.getRate(); return instGetsRate; } public int getLockWaitsInProgress() { return getMemberLevelStatistic(StatsKey.LOCK_WAITS_IN_PROGRESS).intValue(); } public int getNumRunningFunctions() { return getMemberLevelStatistic(StatsKey.FUNCTION_EXECUTIONS_RUNNING) .intValue(); } public int getNumRunningFunctionsHavingResults() { return getMemberLevelStatistic( StatsKey.FUNCTION_EXECUTIONS_HASRESULT_RUNNING).intValue(); } public long getPutAllAvgLatency() { return putAllAvgLatency.getAverageLatency(); } public float getPutAllRate() { this.instPutAllRate = putAllRate.getRate(); return instPutAllRate; } public long getPutsAvgLatency() { return putsAvgLatency.getAverageLatency(); } public float getPutsRate() { this.instPutsRate = putsRate.getRate(); return instPutsRate; } public int getLockRequestQueues() { return getMemberLevelStatistic(StatsKey.LOCK_REQUEST_QUEUE).intValue(); } public int getPartitionRegionCount() { return getMemberLevelStatistic(StatsKey.PARTITIONED_REGIONS).intValue(); } public int getTotalPrimaryBucketCount() { return regionMonitor.getTotalPrimaryBucketCount(); } public int getTotalBucketCount() { return regionMonitor.getTotalBucketCount(); } public int getTotalBucketSize() { return regionMonitor.getTotalBucketSize(); } public int getTotalHitCount() { return getMemberLevelStatistic(StatsKey.GETS).intValue() - getTotalMissCount(); } public float getLruDestroyRate() { return lruDestroyRate.getRate(); } public float getLruEvictionRate() { return lruEvictionRate.getRate(); } public int getTotalLoadsCompleted() { return getMemberLevelStatistic(StatsKey.LOADS_COMPLETED).intValue(); } public long getLoadsAverageLatency() { return loadsAverageLatency.getAverageLatency(); } public int getTotalNetLoadsCompleted() { return getMemberLevelStatistic(StatsKey.NET_LOADS_COMPLETED).intValue(); } public long getNetLoadsAverageLatency() { return netLoadsAverageLatency.getAverageLatency(); } public int getTotalNetSearchCompleted() { return getMemberLevelStatistic(StatsKey.NET_SEARCH_COMPLETED).intValue(); } public long getNetSearchAverageLatency() { return netSearchAverageLatency.getAverageLatency(); } public long getTotalLockWaitTime() { return getMemberLevelStatistic(StatsKey.LOCK_WAIT_TIME).intValue(); } public int getTotalMissCount() { return getMemberLevelStatistic(StatsKey.MISSES).intValue(); } public int getTotalNumberOfLockService() { return getMemberLevelStatistic(StatsKey.LOCK_SERVICES).intValue(); } public int getTotalNumberOfGrantors() { return getMemberLevelStatistic(StatsKey.LOCK_GRANTORS).intValue(); } public int getTotalDiskTasksWaiting() { return getMemberLevelStatistic(StatsKey.TOTAL_DISK_TASK_WAITING).intValue(); } public int getTotalRegionCount() { return getMemberLevelStatistic(StatsKey.REGIONS).intValue(); } public int getTotalRegionEntryCount() { return getMemberLevelStatistic(StatsKey.ENTRIES).intValue(); } public int getTotalTransactionsCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue() + getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getTransactionCommitsAvgLatency() { return transactionCommitsAvgLatency.getAverageLatency(); } public float getTransactionCommitsRate() { return transactionCommitsRate.getRate(); } public int getTransactionCommittedTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_COMMITS).intValue(); } public int getTransactionRolledBackTotalCount() { return getMemberLevelStatistic(StatsKey.TRANSACTION_ROLLBACKS).intValue(); } public long getDeserializationAvgLatency() { return deserializationAvgLatency.getAverageLatency(); } public long getDeserializationLatency() { return deserializationLatency.getLatency(); } public float getDeserializationRate() { return deserializationRate.getRate(); } public long getSerializationAvgLatency() { return serializationAvgLatency.getAverageLatency(); } public long getSerializationLatency() { return serializationLatency.getLatency(); } public float getSerializationRate() { return serializationRate.getRate(); } public long getPDXDeserializationAvgLatency() { return pdxDeserializationAvgLatency.getAverageLatency(); } public float getPDXDeserializationRate() { return pdxDeserializationRate.getRate(); } /** * Processes the given command string using the given environment information * if it's non-empty. Result returned is in a JSON format. * * @param commandString * command string to be processed * @param env * environment information to be used for processing the command * @return result of the processing the given command string. */ public String processCommand(String commandString, Map<String, String> env) { if (commandService == null) { throw new JMRuntimeException( "Command can not be processed as Command Service did not get initialized. Reason: "+commandServiceInitError); } boolean isGfshRequest = isGfshRequest(env); if (isGfshRequest) { CommandExecutionContext.setShellRequest(); } // System.out.println("isGfshRequest :: "+isGfshRequest); Result result = ((MemberCommandService)commandService).processCommand(commandString, env); if (!(result instanceof CommandResult)) {// TODO - Abhishek - Shouldn't be needed while (result.hasNextLine()) { result = ResultBuilder.createInfoResult(result.nextLine()); } } if (isGfshRequest) { String responseJson = CommandResponseBuilder.createCommandResponseJson(getMember(), (CommandResult) result); // System.out.println("responseJson :: "+responseJson); return responseJson; } else { return ResultBuilder.resultAsString(result); } } private boolean isGfshRequest(Map<String, String> env) { String appName = null; if (env != null) { appName = env.get(Gfsh.ENV_APP_NAME); } // System.out.println("appName :: "+appName); return Gfsh.GFSH_APP_NAME.equals(appName); } public long getTotalDiskUsage() { long diskSpaceUsage = regionMonitor.getDiskSpace(); return diskSpaceUsage; } public float getAverageReads() { return instGetsRate; } public float getAverageWrites() { return instCreatesRate + instPutsRate + instPutAllRate; } public long getGarbageCollectionTime() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTION_TIME).longValue(); } public long getGarbageCollectionCount() { return getGCStatistic(StatsKey.VM_GC_STATS_COLLECTIONS).longValue(); } public long getJVMPauses() { return getSystemStatistic(StatsKey.JVM_PAUSES).intValue(); } public double getLoadAverage() { return osBean.getSystemLoadAverage(); } public int getNumThreads() { return getVMStatistic(StatsKey.VM_STATS_NUM_THREADS).intValue(); } /** * * @return max limit of FD ..Ulimit */ public long getFileDescriptorLimit() { if (!osName.startsWith(ManagementConstants.LINUX_SYSTEM)) { return -1; } long maxFileDescriptorCount = 0; try { maxFileDescriptorCount = (Long) mbeanServer.getAttribute(osObjectName, "MaxFileDescriptorCount"); } catch (Exception e) { maxFileDescriptorCount = -1; } return maxFileDescriptorCount; } /** * * @return count of currently opened FDs */ public long getTotalFileDescriptorOpen() { if(!osName.startsWith(ManagementConstants.LINUX_SYSTEM)){ return -1; } return getVMStatistic(StatsKey.VM_STATS_OPEN_FDS).longValue(); } public int getOffHeapObjects() { int objects = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { objects = stats.getObjects(); } return objects; } @Deprecated public long getOffHeapFreeSize() { return getOffHeapFreeMemory(); } @Deprecated public long getOffHeapUsedSize() { return getOffHeapUsedMemory(); } public long getOffHeapMaxMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { usedSize = stats.getMaxMemory(); } return usedSize; } public long getOffHeapFreeMemory() { long freeSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { freeSize = stats.getFreeMemory(); } return freeSize; } public long getOffHeapUsedMemory() { long usedSize = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { usedSize = stats.getUsedMemory(); } return usedSize; } public int getOffHeapFragmentation() { int fragmentation = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { fragmentation = stats.getFragmentation(); } return fragmentation; } public long getOffHeapCompactionTime() { long compactionTime = 0; OffHeapMemoryStats stats = getOffHeapStats(); if(null != stats) { compactionTime = stats.getCompactionTime(); } return compactionTime; } /** * Returns the OffHeapMemoryStats for this VM. */ private OffHeapMemoryStats getOffHeapStats() { OffHeapMemoryStats stats = null; MemoryAllocator offHeap = this.cache.getOffHeapStore(); if(null != offHeap) { stats = offHeap.getStats(); } return stats; } public int getHostCpuUsage() { if (systemStat != null) { return systemStat.get(StatsKey.SYSTEM_CPU_ACTIVE).intValue(); } else { return ManagementConstants.NOT_AVAILABLE_INT; } } public boolean isCacheServer() { return cacheServer; } public void setCacheServer(boolean cacheServer) { this.cacheServer = cacheServer; } public String getRedundancyZone() { return redundancyZone; } public int getRebalancesInProgress() { return resourceManagerStats.getRebalancesInProgress(); } public int getReplyWaitsInProgress() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_IN_PROGRESS).intValue(); } public int getReplyWaitsCompleted() { return getMemberLevelStatistic(StatsKey.REPLY_WAITS_COMPLETED).intValue(); } public int getVisibleNodes() { return getMemberLevelStatistic(StatsKey.NODES).intValue(); } public long getMaxMemory() { Runtime rt = Runtime.getRuntime(); return rt.maxMemory() / MBFactor; } public long getFreeMemory() { Runtime rt = Runtime.getRuntime(); return rt.freeMemory() / MBFactor; } public long getUsedMemory() { return getVMStatistic(StatsKey.VM_USED_MEMORY).longValue() / MBFactor; } }
GEODE-380 ensure that gfsh shutdown does not leave only daemon threads
gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java
GEODE-380 ensure that gfsh shutdown does not leave only daemon threads
<ide><path>emfire-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java <ide> } <ide> } <ide> }); <add> t.setDaemon(false); <ide> t.start(); <ide> } <ide>
Java
mit
6faf0012e07e240c23e0981c335886494b210677
0
stachon/XChange,timmolter/XChange
package org.knowm.xchange.binance; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Map; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.knowm.xchange.binance.dto.BinanceException; import org.knowm.xchange.binance.dto.account.*; import org.knowm.xchange.binance.dto.trade.BinanceCancelledOrder; import org.knowm.xchange.binance.dto.trade.BinanceListenKey; import org.knowm.xchange.binance.dto.trade.BinanceNewOrder; import org.knowm.xchange.binance.dto.trade.BinanceOrder; import org.knowm.xchange.binance.dto.trade.BinanceTrade; import org.knowm.xchange.binance.dto.trade.OrderSide; import org.knowm.xchange.binance.dto.trade.OrderType; import org.knowm.xchange.binance.dto.trade.TimeInForce; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; @Path("") @Produces(MediaType.APPLICATION_JSON) public interface BinanceAuthenticated extends Binance { String SIGNATURE = "signature"; String X_MBX_APIKEY = "X-MBX-APIKEY"; /** * Send in a new order * * @param symbol * @param side * @param type * @param timeInForce * @param quantity * @param price optional, must be provided for limit orders only * @param newClientOrderId optional, a unique id for the order. Automatically generated if not * sent. * @param stopPrice optional, used with stop orders * @param icebergQty optional, used with iceberg orders * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ @POST @Path("api/v3/order") BinanceNewOrder newOrder( @FormParam("symbol") String symbol, @FormParam("side") OrderSide side, @FormParam("type") OrderType type, @FormParam("timeInForce") TimeInForce timeInForce, @FormParam("quantity") BigDecimal quantity, @FormParam("price") BigDecimal price, @FormParam("newClientOrderId") String newClientOrderId, @FormParam("stopPrice") BigDecimal stopPrice, @FormParam("icebergQty") BigDecimal icebergQty, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Test new order creation and signature/recvWindow long. Creates and validates a new order but * does not send it into the matching engine. * * @param symbol * @param side * @param type * @param timeInForce * @param quantity * @param price * @param newClientOrderId optional, a unique id for the order. Automatically generated by * default. * @param stopPrice optional, used with STOP orders * @param icebergQty optional used with icebergOrders * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ @POST @Path("api/v3/order/test") Object testNewOrder( @FormParam("symbol") String symbol, @FormParam("side") OrderSide side, @FormParam("type") OrderType type, @FormParam("timeInForce") TimeInForce timeInForce, @FormParam("quantity") BigDecimal quantity, @FormParam("price") BigDecimal price, @FormParam("newClientOrderId") String newClientOrderId, @FormParam("stopPrice") BigDecimal stopPrice, @FormParam("icebergQty") BigDecimal icebergQty, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Check an order's status.<br> * Either orderId or origClientOrderId must be sent. * * @param symbol * @param orderId optional * @param origClientOrderId optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("api/v3/order") BinanceOrder orderStatus( @QueryParam("symbol") String symbol, @QueryParam("orderId") long orderId, @QueryParam("origClientOrderId") String origClientOrderId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Cancel an active order. * * @param symbol * @param orderId optional * @param origClientOrderId optional * @param newClientOrderId optional, used to uniquely identify this cancel. Automatically * generated by default. * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @DELETE @Path("api/v3/order") BinanceCancelledOrder cancelOrder( @QueryParam("symbol") String symbol, @QueryParam("orderId") long orderId, @QueryParam("origClientOrderId") String origClientOrderId, @QueryParam("newClientOrderId") String newClientOrderId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Cancels all active orders on a symbol. This includes OCO orders. * * @param symbol * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ @DELETE @Path("api/v3/openOrders") List<BinanceCancelledOrder> cancelAllOpenOrders( @QueryParam("symbol") String symbol, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Get open orders on a symbol. * * @param symbol optional * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ @GET @Path("api/v3/openOrders") List<BinanceOrder> openOrders( @QueryParam("symbol") String symbol, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Get all account orders; active, canceled, or filled. <br> * If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are * returned. * * @param symbol * @param orderId optional * @param limit optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("api/v3/allOrders") List<BinanceOrder> allOrders( @QueryParam("symbol") String symbol, @QueryParam("orderId") Long orderId, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Get current account information. * * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ @GET @Path("api/v3/account") BinanceAccountInformation account( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Get trades for a specific account and symbol. * * @param symbol * @param orderId optional * @param startTime optional * @param endTime optional * @param fromId optional, tradeId to fetch from. Default gets most recent trades. * @param limit optional, default 500; max 1000. * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("api/v3/myTrades") List<BinanceTrade> myTrades( @QueryParam("symbol") String symbol, @QueryParam("orderId") Long orderId, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("fromId") Long fromId, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Submit a withdraw request. * * @param coin * @param address * @param addressTag optional for Ripple * @param amount * @param name optional, description of the address * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @POST @Path("/sapi/v1/capital/withdraw/apply") WithdrawResponse withdraw( @FormParam("coin") String coin, @FormParam("address") String address, @FormParam("addressTag") String addressTag, @FormParam("amount") BigDecimal amount, @FormParam("name") String name, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch deposit history. * * @param coin optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/capital/deposit/hisrec") List<BinanceDeposit> depositHistory( @QueryParam("coin") String coin, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch withdraw history. * * @param coin optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/capital/withdraw/history") List<BinanceWithdraw> withdrawHistory( @QueryParam("coin") String coin, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch small amounts of assets exchanged BNB records. * * @param asset optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/asset/assetDividend") AssetDividendResponse assetDividend( @QueryParam("asset") String asset, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/sub-account/sub/transfer/history") List<TransferHistory> transferHistory( @QueryParam("fromEmail") String fromEmail, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("page") Integer page, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/sub-account/transfer/subUserHistory") List<TransferSubUserHistory> transferSubUserHistory( @QueryParam("asset") String asset, @QueryParam("type") Integer type, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch deposit address. * * @param coin * @param recvWindow * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/capital/deposit/address") DepositAddress depositAddress( @QueryParam("coin") String coin, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch asset details. * * @param recvWindow * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/asset/assetDetail") Map<String, AssetDetail> assetDetail( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Returns a listen key for websocket login. * * @param apiKey the api key * @return * @throws BinanceException * @throws IOException */ @POST @Path("/api/v3/userDataStream") BinanceListenKey startUserDataStream(@HeaderParam(X_MBX_APIKEY) String apiKey) throws IOException, BinanceException; /** * Keeps the authenticated websocket session alive. * * @param apiKey the api key * @param listenKey the api secret * @return * @throws BinanceException * @throws IOException */ @PUT @Path("/api/v3/userDataStream?listenKey={listenKey}") Map<?, ?> keepAliveUserDataStream( @HeaderParam(X_MBX_APIKEY) String apiKey, @PathParam("listenKey") String listenKey) throws IOException, BinanceException; /** * Closes the websocket authenticated connection. * * @param apiKey the api key * @param listenKey the api secret * @return * @throws BinanceException * @throws IOException */ @DELETE @Path("/api/v3/userDataStream?listenKey={listenKey}") Map<?, ?> closeUserDataStream( @HeaderParam(X_MBX_APIKEY) String apiKey, @PathParam("listenKey") String listenKey) throws IOException, BinanceException; }
xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java
package org.knowm.xchange.binance; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import java.util.Map; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.knowm.xchange.binance.dto.BinanceException; import org.knowm.xchange.binance.dto.account.*; import org.knowm.xchange.binance.dto.trade.BinanceCancelledOrder; import org.knowm.xchange.binance.dto.trade.BinanceListenKey; import org.knowm.xchange.binance.dto.trade.BinanceNewOrder; import org.knowm.xchange.binance.dto.trade.BinanceOrder; import org.knowm.xchange.binance.dto.trade.BinanceTrade; import org.knowm.xchange.binance.dto.trade.OrderSide; import org.knowm.xchange.binance.dto.trade.OrderType; import org.knowm.xchange.binance.dto.trade.TimeInForce; import si.mazi.rescu.ParamsDigest; import si.mazi.rescu.SynchronizedValueFactory; @Path("") @Produces(MediaType.APPLICATION_JSON) public interface BinanceAuthenticated extends Binance { String SIGNATURE = "signature"; String X_MBX_APIKEY = "X-MBX-APIKEY"; @POST @Path("api/v3/order") /** * Send in a new order * * @param symbol * @param side * @param type * @param timeInForce * @param quantity * @param price optional, must be provided for limit orders only * @param newClientOrderId optional, a unique id for the order. Automatically generated if not * sent. * @param stopPrice optional, used with stop orders * @param icebergQty optional, used with iceberg orders * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ BinanceNewOrder newOrder( @FormParam("symbol") String symbol, @FormParam("side") OrderSide side, @FormParam("type") OrderType type, @FormParam("timeInForce") TimeInForce timeInForce, @FormParam("quantity") BigDecimal quantity, @FormParam("price") BigDecimal price, @FormParam("newClientOrderId") String newClientOrderId, @FormParam("stopPrice") BigDecimal stopPrice, @FormParam("icebergQty") BigDecimal icebergQty, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @POST @Path("api/v3/order/test") /** * Test new order creation and signature/recvWindow long. Creates and validates a new order but * does not send it into the matching engine. * * @param symbol * @param side * @param type * @param timeInForce * @param quantity * @param price * @param newClientOrderId optional, a unique id for the order. Automatically generated by * default. * @param stopPrice optional, used with STOP orders * @param icebergQty optional used with icebergOrders * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ Object testNewOrder( @FormParam("symbol") String symbol, @FormParam("side") OrderSide side, @FormParam("type") OrderType type, @FormParam("timeInForce") TimeInForce timeInForce, @FormParam("quantity") BigDecimal quantity, @FormParam("price") BigDecimal price, @FormParam("newClientOrderId") String newClientOrderId, @FormParam("stopPrice") BigDecimal stopPrice, @FormParam("icebergQty") BigDecimal icebergQty, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/order") /** * Check an order's status.<br> * Either orderId or origClientOrderId must be sent. * * @param symbol * @param orderId optional * @param origClientOrderId optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ BinanceOrder orderStatus( @QueryParam("symbol") String symbol, @QueryParam("orderId") long orderId, @QueryParam("origClientOrderId") String origClientOrderId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @DELETE @Path("api/v3/order") /** * Cancel an active order. * * @param symbol * @param orderId optional * @param origClientOrderId optional * @param newClientOrderId optional, used to uniquely identify this cancel. Automatically * generated by default. * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ BinanceCancelledOrder cancelOrder( @QueryParam("symbol") String symbol, @QueryParam("orderId") long orderId, @QueryParam("origClientOrderId") String origClientOrderId, @QueryParam("newClientOrderId") String newClientOrderId, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @DELETE @Path("api/v3/openOrders") /** * Cancels all active orders on a symbol. This includes OCO orders. * * @param symbol * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ List<BinanceCancelledOrder> cancelAllOpenOrders( @QueryParam("symbol") String symbol, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/openOrders") /** * Get open orders on a symbol. * * @param symbol optional * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ List<BinanceOrder> openOrders( @QueryParam("symbol") String symbol, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/allOrders") /** * Get all account orders; active, canceled, or filled. <br> * If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are * returned. * * @param symbol * @param orderId optional * @param limit optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ List<BinanceOrder> allOrders( @QueryParam("symbol") String symbol, @QueryParam("orderId") Long orderId, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("api/v3/account") /** * Get current account information. * * @param recvWindow optional * @param timestamp * @return * @throws IOException * @throws BinanceException */ BinanceAccountInformation account( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Get trades for a specific account and symbol. * * @param symbol * @param orderId optional * @param startTime optional * @param endTime optional * @param fromId optional, tradeId to fetch from. Default gets most recent trades. * @param limit optional, default 500; max 1000. * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("api/v3/myTrades") List<BinanceTrade> myTrades( @QueryParam("symbol") String symbol, @QueryParam("orderId") Long orderId, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("fromId") Long fromId, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @POST @Path("/sapi/v1/capital/withdraw/apply") /** * Submit a withdraw request. * * @param coin * @param address * @param addressTag optional for Ripple * @param amount * @param name optional, description of the address * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ WithdrawResponse withdraw( @FormParam("coin") String coin, @FormParam("address") String address, @FormParam("addressTag") String addressTag, @FormParam("amount") BigDecimal amount, @FormParam("name") String name, @FormParam("recvWindow") Long recvWindow, @FormParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/capital/deposit/hisrec") /** * Fetch deposit history. * * @param coin optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ List<BinanceDeposit> depositHistory( @QueryParam("coin") String coin, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/capital/withdraw/history") /** * Fetch withdraw history. * * @param coin optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ List<BinanceWithdraw> withdrawHistory( @QueryParam("coin") String coin, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Fetch small amounts of assets exchanged BNB records. * * @param asset optional * @param startTime optional * @param endTime optional * @param recvWindow optional * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ @GET @Path("/sapi/v1/asset/assetDividend") AssetDividendResponse assetDividend( @QueryParam("asset") String asset, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/sub-account/sub/transfer/history") List<TransferHistory> transferHistory( @QueryParam("fromEmail") String fromEmail, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("page") Integer page, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/sub-account/transfer/subUserHistory") List<TransferSubUserHistory> transferSubUserHistory( @QueryParam("asset") String asset, @QueryParam("type") Integer type, @QueryParam("startTime") Long startTime, @QueryParam("endTime") Long endTime, @QueryParam("limit") Integer limit, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/capital/deposit/address") /** * Fetch deposit address. * * @param coin * @param recvWindow * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ DepositAddress depositAddress( @QueryParam("coin") String coin, @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; @GET @Path("/sapi/v1/asset/assetDetail") /** * Fetch asset details. * * @param recvWindow * @param timestamp * @param apiKey * @param signature * @return * @throws IOException * @throws BinanceException */ Map<String, AssetDetail> assetDetail( @QueryParam("recvWindow") Long recvWindow, @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, @HeaderParam(X_MBX_APIKEY) String apiKey, @QueryParam(SIGNATURE) ParamsDigest signature) throws IOException, BinanceException; /** * Returns a listen key for websocket login. * * @param apiKey the api key * @return * @throws BinanceException * @throws IOException */ @POST @Path("/api/v3/userDataStream") BinanceListenKey startUserDataStream(@HeaderParam(X_MBX_APIKEY) String apiKey) throws IOException, BinanceException; /** * Keeps the authenticated websocket session alive. * * @param apiKey the api key * @param listenKey the api secret * @return * @throws BinanceException * @throws IOException */ @PUT @Path("/api/v3/userDataStream?listenKey={listenKey}") Map<?, ?> keepAliveUserDataStream( @HeaderParam(X_MBX_APIKEY) String apiKey, @PathParam("listenKey") String listenKey) throws IOException, BinanceException; /** * Closes the websocket authenticated connection. * * @param apiKey the api key * @param listenKey the api secret * @return * @throws BinanceException * @throws IOException */ @DELETE @Path("/api/v3/userDataStream?listenKey={listenKey}") Map<?, ?> closeUserDataStream( @HeaderParam(X_MBX_APIKEY) String apiKey, @PathParam("listenKey") String listenKey) throws IOException, BinanceException; }
Update BinanceAuthenticated.java
xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java
Update BinanceAuthenticated.java
<ide><path>change-binance/src/main/java/org/knowm/xchange/binance/BinanceAuthenticated.java <ide> String SIGNATURE = "signature"; <ide> String X_MBX_APIKEY = "X-MBX-APIKEY"; <ide> <del> @POST <del> @Path("api/v3/order") <ide> /** <ide> * Send in a new order <ide> * <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @POST <add> @Path("api/v3/order") <ide> BinanceNewOrder newOrder( <ide> @FormParam("symbol") String symbol, <ide> @FormParam("side") OrderSide side, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @POST <del> @Path("api/v3/order/test") <ide> /** <ide> * Test new order creation and signature/recvWindow long. Creates and validates a new order but <ide> * does not send it into the matching engine. <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @POST <add> @Path("api/v3/order/test") <ide> Object testNewOrder( <ide> @FormParam("symbol") String symbol, <ide> @FormParam("side") OrderSide side, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @GET <del> @Path("api/v3/order") <ide> /** <ide> * Check an order's status.<br> <ide> * Either orderId or origClientOrderId must be sent. <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @GET <add> @Path("api/v3/order") <ide> BinanceOrder orderStatus( <ide> @QueryParam("symbol") String symbol, <ide> @QueryParam("orderId") long orderId, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @DELETE <del> @Path("api/v3/order") <ide> /** <ide> * Cancel an active order. <ide> * <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @DELETE <add> @Path("api/v3/order") <ide> BinanceCancelledOrder cancelOrder( <ide> @QueryParam("symbol") String symbol, <ide> @QueryParam("orderId") long orderId, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <add> /** <add> * Cancels all active orders on a symbol. This includes OCO orders. <add> * <add> * @param symbol <add> * @param recvWindow optional <add> * @param timestamp <add> * @return <add> * @throws IOException <add> * @throws BinanceException <add> */ <ide> @DELETE <ide> @Path("api/v3/openOrders") <del> /** <del> * Cancels all active orders on a symbol. This includes OCO orders. <del> * <del> * @param symbol <del> * @param recvWindow optional <del> * @param timestamp <del> * @return <del> * @throws IOException <del> * @throws BinanceException <del> */ <ide> List<BinanceCancelledOrder> cancelAllOpenOrders( <ide> @QueryParam("symbol") String symbol, <ide> @QueryParam("recvWindow") Long recvWindow, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <add> /** <add> * Get open orders on a symbol. <add> * <add> * @param symbol optional <add> * @param recvWindow optional <add> * @param timestamp <add> * @return <add> * @throws IOException <add> * @throws BinanceException <add> */ <ide> @GET <ide> @Path("api/v3/openOrders") <del> /** <del> * Get open orders on a symbol. <del> * <del> * @param symbol optional <del> * @param recvWindow optional <del> * @param timestamp <del> * @return <del> * @throws IOException <del> * @throws BinanceException <del> */ <ide> List<BinanceOrder> openOrders( <ide> @QueryParam("symbol") String symbol, <ide> @QueryParam("recvWindow") Long recvWindow, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @GET <del> @Path("api/v3/allOrders") <ide> /** <ide> * Get all account orders; active, canceled, or filled. <br> <ide> * If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @GET <add> @Path("api/v3/allOrders") <ide> List<BinanceOrder> allOrders( <ide> @QueryParam("symbol") String symbol, <ide> @QueryParam("orderId") Long orderId, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <add> /** <add> * Get current account information. <add> * <add> * @param recvWindow optional <add> * @param timestamp <add> * @return <add> * @throws IOException <add> * @throws BinanceException <add> */ <ide> @GET <ide> @Path("api/v3/account") <del> /** <del> * Get current account information. <del> * <del> * @param recvWindow optional <del> * @param timestamp <del> * @return <del> * @throws IOException <del> * @throws BinanceException <del> */ <ide> BinanceAccountInformation account( <ide> @QueryParam("recvWindow") Long recvWindow, <ide> @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> /** <add> /** <ide> * Get trades for a specific account and symbol. <ide> * <ide> * @param symbol <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @POST <del> @Path("/sapi/v1/capital/withdraw/apply") <ide> /** <ide> * Submit a withdraw request. <ide> * <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @POST <add> @Path("/sapi/v1/capital/withdraw/apply") <ide> WithdrawResponse withdraw( <ide> @FormParam("coin") String coin, <ide> @FormParam("address") String address, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @GET <del> @Path("/sapi/v1/capital/deposit/hisrec") <ide> /** <ide> * Fetch deposit history. <ide> * <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @GET <add> @Path("/sapi/v1/capital/deposit/hisrec") <ide> List<BinanceDeposit> depositHistory( <ide> @QueryParam("coin") String coin, <ide> @QueryParam("startTime") Long startTime, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @GET <del> @Path("/sapi/v1/capital/withdraw/history") <ide> /** <ide> * Fetch withdraw history. <ide> * <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @GET <add> @Path("/sapi/v1/capital/withdraw/history") <ide> List<BinanceWithdraw> withdrawHistory( <ide> @QueryParam("coin") String coin, <ide> @QueryParam("startTime") Long startTime, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <del> @GET <del> @Path("/sapi/v1/capital/deposit/address") <ide> /** <ide> * Fetch deposit address. <ide> * <ide> * @throws IOException <ide> * @throws BinanceException <ide> */ <add> @GET <add> @Path("/sapi/v1/capital/deposit/address") <ide> DepositAddress depositAddress( <ide> @QueryParam("coin") String coin, <ide> @QueryParam("recvWindow") Long recvWindow, <ide> @QueryParam(SIGNATURE) ParamsDigest signature) <ide> throws IOException, BinanceException; <ide> <add> /** <add> * Fetch asset details. <add> * <add> * @param recvWindow <add> * @param timestamp <add> * @param apiKey <add> * @param signature <add> * @return <add> * @throws IOException <add> * @throws BinanceException <add> */ <ide> @GET <ide> @Path("/sapi/v1/asset/assetDetail") <del> /** <del> * Fetch asset details. <del> * <del> * @param recvWindow <del> * @param timestamp <del> * @param apiKey <del> * @param signature <del> * @return <del> * @throws IOException <del> * @throws BinanceException <del> */ <ide> Map<String, AssetDetail> assetDetail( <ide> @QueryParam("recvWindow") Long recvWindow, <ide> @QueryParam("timestamp") SynchronizedValueFactory<Long> timestamp,
JavaScript
mit
040ad39d2b7612914fb818c0dbe24129f6438d3a
0
jmhardison/adfsusermappingapi
//////////////////////////////////////// // ADFSUserMappingAPI // // Copyright (c) 2017 Jonathan Hardison // /controllers/user.js /////////////////////////////////////// import mongoose from 'mongoose'; import express from 'express'; import {Router} from 'express'; import User from '../models/user'; import Altid from '../models/altid'; export default({ config, db}) => { let api = Router(); // general get from alternate email address input api.get('/altid/email/:altemail', (req, res) => { Altid.find({email: req.params.altemail}, (err, altid) =>{ if(err){ res.status(500).send(err); } if(typeof altid !== "undefined"){ User.findById(altid[0].user, (err, user) =>{ if(err){ res.status(500).send(err); } res.status(200).send(user.realid); }); } else{ res.status(200).send(req.params.altemail); } }) }); // general get from alternate email by id api.get('/altid/:id', (req, res) => { Altid.findById(req.params.id, (err, altid) =>{ if(err){ res.status(500).send(err); } res.status(200).send(altid.realid); }) }); // general get from real email address input api.get('/email/:realemail', (req, res) => { User.find({realid: req.params.realemail}, (err, user) =>{ if(err){ res.status(500).send(err); } res.status(200).json(user); }) }); // general get from real email address input with ID api.get('/:id', (req, res) => { User.findById(req.params.realemail, (err, user) =>{ if(err){ res.status(500).send(err); } res.status(200).json(user); }) }); // general post to stage some users api.post('/', (req, res) => { let newUser = new User(); newUser.realid = req.body.realid; newUser.save(err => { if(err){ res.status(500).send(err); } res.status(200).json({message: "Real user created successfully"}); }); }); // general post to stage some alt id's api.post('/altid/:realid', (req, res) => { User.findById(req.params.realid, (err, user) => { if(err){ res.status(500).send(err); } let newAltID = new Altid(); newAltID.email = req.body.email; newAltID.user = user.id; newAltID.save((err, altid) => { if(err){ res.status(500).send(err); } user.altids.push(newAltID); user.save(err => { if(err){ res.status(500).send(err); } res.status(200).json({message: "Alt ID created successfully"}); }); }); }); }); return api; }
src/controllers/user.js
//////////////////////////////////////// // ADFSUserMappingAPI // // Copyright (c) 2017 Jonathan Hardison // /controllers/user.js /////////////////////////////////////// import mongoose from 'mongoose'; import express from 'express'; import {Router} from 'express'; import User from '../models/user'; import Altid from '../models/altid'; export default({ config, db}) => { let api = Router(); // general get from alternate email address input api.get('/altid/email/:altemail', (req, res) => { Altid.find({email: req.params.altemail}, (err, altid) =>{ if(err){ res.status(500).send(err); } if((altid != null) && (typeof altid !== "undefined")){ User.findById(altid[0].user, (err, user) =>{ if(err){ res.status(500).send(err); } res.status(200).send(user.realid); }); } else{ res.status(200).send(req.params.altemail); } }) }); // general get from alternate email by id api.get('/altid/:id', (req, res) => { Altid.findById(req.params.id, (err, altid) =>{ if(err){ res.status(500).send(err); } res.status(200).send(altid.realid); }) }); // general get from real email address input api.get('/email/:realemail', (req, res) => { User.find({realid: req.params.realemail}, (err, user) =>{ if(err){ res.status(500).send(err); } res.status(200).json(user); }) }); // general get from real email address input with ID api.get('/:id', (req, res) => { User.findById(req.params.realemail, (err, user) =>{ if(err){ res.status(500).send(err); } res.status(200).json(user); }) }); // general post to stage some users api.post('/', (req, res) => { let newUser = new User(); newUser.realid = req.body.realid; newUser.save(err => { if(err){ res.status(500).send(err); } res.status(200).json({message: "Real user created successfully"}); }); }); // general post to stage some alt id's api.post('/altid/:realid', (req, res) => { User.findById(req.params.realid, (err, user) => { if(err){ res.status(500).send(err); } let newAltID = new Altid(); newAltID.email = req.body.email; newAltID.user = user.id; newAltID.save((err, altid) => { if(err){ res.status(500).send(err); } user.altids.push(newAltID); user.save(err => { if(err){ res.status(500).send(err); } res.status(200).json({message: "Alt ID created successfully"}); }); }); }); }); return api; }
typof change
src/controllers/user.js
typof change
<ide><path>rc/controllers/user.js <ide> res.status(500).send(err); <ide> } <ide> <del> if((altid != null) && (typeof altid !== "undefined")){ <add> if(typeof altid !== "undefined"){ <ide> User.findById(altid[0].user, (err, user) =>{ <ide> if(err){ <ide> res.status(500).send(err);
Java
apache-2.0
19fd1c7f0c33c69d8826e011c7fbf7ae237f2f0f
0
muntasirsyed/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,apixandru/intellij-community,apixandru/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,da1z/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ibinti/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,samthor/intellij-community,amith01994/intellij-community,fnouama/intellij-community,hurricup/intellij-community,allotria/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kdwink/intellij-community,da1z/intellij-community,kool79/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,allotria/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,da1z/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,semonte/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,da1z/intellij-community,semonte/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,semonte/intellij-community,amith01994/intellij-community,jagguli/intellij-community,vladmm/intellij-community,slisson/intellij-community,blademainer/intellij-community,retomerz/intellij-community,slisson/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,blademainer/intellij-community,semonte/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,kool79/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,signed/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,slisson/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,blademainer/intellij-community,jagguli/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,blademainer/intellij-community,FHannes/intellij-community,kool79/intellij-community,jagguli/intellij-community,da1z/intellij-community,ibinti/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,vladmm/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,apixandru/intellij-community,FHannes/intellij-community,asedunov/intellij-community,asedunov/intellij-community,kool79/intellij-community,signed/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,slisson/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,clumsy/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,semonte/intellij-community,ibinti/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,da1z/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,samthor/intellij-community,xfournet/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,clumsy/intellij-community,xfournet/intellij-community,vladmm/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,samthor/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,allotria/intellij-community,FHannes/intellij-community,signed/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,fnouama/intellij-community,allotria/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,samthor/intellij-community,allotria/intellij-community,kool79/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,vladmm/intellij-community,signed/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,apixandru/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,retomerz/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,jagguli/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,hurricup/intellij-community,blademainer/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,allotria/intellij-community,hurricup/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,da1z/intellij-community,allotria/intellij-community,ibinti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,signed/intellij-community,semonte/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,samthor/intellij-community,samthor/intellij-community,fnouama/intellij-community,asedunov/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,wreckJ/intellij-community,samthor/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,samthor/intellij-community,FHannes/intellij-community,jagguli/intellij-community,allotria/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,kool79/intellij-community,semonte/intellij-community,fitermay/intellij-community,clumsy/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,da1z/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,fnouama/intellij-community,da1z/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,blademainer/intellij-community,retomerz/intellij-community,signed/intellij-community,vladmm/intellij-community,ibinti/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,fnouama/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,slisson/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,slisson/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,vladmm/intellij-community,allotria/intellij-community,semonte/intellij-community,blademainer/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Class EvaluatorBuilderImpl * @author Jeka */ package com.intellij.debugger.engine.evaluation.expression; import com.intellij.codeInsight.daemon.JavaErrorMessages; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.SourcePosition; import com.intellij.debugger.engine.ContextUtil; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.debugger.engine.JVMName; import com.intellij.debugger.engine.JVMNameUtil; import com.intellij.debugger.engine.evaluation.*; import com.intellij.debugger.impl.DebuggerUtilsEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.IncorrectOperationException; import com.sun.jdi.Value; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class EvaluatorBuilderImpl implements EvaluatorBuilder { private static final EvaluatorBuilderImpl ourInstance = new EvaluatorBuilderImpl(); private EvaluatorBuilderImpl() { } public static EvaluatorBuilder getInstance() { return ourInstance; } public static ExpressionEvaluator build(final TextWithImports text, @Nullable PsiElement contextElement, final SourcePosition position) throws EvaluateException { if (contextElement == null) { throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS; } final Project project = contextElement.getProject(); CodeFragmentFactory factory = DebuggerUtilsEx.findAppropriateCodeFragmentFactory(text, contextElement); PsiCodeFragment codeFragment = factory.createCodeFragment(text, contextElement, project); if (codeFragment == null) { throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", text.getText())); } codeFragment.forceResolveScope(GlobalSearchScope.allScope(project)); DebuggerUtils.checkSyntax(codeFragment); return factory.getEvaluatorBuilder().build(codeFragment, position); } @Override public ExpressionEvaluator build(final PsiElement codeFragment, final SourcePosition position) throws EvaluateException { return new Builder(position).buildElement(codeFragment); } private static class Builder extends JavaElementVisitor { private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl"); private Evaluator myResult = null; private PsiClass myContextPsiClass; private CodeFragmentEvaluator myCurrentFragmentEvaluator; private final Set<JavaCodeFragment> myVisitedFragments = new HashSet<JavaCodeFragment>(); @Nullable private final SourcePosition myPosition; private Builder(@Nullable SourcePosition position) { myPosition = position; } @Override public void visitCodeFragment(JavaCodeFragment codeFragment) { myVisitedFragments.add(codeFragment); ArrayList<Evaluator> evaluators = new ArrayList<Evaluator>(); CodeFragmentEvaluator oldFragmentEvaluator = myCurrentFragmentEvaluator; myCurrentFragmentEvaluator = new CodeFragmentEvaluator(oldFragmentEvaluator); for (PsiElement child = codeFragment.getFirstChild(); child != null; child = child.getNextSibling()) { child.accept(this); if(myResult != null) { evaluators.add(myResult); } myResult = null; } myCurrentFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[evaluators.size()])); myResult = myCurrentFragmentEvaluator; myCurrentFragmentEvaluator = oldFragmentEvaluator; } @Override public void visitErrorElement(PsiErrorElement element) { throwExpressionInvalid(element); } @Override public void visitAssignmentExpression(PsiAssignmentExpression expression) { final PsiExpression rExpression = expression.getRExpression(); if(rExpression == null) { throwExpressionInvalid(expression); } rExpression.accept(this); Evaluator rEvaluator = myResult; final PsiExpression lExpression = expression.getLExpression(); final PsiType lType = lExpression.getType(); if(lType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", lExpression.getText())); } IElementType assignmentType = expression.getOperationTokenType(); PsiType rType = rExpression.getType(); if(!TypeConversionUtil.areTypesAssignmentCompatible(lType, rExpression) && rType != null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.incompatible.types", expression.getOperationSign().getText())); } lExpression.accept(this); Evaluator lEvaluator = myResult; rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(lType, rType, rEvaluator); if (assignmentType != JavaTokenType.EQ) { IElementType opType = TypeConversionUtil.convertEQtoOperation(assignmentType); final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true); if (typeForBinOp == null || rType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } rEvaluator = createBinaryEvaluator(lEvaluator, lType, rEvaluator, rType, opType, typeForBinOp); } myResult = new AssignmentEvaluator(lEvaluator, rEvaluator); } // returns rEvaluator possibly wrapped with boxing/unboxing and casting evaluators private static Evaluator handleAssignmentBoxingAndPrimitiveTypeConversions(PsiType lType, PsiType rType, Evaluator rEvaluator) { final PsiType unboxedLType = PsiPrimitiveType.getUnboxedType(lType); if (unboxedLType != null) { if (rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(rType)) { if (!rType.equals(unboxedLType)) { rEvaluator = new TypeCastEvaluator(rEvaluator, unboxedLType.getCanonicalText(), true); } rEvaluator = new BoxingEvaluator(rEvaluator); } } else { // either primitive type or not unboxable type if (lType instanceof PsiPrimitiveType) { if (rType instanceof PsiClassType) { rEvaluator = new UnBoxingEvaluator(rEvaluator); } final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType); final PsiType _rType = unboxedRType != null? unboxedRType : rType; if (_rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(_rType)) { if (!lType.equals(_rType)) { rEvaluator = new TypeCastEvaluator(rEvaluator, lType.getCanonicalText(), true); } } } } return rEvaluator; } @Override public void visitTryStatement(PsiTryStatement statement) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(statement.getText())); } @Override public void visitStatement(PsiStatement statement) { throwEvaluateException(DebuggerBundle.message("evaluation.error.statement.not.supported", statement.getText())); } @Override public void visitBlockStatement(PsiBlockStatement statement) { PsiStatement[] statements = statement.getCodeBlock().getStatements(); Evaluator [] evaluators = new Evaluator[statements.length]; for (int i = 0; i < statements.length; i++) { PsiStatement psiStatement = statements[i]; psiStatement.accept(this); evaluators[i] = new DisableGC(myResult); myResult = null; } myResult = new BlockStatementEvaluator(evaluators); } @Override public void visitLabeledStatement(PsiLabeledStatement labeledStatement) { PsiStatement statement = labeledStatement.getStatement(); if (statement != null) { statement.accept(this); } } private static String getLabel(PsiElement element) { String label = null; if(element.getParent() instanceof PsiLabeledStatement) { label = ((PsiLabeledStatement)element.getParent()).getName(); } return label; } @Override public void visitDoWhileStatement(PsiDoWhileStatement statement) { Evaluator bodyEvaluator = accept(statement.getBody()); Evaluator conditionEvaluator = accept(statement.getCondition()); if (conditionEvaluator != null) { myResult = new DoWhileStatementEvaluator(new UnBoxingEvaluator(conditionEvaluator), bodyEvaluator, getLabel(statement)); } } @Override public void visitWhileStatement(PsiWhileStatement statement) { Evaluator bodyEvaluator = accept(statement.getBody()); Evaluator conditionEvaluator = accept(statement.getCondition()); if (conditionEvaluator != null) { myResult = new WhileStatementEvaluator(new UnBoxingEvaluator(conditionEvaluator), bodyEvaluator, getLabel(statement)); } } @Override public void visitForStatement(PsiForStatement statement) { Evaluator initializerEvaluator = accept(statement.getInitialization()); Evaluator conditionEvaluator = accept(statement.getCondition()); if (conditionEvaluator != null) { conditionEvaluator = new UnBoxingEvaluator(conditionEvaluator); } Evaluator updateEvaluator = accept(statement.getUpdate()); Evaluator bodyEvaluator = accept(statement.getBody()); if (bodyEvaluator != null) { myResult = new ForStatementEvaluator(initializerEvaluator, conditionEvaluator, updateEvaluator, bodyEvaluator, getLabel(statement)); } } @Override public void visitForeachStatement(PsiForeachStatement statement) { try { String iterationParameterName = statement.getIterationParameter().getName(); myCurrentFragmentEvaluator.setInitialValue(iterationParameterName, null); SyntheticVariableEvaluator iterationParameterEvaluator = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, iterationParameterName); Evaluator iteratedValueEvaluator = accept(statement.getIteratedValue()); Evaluator bodyEvaluator = accept(statement.getBody()); if (bodyEvaluator != null) { myResult = new ForeachStatementEvaluator(iterationParameterEvaluator, iteratedValueEvaluator, bodyEvaluator, getLabel(statement)); } } catch (EvaluateException e) { throw new EvaluateRuntimeException(e); } } @Nullable private Evaluator accept(@Nullable PsiElement element) { if (element == null || element instanceof PsiEmptyStatement) { return null; } element.accept(this); return myResult; } @Override public void visitIfStatement(PsiIfStatement statement) { PsiStatement thenBranch = statement.getThenBranch(); if(thenBranch == null) return; thenBranch.accept(this); Evaluator thenEvaluator = myResult; PsiStatement elseBranch = statement.getElseBranch(); Evaluator elseEvaluator = null; if(elseBranch != null){ elseBranch.accept(this); elseEvaluator = myResult; } PsiExpression condition = statement.getCondition(); if(condition == null) return; condition.accept(this); myResult = new IfStatementEvaluator(new UnBoxingEvaluator(myResult), thenEvaluator, elseEvaluator); } @Override public void visitBreakStatement(PsiBreakStatement statement) { PsiIdentifier labelIdentifier = statement.getLabelIdentifier(); myResult = BreakContinueStatementEvaluator.createBreakEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null); } @Override public void visitContinueStatement(PsiContinueStatement statement) { PsiIdentifier labelIdentifier = statement.getLabelIdentifier(); myResult = BreakContinueStatementEvaluator.createContinueEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null); } @Override public void visitExpressionStatement(PsiExpressionStatement statement) { statement.getExpression().accept(this); } @Override public void visitExpression(PsiExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitExpression " + expression); } } @Override public void visitPolyadicExpression(PsiPolyadicExpression wideExpression) { if (LOG.isDebugEnabled()) { LOG.debug("visitPolyadicExpression " + wideExpression); } PsiExpression[] operands = wideExpression.getOperands(); operands[0].accept(this); Evaluator result = myResult; PsiType lType = operands[0].getType(); for (int i = 1; i < operands.length; i++) { PsiExpression expression = operands[i]; if (expression == null) { throwExpressionInvalid(wideExpression); } expression.accept(this); Evaluator rResult = myResult; IElementType opType = wideExpression.getOperationTokenType(); PsiType rType = expression.getType(); if (rType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true); if (typeForBinOp == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", wideExpression.getText())); } myResult = createBinaryEvaluator(result, lType, rResult, rType, opType, typeForBinOp); lType = typeForBinOp; result = myResult; } } // constructs binary evaluator handling unboxing and numeric promotion issues private static BinaryExpressionEvaluator createBinaryEvaluator(Evaluator lResult, PsiType lType, Evaluator rResult, @NotNull PsiType rType, @NotNull IElementType operation, @NotNull PsiType expressionExpectedType) { // handle unboxing if necessary if (isUnboxingInBinaryExpressionApplicable(lType, rType, operation)) { if (rType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(rType.getCanonicalText())) { rResult = new UnBoxingEvaluator(rResult); } if (lType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(lType.getCanonicalText())) { lResult = new UnBoxingEvaluator(lResult); } } if (isBinaryNumericPromotionApplicable(lType, rType, operation)) { PsiType _lType = lType; final PsiPrimitiveType unboxedLType = PsiPrimitiveType.getUnboxedType(lType); if (unboxedLType != null) { _lType = unboxedLType; } PsiType _rType = rType; final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType); if (unboxedRType != null) { _rType = unboxedRType; } // handle numeric promotion if (PsiType.DOUBLE.equals(_lType)) { if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.DOUBLE)) { rResult = new TypeCastEvaluator(rResult, PsiType.DOUBLE.getCanonicalText(), true); } } else if (PsiType.DOUBLE.equals(_rType)) { if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.DOUBLE)) { lResult = new TypeCastEvaluator(lResult, PsiType.DOUBLE.getCanonicalText(), true); } } else if (PsiType.FLOAT.equals(_lType)) { if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.FLOAT)) { rResult = new TypeCastEvaluator(rResult, PsiType.FLOAT.getCanonicalText(), true); } } else if (PsiType.FLOAT.equals(_rType)) { if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.FLOAT)) { lResult = new TypeCastEvaluator(lResult, PsiType.FLOAT.getCanonicalText(), true); } } else if (PsiType.LONG.equals(_lType)) { if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.LONG)) { rResult = new TypeCastEvaluator(rResult, PsiType.LONG.getCanonicalText(), true); } } else if (PsiType.LONG.equals(_rType)) { if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.LONG)) { lResult = new TypeCastEvaluator(lResult, PsiType.LONG.getCanonicalText(), true); } } else { if (!PsiType.INT.equals(_lType) && TypeConversionUtil.areTypesConvertible(_lType, PsiType.INT)) { lResult = new TypeCastEvaluator(lResult, PsiType.INT.getCanonicalText(), true); } if (!PsiType.INT.equals(_rType) && TypeConversionUtil.areTypesConvertible(_rType, PsiType.INT)) { rResult = new TypeCastEvaluator(rResult, PsiType.INT.getCanonicalText(), true); } } } return new BinaryExpressionEvaluator(lResult, rResult, operation, expressionExpectedType.getCanonicalText()); } private static boolean isBinaryNumericPromotionApplicable(PsiType lType, PsiType rType, IElementType opType) { if (lType == null || rType == null) { return false; } if (!TypeConversionUtil.isNumericType(lType) || !TypeConversionUtil.isNumericType(rType)) { return false; } if (opType == JavaTokenType.EQEQ || opType == JavaTokenType.NE) { if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) { return false; } if (lType instanceof PsiClassType && rType instanceof PsiClassType) { return false; } if (lType instanceof PsiClassType) { return PsiPrimitiveType.getUnboxedType(lType) != null; // should be unboxable } if (rType instanceof PsiClassType) { return PsiPrimitiveType.getUnboxedType(rType) != null; // should be unboxable } return true; } return opType == JavaTokenType.ASTERISK || opType == JavaTokenType.DIV || opType == JavaTokenType.PERC || opType == JavaTokenType.PLUS || opType == JavaTokenType.MINUS || opType == JavaTokenType.LT || opType == JavaTokenType.LE || opType == JavaTokenType.GT || opType == JavaTokenType.GE || opType == JavaTokenType.AND || opType == JavaTokenType.XOR || opType == JavaTokenType.OR; } private static boolean isUnboxingInBinaryExpressionApplicable(PsiType lType, PsiType rType, IElementType opCode) { if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) { return false; } // handle '==' and '!=' separately if (opCode == JavaTokenType.EQEQ || opCode == JavaTokenType.NE) { return lType instanceof PsiPrimitiveType && rType instanceof PsiClassType || lType instanceof PsiClassType && rType instanceof PsiPrimitiveType; } // concat with a String if (opCode == JavaTokenType.PLUS) { if ((lType instanceof PsiClassType && lType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) || (rType instanceof PsiClassType && rType.equalsToText(CommonClassNames.JAVA_LANG_STRING))){ return false; } } // all other operations at least one should be of class type return lType instanceof PsiClassType || rType instanceof PsiClassType; } /** * @param type * @return promotion type to cast to or null if no casting needed */ @Nullable private static PsiType calcUnaryNumericPromotionType(PsiPrimitiveType type) { if (PsiType.BYTE.equals(type) || PsiType.SHORT.equals(type) || PsiType.CHAR.equals(type) || PsiType.INT.equals(type)) { return PsiType.INT; } return null; } @Override public void visitDeclarationStatement(PsiDeclarationStatement statement) { List<Evaluator> evaluators = new ArrayList<Evaluator>(); PsiElement[] declaredElements = statement.getDeclaredElements(); for (PsiElement declaredElement : declaredElements) { if (declaredElement instanceof PsiLocalVariable) { if (myCurrentFragmentEvaluator != null) { final PsiLocalVariable localVariable = (PsiLocalVariable)declaredElement; final PsiType lType = localVariable.getType(); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(localVariable.getProject()).getElementFactory(); try { PsiExpression initialValue = elementFactory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(lType), null); Object value = JavaConstantExpressionEvaluator.computeConstantExpression(initialValue, true); myCurrentFragmentEvaluator.setInitialValue(localVariable.getName(), value); } catch (IncorrectOperationException e) { LOG.error(e); } catch (EvaluateException e) { throw new EvaluateRuntimeException(e); } PsiExpression initializer = localVariable.getInitializer(); if (initializer != null) { try { if (!TypeConversionUtil.areTypesAssignmentCompatible(lType, initializer)) { throwEvaluateException( DebuggerBundle.message("evaluation.error.incompatible.variable.initializer.type", localVariable.getName())); } final PsiType rType = initializer.getType(); initializer.accept(this); Evaluator rEvaluator = myResult; PsiExpression localVarReference = elementFactory.createExpressionFromText(localVariable.getName(), initializer); localVarReference.accept(this); Evaluator lEvaluator = myResult; rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(localVarReference.getType(), rType, rEvaluator); Evaluator assignment = new AssignmentEvaluator(lEvaluator, rEvaluator); evaluators.add(assignment); } catch (IncorrectOperationException e) { LOG.error(e); } } } else { throw new EvaluateRuntimeException(new EvaluateException( DebuggerBundle.message("evaluation.error.local.variable.declarations.not.supported"), null)); } } else { throw new EvaluateRuntimeException(new EvaluateException( DebuggerBundle.message("evaluation.error.unsupported.declaration", declaredElement.getText()), null)); } } if(!evaluators.isEmpty()) { CodeFragmentEvaluator codeFragmentEvaluator = new CodeFragmentEvaluator(myCurrentFragmentEvaluator); codeFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[evaluators.size()])); myResult = codeFragmentEvaluator; } else { myResult = null; } } @Override public void visitConditionalExpression(PsiConditionalExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitConditionalExpression " + expression); } final PsiExpression thenExpression = expression.getThenExpression(); final PsiExpression elseExpression = expression.getElseExpression(); if (thenExpression == null || elseExpression == null){ throwExpressionInvalid(expression); } PsiExpression condition = expression.getCondition(); condition.accept(this); if (myResult == null) { throwExpressionInvalid(condition); } Evaluator conditionEvaluator = new UnBoxingEvaluator(myResult); thenExpression.accept(this); if (myResult == null) { throwExpressionInvalid(thenExpression); } Evaluator thenEvaluator = myResult; elseExpression.accept(this); if (myResult == null) { throwExpressionInvalid(elseExpression); } Evaluator elseEvaluator = myResult; myResult = new ConditionalExpressionEvaluator(conditionEvaluator, thenEvaluator, elseEvaluator); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitReferenceExpression " + expression); } PsiExpression qualifier = expression.getQualifierExpression(); JavaResolveResult resolveResult = expression.advancedResolve(true); PsiElement element = resolveResult.getElement(); if (element instanceof PsiLocalVariable || element instanceof PsiParameter) { final Value labeledValue = element.getUserData(CodeFragmentFactoryContextWrapper.LABEL_VARIABLE_VALUE_KEY); if (labeledValue != null) { myResult = new IdentityEvaluator(labeledValue); return; } //synthetic variable final PsiFile containingFile = element.getContainingFile(); if(containingFile instanceof PsiCodeFragment && myCurrentFragmentEvaluator != null && myVisitedFragments.contains(containingFile)) { // psiVariable may live in PsiCodeFragment not only in debugger editors, for example Fabrique has such variables. // So treat it as synthetic var only when this code fragment is located in DebuggerEditor, // that's why we need to check that containing code fragment is the one we visited myResult = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, ((PsiVariable)element).getName()); return; } // local variable final PsiVariable psiVar = (PsiVariable)element; final String localName = psiVar.getName(); PsiClass variableClass = getContainingClass(psiVar); if (getContextPsiClass() == null || getContextPsiClass().equals(variableClass)) { PsiElement method = PsiTreeUtil.getContextOfType(expression, PsiMethod.class, PsiLambdaExpression.class); boolean canScanFrames = method instanceof PsiLambdaExpression || ContextUtil.isJspImplicit(element); LocalVariableEvaluator localVarEvaluator = new LocalVariableEvaluator(localName, canScanFrames); if (psiVar instanceof PsiParameter) { final PsiParameter param = (PsiParameter)psiVar; final PsiParameterList paramList = PsiTreeUtil.getParentOfType(param, PsiParameterList.class, true); if (paramList != null) { localVarEvaluator.setParameterIndex(paramList.getParameterIndex(param)); } } myResult = localVarEvaluator; return; } // the expression references final var outside the context's class (in some of the outer classes) int iterationCount = 0; PsiClass aClass = getOuterClass(getContextPsiClass()); while (aClass != null && !aClass.equals(variableClass)) { iterationCount++; aClass = getOuterClass(aClass); } if (aClass != null) { PsiExpression initializer = psiVar.getInitializer(); if(initializer != null) { Object value = JavaPsiFacade.getInstance(psiVar.getProject()).getConstantEvaluationHelper().computeConstantExpression(initializer); if(value != null) { PsiType type = resolveResult.getSubstitutor().substitute(psiVar.getType()); myResult = new LiteralEvaluator(value, type.getCanonicalText()); return; } } Evaluator objectEvaluator = new ThisEvaluator(iterationCount); //noinspection HardCodedStringLiteral final PsiClass classAt = myPosition != null? JVMNameUtil.getClassAt(myPosition) : null; FieldEvaluator.TargetClassFilter filter = FieldEvaluator.createClassFilter(classAt != null? classAt : getContextPsiClass()); myResult = new FieldEvaluator(objectEvaluator, filter, "val$" + localName); return; } throwEvaluateException(DebuggerBundle.message("evaluation.error.local.variable.missing.from.class.closure", localName)); } else if (element instanceof PsiField) { final PsiField psiField = (PsiField)element; final PsiClass fieldClass = psiField.getContainingClass(); if(fieldClass == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.resolve.field.class", psiField.getName())); return; } Evaluator objectEvaluator; if (psiField.hasModifierProperty(PsiModifier.STATIC)) { objectEvaluator = new TypeEvaluator(JVMNameUtil.getContextClassJVMQualifiedName(SourcePosition.createFromElement(psiField))); } else if(qualifier != null) { qualifier.accept(this); objectEvaluator = myResult; } else if (fieldClass.equals(getContextPsiClass()) || (getContextPsiClass() != null && getContextPsiClass().isInheritor(fieldClass, true))) { objectEvaluator = new ThisEvaluator(); } else { // myContextPsiClass != fieldClass && myContextPsiClass is not a subclass of fieldClass int iterationCount = 0; PsiClass aClass = getContextPsiClass(); while (aClass != null && !(aClass.equals(fieldClass) || aClass.isInheritor(fieldClass, true))) { iterationCount++; aClass = getOuterClass(aClass); } if (aClass == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.sources.for.field.class", psiField.getName())); } objectEvaluator = new ThisEvaluator(iterationCount); } myResult = new FieldEvaluator(objectEvaluator, FieldEvaluator.createClassFilter(fieldClass), psiField.getName()); } else { //let's guess what this could be PsiElement nameElement = expression.getReferenceNameElement(); // get "b" part String name; if (nameElement instanceof PsiIdentifier) { name = nameElement.getText(); } else { //noinspection HardCodedStringLiteral final String elementDisplayString = nameElement != null ? nameElement.getText() : "(null)"; throwEvaluateException(DebuggerBundle.message("evaluation.error.identifier.expected", elementDisplayString)); return; } if(qualifier != null) { final PsiElement qualifierTarget = qualifier instanceof PsiReferenceExpression ? ((PsiReferenceExpression)qualifier).resolve() : null; if (qualifierTarget instanceof PsiClass) { // this is a call to a 'static' field PsiClass psiClass = (PsiClass)qualifierTarget; final JVMName typeName = JVMNameUtil.getJVMQualifiedName(psiClass); myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.createClassFilter(psiClass), name); } else { qualifier.accept(this); if (myResult == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.evaluate.qualifier", qualifier.getText())); } myResult = new FieldEvaluator(myResult, FieldEvaluator.createClassFilter(qualifier.getType()), name); } } else { myResult = new LocalVariableEvaluator(name, false); } } } private static void throwExpressionInvalid(PsiElement expression) { throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText())); } private static void throwEvaluateException(String message) throws EvaluateRuntimeException { throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(message)); } @Override public void visitSuperExpression(PsiSuperExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitSuperExpression " + expression); } final int iterationCount = calcIterationCount(expression.getQualifier()); myResult = new SuperEvaluator(iterationCount); } @Override public void visitThisExpression(PsiThisExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitThisExpression " + expression); } final int iterationCount = calcIterationCount(expression.getQualifier()); myResult = new ThisEvaluator(iterationCount); } private int calcIterationCount(final PsiJavaCodeReferenceElement qualifier) { if (qualifier != null) { return calcIterationCount(qualifier.resolve(), qualifier.getText()); } return 0; } private int calcIterationCount(PsiElement targetClass, String name) { int iterationCount = 0; if (targetClass == null || getContextPsiClass() == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", name)); } try { PsiClass aClass = getContextPsiClass(); while (aClass != null && !aClass.equals(targetClass)) { iterationCount++; aClass = getOuterClass(aClass); } } catch (Exception e) { //noinspection ThrowableResultOfMethodCallIgnored throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(e)); } return iterationCount; } @Override public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitInstanceOfExpression " + expression); } PsiTypeElement checkType = expression.getCheckType(); if(checkType == null) { throwExpressionInvalid(expression); } PsiType type = checkType.getType(); expression.getOperand().accept(this); // ClassObjectEvaluator typeEvaluator = new ClassObjectEvaluator(type.getCanonicalText()); Evaluator operandEvaluator = myResult; myResult = new InstanceofEvaluator(operandEvaluator, new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type))); } @Override public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitParenthesizedExpression " + expression); } PsiExpression expr = expression.getExpression(); if (expr != null){ expr.accept(this); } } @Override public void visitPostfixExpression(PsiPostfixExpression expression) { if(expression.getType() == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } final PsiExpression operandExpression = expression.getOperand(); operandExpression.accept(this); final Evaluator operandEvaluator = myResult; final IElementType operation = expression.getOperationTokenType(); final PsiType operandType = operandExpression.getType(); @Nullable final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType); Evaluator incrementImpl = createBinaryEvaluator( operandEvaluator, operandType, new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT, operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS, unboxedOperandType!= null? unboxedOperandType : operandType ); if (unboxedOperandType != null) { incrementImpl = new BoxingEvaluator(incrementImpl); } myResult = new PostfixOperationEvaluator(operandEvaluator, incrementImpl); } @Override public void visitPrefixExpression(final PsiPrefixExpression expression) { final PsiType expressionType = expression.getType(); if(expressionType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } final PsiExpression operandExpression = expression.getOperand(); if (operandExpression == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.operand", expression.getText())); } operandExpression.accept(this); Evaluator operandEvaluator = myResult; // handle unboxing issues final PsiType operandType = operandExpression.getType(); @Nullable final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType); final IElementType operation = expression.getOperationTokenType(); if(operation == JavaTokenType.PLUSPLUS || operation == JavaTokenType.MINUSMINUS) { try { final BinaryExpressionEvaluator rightEval = createBinaryEvaluator( operandEvaluator, operandType, new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT, operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS, unboxedOperandType!= null? unboxedOperandType : operandType ); myResult = new AssignmentEvaluator(operandEvaluator, unboxedOperandType != null? new BoxingEvaluator(rightEval) : rightEval); } catch (IncorrectOperationException e) { LOG.error(e); } } else { if (JavaTokenType.PLUS.equals(operation) || JavaTokenType.MINUS.equals(operation)|| JavaTokenType.TILDE.equals(operation)) { operandEvaluator = handleUnaryNumericPromotion(operandType, operandEvaluator); } else { if (unboxedOperandType != null) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); } } myResult = new UnaryExpressionEvaluator(operation, expressionType.getCanonicalText(), operandEvaluator, expression.getOperationSign().getText()); } } @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitMethodCallExpression " + expression); } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] argExpressions = argumentList.getExpressions(); Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length]; // evaluate arguments for (int idx = 0; idx < argExpressions.length; idx++) { final PsiExpression psiExpression = argExpressions[idx]; psiExpression.accept(this); if (myResult == null) { // cannot build evaluator throwExpressionInvalid(psiExpression); } argumentEvaluators[idx] = new DisableGC(myResult); } PsiReferenceExpression methodExpr = expression.getMethodExpression(); final JavaResolveResult resolveResult = methodExpr.advancedResolve(false); final PsiMethod psiMethod = (PsiMethod)resolveResult.getElement(); PsiExpression qualifier = methodExpr.getQualifierExpression(); Evaluator objectEvaluator; JVMName contextClass = null; if(psiMethod != null) { PsiClass methodPsiClass = psiMethod.getContainingClass(); contextClass = JVMNameUtil.getJVMQualifiedName(methodPsiClass); if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) { objectEvaluator = new TypeEvaluator(contextClass); } else if (qualifier != null ) { qualifier.accept(this); objectEvaluator = myResult; } else { int iterationCount = 0; final PsiElement currentFileResolveScope = resolveResult.getCurrentFileResolveScope(); if (currentFileResolveScope instanceof PsiClass) { PsiClass aClass = getContextPsiClass(); while(aClass != null && !aClass.equals(currentFileResolveScope)) { aClass = getOuterClass(aClass); iterationCount++; } } objectEvaluator = new ThisEvaluator(iterationCount); } } else { //trying to guess if (qualifier != null) { PsiType type = qualifier.getType(); if (type != null) { contextClass = JVMNameUtil.getJVMQualifiedName(type); } if (qualifier instanceof PsiReferenceExpression && ((PsiReferenceExpression)qualifier).resolve() instanceof PsiClass) { // this is a call to a 'static' method but class is not available, try to evaluate by qname if (contextClass == null) { contextClass = JVMNameUtil.getJVMRawText(((PsiReferenceExpression)qualifier).getQualifiedName()); } objectEvaluator = new TypeEvaluator(contextClass); } else { qualifier.accept(this); objectEvaluator = myResult; } } else { objectEvaluator = new ThisEvaluator(); contextClass = JVMNameUtil.getContextClassJVMQualifiedName(myPosition); if(contextClass == null && myContextPsiClass != null) { contextClass = JVMNameUtil.getJVMQualifiedName(myContextPsiClass); } //else { // throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException( // DebuggerBundle.message("evaluation.error.method.not.found", methodExpr.getReferenceName())) // ); //} } } if (objectEvaluator == null) { throwExpressionInvalid(expression); } if (psiMethod != null && !psiMethod.isConstructor()) { if (psiMethod.getReturnType() == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.method.return.type", psiMethod.getText())); } } boolean defaultInterfaceMethod = false; boolean mustBeVararg = false; if (psiMethod != null) { processBoxingConversions(psiMethod.getParameterList().getParameters(), argExpressions, resolveResult.getSubstitutor(), argumentEvaluators); argumentEvaluators = wrapVarargs(psiMethod.getParameterList().getParameters(), argExpressions, resolveResult.getSubstitutor(), argumentEvaluators); defaultInterfaceMethod = psiMethod.hasModifierProperty(PsiModifier.DEFAULT); mustBeVararg = psiMethod.isVarArgs(); } myResult = new MethodEvaluator(objectEvaluator, contextClass, methodExpr.getReferenceName(), psiMethod != null ? JVMNameUtil.getJVMSignature(psiMethod) : null, argumentEvaluators, defaultInterfaceMethod, mustBeVararg); } @Override public void visitLiteralExpression(PsiLiteralExpression expression) { final HighlightInfo parsingError = HighlightUtil.checkLiteralExpressionParsingError(expression, null, null); if (parsingError != null) { throwEvaluateException(parsingError.getDescription()); return; } final PsiType type = expression.getType(); if (type == null) { throwEvaluateException(expression + ": null type"); return; } myResult = new LiteralEvaluator(expression.getValue(), type.getCanonicalText()); } @Override public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { final PsiExpression indexExpression = expression.getIndexExpression(); if(indexExpression == null) { throwExpressionInvalid(expression); } indexExpression.accept(this); final Evaluator indexEvaluator = handleUnaryNumericPromotion(indexExpression.getType(), myResult); expression.getArrayExpression().accept(this); Evaluator arrayEvaluator = myResult; myResult = new ArrayAccessEvaluator(arrayEvaluator, indexEvaluator); } /** * Handles unboxing and numeric promotion issues for * - array dimension expressions * - array index expression * - unary +, -, and ~ operations * @param operandExpressionType * @param operandEvaluator @return operandEvaluator possibly 'wrapped' with necessary unboxing and type-casting evaluators to make returning value * suitable for mentioned contexts */ private static Evaluator handleUnaryNumericPromotion(final PsiType operandExpressionType, Evaluator operandEvaluator) { final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(operandExpressionType); if (unboxedType != null && !PsiType.BOOLEAN.equals(unboxedType)) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); } // handle numeric promotion final PsiType _unboxedIndexType = unboxedType != null? unboxedType : operandExpressionType; if (_unboxedIndexType instanceof PsiPrimitiveType) { final PsiType promotionType = calcUnaryNumericPromotionType((PsiPrimitiveType)_unboxedIndexType); if (promotionType != null) { operandEvaluator = new TypeCastEvaluator(operandEvaluator, promotionType.getCanonicalText(), true); } } return operandEvaluator; } @Override public void visitTypeCastExpression(PsiTypeCastExpression expression) { PsiExpression operandExpr = expression.getOperand(); if (operandExpr == null) { throwExpressionInvalid(expression); } operandExpr.accept(this); Evaluator operandEvaluator = myResult; PsiTypeElement castTypeElem = expression.getCastType(); if (castTypeElem == null) { throwExpressionInvalid(expression); } PsiType castType = castTypeElem.getType(); PsiType operandType = operandExpr.getType(); // if operand type can not be resolved in current context - leave it for runtime checks if (operandType != null && !TypeConversionUtil.areTypesConvertible(operandType, castType) && PsiUtil.resolveClassInType(operandType) != null) { throw new EvaluateRuntimeException( new EvaluateException(JavaErrorMessages.message("inconvertible.type.cast", JavaHighlightUtil.formatType(operandType), JavaHighlightUtil .formatType(castType))) ); } boolean shouldPerformBoxingConversion = operandType != null && TypeConversionUtil.boxingConversionApplicable(castType, operandType); final boolean castingToPrimitive = castType instanceof PsiPrimitiveType; if (shouldPerformBoxingConversion && castingToPrimitive) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); } final boolean performCastToWrapperClass = shouldPerformBoxingConversion && !castingToPrimitive; if (!(PsiUtil.resolveClassInClassTypeOnly(castType) instanceof PsiTypeParameter)) { String castTypeName = castType.getCanonicalText(); if (performCastToWrapperClass) { final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(castType); if (unboxedType != null) { castTypeName = unboxedType.getCanonicalText(); } } myResult = new TypeCastEvaluator(operandEvaluator, castTypeName, castingToPrimitive); } if (performCastToWrapperClass) { myResult = new BoxingEvaluator(myResult); } } @Override public void visitClassObjectAccessExpression(PsiClassObjectAccessExpression expression) { PsiType type = expression.getOperand().getType(); if (type instanceof PsiPrimitiveType) { final JVMName typeName = JVMNameUtil.getJVMRawText(((PsiPrimitiveType)type).getBoxedTypeName()); myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.TargetClassFilter.ALL, "TYPE"); } else { myResult = new ClassObjectEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type))); } } @Override public void visitLambdaExpression(PsiLambdaExpression expression) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(DebuggerBundle.message("evaluation.error.lambda.evaluation.not.supported"))); } @Override public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(DebuggerBundle.message("evaluation.error.method.reference.evaluation.not.supported"))); } @Override public void visitNewExpression(final PsiNewExpression expression) { PsiType expressionPsiType = expression.getType(); if (expressionPsiType instanceof PsiArrayType) { Evaluator dimensionEvaluator = null; PsiExpression[] dimensions = expression.getArrayDimensions(); if (dimensions.length == 1){ PsiExpression dimensionExpression = dimensions[0]; dimensionExpression.accept(this); if (myResult != null) { dimensionEvaluator = handleUnaryNumericPromotion(dimensionExpression.getType(), myResult); } else { throwEvaluateException( DebuggerBundle.message("evaluation.error.invalid.array.dimension.expression", dimensionExpression.getText())); } } else if (dimensions.length > 1){ throwEvaluateException(DebuggerBundle.message("evaluation.error.multi.dimensional.arrays.creation.not.supported")); } Evaluator initializerEvaluator = null; PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer(); if (arrayInitializer != null) { if (dimensionEvaluator != null) { // initializer already exists throwExpressionInvalid(expression); } arrayInitializer.accept(this); if (myResult != null) { initializerEvaluator = handleUnaryNumericPromotion(arrayInitializer.getType(), myResult); } else { throwExpressionInvalid(arrayInitializer); } /* PsiExpression[] initializers = arrayInitializer.getInitializers(); initializerEvaluators = new Evaluator[initializers.length]; for (int idx = 0; idx < initializers.length; idx++) { PsiExpression initializer = initializers[idx]; initializer.accept(this); if (myResult instanceof Evaluator) { initializerEvaluators[idx] = myResult; } else { throw new EvaluateException("Invalid expression for array initializer: " + initializer.getText(), true); } } */ } if (dimensionEvaluator == null && initializerEvaluator == null) { throwExpressionInvalid(expression); } myResult = new NewArrayInstanceEvaluator( new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)), dimensionEvaluator, initializerEvaluator ); } else if (expressionPsiType instanceof PsiClassType){ // must be a class ref PsiClass aClass = ((PsiClassType)expressionPsiType).resolve(); if(aClass instanceof PsiAnonymousClass) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(DebuggerBundle.message("evaluation.error.anonymous.class.evaluation.not.supported"))); } PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList == null) { throwExpressionInvalid(expression); } final PsiExpression[] argExpressions = argumentList.getExpressions(); final JavaResolveResult constructorResolveResult = expression.resolveMethodGenerics(); final PsiMethod constructor = (PsiMethod)constructorResolveResult.getElement(); if (constructor == null && argExpressions.length > 0) { throw new EvaluateRuntimeException(new EvaluateException( DebuggerBundle.message("evaluation.error.cannot.resolve.constructor", expression.getText()), null)); } Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length]; // evaluate arguments for (int idx = 0; idx < argExpressions.length; idx++) { PsiExpression argExpression = argExpressions[idx]; argExpression.accept(this); if (myResult != null) { argumentEvaluators[idx] = new DisableGC(myResult); } else { throwExpressionInvalid(argExpression); } } if (constructor != null) { processBoxingConversions(constructor.getParameterList().getParameters(), argExpressions, constructorResolveResult.getSubstitutor(), argumentEvaluators); argumentEvaluators = wrapVarargs(constructor.getParameterList().getParameters(), argExpressions, constructorResolveResult.getSubstitutor(), argumentEvaluators); } if (aClass != null && aClass.getContainingClass() != null && !aClass.hasModifierProperty(PsiModifier.STATIC)) { argumentEvaluators = addThisEvaluator(argumentEvaluators, aClass.getContainingClass()); } JVMName signature = JVMNameUtil.getJVMConstructorSignature(constructor, aClass); myResult = new NewClassInstanceEvaluator( new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)), signature, argumentEvaluators ); } else { if (expressionPsiType != null) { throwEvaluateException("Unsupported expression type: " + expressionPsiType.getPresentableText()); } else { throwEvaluateException("Unknown type for expression: " + expression.getText()); } } } private Evaluator[] addThisEvaluator(Evaluator[] argumentEvaluators, PsiClass cls) { Evaluator[] res = new Evaluator[argumentEvaluators.length+1]; int depth = calcIterationCount(cls, "this"); res[0] = new ThisEvaluator(depth); System.arraycopy(argumentEvaluators, 0, res, 1, argumentEvaluators.length); return res; } @Override public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) { PsiExpression[] initializers = expression.getInitializers(); Evaluator[] evaluators = new Evaluator[initializers.length]; final PsiType type = expression.getType(); boolean primitive = type instanceof PsiArrayType && ((PsiArrayType)type).getComponentType() instanceof PsiPrimitiveType; for (int idx = 0; idx < initializers.length; idx++) { PsiExpression initializer = initializers[idx]; initializer.accept(this); if (myResult != null) { final Evaluator coerced = primitive ? handleUnaryNumericPromotion(initializer.getType(), myResult) : new BoxingEvaluator(myResult); evaluators[idx] = new DisableGC(coerced); } else { throwExpressionInvalid(initializer); } } myResult = new ArrayInitializerEvaluator(evaluators); if (type != null && !(expression.getParent() instanceof PsiNewExpression)) { myResult = new NewArrayInstanceEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)), null, myResult); } } @Nullable private static PsiClass getOuterClass(PsiClass aClass) { return aClass == null ? null : PsiTreeUtil.getContextOfType(aClass, PsiClass.class, true); } private PsiClass getContainingClass(PsiVariable variable) { PsiElement element = PsiTreeUtil.getParentOfType(variable.getParent(), PsiClass.class, false); return element == null ? getContextPsiClass() : (PsiClass)element; } @Nullable public PsiClass getContextPsiClass() { return myContextPsiClass; } protected ExpressionEvaluator buildElement(final PsiElement element) throws EvaluateException { LOG.assertTrue(element.isValid()); myContextPsiClass = PsiTreeUtil.getContextOfType(element, PsiClass.class, false); try { element.accept(this); } catch (EvaluateRuntimeException e) { throw e.getCause(); } if (myResult == null) { throw EvaluateExceptionUtil .createEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", element.toString())); } return new ExpressionEvaluatorImpl(myResult); } } private static Evaluator[] wrapVarargs(final PsiParameter[] declaredParams, final PsiExpression[] actualArgumentExpressions, final PsiSubstitutor methodResolveSubstitutor, final Evaluator[] argumentEvaluators) { int lastParam = declaredParams.length - 1; if (lastParam >= 0 && declaredParams[lastParam].isVarArgs() && argumentEvaluators.length > lastParam) { // only wrap if the first varargs parameter is null for now if (!TypeConversionUtil.isNullType(actualArgumentExpressions[lastParam].getType())) { return argumentEvaluators; } // do not wrap arrays twice if (argumentEvaluators.length - lastParam == 1 && actualArgumentExpressions[lastParam].getType() instanceof PsiArrayType) { return argumentEvaluators; } PsiEllipsisType declaredParamType = (PsiEllipsisType)methodResolveSubstitutor.substitute(declaredParams[lastParam].getType()); ArrayInitializerEvaluator varargArrayEvaluator = new ArrayInitializerEvaluator(Arrays.copyOfRange(argumentEvaluators, lastParam, argumentEvaluators.length)); NewArrayInstanceEvaluator evaluator = new NewArrayInstanceEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(declaredParamType.toArrayType())), null, varargArrayEvaluator); Evaluator[] res = new Evaluator[declaredParams.length]; System.arraycopy(argumentEvaluators, 0, res, 0, lastParam); res[lastParam] = new DisableGC(evaluator); return res; } return argumentEvaluators; } private static void processBoxingConversions(final PsiParameter[] declaredParams, final PsiExpression[] actualArgumentExpressions, final PsiSubstitutor methodResolveSubstitutor, final Evaluator[] argumentEvaluators) { if (declaredParams.length > 0) { final int paramCount = Math.max(declaredParams.length, actualArgumentExpressions.length); PsiType varargType = null; for (int idx = 0; idx < paramCount; idx++) { if (idx >= actualArgumentExpressions.length) { break; // actual arguments count is less than number of declared params } PsiType declaredParamType; if (idx < declaredParams.length) { declaredParamType = methodResolveSubstitutor.substitute(declaredParams[idx].getType()); if (declaredParamType instanceof PsiEllipsisType) { declaredParamType = varargType = ((PsiEllipsisType)declaredParamType).getComponentType(); } } else if (varargType != null) { declaredParamType = varargType; } else { break; } final PsiType actualArgType = actualArgumentExpressions[idx].getType(); if (TypeConversionUtil.boxingConversionApplicable(declaredParamType, actualArgType)) { final Evaluator argEval = argumentEvaluators[idx]; argumentEvaluators[idx] = declaredParamType instanceof PsiPrimitiveType ? new UnBoxingEvaluator(argEval) : new BoxingEvaluator(argEval); } } } } }
java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Class EvaluatorBuilderImpl * @author Jeka */ package com.intellij.debugger.engine.evaluation.expression; import com.intellij.codeInsight.daemon.JavaErrorMessages; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.SourcePosition; import com.intellij.debugger.engine.ContextUtil; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.debugger.engine.JVMName; import com.intellij.debugger.engine.JVMNameUtil; import com.intellij.debugger.engine.evaluation.*; import com.intellij.debugger.impl.DebuggerUtilsEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.impl.JavaConstantExpressionEvaluator; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.IncorrectOperationException; import com.sun.jdi.Value; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class EvaluatorBuilderImpl implements EvaluatorBuilder { private static final EvaluatorBuilderImpl ourInstance = new EvaluatorBuilderImpl(); private EvaluatorBuilderImpl() { } public static EvaluatorBuilder getInstance() { return ourInstance; } public static ExpressionEvaluator build(final TextWithImports text, @Nullable PsiElement contextElement, final SourcePosition position) throws EvaluateException { if (contextElement == null) { throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS; } final Project project = contextElement.getProject(); CodeFragmentFactory factory = DebuggerUtilsEx.findAppropriateCodeFragmentFactory(text, contextElement); PsiCodeFragment codeFragment = factory.createCodeFragment(text, contextElement, project); if (codeFragment == null) { throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", text.getText())); } codeFragment.forceResolveScope(GlobalSearchScope.allScope(project)); DebuggerUtils.checkSyntax(codeFragment); return factory.getEvaluatorBuilder().build(codeFragment, position); } @Override public ExpressionEvaluator build(final PsiElement codeFragment, final SourcePosition position) throws EvaluateException { return new Builder(position).buildElement(codeFragment); } private static class Builder extends JavaElementVisitor { private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl"); private Evaluator myResult = null; private PsiClass myContextPsiClass; private CodeFragmentEvaluator myCurrentFragmentEvaluator; private final Set<JavaCodeFragment> myVisitedFragments = new HashSet<JavaCodeFragment>(); @Nullable private final SourcePosition myPosition; private Builder(@Nullable SourcePosition position) { myPosition = position; } @Override public void visitCodeFragment(JavaCodeFragment codeFragment) { myVisitedFragments.add(codeFragment); ArrayList<Evaluator> evaluators = new ArrayList<Evaluator>(); CodeFragmentEvaluator oldFragmentEvaluator = myCurrentFragmentEvaluator; myCurrentFragmentEvaluator = new CodeFragmentEvaluator(oldFragmentEvaluator); for (PsiElement child = codeFragment.getFirstChild(); child != null; child = child.getNextSibling()) { child.accept(this); if(myResult != null) { evaluators.add(myResult); } myResult = null; } myCurrentFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[evaluators.size()])); myResult = myCurrentFragmentEvaluator; myCurrentFragmentEvaluator = oldFragmentEvaluator; } @Override public void visitErrorElement(PsiErrorElement element) { throwExpressionInvalid(element); } @Override public void visitAssignmentExpression(PsiAssignmentExpression expression) { final PsiExpression rExpression = expression.getRExpression(); if(rExpression == null) { throwExpressionInvalid(expression); } rExpression.accept(this); Evaluator rEvaluator = myResult; final PsiExpression lExpression = expression.getLExpression(); final PsiType lType = lExpression.getType(); if(lType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", lExpression.getText())); } IElementType assignmentType = expression.getOperationTokenType(); PsiType rType = rExpression.getType(); if(!TypeConversionUtil.areTypesAssignmentCompatible(lType, rExpression) && rType != null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.incompatible.types", expression.getOperationSign().getText())); } lExpression.accept(this); Evaluator lEvaluator = myResult; rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(lType, rType, rEvaluator); if (assignmentType != JavaTokenType.EQ) { IElementType opType = TypeConversionUtil.convertEQtoOperation(assignmentType); final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true); if (typeForBinOp == null || rType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } rEvaluator = createBinaryEvaluator(lEvaluator, lType, rEvaluator, rType, opType, typeForBinOp); } myResult = new AssignmentEvaluator(lEvaluator, rEvaluator); } // returns rEvaluator possibly wrapped with boxing/unboxing and casting evaluators private static Evaluator handleAssignmentBoxingAndPrimitiveTypeConversions(PsiType lType, PsiType rType, Evaluator rEvaluator) { final PsiType unboxedLType = PsiPrimitiveType.getUnboxedType(lType); if (unboxedLType != null) { if (rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(rType)) { if (!rType.equals(unboxedLType)) { rEvaluator = new TypeCastEvaluator(rEvaluator, unboxedLType.getCanonicalText(), true); } rEvaluator = new BoxingEvaluator(rEvaluator); } } else { // either primitive type or not unboxable type if (lType instanceof PsiPrimitiveType) { if (rType instanceof PsiClassType) { rEvaluator = new UnBoxingEvaluator(rEvaluator); } final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType); final PsiType _rType = unboxedRType != null? unboxedRType : rType; if (_rType instanceof PsiPrimitiveType && !PsiType.NULL.equals(_rType)) { if (!lType.equals(_rType)) { rEvaluator = new TypeCastEvaluator(rEvaluator, lType.getCanonicalText(), true); } } } } return rEvaluator; } @Override public void visitTryStatement(PsiTryStatement statement) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(statement.getText())); } @Override public void visitStatement(PsiStatement statement) { throwEvaluateException(DebuggerBundle.message("evaluation.error.statement.not.supported", statement.getText())); } @Override public void visitBlockStatement(PsiBlockStatement statement) { PsiStatement[] statements = statement.getCodeBlock().getStatements(); Evaluator [] evaluators = new Evaluator[statements.length]; for (int i = 0; i < statements.length; i++) { PsiStatement psiStatement = statements[i]; psiStatement.accept(this); evaluators[i] = new DisableGC(myResult); myResult = null; } myResult = new BlockStatementEvaluator(evaluators); } @Override public void visitLabeledStatement(PsiLabeledStatement labeledStatement) { PsiStatement statement = labeledStatement.getStatement(); if (statement != null) { statement.accept(this); } } private static String getLabel(PsiElement element) { String label = null; if(element.getParent() instanceof PsiLabeledStatement) { label = ((PsiLabeledStatement)element.getParent()).getName(); } return label; } @Override public void visitDoWhileStatement(PsiDoWhileStatement statement) { Evaluator bodyEvaluator = accept(statement.getBody()); Evaluator conditionEvaluator = accept(statement.getCondition()); if (conditionEvaluator != null) { myResult = new DoWhileStatementEvaluator(new UnBoxingEvaluator(conditionEvaluator), bodyEvaluator, getLabel(statement)); } } @Override public void visitWhileStatement(PsiWhileStatement statement) { Evaluator bodyEvaluator = accept(statement.getBody()); Evaluator conditionEvaluator = accept(statement.getCondition()); if (conditionEvaluator != null) { myResult = new WhileStatementEvaluator(new UnBoxingEvaluator(conditionEvaluator), bodyEvaluator, getLabel(statement)); } } @Override public void visitForStatement(PsiForStatement statement) { Evaluator initializerEvaluator = accept(statement.getInitialization()); Evaluator conditionEvaluator = accept(statement.getCondition()); if (conditionEvaluator != null) { conditionEvaluator = new UnBoxingEvaluator(conditionEvaluator); } Evaluator updateEvaluator = accept(statement.getUpdate()); Evaluator bodyEvaluator = accept(statement.getBody()); if (bodyEvaluator != null) { myResult = new ForStatementEvaluator(initializerEvaluator, conditionEvaluator, updateEvaluator, bodyEvaluator, getLabel(statement)); } } @Override public void visitForeachStatement(PsiForeachStatement statement) { try { String iterationParameterName = statement.getIterationParameter().getName(); myCurrentFragmentEvaluator.setInitialValue(iterationParameterName, null); SyntheticVariableEvaluator iterationParameterEvaluator = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, iterationParameterName); Evaluator iteratedValueEvaluator = accept(statement.getIteratedValue()); Evaluator bodyEvaluator = accept(statement.getBody()); if (bodyEvaluator != null) { myResult = new ForeachStatementEvaluator(iterationParameterEvaluator, iteratedValueEvaluator, bodyEvaluator, getLabel(statement)); } } catch (EvaluateException e) { throw new EvaluateRuntimeException(e); } } @Nullable private Evaluator accept(@Nullable PsiElement element) { if (element == null || element instanceof PsiEmptyStatement) { return null; } element.accept(this); return myResult; } @Override public void visitIfStatement(PsiIfStatement statement) { PsiStatement thenBranch = statement.getThenBranch(); if(thenBranch == null) return; thenBranch.accept(this); Evaluator thenEvaluator = myResult; PsiStatement elseBranch = statement.getElseBranch(); Evaluator elseEvaluator = null; if(elseBranch != null){ elseBranch.accept(this); elseEvaluator = myResult; } PsiExpression condition = statement.getCondition(); if(condition == null) return; condition.accept(this); myResult = new IfStatementEvaluator(new UnBoxingEvaluator(myResult), thenEvaluator, elseEvaluator); } @Override public void visitBreakStatement(PsiBreakStatement statement) { PsiIdentifier labelIdentifier = statement.getLabelIdentifier(); myResult = BreakContinueStatementEvaluator.createBreakEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null); } @Override public void visitContinueStatement(PsiContinueStatement statement) { PsiIdentifier labelIdentifier = statement.getLabelIdentifier(); myResult = BreakContinueStatementEvaluator.createContinueEvaluator(labelIdentifier != null ? labelIdentifier.getText() : null); } @Override public void visitExpressionStatement(PsiExpressionStatement statement) { statement.getExpression().accept(this); } @Override public void visitExpression(PsiExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitExpression " + expression); } } @Override public void visitPolyadicExpression(PsiPolyadicExpression wideExpression) { if (LOG.isDebugEnabled()) { LOG.debug("visitPolyadicExpression " + wideExpression); } PsiExpression[] operands = wideExpression.getOperands(); operands[0].accept(this); Evaluator result = myResult; PsiType lType = operands[0].getType(); for (int i = 1; i < operands.length; i++) { PsiExpression expression = operands[i]; if (expression == null) { throwExpressionInvalid(wideExpression); } expression.accept(this); Evaluator rResult = myResult; IElementType opType = wideExpression.getOperationTokenType(); PsiType rType = expression.getType(); if (rType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } final PsiType typeForBinOp = TypeConversionUtil.calcTypeForBinaryExpression(lType, rType, opType, true); if (typeForBinOp == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", wideExpression.getText())); } myResult = createBinaryEvaluator(result, lType, rResult, rType, opType, typeForBinOp); lType = typeForBinOp; result = myResult; } } // constructs binary evaluator handling unboxing and numeric promotion issues private static BinaryExpressionEvaluator createBinaryEvaluator(Evaluator lResult, PsiType lType, Evaluator rResult, @NotNull PsiType rType, @NotNull IElementType operation, @NotNull PsiType expressionExpectedType) { // handle unboxing if necessary if (isUnboxingInBinaryExpressionApplicable(lType, rType, operation)) { if (rType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(rType.getCanonicalText())) { rResult = new UnBoxingEvaluator(rResult); } if (lType instanceof PsiClassType && UnBoxingEvaluator.isTypeUnboxable(lType.getCanonicalText())) { lResult = new UnBoxingEvaluator(lResult); } } if (isBinaryNumericPromotionApplicable(lType, rType, operation)) { PsiType _lType = lType; final PsiPrimitiveType unboxedLType = PsiPrimitiveType.getUnboxedType(lType); if (unboxedLType != null) { _lType = unboxedLType; } PsiType _rType = rType; final PsiPrimitiveType unboxedRType = PsiPrimitiveType.getUnboxedType(rType); if (unboxedRType != null) { _rType = unboxedRType; } // handle numeric promotion if (PsiType.DOUBLE.equals(_lType)) { if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.DOUBLE)) { rResult = new TypeCastEvaluator(rResult, PsiType.DOUBLE.getCanonicalText(), true); } } else if (PsiType.DOUBLE.equals(_rType)) { if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.DOUBLE)) { lResult = new TypeCastEvaluator(lResult, PsiType.DOUBLE.getCanonicalText(), true); } } else if (PsiType.FLOAT.equals(_lType)) { if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.FLOAT)) { rResult = new TypeCastEvaluator(rResult, PsiType.FLOAT.getCanonicalText(), true); } } else if (PsiType.FLOAT.equals(_rType)) { if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.FLOAT)) { lResult = new TypeCastEvaluator(lResult, PsiType.FLOAT.getCanonicalText(), true); } } else if (PsiType.LONG.equals(_lType)) { if (TypeConversionUtil.areTypesConvertible(_rType, PsiType.LONG)) { rResult = new TypeCastEvaluator(rResult, PsiType.LONG.getCanonicalText(), true); } } else if (PsiType.LONG.equals(_rType)) { if (TypeConversionUtil.areTypesConvertible(_lType, PsiType.LONG)) { lResult = new TypeCastEvaluator(lResult, PsiType.LONG.getCanonicalText(), true); } } else { if (!PsiType.INT.equals(_lType) && TypeConversionUtil.areTypesConvertible(_lType, PsiType.INT)) { lResult = new TypeCastEvaluator(lResult, PsiType.INT.getCanonicalText(), true); } if (!PsiType.INT.equals(_rType) && TypeConversionUtil.areTypesConvertible(_rType, PsiType.INT)) { rResult = new TypeCastEvaluator(rResult, PsiType.INT.getCanonicalText(), true); } } } return new BinaryExpressionEvaluator(lResult, rResult, operation, expressionExpectedType.getCanonicalText()); } private static boolean isBinaryNumericPromotionApplicable(PsiType lType, PsiType rType, IElementType opType) { if (lType == null || rType == null) { return false; } if (!TypeConversionUtil.isNumericType(lType) || !TypeConversionUtil.isNumericType(rType)) { return false; } if (opType == JavaTokenType.EQEQ || opType == JavaTokenType.NE) { if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) { return false; } if (lType instanceof PsiClassType && rType instanceof PsiClassType) { return false; } if (lType instanceof PsiClassType) { return PsiPrimitiveType.getUnboxedType(lType) != null; // should be unboxable } if (rType instanceof PsiClassType) { return PsiPrimitiveType.getUnboxedType(rType) != null; // should be unboxable } return true; } return opType == JavaTokenType.ASTERISK || opType == JavaTokenType.DIV || opType == JavaTokenType.PERC || opType == JavaTokenType.PLUS || opType == JavaTokenType.MINUS || opType == JavaTokenType.LT || opType == JavaTokenType.LE || opType == JavaTokenType.GT || opType == JavaTokenType.GE || opType == JavaTokenType.AND || opType == JavaTokenType.XOR || opType == JavaTokenType.OR; } private static boolean isUnboxingInBinaryExpressionApplicable(PsiType lType, PsiType rType, IElementType opCode) { if (PsiType.NULL.equals(lType) || PsiType.NULL.equals(rType)) { return false; } // handle '==' and '!=' separately if (opCode == JavaTokenType.EQEQ || opCode == JavaTokenType.NE) { return lType instanceof PsiPrimitiveType && rType instanceof PsiClassType || lType instanceof PsiClassType && rType instanceof PsiPrimitiveType; } // concat with a String if (opCode == JavaTokenType.PLUS) { if ((lType instanceof PsiClassType && lType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) || (rType instanceof PsiClassType && rType.equalsToText(CommonClassNames.JAVA_LANG_STRING))){ return false; } } // all other operations at least one should be of class type return lType instanceof PsiClassType || rType instanceof PsiClassType; } /** * @param type * @return promotion type to cast to or null if no casting needed */ @Nullable private static PsiType calcUnaryNumericPromotionType(PsiPrimitiveType type) { if (PsiType.BYTE.equals(type) || PsiType.SHORT.equals(type) || PsiType.CHAR.equals(type) || PsiType.INT.equals(type)) { return PsiType.INT; } return null; } @Override public void visitDeclarationStatement(PsiDeclarationStatement statement) { List<Evaluator> evaluators = new ArrayList<Evaluator>(); PsiElement[] declaredElements = statement.getDeclaredElements(); for (PsiElement declaredElement : declaredElements) { if (declaredElement instanceof PsiLocalVariable) { if (myCurrentFragmentEvaluator != null) { final PsiLocalVariable localVariable = (PsiLocalVariable)declaredElement; final PsiType lType = localVariable.getType(); PsiElementFactory elementFactory = JavaPsiFacade.getInstance(localVariable.getProject()).getElementFactory(); try { PsiExpression initialValue = elementFactory.createExpressionFromText(PsiTypesUtil.getDefaultValueOfType(lType), null); Object value = JavaConstantExpressionEvaluator.computeConstantExpression(initialValue, true); myCurrentFragmentEvaluator.setInitialValue(localVariable.getName(), value); } catch (IncorrectOperationException e) { LOG.error(e); } catch (EvaluateException e) { throw new EvaluateRuntimeException(e); } PsiExpression initializer = localVariable.getInitializer(); if (initializer != null) { try { if (!TypeConversionUtil.areTypesAssignmentCompatible(lType, initializer)) { throwEvaluateException( DebuggerBundle.message("evaluation.error.incompatible.variable.initializer.type", localVariable.getName())); } final PsiType rType = initializer.getType(); initializer.accept(this); Evaluator rEvaluator = myResult; PsiExpression localVarReference = elementFactory.createExpressionFromText(localVariable.getName(), initializer); localVarReference.accept(this); Evaluator lEvaluator = myResult; rEvaluator = handleAssignmentBoxingAndPrimitiveTypeConversions(localVarReference.getType(), rType, rEvaluator); Evaluator assignment = new AssignmentEvaluator(lEvaluator, rEvaluator); evaluators.add(assignment); } catch (IncorrectOperationException e) { LOG.error(e); } } } else { throw new EvaluateRuntimeException(new EvaluateException( DebuggerBundle.message("evaluation.error.local.variable.declarations.not.supported"), null)); } } else { throw new EvaluateRuntimeException(new EvaluateException( DebuggerBundle.message("evaluation.error.unsupported.declaration", declaredElement.getText()), null)); } } if(!evaluators.isEmpty()) { CodeFragmentEvaluator codeFragmentEvaluator = new CodeFragmentEvaluator(myCurrentFragmentEvaluator); codeFragmentEvaluator.setStatements(evaluators.toArray(new Evaluator[evaluators.size()])); myResult = codeFragmentEvaluator; } else { myResult = null; } } @Override public void visitConditionalExpression(PsiConditionalExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitConditionalExpression " + expression); } final PsiExpression thenExpression = expression.getThenExpression(); final PsiExpression elseExpression = expression.getElseExpression(); if (thenExpression == null || elseExpression == null){ throwExpressionInvalid(expression); } PsiExpression condition = expression.getCondition(); condition.accept(this); if (myResult == null) { throwExpressionInvalid(condition); } Evaluator conditionEvaluator = new UnBoxingEvaluator(myResult); thenExpression.accept(this); if (myResult == null) { throwExpressionInvalid(thenExpression); } Evaluator thenEvaluator = myResult; elseExpression.accept(this); if (myResult == null) { throwExpressionInvalid(elseExpression); } Evaluator elseEvaluator = myResult; myResult = new ConditionalExpressionEvaluator(conditionEvaluator, thenEvaluator, elseEvaluator); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitReferenceExpression " + expression); } PsiExpression qualifier = expression.getQualifierExpression(); JavaResolveResult resolveResult = expression.advancedResolve(true); PsiElement element = resolveResult.getElement(); if (element instanceof PsiLocalVariable || element instanceof PsiParameter) { final Value labeledValue = element.getUserData(CodeFragmentFactoryContextWrapper.LABEL_VARIABLE_VALUE_KEY); if (labeledValue != null) { myResult = new IdentityEvaluator(labeledValue); return; } //synthetic variable final PsiFile containingFile = element.getContainingFile(); if(containingFile instanceof PsiCodeFragment && myCurrentFragmentEvaluator != null && myVisitedFragments.contains(containingFile)) { // psiVariable may live in PsiCodeFragment not only in debugger editors, for example Fabrique has such variables. // So treat it as synthetic var only when this code fragment is located in DebuggerEditor, // that's why we need to check that containing code fragment is the one we visited myResult = new SyntheticVariableEvaluator(myCurrentFragmentEvaluator, ((PsiVariable)element).getName()); return; } // local variable final PsiVariable psiVar = (PsiVariable)element; final String localName = psiVar.getName(); PsiClass variableClass = getContainingClass(psiVar); if (getContextPsiClass() == null || getContextPsiClass().equals(variableClass)) { PsiElement method = PsiTreeUtil.getContextOfType(expression, PsiMethod.class, PsiLambdaExpression.class); boolean canScanFrames = method instanceof PsiLambdaExpression || ContextUtil.isJspImplicit(element); LocalVariableEvaluator localVarEvaluator = new LocalVariableEvaluator(localName, canScanFrames); if (psiVar instanceof PsiParameter) { final PsiParameter param = (PsiParameter)psiVar; final PsiParameterList paramList = PsiTreeUtil.getParentOfType(param, PsiParameterList.class, true); if (paramList != null) { localVarEvaluator.setParameterIndex(paramList.getParameterIndex(param)); } } myResult = localVarEvaluator; return; } // the expression references final var outside the context's class (in some of the outer classes) int iterationCount = 0; PsiClass aClass = getOuterClass(getContextPsiClass()); while (aClass != null && !aClass.equals(variableClass)) { iterationCount++; aClass = getOuterClass(aClass); } if (aClass != null) { PsiExpression initializer = psiVar.getInitializer(); if(initializer != null) { Object value = JavaPsiFacade.getInstance(psiVar.getProject()).getConstantEvaluationHelper().computeConstantExpression(initializer); if(value != null) { PsiType type = resolveResult.getSubstitutor().substitute(psiVar.getType()); myResult = new LiteralEvaluator(value, type.getCanonicalText()); return; } } Evaluator objectEvaluator = new ThisEvaluator(iterationCount); //noinspection HardCodedStringLiteral final PsiClass classAt = myPosition != null? JVMNameUtil.getClassAt(myPosition) : null; FieldEvaluator.TargetClassFilter filter = FieldEvaluator.createClassFilter(classAt != null? classAt : getContextPsiClass()); myResult = new FieldEvaluator(objectEvaluator, filter, "val$" + localName); return; } throwEvaluateException(DebuggerBundle.message("evaluation.error.local.variable.missing.from.class.closure", localName)); } else if (element instanceof PsiField) { final PsiField psiField = (PsiField)element; final PsiClass fieldClass = psiField.getContainingClass(); if(fieldClass == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.resolve.field.class", psiField.getName())); return; } Evaluator objectEvaluator; if (psiField.hasModifierProperty(PsiModifier.STATIC)) { objectEvaluator = new TypeEvaluator(JVMNameUtil.getContextClassJVMQualifiedName(SourcePosition.createFromElement(psiField))); } else if(qualifier != null) { qualifier.accept(this); objectEvaluator = myResult; } else if (fieldClass.equals(getContextPsiClass()) || getContextPsiClass().isInheritor(fieldClass, true)) { objectEvaluator = new ThisEvaluator(); } else { // myContextPsiClass != fieldClass && myContextPsiClass is not a subclass of fieldClass int iterationCount = 0; PsiClass aClass = getContextPsiClass(); while (aClass != null && !(aClass.equals(fieldClass) || aClass.isInheritor(fieldClass, true))) { iterationCount++; aClass = getOuterClass(aClass); } if (aClass == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.sources.for.field.class", psiField.getName())); } objectEvaluator = new ThisEvaluator(iterationCount); } myResult = new FieldEvaluator(objectEvaluator, FieldEvaluator.createClassFilter(fieldClass), psiField.getName()); } else { //let's guess what this could be PsiElement nameElement = expression.getReferenceNameElement(); // get "b" part String name; if (nameElement instanceof PsiIdentifier) { name = nameElement.getText(); } else { //noinspection HardCodedStringLiteral final String elementDisplayString = nameElement != null ? nameElement.getText() : "(null)"; throwEvaluateException(DebuggerBundle.message("evaluation.error.identifier.expected", elementDisplayString)); return; } if(qualifier != null) { final PsiElement qualifierTarget = qualifier instanceof PsiReferenceExpression ? ((PsiReferenceExpression)qualifier).resolve() : null; if (qualifierTarget instanceof PsiClass) { // this is a call to a 'static' field PsiClass psiClass = (PsiClass)qualifierTarget; final JVMName typeName = JVMNameUtil.getJVMQualifiedName(psiClass); myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.createClassFilter(psiClass), name); } else { qualifier.accept(this); if (myResult == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.cannot.evaluate.qualifier", qualifier.getText())); } myResult = new FieldEvaluator(myResult, FieldEvaluator.createClassFilter(qualifier.getType()), name); } } else { myResult = new LocalVariableEvaluator(name, false); } } } private static void throwExpressionInvalid(PsiElement expression) { throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", expression.getText())); } private static void throwEvaluateException(String message) throws EvaluateRuntimeException { throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(message)); } @Override public void visitSuperExpression(PsiSuperExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitSuperExpression " + expression); } final int iterationCount = calcIterationCount(expression.getQualifier()); myResult = new SuperEvaluator(iterationCount); } @Override public void visitThisExpression(PsiThisExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitThisExpression " + expression); } final int iterationCount = calcIterationCount(expression.getQualifier()); myResult = new ThisEvaluator(iterationCount); } private int calcIterationCount(final PsiJavaCodeReferenceElement qualifier) { if (qualifier != null) { return calcIterationCount(qualifier.resolve(), qualifier.getText()); } return 0; } private int calcIterationCount(PsiElement targetClass, String name) { int iterationCount = 0; if (targetClass == null || getContextPsiClass() == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", name)); } try { PsiClass aClass = getContextPsiClass(); while (aClass != null && !aClass.equals(targetClass)) { iterationCount++; aClass = getOuterClass(aClass); } } catch (Exception e) { //noinspection ThrowableResultOfMethodCallIgnored throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException(e)); } return iterationCount; } @Override public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitInstanceOfExpression " + expression); } PsiTypeElement checkType = expression.getCheckType(); if(checkType == null) { throwExpressionInvalid(expression); } PsiType type = checkType.getType(); expression.getOperand().accept(this); // ClassObjectEvaluator typeEvaluator = new ClassObjectEvaluator(type.getCanonicalText()); Evaluator operandEvaluator = myResult; myResult = new InstanceofEvaluator(operandEvaluator, new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type))); } @Override public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitParenthesizedExpression " + expression); } PsiExpression expr = expression.getExpression(); if (expr != null){ expr.accept(this); } } @Override public void visitPostfixExpression(PsiPostfixExpression expression) { if(expression.getType() == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } final PsiExpression operandExpression = expression.getOperand(); operandExpression.accept(this); final Evaluator operandEvaluator = myResult; final IElementType operation = expression.getOperationTokenType(); final PsiType operandType = operandExpression.getType(); @Nullable final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType); Evaluator incrementImpl = createBinaryEvaluator( operandEvaluator, operandType, new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT, operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS, unboxedOperandType!= null? unboxedOperandType : operandType ); if (unboxedOperandType != null) { incrementImpl = new BoxingEvaluator(incrementImpl); } myResult = new PostfixOperationEvaluator(operandEvaluator, incrementImpl); } @Override public void visitPrefixExpression(final PsiPrefixExpression expression) { final PsiType expressionType = expression.getType(); if(expressionType == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", expression.getText())); } final PsiExpression operandExpression = expression.getOperand(); if (operandExpression == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.operand", expression.getText())); } operandExpression.accept(this); Evaluator operandEvaluator = myResult; // handle unboxing issues final PsiType operandType = operandExpression.getType(); @Nullable final PsiType unboxedOperandType = PsiPrimitiveType.getUnboxedType(operandType); final IElementType operation = expression.getOperationTokenType(); if(operation == JavaTokenType.PLUSPLUS || operation == JavaTokenType.MINUSMINUS) { try { final BinaryExpressionEvaluator rightEval = createBinaryEvaluator( operandEvaluator, operandType, new LiteralEvaluator(Integer.valueOf(1), "int"), PsiType.INT, operation == JavaTokenType.PLUSPLUS ? JavaTokenType.PLUS : JavaTokenType.MINUS, unboxedOperandType!= null? unboxedOperandType : operandType ); myResult = new AssignmentEvaluator(operandEvaluator, unboxedOperandType != null? new BoxingEvaluator(rightEval) : rightEval); } catch (IncorrectOperationException e) { LOG.error(e); } } else { if (JavaTokenType.PLUS.equals(operation) || JavaTokenType.MINUS.equals(operation)|| JavaTokenType.TILDE.equals(operation)) { operandEvaluator = handleUnaryNumericPromotion(operandType, operandEvaluator); } else { if (unboxedOperandType != null) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); } } myResult = new UnaryExpressionEvaluator(operation, expressionType.getCanonicalText(), operandEvaluator, expression.getOperationSign().getText()); } } @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { if (LOG.isDebugEnabled()) { LOG.debug("visitMethodCallExpression " + expression); } final PsiExpressionList argumentList = expression.getArgumentList(); final PsiExpression[] argExpressions = argumentList.getExpressions(); Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length]; // evaluate arguments for (int idx = 0; idx < argExpressions.length; idx++) { final PsiExpression psiExpression = argExpressions[idx]; psiExpression.accept(this); if (myResult == null) { // cannot build evaluator throwExpressionInvalid(psiExpression); } argumentEvaluators[idx] = new DisableGC(myResult); } PsiReferenceExpression methodExpr = expression.getMethodExpression(); final JavaResolveResult resolveResult = methodExpr.advancedResolve(false); final PsiMethod psiMethod = (PsiMethod)resolveResult.getElement(); PsiExpression qualifier = methodExpr.getQualifierExpression(); Evaluator objectEvaluator; JVMName contextClass = null; if(psiMethod != null) { PsiClass methodPsiClass = psiMethod.getContainingClass(); contextClass = JVMNameUtil.getJVMQualifiedName(methodPsiClass); if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) { objectEvaluator = new TypeEvaluator(contextClass); } else if (qualifier != null ) { qualifier.accept(this); objectEvaluator = myResult; } else { int iterationCount = 0; final PsiElement currentFileResolveScope = resolveResult.getCurrentFileResolveScope(); if (currentFileResolveScope instanceof PsiClass) { PsiClass aClass = getContextPsiClass(); while(aClass != null && !aClass.equals(currentFileResolveScope)) { aClass = getOuterClass(aClass); iterationCount++; } } objectEvaluator = new ThisEvaluator(iterationCount); } } else { //trying to guess if (qualifier != null) { PsiType type = qualifier.getType(); if (type != null) { contextClass = JVMNameUtil.getJVMQualifiedName(type); } if (qualifier instanceof PsiReferenceExpression && ((PsiReferenceExpression)qualifier).resolve() instanceof PsiClass) { // this is a call to a 'static' method but class is not available, try to evaluate by qname if (contextClass == null) { contextClass = JVMNameUtil.getJVMRawText(((PsiReferenceExpression)qualifier).getQualifiedName()); } objectEvaluator = new TypeEvaluator(contextClass); } else { qualifier.accept(this); objectEvaluator = myResult; } } else { objectEvaluator = new ThisEvaluator(); contextClass = JVMNameUtil.getContextClassJVMQualifiedName(myPosition); if(contextClass == null && myContextPsiClass != null) { contextClass = JVMNameUtil.getJVMQualifiedName(myContextPsiClass); } //else { // throw new EvaluateRuntimeException(EvaluateExceptionUtil.createEvaluateException( // DebuggerBundle.message("evaluation.error.method.not.found", methodExpr.getReferenceName())) // ); //} } } if (objectEvaluator == null) { throwExpressionInvalid(expression); } if (psiMethod != null && !psiMethod.isConstructor()) { if (psiMethod.getReturnType() == null) { throwEvaluateException(DebuggerBundle.message("evaluation.error.unknown.method.return.type", psiMethod.getText())); } } boolean defaultInterfaceMethod = false; boolean mustBeVararg = false; if (psiMethod != null) { processBoxingConversions(psiMethod.getParameterList().getParameters(), argExpressions, resolveResult.getSubstitutor(), argumentEvaluators); argumentEvaluators = wrapVarargs(psiMethod.getParameterList().getParameters(), argExpressions, resolveResult.getSubstitutor(), argumentEvaluators); defaultInterfaceMethod = psiMethod.hasModifierProperty(PsiModifier.DEFAULT); mustBeVararg = psiMethod.isVarArgs(); } myResult = new MethodEvaluator(objectEvaluator, contextClass, methodExpr.getReferenceName(), psiMethod != null ? JVMNameUtil.getJVMSignature(psiMethod) : null, argumentEvaluators, defaultInterfaceMethod, mustBeVararg); } @Override public void visitLiteralExpression(PsiLiteralExpression expression) { final HighlightInfo parsingError = HighlightUtil.checkLiteralExpressionParsingError(expression, null, null); if (parsingError != null) { throwEvaluateException(parsingError.getDescription()); return; } final PsiType type = expression.getType(); if (type == null) { throwEvaluateException(expression + ": null type"); return; } myResult = new LiteralEvaluator(expression.getValue(), type.getCanonicalText()); } @Override public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { final PsiExpression indexExpression = expression.getIndexExpression(); if(indexExpression == null) { throwExpressionInvalid(expression); } indexExpression.accept(this); final Evaluator indexEvaluator = handleUnaryNumericPromotion(indexExpression.getType(), myResult); expression.getArrayExpression().accept(this); Evaluator arrayEvaluator = myResult; myResult = new ArrayAccessEvaluator(arrayEvaluator, indexEvaluator); } /** * Handles unboxing and numeric promotion issues for * - array dimension expressions * - array index expression * - unary +, -, and ~ operations * @param operandExpressionType * @param operandEvaluator @return operandEvaluator possibly 'wrapped' with necessary unboxing and type-casting evaluators to make returning value * suitable for mentioned contexts */ private static Evaluator handleUnaryNumericPromotion(final PsiType operandExpressionType, Evaluator operandEvaluator) { final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(operandExpressionType); if (unboxedType != null && !PsiType.BOOLEAN.equals(unboxedType)) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); } // handle numeric promotion final PsiType _unboxedIndexType = unboxedType != null? unboxedType : operandExpressionType; if (_unboxedIndexType instanceof PsiPrimitiveType) { final PsiType promotionType = calcUnaryNumericPromotionType((PsiPrimitiveType)_unboxedIndexType); if (promotionType != null) { operandEvaluator = new TypeCastEvaluator(operandEvaluator, promotionType.getCanonicalText(), true); } } return operandEvaluator; } @Override public void visitTypeCastExpression(PsiTypeCastExpression expression) { PsiExpression operandExpr = expression.getOperand(); if (operandExpr == null) { throwExpressionInvalid(expression); } operandExpr.accept(this); Evaluator operandEvaluator = myResult; PsiTypeElement castTypeElem = expression.getCastType(); if (castTypeElem == null) { throwExpressionInvalid(expression); } PsiType castType = castTypeElem.getType(); PsiType operandType = operandExpr.getType(); // if operand type can not be resolved in current context - leave it for runtime checks if (operandType != null && !TypeConversionUtil.areTypesConvertible(operandType, castType) && PsiUtil.resolveClassInType(operandType) != null) { throw new EvaluateRuntimeException( new EvaluateException(JavaErrorMessages.message("inconvertible.type.cast", JavaHighlightUtil.formatType(operandType), JavaHighlightUtil .formatType(castType))) ); } boolean shouldPerformBoxingConversion = operandType != null && TypeConversionUtil.boxingConversionApplicable(castType, operandType); final boolean castingToPrimitive = castType instanceof PsiPrimitiveType; if (shouldPerformBoxingConversion && castingToPrimitive) { operandEvaluator = new UnBoxingEvaluator(operandEvaluator); } final boolean performCastToWrapperClass = shouldPerformBoxingConversion && !castingToPrimitive; if (!(PsiUtil.resolveClassInClassTypeOnly(castType) instanceof PsiTypeParameter)) { String castTypeName = castType.getCanonicalText(); if (performCastToWrapperClass) { final PsiPrimitiveType unboxedType = PsiPrimitiveType.getUnboxedType(castType); if (unboxedType != null) { castTypeName = unboxedType.getCanonicalText(); } } myResult = new TypeCastEvaluator(operandEvaluator, castTypeName, castingToPrimitive); } if (performCastToWrapperClass) { myResult = new BoxingEvaluator(myResult); } } @Override public void visitClassObjectAccessExpression(PsiClassObjectAccessExpression expression) { PsiType type = expression.getOperand().getType(); if (type instanceof PsiPrimitiveType) { final JVMName typeName = JVMNameUtil.getJVMRawText(((PsiPrimitiveType)type).getBoxedTypeName()); myResult = new FieldEvaluator(new TypeEvaluator(typeName), FieldEvaluator.TargetClassFilter.ALL, "TYPE"); } else { myResult = new ClassObjectEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type))); } } @Override public void visitLambdaExpression(PsiLambdaExpression expression) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(DebuggerBundle.message("evaluation.error.lambda.evaluation.not.supported"))); } @Override public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(DebuggerBundle.message("evaluation.error.method.reference.evaluation.not.supported"))); } @Override public void visitNewExpression(final PsiNewExpression expression) { PsiType expressionPsiType = expression.getType(); if (expressionPsiType instanceof PsiArrayType) { Evaluator dimensionEvaluator = null; PsiExpression[] dimensions = expression.getArrayDimensions(); if (dimensions.length == 1){ PsiExpression dimensionExpression = dimensions[0]; dimensionExpression.accept(this); if (myResult != null) { dimensionEvaluator = handleUnaryNumericPromotion(dimensionExpression.getType(), myResult); } else { throwEvaluateException( DebuggerBundle.message("evaluation.error.invalid.array.dimension.expression", dimensionExpression.getText())); } } else if (dimensions.length > 1){ throwEvaluateException(DebuggerBundle.message("evaluation.error.multi.dimensional.arrays.creation.not.supported")); } Evaluator initializerEvaluator = null; PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer(); if (arrayInitializer != null) { if (dimensionEvaluator != null) { // initializer already exists throwExpressionInvalid(expression); } arrayInitializer.accept(this); if (myResult != null) { initializerEvaluator = handleUnaryNumericPromotion(arrayInitializer.getType(), myResult); } else { throwExpressionInvalid(arrayInitializer); } /* PsiExpression[] initializers = arrayInitializer.getInitializers(); initializerEvaluators = new Evaluator[initializers.length]; for (int idx = 0; idx < initializers.length; idx++) { PsiExpression initializer = initializers[idx]; initializer.accept(this); if (myResult instanceof Evaluator) { initializerEvaluators[idx] = myResult; } else { throw new EvaluateException("Invalid expression for array initializer: " + initializer.getText(), true); } } */ } if (dimensionEvaluator == null && initializerEvaluator == null) { throwExpressionInvalid(expression); } myResult = new NewArrayInstanceEvaluator( new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)), dimensionEvaluator, initializerEvaluator ); } else if (expressionPsiType instanceof PsiClassType){ // must be a class ref PsiClass aClass = ((PsiClassType)expressionPsiType).resolve(); if(aClass instanceof PsiAnonymousClass) { throw new EvaluateRuntimeException(new UnsupportedExpressionException(DebuggerBundle.message("evaluation.error.anonymous.class.evaluation.not.supported"))); } PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList == null) { throwExpressionInvalid(expression); } final PsiExpression[] argExpressions = argumentList.getExpressions(); final JavaResolveResult constructorResolveResult = expression.resolveMethodGenerics(); final PsiMethod constructor = (PsiMethod)constructorResolveResult.getElement(); if (constructor == null && argExpressions.length > 0) { throw new EvaluateRuntimeException(new EvaluateException( DebuggerBundle.message("evaluation.error.cannot.resolve.constructor", expression.getText()), null)); } Evaluator[] argumentEvaluators = new Evaluator[argExpressions.length]; // evaluate arguments for (int idx = 0; idx < argExpressions.length; idx++) { PsiExpression argExpression = argExpressions[idx]; argExpression.accept(this); if (myResult != null) { argumentEvaluators[idx] = new DisableGC(myResult); } else { throwExpressionInvalid(argExpression); } } if (constructor != null) { processBoxingConversions(constructor.getParameterList().getParameters(), argExpressions, constructorResolveResult.getSubstitutor(), argumentEvaluators); argumentEvaluators = wrapVarargs(constructor.getParameterList().getParameters(), argExpressions, constructorResolveResult.getSubstitutor(), argumentEvaluators); } if (aClass != null && aClass.getContainingClass() != null && !aClass.hasModifierProperty(PsiModifier.STATIC)) { argumentEvaluators = addThisEvaluator(argumentEvaluators, aClass.getContainingClass()); } JVMName signature = JVMNameUtil.getJVMConstructorSignature(constructor, aClass); myResult = new NewClassInstanceEvaluator( new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(expressionPsiType)), signature, argumentEvaluators ); } else { if (expressionPsiType != null) { throwEvaluateException("Unsupported expression type: " + expressionPsiType.getPresentableText()); } else { throwEvaluateException("Unknown type for expression: " + expression.getText()); } } } private Evaluator[] addThisEvaluator(Evaluator[] argumentEvaluators, PsiClass cls) { Evaluator[] res = new Evaluator[argumentEvaluators.length+1]; int depth = calcIterationCount(cls, "this"); res[0] = new ThisEvaluator(depth); System.arraycopy(argumentEvaluators, 0, res, 1, argumentEvaluators.length); return res; } @Override public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) { PsiExpression[] initializers = expression.getInitializers(); Evaluator[] evaluators = new Evaluator[initializers.length]; final PsiType type = expression.getType(); boolean primitive = type instanceof PsiArrayType && ((PsiArrayType)type).getComponentType() instanceof PsiPrimitiveType; for (int idx = 0; idx < initializers.length; idx++) { PsiExpression initializer = initializers[idx]; initializer.accept(this); if (myResult != null) { final Evaluator coerced = primitive ? handleUnaryNumericPromotion(initializer.getType(), myResult) : new BoxingEvaluator(myResult); evaluators[idx] = new DisableGC(coerced); } else { throwExpressionInvalid(initializer); } } myResult = new ArrayInitializerEvaluator(evaluators); if (type != null && !(expression.getParent() instanceof PsiNewExpression)) { myResult = new NewArrayInstanceEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(type)), null, myResult); } } @Nullable private static PsiClass getOuterClass(PsiClass aClass) { return aClass == null ? null : PsiTreeUtil.getContextOfType(aClass, PsiClass.class, true); } private PsiClass getContainingClass(PsiVariable variable) { PsiElement element = PsiTreeUtil.getParentOfType(variable.getParent(), PsiClass.class, false); return element == null ? getContextPsiClass() : (PsiClass)element; } public PsiClass getContextPsiClass() { return myContextPsiClass; } protected ExpressionEvaluator buildElement(final PsiElement element) throws EvaluateException { LOG.assertTrue(element.isValid()); myContextPsiClass = PsiTreeUtil.getContextOfType(element, PsiClass.class, false); try { element.accept(this); } catch (EvaluateRuntimeException e) { throw e.getCause(); } if (myResult == null) { throw EvaluateExceptionUtil .createEvaluateException(DebuggerBundle.message("evaluation.error.invalid.expression", element.toString())); } return new ExpressionEvaluatorImpl(myResult); } } private static Evaluator[] wrapVarargs(final PsiParameter[] declaredParams, final PsiExpression[] actualArgumentExpressions, final PsiSubstitutor methodResolveSubstitutor, final Evaluator[] argumentEvaluators) { int lastParam = declaredParams.length - 1; if (lastParam >= 0 && declaredParams[lastParam].isVarArgs() && argumentEvaluators.length > lastParam) { // only wrap if the first varargs parameter is null for now if (!TypeConversionUtil.isNullType(actualArgumentExpressions[lastParam].getType())) { return argumentEvaluators; } // do not wrap arrays twice if (argumentEvaluators.length - lastParam == 1 && actualArgumentExpressions[lastParam].getType() instanceof PsiArrayType) { return argumentEvaluators; } PsiEllipsisType declaredParamType = (PsiEllipsisType)methodResolveSubstitutor.substitute(declaredParams[lastParam].getType()); ArrayInitializerEvaluator varargArrayEvaluator = new ArrayInitializerEvaluator(Arrays.copyOfRange(argumentEvaluators, lastParam, argumentEvaluators.length)); NewArrayInstanceEvaluator evaluator = new NewArrayInstanceEvaluator(new TypeEvaluator(JVMNameUtil.getJVMQualifiedName(declaredParamType.toArrayType())), null, varargArrayEvaluator); Evaluator[] res = new Evaluator[declaredParams.length]; System.arraycopy(argumentEvaluators, 0, res, 0, lastParam); res[lastParam] = new DisableGC(evaluator); return res; } return argumentEvaluators; } private static void processBoxingConversions(final PsiParameter[] declaredParams, final PsiExpression[] actualArgumentExpressions, final PsiSubstitutor methodResolveSubstitutor, final Evaluator[] argumentEvaluators) { if (declaredParams.length > 0) { final int paramCount = Math.max(declaredParams.length, actualArgumentExpressions.length); PsiType varargType = null; for (int idx = 0; idx < paramCount; idx++) { if (idx >= actualArgumentExpressions.length) { break; // actual arguments count is less than number of declared params } PsiType declaredParamType; if (idx < declaredParams.length) { declaredParamType = methodResolveSubstitutor.substitute(declaredParams[idx].getType()); if (declaredParamType instanceof PsiEllipsisType) { declaredParamType = varargType = ((PsiEllipsisType)declaredParamType).getComponentType(); } } else if (varargType != null) { declaredParamType = varargType; } else { break; } final PsiType actualArgType = actualArgumentExpressions[idx].getType(); if (TypeConversionUtil.boxingConversionApplicable(declaredParamType, actualArgType)) { final Evaluator argEval = argumentEvaluators[idx]; argumentEvaluators[idx] = declaredParamType instanceof PsiPrimitiveType ? new UnBoxingEvaluator(argEval) : new BoxingEvaluator(argEval); } } } } }
EA-61990 - NPE: EvaluatorBuilderImpl$Builder.visitReferenceExpression
java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java
EA-61990 - NPE: EvaluatorBuilderImpl$Builder.visitReferenceExpression
<ide><path>ava/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/EvaluatorBuilderImpl.java <ide> qualifier.accept(this); <ide> objectEvaluator = myResult; <ide> } <del> else if (fieldClass.equals(getContextPsiClass()) || getContextPsiClass().isInheritor(fieldClass, true)) { <add> else if (fieldClass.equals(getContextPsiClass()) || <add> (getContextPsiClass() != null && getContextPsiClass().isInheritor(fieldClass, true))) { <ide> objectEvaluator = new ThisEvaluator(); <ide> } <ide> else { // myContextPsiClass != fieldClass && myContextPsiClass is not a subclass of fieldClass <ide> return element == null ? getContextPsiClass() : (PsiClass)element; <ide> } <ide> <add> @Nullable <ide> public PsiClass getContextPsiClass() { <ide> return myContextPsiClass; <ide> }
Java
apache-2.0
1fcdd6bd100b21fbf62abf30f2a0f3a753ead88b
0
ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,leeper/dataverse-1,JayanthyChengan/dataverse,quarian/dataverse,leeper/dataverse-1,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,majorseitan/dataverse,quarian/dataverse,majorseitan/dataverse,quarian/dataverse,leeper/dataverse-1,leeper/dataverse-1,JayanthyChengan/dataverse,leeper/dataverse-1,leeper/dataverse-1,JayanthyChengan/dataverse,majorseitan/dataverse,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,jacksonokuhn/dataverse,jacksonokuhn/dataverse,jacksonokuhn/dataverse,quarian/dataverse,ekoi/DANS-DVN-4.6.1,quarian/dataverse,majorseitan/dataverse,bmckinney/dataverse-canonical,leeper/dataverse-1,majorseitan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,ekoi/DANS-DVN-4.6.1,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,majorseitan/dataverse,JayanthyChengan/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,bmckinney/dataverse-canonical,ekoi/DANS-DVN-4.6.1,jacksonokuhn/dataverse,majorseitan/dataverse,ekoi/DANS-DVN-4.6.1,majorseitan/dataverse,leeper/dataverse-1,quarian/dataverse,quarian/dataverse,bmckinney/dataverse-canonical,JayanthyChengan/dataverse,quarian/dataverse,jacksonokuhn/dataverse,bmckinney/dataverse-canonical
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse; import java.util.Collection; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.*; /** * * @author Stephen Kraffmiller */ @Entity public class DatasetField implements Serializable, Comparable<DatasetField> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name="name", columnDefinition="TEXT") private String name; // This is the internal, DDI-like name, no spaces, etc. @Column(name="title", columnDefinition="TEXT") private String title; // A longer, human-friendlier name - punctuation allowed @Column(name="description", columnDefinition="TEXT") private String description; // A user-friendly Description; will be used for // mouse-overs, etc. private String fieldType; private boolean allowControlledVocabulary; @Transient private String searchValue; public DatasetField() { } private int displayOrder; public int getDisplayOrder() { return this.displayOrder; } public void setDisplayOrder(int displayOrder) { this.displayOrder = displayOrder; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isAllowControlledVocabulary() { return allowControlledVocabulary; } public void setAllowControlledVocabulary(boolean allowControlledVocabulary) { this.allowControlledVocabulary = allowControlledVocabulary; } private boolean allowMultiples; public boolean isAllowMultiples() { return this.allowMultiples; } public void setAllowMultiples(boolean allowMultiples) { this.allowMultiples = allowMultiples; } public String getFieldType() { return fieldType; } public void setFieldType(String fieldType) { this.fieldType = fieldType; } @ManyToOne(cascade = CascadeType.MERGE) private MetadataBlock metadataBlock; public MetadataBlock getMetadataBlock() { return metadataBlock; } public void setMetadataBlock(MetadataBlock metadataBlock) { this.metadataBlock = metadataBlock; } @OneToMany(mappedBy = "parentDatasetField", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) @OrderBy("displayOrder ASC") private Collection<DatasetField> childDatasetFields; public Collection<DatasetField> getChildDatasetFields() { return this.childDatasetFields; } public void setChildDatasetFields(Collection<DatasetField> childDatasetFields) { this.childDatasetFields = childDatasetFields; } @ManyToOne(cascade = CascadeType.MERGE) private DatasetField parentDatasetField; public DatasetField getParentDatasetField() { return parentDatasetField; } public void setParentDatasetField(DatasetField parentDatasetField) { this.parentDatasetField = parentDatasetField; } /** * Holds value of property studies. */ /* @ManyToMany(mappedBy="summaryFields",cascade={CascadeType.REMOVE }) private Collection<Study> studies; @ManyToMany(mappedBy="advSearchFields",cascade={CascadeType.REMOVE }) private Collection<VDC> advSearchFieldVDCs; @ManyToMany(mappedBy="searchResultFields",cascade={CascadeType.REMOVE }) private Collection<VDC> searchResultFieldVDCs; @ManyToMany(mappedBy="anySearchFields",cascade={CascadeType.REMOVE }) private Collection<VDC> anySearchFieldVDCs; @ManyToMany(mappedBy="summaryFields",cascade={CascadeType.REMOVE }) private Collection<VDC> summaryFieldVDCs; */ public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } private boolean required; public boolean isRequired() { return this.required; } public void setRequired(boolean required) { this.required = required; } private boolean basicSearchField; public boolean isBasicSearchField() { return this.basicSearchField; } public void setBasicSearchField(boolean basicSearchField) { this.basicSearchField = basicSearchField; } private boolean advancedSearchField; public boolean isAdvancedSearchField() { return this.advancedSearchField; } public void setAdvancedSearchField(boolean advancedSearchField) { this.advancedSearchField = advancedSearchField; } private boolean searchResultField; public boolean isSearchResultField() { return this.searchResultField; } public void setSearchResultField(boolean searchResultField) { this.searchResultField = searchResultField; } public boolean isHasChildren(){ return !this.childDatasetFields.isEmpty(); } public boolean isHasParent(){ return this.parentDatasetField != null; } public int hashCode() { int hash = 0; hash += (this.id != null ? this.id.hashCode() : 0); return hash; } public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatasetField)) { return false; } DatasetField other = (DatasetField)object; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false; return true; } @OneToMany (mappedBy="datasetField", cascade={ CascadeType.REMOVE, CascadeType.MERGE,CascadeType.PERSIST}) private List<DatasetFieldValue> datasetFieldValues; public List<DatasetFieldValue> getDatasetFieldValues() { return datasetFieldValues; } public void setDatasetFieldValues(List<DatasetFieldValue> datasetFieldValues) { this.datasetFieldValues = datasetFieldValues; } @OneToMany (mappedBy="datasetField", cascade={ CascadeType.REMOVE, CascadeType.MERGE,CascadeType.PERSIST}) private List<DatasetFieldDefaultValue> datasetFieldDefaultValues; public List<DatasetFieldDefaultValue> getDatasetFieldDefaultValues() { return datasetFieldDefaultValues; } public void setDatasetFieldDefaultValues(List<DatasetFieldDefaultValue> datasetFieldDefaultValues) { this.datasetFieldDefaultValues = datasetFieldDefaultValues; } // helper methods for getting the internal string values public List<String> getDatasetFieldValueStrings() { List <String> retString = new ArrayList(); for (DatasetFieldValue sfv:datasetFieldValues){ String testString = sfv.getStrValue(); if (!testString.isEmpty()) { retString.add(sfv.getStrValue()); } } return retString; } public String getDatasetFieldValueSingleString() { return datasetFieldValues.size() > 0 ? datasetFieldValues.get(0).getStrValue() : ""; } public void setDatasetFieldValueStrings(List<String> newValList) {} public void setDatasetFieldValueSingleString(String newVal) {} @Override public int compareTo(DatasetField o) { return Integer.compare(this.getDisplayOrder(),(o.getDisplayOrder())); } public String getSolrField() { String solrType; if (fieldType != null) { // these are all "dynamic fields" from a Solr perspective if (fieldType.equals("textBox")) { solrType = "_s"; } else if (fieldType.equals("date")) { solrType = "_i"; } else if (fieldType.equals("email")) { solrType = "_s"; } else if (fieldType.equals("url")) { solrType = "_s"; } else { solrType = "_s"; } return name + solrType; } else { return "nulltype_s"; } } }
src/main/java/edu/harvard/iq/dataverse/DatasetField.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dataverse; import java.util.Collection; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.*; /** * * @author Stephen Kraffmiller */ @Entity public class DatasetField implements Serializable, Comparable<DatasetField> { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name="name", columnDefinition="TEXT") private String name; // This is the internal, DDI-like name, no spaces, etc. @Column(name="title", columnDefinition="TEXT") private String title; // A longer, human-friendlier name - punctuation allowed @Column(name="description", columnDefinition="TEXT") private String description; // A user-friendly Description; will be used for // mouse-overs, etc. private String fieldType; private boolean allowControlledVocabulary; @Transient private String searchValue; public DatasetField() { } private int displayOrder; public int getDisplayOrder() { return this.displayOrder; } public void setDisplayOrder(int displayOrder) { this.displayOrder = displayOrder; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isAllowControlledVocabulary() { return allowControlledVocabulary; } public void setAllowControlledVocabulary(boolean allowControlledVocabulary) { this.allowControlledVocabulary = allowControlledVocabulary; } private boolean allowMultiples; public boolean isAllowMultiples() { return this.allowMultiples; } public void setAllowMultiples(boolean allowMultiples) { this.allowMultiples = allowMultiples; } public String getFieldType() { return fieldType; } public void setFieldType(String fieldType) { this.fieldType = fieldType; } @ManyToOne(cascade = CascadeType.MERGE) private MetadataBlock metadataBlock; public MetadataBlock getMetadataBlock() { return metadataBlock; } public void setMetadataBlock(MetadataBlock metadataBlock) { this.metadataBlock = metadataBlock; } @OneToMany(mappedBy = "parentDatasetField", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) @OrderBy("displayOrder ASC") private Collection<DatasetField> childDatasetFields; public Collection<DatasetField> getChildDatasetFields() { return this.childDatasetFields; } public void setChildDatasetFields(Collection<DatasetField> childDatasetFields) { this.childDatasetFields = childDatasetFields; } @ManyToOne(cascade = CascadeType.MERGE) private DatasetField parentDatasetField; public DatasetField getParentDatasetField() { return parentDatasetField; } public void setParentDatasetField(DatasetField parentDatasetField) { this.parentDatasetField = parentDatasetField; } /** * Holds value of property studies. */ /* @ManyToMany(mappedBy="summaryFields",cascade={CascadeType.REMOVE }) private Collection<Study> studies; @ManyToMany(mappedBy="advSearchFields",cascade={CascadeType.REMOVE }) private Collection<VDC> advSearchFieldVDCs; @ManyToMany(mappedBy="searchResultFields",cascade={CascadeType.REMOVE }) private Collection<VDC> searchResultFieldVDCs; @ManyToMany(mappedBy="anySearchFields",cascade={CascadeType.REMOVE }) private Collection<VDC> anySearchFieldVDCs; @ManyToMany(mappedBy="summaryFields",cascade={CascadeType.REMOVE }) private Collection<VDC> summaryFieldVDCs; */ public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } private boolean required; public boolean isRequired() { return this.required; } public void setRequired(boolean required) { this.required = required; } private boolean basicSearchField; public boolean isBasicSearchField() { return this.basicSearchField; } public void setBasicSearchField(boolean basicSearchField) { this.basicSearchField = basicSearchField; } private boolean advancedSearchField; public boolean isAdvancedSearchField() { return this.advancedSearchField; } public void setAdvancedSearchField(boolean advancedSearchField) { this.advancedSearchField = advancedSearchField; } private boolean searchResultField; public boolean isSearchResultField() { return this.searchResultField; } public void setSearchResultField(boolean searchResultField) { this.searchResultField = searchResultField; } public boolean isHasChildren(){ return !this.childDatasetFields.isEmpty(); } public boolean isHasParent(){ return this.parentDatasetField != null; } public int hashCode() { int hash = 0; hash += (this.id != null ? this.id.hashCode() : 0); return hash; } public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatasetField)) { return false; } DatasetField other = (DatasetField)object; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false; return true; } @OneToMany (mappedBy="datasetField", cascade={ CascadeType.REMOVE, CascadeType.MERGE,CascadeType.PERSIST}) private List<DatasetFieldValue> datasetFieldValues; public List<DatasetFieldValue> getDatasetFieldValues() { return datasetFieldValues; } public void setDatasetFieldValues(List<DatasetFieldValue> datasetFieldValues) { this.datasetFieldValues = datasetFieldValues; } @OneToMany (mappedBy="datasetField", cascade={ CascadeType.REMOVE, CascadeType.MERGE,CascadeType.PERSIST}) private List<DatasetFieldDefaultValue> datasetFieldDefaultValues; public List<DatasetFieldDefaultValue> getDatasetFieldDefaultValues() { return datasetFieldDefaultValues; } public void setDatasetFieldDefaultValues(List<DatasetFieldDefaultValue> datasetFieldDefaultValues) { this.datasetFieldDefaultValues = datasetFieldDefaultValues; } // helper methods for getting the internal string values public List<String> getDatasetFieldValueStrings() { List <String> retString = new ArrayList(); for (DatasetFieldValue sfv:datasetFieldValues){ String testString = sfv.getStrValue(); if (!testString.isEmpty()) { retString.add(sfv.getStrValue()); } } return retString; } public String getDatasetFieldValueSingleString() { return datasetFieldValues.size() > 0 ? datasetFieldValues.get(0).getStrValue() : ""; } public void setDatasetFieldValueStrings(List<String> newValList) {} public void setDatasetFieldValueSingleString(String newVal) {} @Override public int compareTo(DatasetField o) { return Integer.compare(this.getDisplayOrder(),(o.getDisplayOrder())); } }
added new getSolrField method on DatasetField
src/main/java/edu/harvard/iq/dataverse/DatasetField.java
added new getSolrField method on DatasetField
<ide><path>rc/main/java/edu/harvard/iq/dataverse/DatasetField.java <ide> public int compareTo(DatasetField o) { <ide> return Integer.compare(this.getDisplayOrder(),(o.getDisplayOrder())); <ide> } <add> <add> public String getSolrField() { <add> String solrType; <add> if (fieldType != null) { <add> // these are all "dynamic fields" from a Solr perspective <add> if (fieldType.equals("textBox")) { <add> solrType = "_s"; <add> } else if (fieldType.equals("date")) { <add> solrType = "_i"; <add> } else if (fieldType.equals("email")) { <add> solrType = "_s"; <add> } else if (fieldType.equals("url")) { <add> solrType = "_s"; <add> } else { <add> solrType = "_s"; <add> } <add> return name + solrType; <add> } else { <add> return "nulltype_s"; <add> } <add> } <ide> }
Java
bsd-3-clause
43defec806df1539f10a045ac1039d708f42c6bd
0
BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex,BaseXdb/basex
package org.basex.query.func; import static org.basex.query.QueryError.*; import static org.basex.query.QueryText.*; import java.util.*; import java.util.Map.*; import org.basex.core.*; import org.basex.query.*; import org.basex.query.ann.*; import org.basex.query.expr.*; import org.basex.query.expr.gflwor.*; import org.basex.query.scope.*; import org.basex.query.util.*; import org.basex.query.util.list.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; /** * Inline function. * * @author BaseX Team 2005-21, BSD License * @author Leo Woerteler */ public final class Closure extends Single implements Scope, XQFunctionExpr { /** Function name, {@code null} if not specified. */ private final QNm name; /** Formal parameters. */ private final Var[] params; /** Value type, {@code null} if not specified. */ private SeqType declType; /** Annotations. */ private AnnList anns; /** Updating flag. */ private boolean updating; /** Map with requested function properties. */ private final EnumMap<Flag, Boolean> map = new EnumMap<>(Flag.class); /** Compilation flag. */ private boolean compiled; /** Local variables in the scope of this function. */ private final VarScope vs; /** Non-local variable bindings. */ private final Map<Var, Expr> global; /** * Constructor. * @param info input info * @param declType declared type (can be {@code null}) * @param params formal parameters * @param expr function body * @param anns annotations * @param global bindings for non-local variables * @param vs scope */ public Closure(final InputInfo info, final SeqType declType, final Var[] params, final Expr expr, final AnnList anns, final Map<Var, Expr> global, final VarScope vs) { this(info, null, declType, params, expr, anns, global, vs); } /** * Package-private constructor allowing a name. * @param info input info * @param name name of the function (can be {@code null}) * @param declType declared type (can be {@code null}) * @param params formal parameters * @param expr function expression * @param anns annotations * @param global bindings for non-local variables (can be {@code null}) * @param vs variable scope */ Closure(final InputInfo info, final QNm name, final SeqType declType, final Var[] params, final Expr expr, final AnnList anns, final Map<Var, Expr> global, final VarScope vs) { super(info, expr, SeqType.FUNCTION_O); this.name = name; this.params = params; this.declType = declType == null || declType.eq(SeqType.ITEM_ZM) ? null : declType; this.anns = anns; this.global = global == null ? Collections.emptyMap() : global; this.vs = vs; } @Override public int arity() { return params.length; } @Override public QNm funcName() { return name; } @Override public QNm paramName(final int pos) { return params[pos].name; } @Override public FuncType funcType() { final FuncType type = super.funcType(); return type != null ? type : FuncType.get(anns, declType, params); } @Override public AnnList annotations() { return anns; } @Override public void comp(final CompileContext cc) throws QueryException { compile(cc); } @Override public Expr compile(final CompileContext cc) throws QueryException { if(compiled) return this; compiled = true; checkUpdating(); // compile closure for(final Entry<Var, Expr> entry : global.entrySet()) { final Expr bound = entry.getValue().compile(cc); entry.setValue(bound); entry.getKey().refineType(bound.seqType(), cc); } cc.pushScope(vs); try { expr = expr.compile(cc); } catch(final QueryException qe) { expr = cc.error(qe, expr); } finally { cc.removeScope(this); } // convert all function calls in tail position to proper tail calls expr.markTailCalls(cc); return optimize(cc); } @Override public Expr optimize(final CompileContext cc) throws QueryException { cc.pushScope(vs); try { // inline all values in the closure final Iterator<Entry<Var, Expr>> iter = global.entrySet().iterator(); Map<Var, Expr> add = null; final int limit = cc.qc.context.options.get(MainOptions.INLINELIMIT); while(iter.hasNext()) { final Entry<Var, Expr> entry = iter.next(); final Var var = entry.getKey(); final Expr ex = entry.getValue(); Expr inline = null; if(ex instanceof Value) { // values are always inlined into the closure inline = var.checkType((Value) ex, cc.qc, true); } else if(ex instanceof Closure) { // nested closures are inlined if their size and number of closed-over variables is small final Closure cl = (Closure) ex; if(!cl.has(Flag.NDT) && cl.global.size() < 5 && expr.count(var) != VarUsage.MORE_THAN_ONCE && cl.exprSize() < limit) { cc.info(OPTINLINE_X, entry); for(final Entry<Var, Expr> expr2 : cl.global.entrySet()) { final Var var2 = cc.copy(expr2.getKey(), null); if(add == null) add = new HashMap<>(); add.put(var2, expr2.getValue()); expr2.setValue(new VarRef(cl.info, var2).optimize(cc)); } inline = cl; } } if(inline != null) { expr = new InlineContext(var, inline, cc).inline(expr); iter.remove(); } } // add all newly added bindings if(add != null) global.putAll(add); } catch(final QueryException qe) { expr = cc.error(qe, expr); } finally { cc.removeScope(this); } final SeqType st = expr.seqType(); final SeqType dt = declType == null || st.instanceOf(declType) ? st : declType; exprType.assign(FuncType.get(anns, dt, params)); // only evaluate if: // - the closure is empty, so we don't lose variables // - the result size does not exceed a specific limit return global.isEmpty() && expr.size() <= CompileContext.MAX_PREEVAL ? cc.preEval(this) : this; } @Override public VarUsage count(final Var var) { VarUsage all = VarUsage.NEVER; for(final Expr ex : global.values()) { if((all = all.plus(ex.count(var))) == VarUsage.MORE_THAN_ONCE) break; } return all; } @Override public Expr inline(final InlineContext ic) throws QueryException { boolean changed = false; for(final Entry<Var, Expr> entry : global.entrySet()) { final Expr inlined = entry.getValue().inline(ic); if(inlined != null) { changed = true; entry.setValue(inlined); } } if(!changed) return null; // invalidate cached flags, optimize closure map.clear(); return optimize(ic.cc); } @Override public Expr copy(final CompileContext cc, final IntObjMap<Var> vm) { final VarScope innerScope = new VarScope(vs.sc); final HashMap<Var, Expr> outer = new HashMap<>(); global.forEach((key, value) -> outer.put(key, value.copy(cc, vm))); cc.pushScope(innerScope); try { final IntObjMap<Var> innerVars = new IntObjMap<>(); vs.copy(cc, innerVars); final HashMap<Var, Expr> nl = new HashMap<>(); outer.forEach((key, value) -> nl.put(innerVars.get(key.id), value)); final Var[] prms = params.clone(); final int pl = prms.length; for(int p = 0; p < pl; p++) prms[p] = innerVars.get(prms[p].id); final Expr ex = expr.copy(cc, innerVars); ex.markTailCalls(null); return copyType(new Closure(info, name, declType, prms, ex, anns, nl, cc.vs())); } finally { cc.removeScope(); } } @Override public Expr inline(final Expr[] exprs, final CompileContext cc) throws QueryException { if(!StaticFunc.inline(cc, anns, expr) || expr.has(Flag.CTX)) return null; cc.info(OPTINLINE_X, this); // create let bindings for all variables final LinkedList<Clause> clauses = new LinkedList<>(); final IntObjMap<Var> vm = new IntObjMap<>(); final int pl = params.length; for(int p = 0; p < pl; p++) { clauses.add(new Let(cc.copy(params[p], vm), exprs[p]).optimize(cc)); } for(final Entry<Var, Expr> entry : global.entrySet()) { clauses.add(new Let(cc.copy(entry.getKey(), vm), entry.getValue()).optimize(cc)); } // create the return clause final Expr body = expr.copy(cc, vm).optimize(cc); final Expr rtrn = declType == null ? body : new TypeCheck(vs.sc, info, body, declType, true).optimize(cc); return clauses.isEmpty() ? rtrn : new GFLWOR(info, clauses, rtrn).optimize(cc); } @Override public FuncItem item(final QueryContext qc, final InputInfo ii) throws QueryException { final Expr body; if(global.isEmpty()) { body = expr; } else { // collect closure final LinkedList<Clause> clauses = new LinkedList<>(); for(final Entry<Var, Expr> entry : global.entrySet()) { clauses.add(new Let(entry.getKey(), entry.getValue().value(qc))); } body = new GFLWOR(info, clauses, expr); } final SeqType argType = body.seqType(); final Expr checked; if(declType == null || argType.instanceOf(declType)) { // return type is already correct checked = body; } else if(body instanceof FuncItem && declType.type instanceof FuncType) { // function item coercion if(!declType.occ.check(1)) throw typeError(body, declType, null, info, true); checked = ((FuncItem) body).coerceTo((FuncType) declType.type, qc, info, true); } else if(body instanceof Value) { // we can type check immediately final Value value = (Value) body; checked = declType.instance(value) ? value : declType.promote(value, null, qc, vs.sc, info, false); } else { // check at each call: reject impossible arities if(argType.type.instanceOf(declType.type) && argType.occ.intersect(declType.occ) == null && !body.has(Flag.NDT)) throw typeError(body, declType, null, info, true); checked = new TypeCheck(vs.sc, info, body, declType, true); } final FuncType type = (FuncType) seqType().type; return new FuncItem(vs.sc, anns, name, params, type, checked, vs.stackSize(), info); } @Override public boolean has(final Flag... flags) { // closure does not perform any updates if(Flag.UPD.in(flags)) return false; // handle recursive calls: check which flags are already or currently assigned final ArrayList<Flag> flgs = new ArrayList<>(); for(final Flag flag : flags) { if(!map.containsKey(flag)) { map.put(flag, Boolean.FALSE); flgs.add(flag); } } // request missing properties for(final Flag flag : flgs) { boolean f = false; for(final Expr ex : global.values()) f = f || ex.has(flag); map.put(flag, f || expr.has(flag)); } // evaluate result for(final Flag flag : flags) { if(map.get(flag)) return true; } return false; } @Override public boolean inlineable(final InlineContext ic) { for(final Expr ex : global.values()) { if(!ex.inlineable(ic)) return false; } return true; } @Override public boolean visit(final ASTVisitor visitor) { for(final Entry<Var, Expr> entry : global.entrySet()) { if(!(entry.getValue().accept(visitor) && visitor.declared(entry.getKey()))) return false; } for(final Var var : params) { if(!visitor.declared(var)) return false; } return expr.accept(visitor); } @Override public void checkUp() throws QueryException { checkUpdating(); if(updating) { expr.checkUp(); if(declType != null && !declType.zero()) throw UUPFUNCTYPE.get(info); } } @Override public boolean vacuous() { return declType != null && declType.zero() && !has(Flag.UPD); } @Override public boolean vacuousBody() { return vacuous(); } @Override public boolean accept(final ASTVisitor visitor) { for(final Expr ex : global.values()) { if(!ex.accept(visitor)) return false; } return visitor.inlineFunc(this); } @Override public int exprSize() { int size = 1; for(final Expr ex : global.values()) size += ex.exprSize(); return size + expr.exprSize(); } @Override public boolean compiled() { return compiled; } /** * Returns an iterator over the non-local bindings of this closure. * @return the iterator */ public Iterator<Entry<Var, Expr>> globalBindings() { return global.entrySet().iterator(); } /** * Fixes the function type of this closure after it was generated for a function literal during * parsing. * @param ft function type */ void adoptSignature(final FuncType ft) { anns = ft.anns; final int pl = params.length; for(int p = 0; p < pl; p++) params[p].declType = ft.argTypes[p]; final SeqType dt = ft.declType; if(!dt.eq(SeqType.ITEM_ZM)) declType = dt; } /** * Assigns the updating flag. * @throws QueryException query exception */ private void checkUpdating() throws QueryException { // derive updating flag from function body updating = expr.has(Flag.UPD); final boolean updAnn = anns.contains(Annotation.UPDATING); if(updating != updAnn) { if(!updAnn) anns.add(new Ann(info, Annotation.UPDATING)); else if(!expr.vacuous()) throw UPEXPECTF.get(info); } } /** * Creates a function literal for a function that was not yet encountered while parsing. * @param name function name * @param arity function arity * @param qc query context * @param sc static context * @param ii input info * @return function literal * @throws QueryException query exception */ public static Closure undeclaredLiteral(final QNm name, final int arity, final QueryContext qc, final StaticContext sc, final InputInfo ii) throws QueryException { final VarScope vs = new VarScope(sc); final Var[] params = new Var[arity]; final Expr[] args = new Expr[arity]; for(int a = 0; a < arity; a++) { params[a] = vs.addNew(new QNm(ARG + (a + 1), ""), null, true, qc, ii); args[a] = new VarRef(ii, params[a]); } final TypedFunc tf = qc.funcs.undeclaredFuncCall(name, args, sc, ii); return new Closure(ii, name, null, params, tf.func, new AnnList(), null, vs); } @Override public boolean equals(final Object obj) { // [CG] could be enhanced return this == obj; } @Override public void plan(final QueryPlan plan) { final ArrayList<Object> list = new ArrayList<>(); global.forEach((key, value) -> { list.add(key); list.add(value); }); final FElem elem = plan.create(this); final int pl = params.length; for(int p = 0; p < pl; p++) plan.addAttribute(elem, ARG + p, params[p].name.string()); plan.add(elem, list.toArray()); } @Override public void plan(final QueryString qs) { final boolean inlined = !global.isEmpty(); if(inlined) { qs.token("((: inline-closure :)"); global.forEach((k, v) -> qs.token(LET).token(k).token(ASSIGN).token(v)); qs.token(RETURN); } qs.token(FUNCTION).params(params); qs.token(AS).token(declType != null ? declType : SeqType.ITEM_ZM).brace(expr); if(inlined) qs.token(')'); } }
basex-core/src/main/java/org/basex/query/func/Closure.java
package org.basex.query.func; import static org.basex.query.QueryError.*; import static org.basex.query.QueryText.*; import java.util.*; import java.util.Map.*; import org.basex.core.*; import org.basex.query.*; import org.basex.query.ann.*; import org.basex.query.expr.*; import org.basex.query.expr.gflwor.*; import org.basex.query.scope.*; import org.basex.query.util.*; import org.basex.query.util.list.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; /** * Inline function. * * @author BaseX Team 2005-21, BSD License * @author Leo Woerteler */ public final class Closure extends Single implements Scope, XQFunctionExpr { /** Function name, {@code null} if not specified. */ private final QNm name; /** Formal parameters. */ private final Var[] params; /** Value type, {@code null} if not specified. */ private SeqType declType; /** Annotations. */ private AnnList anns; /** Updating flag. */ private boolean updating; /** Map with requested function properties. */ private final EnumMap<Flag, Boolean> map = new EnumMap<>(Flag.class); /** Compilation flag. */ private boolean compiled; /** Local variables in the scope of this function. */ private final VarScope vs; /** Non-local variable bindings. */ private final Map<Var, Expr> global; /** * Constructor. * @param info input info * @param declType declared type (can be {@code null}) * @param params formal parameters * @param expr function body * @param anns annotations * @param global bindings for non-local variables * @param vs scope */ public Closure(final InputInfo info, final SeqType declType, final Var[] params, final Expr expr, final AnnList anns, final Map<Var, Expr> global, final VarScope vs) { this(info, null, declType, params, expr, anns, global, vs); } /** * Package-private constructor allowing a name. * @param info input info * @param name name of the function (can be {@code null}) * @param declType declared type (can be {@code null}) * @param params formal parameters * @param expr function expression * @param anns annotations * @param global bindings for non-local variables (can be {@code null}) * @param vs variable scope */ Closure(final InputInfo info, final QNm name, final SeqType declType, final Var[] params, final Expr expr, final AnnList anns, final Map<Var, Expr> global, final VarScope vs) { super(info, expr, SeqType.FUNCTION_O); this.name = name; this.params = params; this.declType = declType == null || declType.eq(SeqType.ITEM_ZM) ? null : declType; this.anns = anns; this.global = global == null ? Collections.emptyMap() : global; this.vs = vs; } @Override public int arity() { return params.length; } @Override public QNm funcName() { return name; } @Override public QNm paramName(final int pos) { return params[pos].name; } @Override public FuncType funcType() { return FuncType.get(anns, declType, params); } @Override public AnnList annotations() { return anns; } @Override public void comp(final CompileContext cc) throws QueryException { compile(cc); } @Override public Expr compile(final CompileContext cc) throws QueryException { if(compiled) return this; compiled = true; checkUpdating(); // compile closure for(final Entry<Var, Expr> entry : global.entrySet()) { final Expr bound = entry.getValue().compile(cc); entry.setValue(bound); entry.getKey().refineType(bound.seqType(), cc); } cc.pushScope(vs); try { expr = expr.compile(cc); } catch(final QueryException qe) { expr = cc.error(qe, expr); } finally { cc.removeScope(this); } // convert all function calls in tail position to proper tail calls expr.markTailCalls(cc); return optimize(cc); } @Override public Expr optimize(final CompileContext cc) throws QueryException { cc.pushScope(vs); try { // inline all values in the closure final Iterator<Entry<Var, Expr>> iter = global.entrySet().iterator(); Map<Var, Expr> add = null; final int limit = cc.qc.context.options.get(MainOptions.INLINELIMIT); while(iter.hasNext()) { final Entry<Var, Expr> entry = iter.next(); final Var var = entry.getKey(); final Expr ex = entry.getValue(); Expr inline = null; if(ex instanceof Value) { // values are always inlined into the closure inline = var.checkType((Value) ex, cc.qc, true); } else if(ex instanceof Closure) { // nested closures are inlined if their size and number of closed-over variables is small final Closure cl = (Closure) ex; if(!cl.has(Flag.NDT) && cl.global.size() < 5 && expr.count(var) != VarUsage.MORE_THAN_ONCE && cl.exprSize() < limit) { cc.info(OPTINLINE_X, entry); for(final Entry<Var, Expr> expr2 : cl.global.entrySet()) { final Var var2 = cc.copy(expr2.getKey(), null); if(add == null) add = new HashMap<>(); add.put(var2, expr2.getValue()); expr2.setValue(new VarRef(cl.info, var2).optimize(cc)); } inline = cl; } } if(inline != null) { expr = new InlineContext(var, inline, cc).inline(expr); iter.remove(); } } // add all newly added bindings if(add != null) global.putAll(add); } catch(final QueryException qe) { expr = cc.error(qe, expr); } finally { cc.removeScope(this); } final SeqType st = expr.seqType(); final SeqType dt = declType == null || st.instanceOf(declType) ? st : declType; exprType.assign(FuncType.get(anns, dt, params)); // only evaluate if: // - the closure is empty, so we don't lose variables // - the result size does not exceed a specific limit return global.isEmpty() && expr.size() <= CompileContext.MAX_PREEVAL ? cc.preEval(this) : this; } @Override public VarUsage count(final Var var) { VarUsage all = VarUsage.NEVER; for(final Expr ex : global.values()) { if((all = all.plus(ex.count(var))) == VarUsage.MORE_THAN_ONCE) break; } return all; } @Override public Expr inline(final InlineContext ic) throws QueryException { boolean changed = false; for(final Entry<Var, Expr> entry : global.entrySet()) { final Expr inlined = entry.getValue().inline(ic); if(inlined != null) { changed = true; entry.setValue(inlined); } } if(!changed) return null; // invalidate cached flags, optimize closure map.clear(); return optimize(ic.cc); } @Override public Expr copy(final CompileContext cc, final IntObjMap<Var> vm) { final VarScope innerScope = new VarScope(vs.sc); final HashMap<Var, Expr> outer = new HashMap<>(); global.forEach((key, value) -> outer.put(key, value.copy(cc, vm))); cc.pushScope(innerScope); try { final IntObjMap<Var> innerVars = new IntObjMap<>(); vs.copy(cc, innerVars); final HashMap<Var, Expr> nl = new HashMap<>(); outer.forEach((key, value) -> nl.put(innerVars.get(key.id), value)); final Var[] prms = params.clone(); final int pl = prms.length; for(int p = 0; p < pl; p++) prms[p] = innerVars.get(prms[p].id); final Expr ex = expr.copy(cc, innerVars); ex.markTailCalls(null); return copyType(new Closure(info, name, declType, prms, ex, anns, nl, cc.vs())); } finally { cc.removeScope(); } } @Override public Expr inline(final Expr[] exprs, final CompileContext cc) throws QueryException { if(!StaticFunc.inline(cc, anns, expr) || expr.has(Flag.CTX)) return null; cc.info(OPTINLINE_X, this); // create let bindings for all variables final LinkedList<Clause> clauses = new LinkedList<>(); final IntObjMap<Var> vm = new IntObjMap<>(); final int pl = params.length; for(int p = 0; p < pl; p++) { clauses.add(new Let(cc.copy(params[p], vm), exprs[p]).optimize(cc)); } for(final Entry<Var, Expr> entry : global.entrySet()) { clauses.add(new Let(cc.copy(entry.getKey(), vm), entry.getValue()).optimize(cc)); } // create the return clause final Expr body = expr.copy(cc, vm).optimize(cc); final Expr rtrn = declType == null ? body : new TypeCheck(vs.sc, info, body, declType, true).optimize(cc); return clauses.isEmpty() ? rtrn : new GFLWOR(info, clauses, rtrn).optimize(cc); } @Override public FuncItem item(final QueryContext qc, final InputInfo ii) throws QueryException { final Expr body; if(global.isEmpty()) { body = expr; } else { // collect closure final LinkedList<Clause> clauses = new LinkedList<>(); for(final Entry<Var, Expr> entry : global.entrySet()) { clauses.add(new Let(entry.getKey(), entry.getValue().value(qc))); } body = new GFLWOR(info, clauses, expr); } final SeqType argType = body.seqType(); final Expr checked; if(declType == null || argType.instanceOf(declType)) { // return type is already correct checked = body; } else if(body instanceof FuncItem && declType.type instanceof FuncType) { // function item coercion if(!declType.occ.check(1)) throw typeError(body, declType, null, info, true); checked = ((FuncItem) body).coerceTo((FuncType) declType.type, qc, info, true); } else if(body instanceof Value) { // we can type check immediately final Value value = (Value) body; checked = declType.instance(value) ? value : declType.promote(value, null, qc, vs.sc, info, false); } else { // check at each call: reject impossible arities if(argType.type.instanceOf(declType.type) && argType.occ.intersect(declType.occ) == null && !body.has(Flag.NDT)) throw typeError(body, declType, null, info, true); checked = new TypeCheck(vs.sc, info, body, declType, true); } final FuncType type = (FuncType) seqType().type; return new FuncItem(vs.sc, anns, name, params, type, checked, vs.stackSize(), info); } @Override public boolean has(final Flag... flags) { // closure does not perform any updates if(Flag.UPD.in(flags)) return false; // handle recursive calls: check which flags are already or currently assigned final ArrayList<Flag> flgs = new ArrayList<>(); for(final Flag flag : flags) { if(!map.containsKey(flag)) { map.put(flag, Boolean.FALSE); flgs.add(flag); } } // request missing properties for(final Flag flag : flgs) { boolean f = false; for(final Expr ex : global.values()) f = f || ex.has(flag); map.put(flag, f || expr.has(flag)); } // evaluate result for(final Flag flag : flags) { if(map.get(flag)) return true; } return false; } @Override public boolean inlineable(final InlineContext ic) { for(final Expr ex : global.values()) { if(!ex.inlineable(ic)) return false; } return true; } @Override public boolean visit(final ASTVisitor visitor) { for(final Entry<Var, Expr> entry : global.entrySet()) { if(!(entry.getValue().accept(visitor) && visitor.declared(entry.getKey()))) return false; } for(final Var var : params) { if(!visitor.declared(var)) return false; } return expr.accept(visitor); } @Override public void checkUp() throws QueryException { checkUpdating(); if(updating) { expr.checkUp(); if(declType != null && !declType.zero()) throw UUPFUNCTYPE.get(info); } } @Override public boolean vacuous() { return declType != null && declType.zero() && !has(Flag.UPD); } @Override public boolean vacuousBody() { return vacuous(); } @Override public boolean accept(final ASTVisitor visitor) { for(final Expr ex : global.values()) { if(!ex.accept(visitor)) return false; } return visitor.inlineFunc(this); } @Override public int exprSize() { int size = 1; for(final Expr ex : global.values()) size += ex.exprSize(); return size + expr.exprSize(); } @Override public boolean compiled() { return compiled; } /** * Returns an iterator over the non-local bindings of this closure. * @return the iterator */ public Iterator<Entry<Var, Expr>> globalBindings() { return global.entrySet().iterator(); } /** * Fixes the function type of this closure after it was generated for a function literal during * parsing. * @param ft function type */ void adoptSignature(final FuncType ft) { anns = ft.anns; final int pl = params.length; for(int p = 0; p < pl; p++) params[p].declType = ft.argTypes[p]; final SeqType dt = ft.declType; if(!dt.eq(SeqType.ITEM_ZM)) declType = dt; } /** * Assigns the updating flag. * @throws QueryException query exception */ private void checkUpdating() throws QueryException { // derive updating flag from function body updating = expr.has(Flag.UPD); final boolean updAnn = anns.contains(Annotation.UPDATING); if(updating != updAnn) { if(!updAnn) anns.add(new Ann(info, Annotation.UPDATING)); else if(!expr.vacuous()) throw UPEXPECTF.get(info); } } /** * Creates a function literal for a function that was not yet encountered while parsing. * @param name function name * @param arity function arity * @param qc query context * @param sc static context * @param ii input info * @return function literal * @throws QueryException query exception */ public static Closure undeclaredLiteral(final QNm name, final int arity, final QueryContext qc, final StaticContext sc, final InputInfo ii) throws QueryException { final VarScope vs = new VarScope(sc); final Var[] params = new Var[arity]; final Expr[] args = new Expr[arity]; for(int a = 0; a < arity; a++) { params[a] = vs.addNew(new QNm(ARG + (a + 1), ""), null, true, qc, ii); args[a] = new VarRef(ii, params[a]); } final TypedFunc tf = qc.funcs.undeclaredFuncCall(name, args, sc, ii); return new Closure(ii, name, null, params, tf.func, new AnnList(), null, vs); } @Override public boolean equals(final Object obj) { // [CG] could be enhanced return this == obj; } @Override public void plan(final QueryPlan plan) { final ArrayList<Object> list = new ArrayList<>(); global.forEach((key, value) -> { list.add(key); list.add(value); }); final FElem elem = plan.create(this); final int pl = params.length; for(int p = 0; p < pl; p++) plan.addAttribute(elem, ARG + p, params[p].name.string()); plan.add(elem, list.toArray()); } @Override public void plan(final QueryString qs) { final boolean inlined = !global.isEmpty(); if(inlined) { qs.token("((: inline-closure :)"); global.forEach((k, v) -> qs.token(LET).token(k).token(ASSIGN).token(v)); qs.token(RETURN); } qs.token(FUNCTION).params(params); qs.token(AS).token(declType != null ? declType : SeqType.ITEM_ZM).brace(expr); if(inlined) qs.token(')'); } }
[MOD] XQuery, closures: check for compiled function type
basex-core/src/main/java/org/basex/query/func/Closure.java
[MOD] XQuery, closures: check for compiled function type
<ide><path>asex-core/src/main/java/org/basex/query/func/Closure.java <ide> <ide> @Override <ide> public FuncType funcType() { <del> return FuncType.get(anns, declType, params); <add> final FuncType type = super.funcType(); <add> return type != null ? type : FuncType.get(anns, declType, params); <ide> } <ide> <ide> @Override
Java
bsd-3-clause
bc89b4a8d99480c149aef13a8701bacefe12cc74
0
CBIIT/caaers,CBIIT/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.grid; import gov.nih.nci.cabig.caaers.dao.SiteInvestigatorDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.query.OrganizationQuery; import gov.nih.nci.cabig.caaers.dao.query.StudyQuery; import gov.nih.nci.cabig.caaers.domain.AeTerminology; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.LocalOrganization; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier; import gov.nih.nci.cabig.caaers.domain.PersonRole; import gov.nih.nci.cabig.caaers.domain.RemoteOrganization; import gov.nih.nci.cabig.caaers.domain.SiteInvestigator; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyCoordinatingCenter; import gov.nih.nci.cabig.caaers.domain.StudyFundingSponsor; import gov.nih.nci.cabig.caaers.domain.StudyInvestigator; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.StudySite; import gov.nih.nci.cabig.caaers.domain.StudyTherapyType; import gov.nih.nci.cabig.caaers.domain.SystemAssignedIdentifier; import gov.nih.nci.cabig.caaers.domain.Term; import gov.nih.nci.cabig.caaers.domain.repository.OrganizationRepository; import gov.nih.nci.cabig.caaers.utils.ConfigProperty; import gov.nih.nci.cabig.caaers.utils.Lov; import gov.nih.nci.cabig.ccts.domain.HealthcareSiteType; import gov.nih.nci.cabig.ccts.domain.IdentifierType; import gov.nih.nci.cabig.ccts.domain.OrganizationAssignedIdentifierType; import gov.nih.nci.cabig.ccts.domain.StudyCoordinatingCenterType; import gov.nih.nci.cabig.ccts.domain.StudyFundingSponsorType; import gov.nih.nci.cabig.ccts.domain.StudyInvestigatorType; import gov.nih.nci.cabig.ccts.domain.StudyOrganizationType; import gov.nih.nci.cabig.ccts.domain.StudySiteType; import gov.nih.nci.cabig.ccts.domain.SystemAssignedIdentifierType; import gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository; import gov.nih.nci.ccts.grid.studyconsumer.common.StudyConsumerI; import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.InvalidStudyException; import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.StudyCreationException; import java.rmi.RemoteException; import java.security.Principal; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.namespace.QName; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse; import org.oasis.wsrf.properties.GetMultipleResourceProperties_Element; import org.oasis.wsrf.properties.GetResourcePropertyResponse; import org.oasis.wsrf.properties.QueryResourcePropertiesResponse; import org.oasis.wsrf.properties.QueryResourceProperties_Element; import org.springframework.beans.factory.annotation.Required; import org.springframework.web.context.request.WebRequest; public class CaaersStudyConsumer implements StudyConsumerI { private static Logger logger = Logger.getLogger(CaaersStudyConsumer.class); private OrganizationRepository organizationRepository; private SiteInvestigatorDao siteInvestigatorDao; private StudyDao studyDao; private ConfigProperty configurationProperty; private AuditHistoryRepository auditHistoryRepository; private String studyConsumerGridServiceUrl; private Integer rollbackInterval; public void commit(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException { logger.info("Begining of studyConsumer : commit"); /* * if(studyDto == null) { InvalidStudyException e = new InvalidStudyException(); * e.setFaultReason("Null input"); e.setFaultString("Null input"); throw e; } * * String ccIdentifier = findCoordinatingCenterIdentifier(studyDto); * * try{ studyDao.commitInprogressStudy(ccIdentifier); * * * }catch(Exception exp){ log.error("Exception while trying to commit the study", exp); * InvalidStudyException e = new InvalidStudyException(); e.setFaultReason("Exception while * comitting study," + exp.getMessage()); e.setFaultString("Exception while comitting * study," + exp.getMessage()); throw e; } */ logger.info("End of studyConsumer : commit"); } /** * This method will remove a study from caAERS. A rollback can only be successful if * <li> the request is received within a minute of study creation </li> * <li> the study was created via the studyConsumerGrid message</li> * * Assumption:- * The study to be deleted is identified using the Coordinating Center identifier. */ public void rollback(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException { if(logger.isDebugEnabled())logger.debug("Begining of studyConsumer : rollback"); if (studyDto == null) { logger.error("Invalid study input message, the studydto is null"); InvalidStudyException invalidStudyException = getInvalidStudyException("Null input"); throw invalidStudyException; } String ccIdentifier = findCoordinatingCenterIdentifier(studyDto); gov.nih.nci.cabig.caaers.domain.Study study = fetchStudy(ccIdentifier,OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE); // check if study was created by the grid service or not if (study == null) { logger.error("Unable to find study having Identifier [type: " + OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE + ", value :" + ccIdentifier + "]" ); String message = "Null input"; throw getInvalidStudyException(message); } boolean checkIfEntityWasCreatedByGridService = auditHistoryRepository.checkIfEntityWasCreatedByUrl(study.getClass(), study.getId(), studyConsumerGridServiceUrl); if (!checkIfEntityWasCreatedByGridService) { logger.warn("Study was not created by the grid service url:" + studyConsumerGridServiceUrl + " so can not rollback this study: " + study.getId()); return; } if(logger.isDebugEnabled()) logger.debug("Study (id:" + study.getId() + ") was created by the grid service url:" + studyConsumerGridServiceUrl); // check if this study was created one minute before or not Calendar calendar = Calendar.getInstance(); boolean recentlyCreated = auditHistoryRepository.checkIfEntityWasCreatedMinutesBeforeSpecificDate(study.getClass(), study.getId(), calendar, rollbackInterval); try { if (recentlyCreated) { if(logger.isInfoEnabled()) logger.info("Study was created one minute before the current time:" + calendar.getTime().toString() + " so deleting this study:" + study.getId()); studyDao.delete(study); } else { logger.warn("Study was not created one minute before the current time:" + calendar.getTime().toString() + " so can not rollback this study:" + study.getId()); } } catch (Exception expception) { String message = "Exception while comitting study," + expception.getMessage(); throw getInvalidStudyException(message); } if(logger.isDebugEnabled()) logger.debug("End of studyConsumer : rollback"); } private AeTerminology createCtcV3Terminology(Study study) { AeTerminology t = new AeTerminology(); Ctc v3 = new Ctc(); v3.setId(3); v3.setName(4 + ""); t.setTerm(Term.CTC); t.setStudy(study); t.setCtcVersion(v3); return t; } /** * This will create a study in the DB. <p/> Assumptions:- Study is identified by Coordinating * Center identifier There will only be one Organization assigned identifier in the input, and it * is the CoordinatingCenterIdentifier */ public void createStudy(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException, StudyCreationException { try { logger.info("Begining of studyConsumer : createStudy"); if (studyDto == null) throw getInvalidStudyException("null input"); gov.nih.nci.cabig.caaers.domain.Study study = null; String ccIdentifier = findCoordinatingCenterIdentifier(studyDto); study = fetchStudy(ccIdentifier, OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE); if (study != null) { logger.error("Already a study with the same Coordinating Center Identifier (" + ccIdentifier + ") exists.Returning without processing the request."); return; } String coppaIdentifier = findCoppaIdentifier(studyDto); if (coppaIdentifier != null) { study = new gov.nih.nci.cabig.caaers.domain.RemoteStudy(); } else { study = new gov.nih.nci.cabig.caaers.domain.LocalStudy(); } study.setGridId(studyDto.getGridId()); populateStudyDetails(studyDto, study, coppaIdentifier); studyDao.save(study); logger.info("Created the study :" + study.getId()); logger.info("End of studyConsumer : createStudy"); } catch (InvalidStudyException e) { throw e; } catch (StudyCreationException e) { throw e; } catch (Exception e) { logger.error("Error while creating study", e); throw new RemoteException("Unable to create study", e); } } /** * This method will retrieve from the Study DTO the identifier value of a specific type. * @param studyDto * @param identifierType * @return */ private String findOrganizationIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto , String identifierType){ for (IdentifierType idType : studyDto.getIdentifier()) { if(idType instanceof SystemAssignedIdentifierType) continue; if (StringUtils.equals(idType.getType(),identifierType)) return idType.getValue(); } return null; } /** * This method will retrieve from the Study DTO the System identifier value of a specific type. * @param studyDto * @param identifierType * @return */ private String findSystemIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto , String identifierType){ for (IdentifierType idType : studyDto.getIdentifier()) { if(idType instanceof OrganizationAssignedIdentifierType) continue; if (StringUtils.equals(idType.getType(),identifierType)) return idType.getValue(); } return null; } /** * This method will return the identifier specified by Coordinating center to this study. * * @param studyDto * @return * @throws InvalidStudyException */ String findCoordinatingCenterIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws InvalidStudyException { String ccIdentifier = findOrganizationIdentifier(studyDto, OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE); if (ccIdentifier == null) { logger.error("Could not find Coordinating center identifier in the Study message"); InvalidStudyException exp = getInvalidStudyException("In Study/Identifiers, Coordinating Center Identifier is not available"); throw exp; } return ccIdentifier; } /** * This method will return the identifier specified by COPPA. */ String findCoppaIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto) { return findSystemIdentifier(studyDto, "COPPA Identifier"); } /** * This method will find out the Sponsor Identifier * @param studyDto * @return */ String findFundingSponsorIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto){ return findOrganizationIdentifier(studyDto, OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE); } void populateStudyDetails(gov.nih.nci.cabig.ccts.domain.Study studyDto, gov.nih.nci.cabig.caaers.domain.Study study, String coppaIdentifier) throws StudyCreationException, InvalidStudyException { System.out.println("Creating study.."); study.setShortTitle(studyDto.getShortTitleText()); study.setLongTitle(studyDto.getLongTitleText()); study.setPrecis(studyDto.getPrecisText()); study.setDescription(studyDto.getDescriptionText()); study.setStatus(gov.nih.nci.cabig.caaers.domain.Study.STATUS_ACTIVE); study.setAdeersReporting(Boolean.FALSE); study.setPhaseCode(studyDto.getPhaseCode()); study.setMultiInstitutionIndicator(BooleanUtils.toBoolean(studyDto .getMultiInstitutionIndicator())); study.addStudyTherapy(StudyTherapyType.DRUG_ADMINISTRATION); study.setBlindedIndicator(BooleanUtils.toBoolean(studyDto.getBlindedIndicator())); if (coppaIdentifier != null ) { study.setExternalId(coppaIdentifier); } //fixed by srini , bug Id CAAERS-1038 AeTerminology aet = createCtcV3Terminology(study); study.setAeTerminology(aet); // populate study coordinating center and study funding sponsor StudyOrganizationType[] studyOrgTypes = studyDto.getStudyOrganization(); populateStudyOrganizations(study, studyOrgTypes); // populate study identifiers IdentifierType[] identifierTypes = studyDto.getIdentifier(); populateIdentifiers(study, identifierTypes); } /** * Populates study identifiers * * @param study * @param identifierTypes * @throws StudyCreationException */ void populateIdentifiers(gov.nih.nci.cabig.caaers.domain.Study study, IdentifierType[] identifierTypes) throws StudyCreationException { if (ArrayUtils.isEmpty(identifierTypes)) { logger.error("No identifiers are associated to this study"); String message = "No identifiers are assigned to this study (grid Id : "+ study.getGridId() + ")"; throw getStudyCreationException(message); } //figure out the list of known identifiers List<Lov> identifierLovs = configurationProperty.getMap().get("identifiersType"); List<String> knownIdentifierTypes = new ArrayList<String>(); for (Lov lov : identifierLovs) { knownIdentifierTypes.add(lov.getCode()); } List<SystemAssignedIdentifier> sysIdentifiers = new ArrayList<SystemAssignedIdentifier>(); List<OrganizationAssignedIdentifier> orgIdentifiers = new ArrayList<OrganizationAssignedIdentifier>(); OrganizationAssignedIdentifier ccIdentifier = null; OrganizationAssignedIdentifier sponsorIdentifier = null; for (IdentifierType identifierType : identifierTypes) { if (!knownIdentifierTypes.contains(identifierType.getType())) { logger.warn("The identifier type '" + identifierType.getType()+ "' is unknown to caAERS. So ignoring the identifier(" + identifierType.getValue() + ")"); continue; } if (identifierType instanceof SystemAssignedIdentifierType) { SystemAssignedIdentifierType sysIdType = (SystemAssignedIdentifierType) identifierType; SystemAssignedIdentifier id = new SystemAssignedIdentifier(); id.setGridId(identifierType.getGridId()); id.setPrimaryIndicator(identifierType.getPrimaryIndicator()); id.setType(sysIdType.getType()); id.setValue(sysIdType.getValue()); id.setSystemName(sysIdType.getSystemName()); sysIdentifiers.add(id); } else if (identifierType instanceof OrganizationAssignedIdentifierType) { OrganizationAssignedIdentifierType orgIdType = (OrganizationAssignedIdentifierType) identifierType; OrganizationAssignedIdentifier id = new OrganizationAssignedIdentifier(); id.setGridId(orgIdType.getGridId()); id.setPrimaryIndicator(orgIdType.getPrimaryIndicator()); id.setType(orgIdType.getType()); id.setValue(orgIdType.getValue()); id.setOrganization(fetchOrganization(orgIdType.getHealthcareSite())); if(StringUtils.equals(id.getType(),OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE)){ ccIdentifier = id; }else if(StringUtils.equals(id.getType(),OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE)){ sponsorIdentifier = id; }else{ orgIdentifiers.add(id); } } } //if the sponsor identifier is not supplied, use coordinating center instead. if(sponsorIdentifier == null){ sponsorIdentifier = new OrganizationAssignedIdentifier(); sponsorIdentifier.setType(OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE); sponsorIdentifier.setValue(ccIdentifier.getValue()); sponsorIdentifier.setOrganization(study.getPrimaryFundingSponsorOrganization()); } study.addIdentifier(sponsorIdentifier); study.addIdentifier(ccIdentifier); for (OrganizationAssignedIdentifier id : orgIdentifiers) { study.addIdentifier(id); } for (SystemAssignedIdentifier id : sysIdentifiers) { study.addIdentifier(id); } } private StudyCreationException getStudyCreationException(String message) { StudyCreationException exp = new StudyCreationException(); exp.setFaultString(message); exp.setFaultReason(message); logger.error(message); return exp; } /** * Populates study organization and returns it. * * @param study * @param studyOrgTypes * @throws InvalidStudyException */ void populateStudyOrganizations(gov.nih.nci.cabig.caaers.domain.Study study, StudyOrganizationType[] studyOrgTypes) throws StudyCreationException, InvalidStudyException { if (ArrayUtils.isEmpty(studyOrgTypes)) { logger.error("No organization is associated to this study (gridId :" + study.getGridId() + ")"); StudyCreationException exp = new StudyCreationException(); exp.setFaultString("No organization is associated to this study"); exp.setFaultReason("No organization is associated to this study (gridId :" + study.getGridId() + ")"); throw exp; } List<StudyOrganization> studyOrgList = new ArrayList<StudyOrganization>(); boolean isPrimarySponsor = true; for (StudyOrganizationType studyOrgType : studyOrgTypes) { StudyOrganization studyOrganization = null; if (studyOrgType instanceof StudyFundingSponsorType) { StudyFundingSponsor fundingSponsor = new StudyFundingSponsor(); fundingSponsor.setPrimary(isPrimarySponsor); isPrimarySponsor = false; studyOrganization = fundingSponsor; } else if (studyOrgType instanceof StudyCoordinatingCenterType) { studyOrganization = new StudyCoordinatingCenter(); } else if (studyOrgType instanceof StudySiteType) { studyOrganization = new StudySite(); } else { logger.error("Unknown StudyOrganizationType in grid Study " + studyOrgType.toString()); throw getInvalidStudyException("Unknown StudyOrganizationType in grid Study "); } studyOrganization.setOrganization(fetchOrganization(studyOrgType.getHealthcareSite(0))); studyOrganization.setStudy(study); studyOrganization.setGridId(studyOrgType.getGridId()); // populate investigators populateInvestigators(studyOrganization, studyOrgType.getStudyInvestigator()); studyOrgList.add(studyOrganization); }// ~for study.setStudyOrganizations(studyOrgList); } /** * Will populate the investigator * * @param studyOrganization * @param invTypes */ void populateInvestigators(StudyOrganization studyOrganization, StudyInvestigatorType[] invTypes) throws StudyCreationException { if (ArrayUtils.isEmpty(invTypes)) { logger.error("No investigators are available in the input message"); return; } for (StudyInvestigatorType invType : invTypes) { String invNCICode = invType.getHealthcareSiteInvestigator().getInvestigator(0) .getNciIdentifier(); SiteInvestigator siteInvestigator = null; if (StringUtils.isEmpty(invNCICode)) { logger.error("Investigator details are missing!"); StudyCreationException exp = new StudyCreationException(); exp .setFaultReason("Missing investigator details in input : InvestigatorType.healthcareSiteInvesitagor.investigatorType[0].nciIdentifier"); exp.setFaultString("Invalid input, missing investigator information"); throw exp; } // find the study Investigator List<SiteInvestigator> siteInvestigators = siteInvestigatorDao .getOrganizationInvestigators(studyOrganization.getOrganization()); if (siteInvestigators != null) { // figure out the correct investigator for (SiteInvestigator si : siteInvestigators) { if (StringUtils.equals(si.getInvestigator().getNciIdentifier(), invNCICode)) { siteInvestigator = si; break; } } } // check if we were able to fetch siteInvestigator if (siteInvestigator == null) { logger .error("Unable to associate investigators.No investigators are associated to organization :" + studyOrganization.getOrganization().getName() + " nciCode :" + studyOrganization.getOrganization() .getNciInstituteCode()); StudyCreationException exp = new StudyCreationException(); exp .setFaultReason("Unable to associate the given investigaor {investigatorNCI code :" + invNCICode + "} to the site {" + studyOrganization.getOrganization().getName() + ", nciCode :" + studyOrganization.getOrganization() .getNciInstituteCode() + "}. The specified investigator should be associated to the organization."); exp .setFaultReason("Missing SiteInvestigator (investigator NCI Code :" + invNCICode + ")details for the Organization {" + studyOrganization.getOrganization().getName() + ", nciCode : " + studyOrganization.getOrganization() .getNciInstituteCode() + "}. The specified investigator should be associated to the organization."); throw exp; } StudyInvestigator studyInvestigator = new StudyInvestigator(); studyInvestigator.setStudyOrganization(studyOrganization); String roleCode = null; PersonRole[] caaersRoles = new PersonRole[]{PersonRole.SITE_INVESTIGATOR, PersonRole.SITE_PRINCIPAL_INVESTIGATOR, PersonRole.PRINCIPAL_INVESTIGATOR}; if (invType.getRoleCode() == null) { StudyCreationException exp = new StudyCreationException(); exp.setFaultReason("Investigator role is NULL in Study message"); throw exp; } for (PersonRole caaersRole:caaersRoles) { if (caaersRole.getDisplayName().equals(invType.getRoleCode())) { roleCode = caaersRole.getRoleCode(); break; } } if (roleCode == null) { StudyCreationException exp = new StudyCreationException(); exp.setFaultReason("Supplied Investigator role "+ invType.getRoleCode() + " does not map with roles in caAERS"); throw exp; } studyInvestigator.setRoleCode(roleCode); studyInvestigator.setStartDate(siteInvestigator.getStartDate()); studyInvestigator.setSiteInvestigator(siteInvestigator); studyOrganization.addStudyInvestigators(studyInvestigator); } } /** * Fetches the organization from the DB. If one does not exist an appropriate Organization is created and saved. * * @param HealthcareSiteType * @return Organization */ protected Organization fetchOrganization(HealthcareSiteType healthCareSiteType) { if(healthCareSiteType == null){ return null; } //Check if an organization exists in caAERS for the given NCI CODE. OrganizationQuery orgQuery = new OrganizationQuery(); if (StringUtils.isNotEmpty(healthCareSiteType.getNciInstituteCode())) { orgQuery.filterByNciCodeExactMatch(healthCareSiteType.getNciInstituteCode()); } List<Organization> orgList = organizationRepository.searchOrganization(orgQuery); Organization organization = null; //If there is no Organization in caAERS with given NCI CODE then create an Organization in caAERS. if (orgList == null || orgList.isEmpty()) { //if externalId is provided it means that Organization is Remote. (Fetched from COPPA) if (StringUtils.isNotEmpty(healthCareSiteType.getGridId())) { organization = new RemoteOrganization(); populateOrganization(healthCareSiteType,organization); }else{ organization = new LocalOrganization(); populateOrganization(healthCareSiteType,organization); } organizationRepository.create(organization); return organization; } return orgList.get(0); } /** * This method populates an Organization entity given a HealthcareSiteType * @param HealthcareSiteType * @param Organization */ protected void populateOrganization(HealthcareSiteType healthCareSiteType, Organization organization){ organization.setNciInstituteCode(healthCareSiteType.getNciInstituteCode()); organization.setName(healthCareSiteType.getName()); organization.setDescriptionText(healthCareSiteType.getDescriptionText()); organization.setExternalId(healthCareSiteType.getGridId()); if(healthCareSiteType.getAddress() != null){ organization.setCity(healthCareSiteType.getAddress().getCity()); organization.setState(healthCareSiteType.getAddress().getStateCode()); organization.setCountry(healthCareSiteType.getAddress().getCountryCode()); } } gov.nih.nci.cabig.caaers.domain.Study fetchStudy(String ccIdentifier, String identifierType) { StudyQuery studyQuery = new StudyQuery(); studyQuery.filterByIdentifierValueExactMatch(ccIdentifier); studyQuery.filterByIdentifierType(identifierType); List<gov.nih.nci.cabig.caaers.domain.Study> studies = studyDao.find(studyQuery); if (studies == null || studies.isEmpty()) return null; return studies.get(0); } private InvalidStudyException getInvalidStudyException(String message) { logger.error(message); InvalidStudyException invalidStudyException = new InvalidStudyException(); invalidStudyException.setFaultReason(message); invalidStudyException.setFaultString(message); return invalidStudyException; } // /CONFIGURATION @Required public SiteInvestigatorDao getSiteInvestigatorDao() { return siteInvestigatorDao; } @Required public void setSiteInvestigatorDao(SiteInvestigatorDao siteInvestigatorDao) { this.siteInvestigatorDao = siteInvestigatorDao; } @Required public StudyDao getStudyDao() { return studyDao; } @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } @Required public void setConfigurationProperty(ConfigProperty configurationProperty) { this.configurationProperty = configurationProperty; } public ConfigProperty getConfigurationProperty() { return configurationProperty; } @Required public void setAuditHistoryRepository(AuditHistoryRepository auditHistoryRepository) { this.auditHistoryRepository = auditHistoryRepository; } @Required public void setStudyConsumerGridServiceUrl(String studyConsumerGridServiceUrl) { this.studyConsumerGridServiceUrl = studyConsumerGridServiceUrl; } @Required public void setRollbackInterval(Integer rollbackInterval) { this.rollbackInterval = rollbackInterval; } public GetMultipleResourcePropertiesResponse getMultipleResourceProperties(GetMultipleResourceProperties_Element params) throws RemoteException { //Auto-generated method stub return null; } public GetResourcePropertyResponse getResourceProperty(QName params) throws RemoteException { //Auto-generated method stub return null; } public QueryResourcePropertiesResponse queryResourceProperties(QueryResourceProperties_Element params) throws RemoteException { //Auto-generated method stub return null; } @Required public void setOrganizationRepository( OrganizationRepository organizationRepository) { this.organizationRepository = organizationRepository; } @SuppressWarnings("unused") private static class StubWebRequest implements WebRequest { public String getParameter(final String paramName) { return null; } public String[] getParameterValues(final String paramName) { return null; } @SuppressWarnings("unchecked") public Map getParameterMap() { return Collections.emptyMap(); } public Locale getLocale() { return null; } public String getContextPath() { return null; } public String getRemoteUser() { return null; } public Principal getUserPrincipal() { return null; } public boolean isUserInRole(String role) { return false; } public boolean isSecure() { return false; } public Object getAttribute(final String name, final int scope) { return null; } public void setAttribute(final String name, final Object value, final int scope) { } public void removeAttribute(final String name, final int scope) { } public void registerDestructionCallback(final String name, final Runnable callback, final int scope) { } public String getSessionId() { return null; } public Object getSessionMutex() { return null; } } }
caAERS/software/grid/study-consumer/src/main/java/gov/nih/nci/cabig/caaers/grid/CaaersStudyConsumer.java
package gov.nih.nci.cabig.caaers.grid; import gov.nih.nci.cabig.caaers.dao.SiteInvestigatorDao; import gov.nih.nci.cabig.caaers.dao.StudyDao; import gov.nih.nci.cabig.caaers.dao.query.OrganizationQuery; import gov.nih.nci.cabig.caaers.dao.query.StudyQuery; import gov.nih.nci.cabig.caaers.domain.AeTerminology; import gov.nih.nci.cabig.caaers.domain.Ctc; import gov.nih.nci.cabig.caaers.domain.LocalOrganization; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier; import gov.nih.nci.cabig.caaers.domain.PersonRole; import gov.nih.nci.cabig.caaers.domain.RemoteOrganization; import gov.nih.nci.cabig.caaers.domain.SiteInvestigator; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudyCoordinatingCenter; import gov.nih.nci.cabig.caaers.domain.StudyFundingSponsor; import gov.nih.nci.cabig.caaers.domain.StudyInvestigator; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.StudySite; import gov.nih.nci.cabig.caaers.domain.StudyTherapyType; import gov.nih.nci.cabig.caaers.domain.SystemAssignedIdentifier; import gov.nih.nci.cabig.caaers.domain.Term; import gov.nih.nci.cabig.caaers.domain.repository.OrganizationRepository; import gov.nih.nci.cabig.caaers.utils.ConfigProperty; import gov.nih.nci.cabig.caaers.utils.Lov; import gov.nih.nci.cabig.ccts.domain.HealthcareSiteType; import gov.nih.nci.cabig.ccts.domain.IdentifierType; import gov.nih.nci.cabig.ccts.domain.OrganizationAssignedIdentifierType; import gov.nih.nci.cabig.ccts.domain.StudyCoordinatingCenterType; import gov.nih.nci.cabig.ccts.domain.StudyFundingSponsorType; import gov.nih.nci.cabig.ccts.domain.StudyInvestigatorType; import gov.nih.nci.cabig.ccts.domain.StudyOrganizationType; import gov.nih.nci.cabig.ccts.domain.StudySiteType; import gov.nih.nci.cabig.ccts.domain.SystemAssignedIdentifierType; import gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository; import gov.nih.nci.ccts.grid.studyconsumer.common.StudyConsumerI; import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.InvalidStudyException; import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.StudyCreationException; import java.rmi.RemoteException; import java.security.Principal; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.namespace.QName; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse; import org.oasis.wsrf.properties.GetMultipleResourceProperties_Element; import org.oasis.wsrf.properties.GetResourcePropertyResponse; import org.oasis.wsrf.properties.QueryResourcePropertiesResponse; import org.oasis.wsrf.properties.QueryResourceProperties_Element; import org.springframework.beans.factory.annotation.Required; import org.springframework.web.context.request.WebRequest; public class CaaersStudyConsumer implements StudyConsumerI { private static Logger logger = Logger.getLogger(CaaersStudyConsumer.class); private OrganizationRepository organizationRepository; private SiteInvestigatorDao siteInvestigatorDao; private StudyDao studyDao; private ConfigProperty configurationProperty; private AuditHistoryRepository auditHistoryRepository; private String studyConsumerGridServiceUrl; private Integer rollbackInterval; public void commit(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException { logger.info("Begining of studyConsumer : commit"); /* * if(studyDto == null) { InvalidStudyException e = new InvalidStudyException(); * e.setFaultReason("Null input"); e.setFaultString("Null input"); throw e; } * * String ccIdentifier = findCoordinatingCenterIdentifier(studyDto); * * try{ studyDao.commitInprogressStudy(ccIdentifier); * * * }catch(Exception exp){ log.error("Exception while trying to commit the study", exp); * InvalidStudyException e = new InvalidStudyException(); e.setFaultReason("Exception while * comitting study," + exp.getMessage()); e.setFaultString("Exception while comitting * study," + exp.getMessage()); throw e; } */ logger.info("End of studyConsumer : commit"); } /** * This method will remove a study from caAERS. A rollback can only be successful if * <li> the request is received within a minute of study creation </li> * <li> the study was created via the studyConsumerGrid message</li> * * Assumption:- * The study to be deleted is identified using the Coordinating Center identifier. */ public void rollback(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException { if(logger.isDebugEnabled())logger.debug("Begining of studyConsumer : rollback"); if (studyDto == null) { logger.error("Invalid study input message, the studydto is null"); InvalidStudyException invalidStudyException = getInvalidStudyException("Null input"); throw invalidStudyException; } String ccIdentifier = findCoordinatingCenterIdentifier(studyDto); gov.nih.nci.cabig.caaers.domain.Study study = fetchStudy(ccIdentifier,OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE); // check if study was created by the grid service or not if (study == null) { logger.error("Unable to find study having Identifier [type: " + OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE + ", value :" + ccIdentifier + "]" ); String message = "Null input"; throw getInvalidStudyException(message); } boolean checkIfEntityWasCreatedByGridService = auditHistoryRepository.checkIfEntityWasCreatedByUrl(study.getClass(), study.getId(), studyConsumerGridServiceUrl); if (!checkIfEntityWasCreatedByGridService) { logger.warn("Study was not created by the grid service url:" + studyConsumerGridServiceUrl + " so can not rollback this study: " + study.getId()); return; } if(logger.isDebugEnabled()) logger.debug("Study (id:" + study.getId() + ") was created by the grid service url:" + studyConsumerGridServiceUrl); // check if this study was created one minute before or not Calendar calendar = Calendar.getInstance(); boolean recentlyCreated = auditHistoryRepository.checkIfEntityWasCreatedMinutesBeforeSpecificDate(study.getClass(), study.getId(), calendar, rollbackInterval); try { if (recentlyCreated) { if(logger.isInfoEnabled()) logger.info("Study was created one minute before the current time:" + calendar.getTime().toString() + " so deleting this study:" + study.getId()); studyDao.delete(study); } else { logger.warn("Study was not created one minute before the current time:" + calendar.getTime().toString() + " so can not rollback this study:" + study.getId()); } } catch (Exception expception) { String message = "Exception while comitting study," + expception.getMessage(); throw getInvalidStudyException(message); } if(logger.isDebugEnabled()) logger.debug("End of studyConsumer : rollback"); } private AeTerminology createCtcV3Terminology(Study study) { AeTerminology t = new AeTerminology(); Ctc v3 = new Ctc(); v3.setId(3); v3.setName(4 + ""); t.setTerm(Term.CTC); t.setStudy(study); t.setCtcVersion(v3); return t; } /** * This will create a study in the DB. <p/> Assumptions:- Study is identified by Coordinating * Center identifier There will only be one Organization assigned identifier in the input, and it * is the CoordinatingCenterIdentifier */ public void createStudy(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException, StudyCreationException { try { logger.info("Begining of studyConsumer : createStudy"); if (studyDto == null) throw getInvalidStudyException("null input"); gov.nih.nci.cabig.caaers.domain.Study study = null; String ccIdentifier = findCoordinatingCenterIdentifier(studyDto); study = fetchStudy(ccIdentifier, OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE); if (study != null) { logger.error("Already a study with the same Coordinating Center Identifier (" + ccIdentifier + ") exists.Returning without processing the request."); return; } String coppaIdentifier = findCoppaIdentifier(studyDto); if (coppaIdentifier != null) { study = new gov.nih.nci.cabig.caaers.domain.RemoteStudy(); } else { study = new gov.nih.nci.cabig.caaers.domain.LocalStudy(); } study.setGridId(studyDto.getGridId()); populateStudyDetails(studyDto, study, coppaIdentifier); studyDao.save(study); logger.info("Created the study :" + study.getId()); logger.info("End of studyConsumer : createStudy"); } catch (InvalidStudyException e) { throw e; } catch (StudyCreationException e) { throw e; } catch (Exception e) { logger.error("Error while creating study", e); throw new RemoteException("Unable to create study", e); } } /** * This method will retrieve from the Study DTO the identifier value of a specific type. * @param studyDto * @param identifierType * @return */ private String findOrganizationIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto , String identifierType){ for (IdentifierType idType : studyDto.getIdentifier()) { if(idType instanceof SystemAssignedIdentifierType) continue; if (StringUtils.equals(idType.getType(),identifierType)) return idType.getValue(); } return null; } /** * This method will retrieve from the Study DTO the System identifier value of a specific type. * @param studyDto * @param identifierType * @return */ private String findSystemIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto , String identifierType){ for (IdentifierType idType : studyDto.getIdentifier()) { if(idType instanceof OrganizationAssignedIdentifierType) continue; if (StringUtils.equals(idType.getType(),identifierType)) return idType.getValue(); } return null; } /** * This method will return the identifier specified by Coordinating center to this study. * * @param studyDto * @return * @throws InvalidStudyException */ String findCoordinatingCenterIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto) throws InvalidStudyException { String ccIdentifier = findOrganizationIdentifier(studyDto, OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE); if (ccIdentifier == null) { logger.error("Could not find Coordinating center identifier in the Study message"); InvalidStudyException exp = getInvalidStudyException("In Study/Identifiers, Coordinating Center Identifier is not available"); throw exp; } return ccIdentifier; } /** * This method will return the identifier specified by COPPA. */ String findCoppaIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto) { return findSystemIdentifier(studyDto, "COPPA Identifier"); } /** * This method will find out the Sponsor Identifier * @param studyDto * @return */ String findFundingSponsorIdentifier(gov.nih.nci.cabig.ccts.domain.Study studyDto){ return findOrganizationIdentifier(studyDto, OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE); } void populateStudyDetails(gov.nih.nci.cabig.ccts.domain.Study studyDto, gov.nih.nci.cabig.caaers.domain.Study study, String coppaIdentifier) throws StudyCreationException, InvalidStudyException { System.out.println("Creating study.."); study.setShortTitle(studyDto.getShortTitleText()); study.setLongTitle(studyDto.getLongTitleText()); study.setPrecis(studyDto.getPrecisText()); study.setDescription(studyDto.getDescriptionText()); study.setStatus(gov.nih.nci.cabig.caaers.domain.Study.STATUS_ACTIVE); study.setAdeersReporting(Boolean.FALSE); study.setPhaseCode(studyDto.getPhaseCode()); study.setMultiInstitutionIndicator(BooleanUtils.toBoolean(studyDto .getMultiInstitutionIndicator())); study.addStudyTherapy(StudyTherapyType.DRUG_ADMINISTRATION); study.setBlindedIndicator(BooleanUtils.toBoolean(studyDto.getBlindedIndicator())); if (coppaIdentifier != null ) { study.setExternalId(coppaIdentifier); } //fixed by srini , bug Id CAAERS-1038 AeTerminology aet = createCtcV3Terminology(study); study.setAeTerminology(aet); // populate study coordinating center and study funding sponsor StudyOrganizationType[] studyOrgTypes = studyDto.getStudyOrganization(); populateStudyOrganizations(study, studyOrgTypes); // populate study identifiers IdentifierType[] identifierTypes = studyDto.getIdentifier(); populateIdentifiers(study, identifierTypes); } /** * Populates study identifiers * * @param study * @param identifierTypes * @throws StudyCreationException */ void populateIdentifiers(gov.nih.nci.cabig.caaers.domain.Study study, IdentifierType[] identifierTypes) throws StudyCreationException { if (ArrayUtils.isEmpty(identifierTypes)) { logger.error("No identifiers are associated to this study"); String message = "No identifiers are assigned to this study (grid Id : "+ study.getGridId() + ")"; throw getStudyCreationException(message); } //figure out the list of known identifiers List<Lov> identifierLovs = configurationProperty.getMap().get("identifiersType"); List<String> knownIdentifierTypes = new ArrayList<String>(); for (Lov lov : identifierLovs) { knownIdentifierTypes.add(lov.getCode()); } List<SystemAssignedIdentifier> sysIdentifiers = new ArrayList<SystemAssignedIdentifier>(); List<OrganizationAssignedIdentifier> orgIdentifiers = new ArrayList<OrganizationAssignedIdentifier>(); OrganizationAssignedIdentifier ccIdentifier = null; OrganizationAssignedIdentifier sponsorIdentifier = null; for (IdentifierType identifierType : identifierTypes) { if (!knownIdentifierTypes.contains(identifierType.getType())) { logger.warn("The identifier type '" + identifierType.getType()+ "' is unknown to caAERS. So ignoring the identifier(" + identifierType.getValue() + ")"); continue; } if (identifierType instanceof SystemAssignedIdentifierType) { SystemAssignedIdentifierType sysIdType = (SystemAssignedIdentifierType) identifierType; SystemAssignedIdentifier id = new SystemAssignedIdentifier(); id.setGridId(identifierType.getGridId()); id.setPrimaryIndicator(identifierType.getPrimaryIndicator()); id.setType(sysIdType.getType()); id.setValue(sysIdType.getValue()); id.setSystemName(sysIdType.getSystemName()); sysIdentifiers.add(id); } else if (identifierType instanceof OrganizationAssignedIdentifierType) { OrganizationAssignedIdentifierType orgIdType = (OrganizationAssignedIdentifierType) identifierType; OrganizationAssignedIdentifier id = new OrganizationAssignedIdentifier(); id.setGridId(orgIdType.getGridId()); id.setPrimaryIndicator(orgIdType.getPrimaryIndicator()); id.setType(orgIdType.getType()); id.setValue(orgIdType.getValue()); id.setOrganization(fetchOrganization(orgIdType.getHealthcareSite())); if(StringUtils.equals(id.getType(),OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE)){ ccIdentifier = id; }else if(StringUtils.equals(id.getType(),OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE)){ sponsorIdentifier = id; }else{ orgIdentifiers.add(id); } } } //if the sponsor identifier is not supplied, use coordinating center instead. if(sponsorIdentifier == null){ sponsorIdentifier = new OrganizationAssignedIdentifier(); sponsorIdentifier.setType(OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE); sponsorIdentifier.setValue(ccIdentifier.getValue()); sponsorIdentifier.setOrganization(study.getPrimaryFundingSponsorOrganization()); } study.addIdentifier(sponsorIdentifier); study.addIdentifier(ccIdentifier); for (OrganizationAssignedIdentifier id : orgIdentifiers) { study.addIdentifier(id); } for (SystemAssignedIdentifier id : sysIdentifiers) { study.addIdentifier(id); } } private StudyCreationException getStudyCreationException(String message) { StudyCreationException exp = new StudyCreationException(); exp.setFaultString(message); exp.setFaultReason(message); logger.error(message); return exp; } /** * Populates study organization and returns it. * * @param study * @param studyOrgTypes * @throws InvalidStudyException */ void populateStudyOrganizations(gov.nih.nci.cabig.caaers.domain.Study study, StudyOrganizationType[] studyOrgTypes) throws StudyCreationException, InvalidStudyException { if (ArrayUtils.isEmpty(studyOrgTypes)) { logger.error("No organization is associated to this study (gridId :" + study.getGridId() + ")"); StudyCreationException exp = new StudyCreationException(); exp.setFaultString("No organization is associated to this study"); exp.setFaultReason("No organization is associated to this study (gridId :" + study.getGridId() + ")"); throw exp; } List<StudyOrganization> studyOrgList = new ArrayList<StudyOrganization>(); boolean isPrimarySponsor = true; for (StudyOrganizationType studyOrgType : studyOrgTypes) { StudyOrganization studyOrganization = null; if (studyOrgType instanceof StudyFundingSponsorType) { StudyFundingSponsor fundingSponsor = new StudyFundingSponsor(); fundingSponsor.setPrimary(isPrimarySponsor); isPrimarySponsor = false; studyOrganization = fundingSponsor; } else if (studyOrgType instanceof StudyCoordinatingCenterType) { studyOrganization = new StudyCoordinatingCenter(); } else if (studyOrgType instanceof StudySiteType) { studyOrganization = new StudySite(); } else { logger.error("Unknown StudyOrganizationType in grid Study " + studyOrgType.toString()); throw getInvalidStudyException("Unknown StudyOrganizationType in grid Study "); } studyOrganization.setOrganization(fetchOrganization(studyOrgType.getHealthcareSite(0))); studyOrganization.setStudy(study); studyOrganization.setGridId(studyOrgType.getGridId()); // populate investigators populateInvestigators(studyOrganization, studyOrgType.getStudyInvestigator()); studyOrgList.add(studyOrganization); }// ~for study.setStudyOrganizations(studyOrgList); } /** * Will populate the investigator * * @param studyOrganization * @param invTypes */ void populateInvestigators(StudyOrganization studyOrganization, StudyInvestigatorType[] invTypes) throws StudyCreationException { if (ArrayUtils.isEmpty(invTypes)) { logger.error("No investigators are available in the input message"); return; } for (StudyInvestigatorType invType : invTypes) { String invNCICode = invType.getHealthcareSiteInvestigator().getInvestigator(0) .getNciIdentifier(); SiteInvestigator siteInvestigator = null; if (StringUtils.isEmpty(invNCICode)) { logger.error("Investigator details are missing!"); StudyCreationException exp = new StudyCreationException(); exp .setFaultReason("Missing investigator details in input : InvestigatorType.healthcareSiteInvesitagor.investigatorType[0].nciIdentifier"); exp.setFaultString("Invalid input, missing investigator information"); throw exp; } // find the study Investigator List<SiteInvestigator> siteInvestigators = siteInvestigatorDao .getOrganizationInvestigators(studyOrganization.getOrganization()); if (siteInvestigators != null) { // figure out the correct investigator for (SiteInvestigator si : siteInvestigators) { if (StringUtils.equals(si.getInvestigator().getNciIdentifier(), invNCICode)) { siteInvestigator = si; break; } } } // check if we were able to fetch siteInvestigator if (siteInvestigator == null) { logger .error("Unable to associate investigators.No investigators are associated to organization :" + studyOrganization.getOrganization().getName() + " nciCode :" + studyOrganization.getOrganization() .getNciInstituteCode()); StudyCreationException exp = new StudyCreationException(); exp .setFaultReason("Unable to associate the given investigaor {investigatorNCI code :" + invNCICode + "} to the site {" + studyOrganization.getOrganization().getName() + ", nciCode :" + studyOrganization.getOrganization() .getNciInstituteCode() + "}. The specified investigator should be associated to the organization."); exp .setFaultReason("Missing SiteInvestigator (investigator NCI Code :" + invNCICode + ")details for the Organization {" + studyOrganization.getOrganization().getName() + ", nciCode : " + studyOrganization.getOrganization() .getNciInstituteCode() + "}. The specified investigator should be associated to the organization."); throw exp; } StudyInvestigator studyInvestigator = new StudyInvestigator(); studyInvestigator.setStudyOrganization(studyOrganization); String roleCode = null; PersonRole[] caaersRoles = new PersonRole[]{PersonRole.SITE_INVESTIGATOR, PersonRole.SITE_PRINCIPAL_INVESTIGATOR, PersonRole.PRINCIPAL_INVESTIGATOR}; if (invType.getRoleCode() == null) { StudyCreationException exp = new StudyCreationException(); exp.setFaultReason("Investigator role is NULL in Study message"); throw exp; } for (PersonRole caaersRole:caaersRoles) { if (caaersRole.getDisplayName().equals(invType.getRoleCode())) { roleCode = caaersRole.getRoleCode(); break; } } if (roleCode == null) { StudyCreationException exp = new StudyCreationException(); exp.setFaultReason("Supplied Investigator role "+ invType.getRoleCode() + " does not map with roles in caAERS"); throw exp; } studyInvestigator.setRoleCode(roleCode); studyInvestigator.setSiteInvestigator(siteInvestigator); studyOrganization.addStudyInvestigators(studyInvestigator); } } /** * Fetches the organization from the DB. If one does not exist an appropriate Organization is created and saved. * * @param HealthcareSiteType * @return Organization */ protected Organization fetchOrganization(HealthcareSiteType healthCareSiteType) { if(healthCareSiteType == null){ return null; } //Check if an organization exists in caAERS for the given NCI CODE. OrganizationQuery orgQuery = new OrganizationQuery(); if (StringUtils.isNotEmpty(healthCareSiteType.getNciInstituteCode())) { orgQuery.filterByNciCodeExactMatch(healthCareSiteType.getNciInstituteCode()); } List<Organization> orgList = organizationRepository.searchOrganization(orgQuery); Organization organization = null; //If there is no Organization in caAERS with given NCI CODE then create an Organization in caAERS. if (orgList == null || orgList.isEmpty()) { //if externalId is provided it means that Organization is Remote. (Fetched from COPPA) if (StringUtils.isNotEmpty(healthCareSiteType.getGridId())) { organization = new RemoteOrganization(); populateOrganization(healthCareSiteType,organization); }else{ organization = new LocalOrganization(); populateOrganization(healthCareSiteType,organization); } organizationRepository.create(organization); return organization; } return orgList.get(0); } /** * This method populates an Organization entity given a HealthcareSiteType * @param HealthcareSiteType * @param Organization */ protected void populateOrganization(HealthcareSiteType healthCareSiteType, Organization organization){ organization.setNciInstituteCode(healthCareSiteType.getNciInstituteCode()); organization.setName(healthCareSiteType.getName()); organization.setDescriptionText(healthCareSiteType.getDescriptionText()); organization.setExternalId(healthCareSiteType.getGridId()); if(healthCareSiteType.getAddress() != null){ organization.setCity(healthCareSiteType.getAddress().getCity()); organization.setState(healthCareSiteType.getAddress().getStateCode()); organization.setCountry(healthCareSiteType.getAddress().getCountryCode()); } } gov.nih.nci.cabig.caaers.domain.Study fetchStudy(String ccIdentifier, String identifierType) { StudyQuery studyQuery = new StudyQuery(); studyQuery.filterByIdentifierValueExactMatch(ccIdentifier); studyQuery.filterByIdentifierType(identifierType); List<gov.nih.nci.cabig.caaers.domain.Study> studies = studyDao.find(studyQuery); if (studies == null || studies.isEmpty()) return null; return studies.get(0); } private InvalidStudyException getInvalidStudyException(String message) { logger.error(message); InvalidStudyException invalidStudyException = new InvalidStudyException(); invalidStudyException.setFaultReason(message); invalidStudyException.setFaultString(message); return invalidStudyException; } // /CONFIGURATION @Required public SiteInvestigatorDao getSiteInvestigatorDao() { return siteInvestigatorDao; } @Required public void setSiteInvestigatorDao(SiteInvestigatorDao siteInvestigatorDao) { this.siteInvestigatorDao = siteInvestigatorDao; } @Required public StudyDao getStudyDao() { return studyDao; } @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } @Required public void setConfigurationProperty(ConfigProperty configurationProperty) { this.configurationProperty = configurationProperty; } public ConfigProperty getConfigurationProperty() { return configurationProperty; } @Required public void setAuditHistoryRepository(AuditHistoryRepository auditHistoryRepository) { this.auditHistoryRepository = auditHistoryRepository; } @Required public void setStudyConsumerGridServiceUrl(String studyConsumerGridServiceUrl) { this.studyConsumerGridServiceUrl = studyConsumerGridServiceUrl; } @Required public void setRollbackInterval(Integer rollbackInterval) { this.rollbackInterval = rollbackInterval; } public GetMultipleResourcePropertiesResponse getMultipleResourceProperties(GetMultipleResourceProperties_Element params) throws RemoteException { //Auto-generated method stub return null; } public GetResourcePropertyResponse getResourceProperty(QName params) throws RemoteException { //Auto-generated method stub return null; } public QueryResourcePropertiesResponse queryResourceProperties(QueryResourceProperties_Element params) throws RemoteException { //Auto-generated method stub return null; } @Required public void setOrganizationRepository( OrganizationRepository organizationRepository) { this.organizationRepository = organizationRepository; } @SuppressWarnings("unused") private static class StubWebRequest implements WebRequest { public String getParameter(final String paramName) { return null; } public String[] getParameterValues(final String paramName) { return null; } @SuppressWarnings("unchecked") public Map getParameterMap() { return Collections.emptyMap(); } public Locale getLocale() { return null; } public String getContextPath() { return null; } public String getRemoteUser() { return null; } public Principal getUserPrincipal() { return null; } public boolean isUserInRole(String role) { return false; } public boolean isSecure() { return false; } public Object getAttribute(final String name, final int scope) { return null; } public void setAttribute(final String name, final Object value, final int scope) { } public void removeAttribute(final String name, final int scope) { } public void registerDestructionCallback(final String name, final Runnable callback, final int scope) { } public String getSessionId() { return null; } public Object getSessionMutex() { return null; } } }
CAAERS-3637 SVN-Revision: 12055
caAERS/software/grid/study-consumer/src/main/java/gov/nih/nci/cabig/caaers/grid/CaaersStudyConsumer.java
CAAERS-3637
<ide><path>aAERS/software/grid/study-consumer/src/main/java/gov/nih/nci/cabig/caaers/grid/CaaersStudyConsumer.java <ide> } <ide> <ide> studyInvestigator.setRoleCode(roleCode); <add> studyInvestigator.setStartDate(siteInvestigator.getStartDate()); <ide> studyInvestigator.setSiteInvestigator(siteInvestigator); <ide> studyOrganization.addStudyInvestigators(studyInvestigator); <ide> }
Java
apache-2.0
a177736c80b77d1bc90f766af3eb6e94daf8fb0c
0
airbnb/reair,airbnb/reair,airbnb/reair
package com.airbnb.di.hive.batchreplication.hivecopy; import com.google.common.collect.ImmutableList; import com.airbnb.di.common.FsUtils; import com.airbnb.di.hive.common.HiveMetastoreException; import com.airbnb.di.hive.common.HiveObjectSpec; import com.airbnb.di.hive.replication.ReplicationUtils; import com.airbnb.di.hive.replication.configuration.ConfigurationException; import com.airbnb.di.hive.replication.deploy.DeployConfigurationKeys; import com.airbnb.di.hive.replication.primitives.TaskEstimate; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.Optional; public class MetastoreReplicationJob extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(MetastoreReplicationJob.class); public static final String USAGE_COMMAND_STR = "Usage: hadoop jar <path to jar> " + "<class reference> -libjar <path hive-metastore.jar,libthrift.jar,libfb303.jar> options"; /** * TODO. * * @param estimate TODO * @param spec TODO * @return TODO */ public static String serializeJobResult(TaskEstimate estimate, HiveObjectSpec spec) { return ReplicationUtils.genValue(estimate.getTaskType().name(), String.valueOf(estimate.isUpdateMetadata()), String.valueOf(estimate.isUpdateData()), !estimate.getSrcPath().isPresent() ? null : estimate.getSrcPath().get().toString(), !estimate.getDestPath().isPresent() ? null : estimate.getDestPath().get().toString(), spec.getDbName(), spec.getTableName(), spec.getPartitionName()); } /** * TODO. * * @param result TODO * @return TODO */ public static Pair<TaskEstimate, HiveObjectSpec> deseralizeJobResult(String result) { String [] fields = result.split("\t"); TaskEstimate estimate = new TaskEstimate(TaskEstimate.TaskType.valueOf(fields[0]), Boolean.valueOf(fields[1]), Boolean.valueOf(fields[2]), fields[3].equals("NULL") ? Optional.empty() : Optional.of(new Path(fields[3])), fields[4].equals("NULL") ? Optional.empty() : Optional.of(new Path(fields[4]))); HiveObjectSpec spec = null; if (fields[7].equals("NULL")) { spec = new HiveObjectSpec(fields[5], fields[6]); } else { spec = new HiveObjectSpec(fields[5], fields[6], fields[7]); } return Pair.of(estimate, spec); } /** * TODO. * * @param applicationName TODO * @param options TODO * @param out TODO */ public static void printUsage(String applicationName, Options options, OutputStream out) { PrintWriter writer = new PrintWriter(out); HelpFormatter usageFormatter = new HelpFormatter(); usageFormatter.printUsage(writer, 80, applicationName, options); writer.flush(); } /** * TODO. * * @param args TODO * @return TODO * * @throws Exception TODO */ public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("config-files") .withDescription( "Comma separated list of paths to configuration files") .hasArg() .withArgName("PATH") .create()); options.addOption(OptionBuilder.withLongOpt("step") .withDescription("Run specific step") .hasArg() .withArgName("ST") .create()); options.addOption(OptionBuilder.withLongOpt("override-input") .withDescription("Input override for step") .hasArg() .withArgName("OI") .create()); CommandLineParser parser = new BasicParser(); CommandLine cl = null; try { cl = parser.parse(options, args); } catch (ParseException e) { System.err.println("Encountered exception while parsing using GnuParser:\n" + e.getMessage()); printUsage(USAGE_COMMAND_STR, options, System.out); System.out.println(); ToolRunner.printGenericCommandUsage(System.err); return 1; } String configPaths = null; if (cl.hasOption("config-files")) { configPaths = cl.getOptionValue("config-files"); LOG.info("configPaths=" + configPaths); // load configure and merge with job conf Configuration conf = new Configuration(); if (configPaths != null) { for (String configPath : configPaths.split(",")) { conf.addResource(new Path(configPath)); } } mergeConfiguration(conf, this.getConf()); } else { LOG.info("Unit test mode, getting configure from caller"); } int step = -1; if (cl.hasOption("step")) { step = Integer.valueOf(cl.getOptionValue("step")); } String finalOutput = this.getConf().get(DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR); if (finalOutput == null) { System.err.println( DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR + " is required in configuration file."); return 1; } String inputTableList = this.getConf().get(DeployConfigurationKeys.BATCH_JOB_INPUT_LIST); Path outputParent = new Path(finalOutput); String step1Out = new Path(outputParent, "step1output").toString(); String step2Out = new Path(outputParent, "step2output").toString(); String step3Out = new Path(outputParent, "step3output").toString(); if (step == -1) { FsUtils.deleteDirectory(this.getConf(), new Path(step1Out)); FsUtils.deleteDirectory(this.getConf(), new Path(step2Out)); FsUtils.deleteDirectory(this.getConf(), new Path(step3Out)); int result = 0; if (inputTableList != null) { result = this.runMetastoreCompareJobWithTextInput(inputTableList, step1Out); } else { result = this.runMetastoreCompareJob(step1Out); } return result == 0 && this.runHdfsCopyJob(step1Out + "/part*", step2Out) == 0 ? this.runCommitChangeJob(step1Out + "/part*", step3Out) : 1; } else { switch (step) { case 1: FsUtils.deleteDirectory(this.getConf(), new Path(step1Out)); if (inputTableList != null) { return this.runMetastoreCompareJobWithTextInput(inputTableList, step1Out); } else { return this.runMetastoreCompareJob(step1Out); } case 2: FsUtils.deleteDirectory(this.getConf(), new Path(step2Out)); if (cl.hasOption("override-input")) { step1Out = cl.getOptionValue("override-input"); } return this.runHdfsCopyJob(step1Out + "/part*", step2Out); case 3: FsUtils.deleteDirectory(this.getConf(), new Path(step3Out)); if (cl.hasOption("override-input")) { step1Out = cl.getOptionValue("override-input"); } return this.runCommitChangeJob(step1Out + "/part*", step3Out); default: LOG.error("Invalid steps specified:" + step); return 1; } } } private void mergeConfiguration(Configuration inputConfig, Configuration merged) { List<String> mergeKeys = ImmutableList.of(DeployConfigurationKeys.SRC_CLUSTER_NAME, DeployConfigurationKeys.SRC_CLUSTER_METASTORE_URL, DeployConfigurationKeys.SRC_HDFS_ROOT, DeployConfigurationKeys.SRC_HDFS_TMP, DeployConfigurationKeys.DEST_CLUSTER_NAME, DeployConfigurationKeys.DEST_CLUSTER_METASTORE_URL, DeployConfigurationKeys.DEST_HDFS_ROOT, DeployConfigurationKeys.DEST_HDFS_TMP, DeployConfigurationKeys.BATCH_JOB_METASTORE_BLACKLIST, DeployConfigurationKeys.BATCH_JOB_CLUSTER_FACTORY_CLASS, DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR, DeployConfigurationKeys.BATCH_JOB_INPUT_LIST, DeployConfigurationKeys.BATCH_JOB_PARALLELISM ); for (String key : mergeKeys) { String value = inputConfig.get(key); if (key.equals(DeployConfigurationKeys.BATCH_JOB_PARALLELISM)) { if (value != null) { merged.set("mapreduce.job.maps", value); merged.set("mapreduce.job.reduces", value); } else { merged.set("mapreduce.job.maps", "150"); merged.set("mapreduce.job.reduces", "150"); } } else { if (value != null) { merged.set(key, value); } } } } private int runMetastoreCompareJob(String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage1: Metastore Compare Job"); job.setJarByClass(this.getClass()); job.setInputFormatClass(MetastoreScanInputFormat.class); job.setMapperClass(Stage1ProcessTableMapper.class); job.setReducerClass(PartitionCompareReducer.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } private int runMetastoreCompareJobWithTextInput(String input, String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage1: Metastore Compare Job with Input List"); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Stage1ProcessTableMapperWithTextInput.class); job.setReducerClass(PartitionCompareReducer.class); FileInputFormat.setInputPaths(job, new Path(input)); FileInputFormat.setMaxInputSplitSize(job, this.getConf().getLong("mapreduce.input.fileinputformat.split.maxsize", 60000L)); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } private int runHdfsCopyJob(String input, String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage2: HDFS Copy Job"); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Stage2FolderCopyMapper.class); job.setReducerClass(Stage2FolderCopyReducer.class); FileInputFormat.setInputPaths(job, new Path(input)); FileInputFormat.setMaxInputSplitSize(job, this.getConf().getLong("mapreduce.input.fileinputformat.split.maxsize", 60000L)); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } private int runCommitChangeJob(String input, String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage3: Commit Change Job"); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Stage3CommitChangeMapper.class); job.setNumReduceTasks(0); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, new Path(input)); FileInputFormat.setMaxInputSplitSize(job, this.getConf().getLong("mapreduce.input.fileinputformat.split.maxsize", 60000L)); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } /** * TODO. * * @param args TODO * * @throws Exception TODO */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new MetastoreReplicationJob(), args); System.exit(res); } public static class Stage1ProcessTableMapper extends Mapper<Text, Text, LongWritable, Text> { private TableCompareWorker worker = new TableCompareWorker(); protected void setup(Context context) throws IOException, InterruptedException { try { worker.setup(context); } catch (ConfigurationException e) { throw new IOException("Invalid configuration", e); } } protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { try { for (String result : worker.processTable(key.toString(), value.toString())) { context.write(new LongWritable((long)result.hashCode()), new Text(result)); } LOG.info( String.format("database %s, table %s processed", key.toString(), value.toString())); } catch (HiveMetastoreException e) { throw new IOException( String.format( "database %s, table %s got exception", key.toString(), value.toString()), e); } } protected void cleanup(Context context) throws IOException, InterruptedException { worker.cleanup(); } } public static class Stage1ProcessTableMapperWithTextInput extends Mapper<LongWritable, Text, LongWritable, Text> { private TableCompareWorker worker = new TableCompareWorker(); protected void setup(Context context) throws IOException, InterruptedException { try { worker.setup(context); } catch (ConfigurationException e) { throw new IOException("Invalid configuration", e); } } protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { try { String [] columns = value.toString().split("\\."); if (columns.length != 2) { LOG.error(String.format("invalid input at line %d: %s", key.get(), value.toString())); return; } for (String result : worker.processTable(columns[0], columns[1])) { context.write(new LongWritable((long)result.hashCode()), new Text(result)); } LOG.info( String.format("database %s, table %s processed", key.toString(), value.toString())); } catch (HiveMetastoreException e) { throw new IOException( String.format( "database %s, table %s got exception", key.toString(), value.toString()), e); } } protected void cleanup(Context context) throws IOException, InterruptedException { worker.cleanup(); } } }
main/src/main/java/com/airbnb/di/hive/batchreplication/hivecopy/MetastoreReplicationJob.java
package com.airbnb.di.hive.batchreplication.hivecopy; import com.google.common.collect.ImmutableList; import com.airbnb.di.common.FsUtils; import com.airbnb.di.hive.common.HiveMetastoreException; import com.airbnb.di.hive.common.HiveObjectSpec; import com.airbnb.di.hive.replication.ReplicationUtils; import com.airbnb.di.hive.replication.configuration.ConfigurationException; import com.airbnb.di.hive.replication.deploy.DeployConfigurationKeys; import com.airbnb.di.hive.replication.primitives.TaskEstimate; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.Optional; public class MetastoreReplicationJob extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(MetastoreReplicationJob.class); public static final String USAGE_COMMAND_STR = "Usage: hadoop jar <path to jar> " + "<class reference> -libjar <path hive-metastore.jar,libthrift.jar,libfb303.jar> options"; /** * TODO. * * @param estimate TODO * @param spec TODO * @return TODO */ public static String serializeJobResult(TaskEstimate estimate, HiveObjectSpec spec) { return ReplicationUtils.genValue(estimate.getTaskType().name(), String.valueOf(estimate.isUpdateMetadata()), String.valueOf(estimate.isUpdateData()), !estimate.getSrcPath().isPresent() ? null : estimate.getSrcPath().get().toString(), !estimate.getDestPath().isPresent() ? null : estimate.getDestPath().get().toString(), spec.getDbName(), spec.getTableName(), spec.getPartitionName()); } /** * TODO. * * @param result TODO * @return TODO */ public static Pair<TaskEstimate, HiveObjectSpec> deseralizeJobResult(String result) { String [] fields = result.split("\t"); TaskEstimate estimate = new TaskEstimate(TaskEstimate.TaskType.valueOf(fields[0]), Boolean.valueOf(fields[1]), Boolean.valueOf(fields[2]), fields[3].equals("NULL") ? Optional.empty() : Optional.of(new Path(fields[3])), fields[4].equals("NULL") ? Optional.empty() : Optional.of(new Path(fields[4]))); HiveObjectSpec spec = null; if (fields[7].equals("NULL")) { spec = new HiveObjectSpec(fields[5], fields[6]); } else { spec = new HiveObjectSpec(fields[5], fields[6], fields[7]); } return Pair.of(estimate, spec); } /** * TODO. * * @param applicationName TODO * @param options TODO * @param out TODO */ public static void printUsage(String applicationName, Options options, OutputStream out) { PrintWriter writer = new PrintWriter(out); HelpFormatter usageFormatter = new HelpFormatter(); usageFormatter.printUsage(writer, 80, applicationName, options); writer.flush(); } /** * TODO. * * @param args TODO * @return TODO * * @throws Exception TODO */ public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withLongOpt("config-files") .withDescription( "Comma separated list of paths to configuration files") .hasArg() .withArgName("PATH") .create()); options.addOption(OptionBuilder.withLongOpt("step") .withDescription("Run specific step") .hasArg() .withArgName("ST") .create()); options.addOption(OptionBuilder.withLongOpt("override-input") .withDescription("Input override for step") .hasArg() .withArgName("OI") .create()); CommandLineParser parser = new BasicParser(); CommandLine cl = null; try { cl = parser.parse(options, args); } catch (ParseException e) { System.err.println("Encountered exception while parsing using GnuParser:\n" + e.getMessage()); printUsage(USAGE_COMMAND_STR, options, System.out); System.out.println(); ToolRunner.printGenericCommandUsage(System.err); return 1; } String configPaths = null; if (cl.hasOption("config-files")) { configPaths = cl.getOptionValue("config-files"); LOG.info("configPaths=" + configPaths); // load configure and merge with job conf Configuration conf = new Configuration(); if (configPaths != null) { for (String configPath : configPaths.split(",")) { conf.addResource(new Path(configPath)); } } mergeConfiguration(conf, this.getConf()); } else { LOG.info("Unit test mode, getting configure from caller"); } int step = -1; if (cl.hasOption("step")) { step = Integer.valueOf(cl.getOptionValue("step")); } String finalOutput = this.getConf().get(DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR); if (finalOutput == null) { System.err.println( DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR + " is required in configuration file."); return 1; } String inputTableList = this.getConf().get(DeployConfigurationKeys.BATCH_JOB_INPUT_LIST); Path outputParent = new Path(finalOutput); String step1Out = new Path(outputParent, "step1output").toString(); String step2Out = new Path(outputParent, "step2output").toString(); String step3Out = new Path(outputParent, "step3output").toString(); if (step == -1) { FsUtils.deleteDirectory(this.getConf(), new Path(step1Out)); FsUtils.deleteDirectory(this.getConf(), new Path(step2Out)); FsUtils.deleteDirectory(this.getConf(), new Path(step3Out)); int result = 0; if (inputTableList != null) { result = this.runMetastoreCompareJobWithTextInput(inputTableList, step1Out); } else { result = this.runMetastoreCompareJob(step1Out); } return result == 0 && this.runHdfsCopyJob(step1Out + "/part*", step2Out) == 0 ? this.runCommitChangeJob(step1Out + "/part*", step3Out) : 1; } else { switch (step) { case 1: FsUtils.deleteDirectory(this.getConf(), new Path(step1Out)); if (inputTableList != null) { return this.runMetastoreCompareJobWithTextInput(inputTableList, step1Out); } else { return this.runMetastoreCompareJob(step1Out); } case 2: FsUtils.deleteDirectory(this.getConf(), new Path(step2Out)); if (cl.hasOption("override-input")) { step1Out = cl.getOptionValue("override-input"); } return this.runHdfsCopyJob(step1Out + "/part*", step2Out); case 3: FsUtils.deleteDirectory(this.getConf(), new Path(step3Out)); if (cl.hasOption("override-input")) { step1Out = cl.getOptionValue("override-input"); } return this.runCommitChangeJob(step1Out + "/part*", step3Out); default: LOG.error("Invalid steps specified:" + step); return 1; } } } private void mergeConfiguration(Configuration inputConfig, Configuration merged) { List<String> mergeKeys = ImmutableList.of(DeployConfigurationKeys.SRC_CLUSTER_NAME, DeployConfigurationKeys.SRC_CLUSTER_METASTORE_URL, DeployConfigurationKeys.SRC_HDFS_ROOT, DeployConfigurationKeys.SRC_HDFS_TMP, DeployConfigurationKeys.DEST_CLUSTER_NAME, DeployConfigurationKeys.DEST_CLUSTER_METASTORE_URL, DeployConfigurationKeys.DEST_HDFS_ROOT, DeployConfigurationKeys.DEST_HDFS_TMP, DeployConfigurationKeys.BATCH_JOB_METASTORE_BLACKLIST, DeployConfigurationKeys.BATCH_JOB_CLUSTER_FACTORY_CLASS, DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR, DeployConfigurationKeys.BATCH_JOB_INPUT_LIST, DeployConfigurationKeys.BATCH_JOB_PARALLELISM, DeployConfigurationKeys.BATCH_JOB_POOL ); for (String key : mergeKeys) { String value = inputConfig.get(key); if (key.equals(DeployConfigurationKeys.BATCH_JOB_PARALLELISM)) { if (value != null) { merged.set("mapreduce.job.maps", value); merged.set("mapreduce.job.reduces", value); } else { merged.set("mapreduce.job.maps", "150"); merged.set("mapreduce.job.reduces", "150"); } } else { if (value != null) { merged.set(key, value); } } } } private int runMetastoreCompareJob(String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage1: Metastore Compare Job"); job.setJarByClass(this.getClass()); job.setInputFormatClass(MetastoreScanInputFormat.class); job.setMapperClass(Stage1ProcessTableMapper.class); job.setReducerClass(PartitionCompareReducer.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } private int runMetastoreCompareJobWithTextInput(String input, String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage1: Metastore Compare Job with Input List"); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Stage1ProcessTableMapperWithTextInput.class); job.setReducerClass(PartitionCompareReducer.class); FileInputFormat.setInputPaths(job, new Path(input)); FileInputFormat.setMaxInputSplitSize(job, this.getConf().getLong("mapreduce.input.fileinputformat.split.maxsize", 60000L)); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } private int runHdfsCopyJob(String input, String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage2: HDFS Copy Job"); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Stage2FolderCopyMapper.class); job.setReducerClass(Stage2FolderCopyReducer.class); FileInputFormat.setInputPaths(job, new Path(input)); FileInputFormat.setMaxInputSplitSize(job, this.getConf().getLong("mapreduce.input.fileinputformat.split.maxsize", 60000L)); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(Text.class); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } private int runCommitChangeJob(String input, String output) throws IOException, InterruptedException, ClassNotFoundException { Job job = Job.getInstance(this.getConf(), "Stage3: Commit Change Job"); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); job.setMapperClass(Stage3CommitChangeMapper.class); job.setNumReduceTasks(0); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, new Path(input)); FileInputFormat.setMaxInputSplitSize(job, this.getConf().getLong("mapreduce.input.fileinputformat.split.maxsize", 60000L)); FileOutputFormat.setOutputPath(job, new Path(output)); FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } /** * TODO. * * @param args TODO * * @throws Exception TODO */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new MetastoreReplicationJob(), args); System.exit(res); } public static class Stage1ProcessTableMapper extends Mapper<Text, Text, LongWritable, Text> { private TableCompareWorker worker = new TableCompareWorker(); protected void setup(Context context) throws IOException, InterruptedException { try { worker.setup(context); } catch (ConfigurationException e) { throw new IOException("Invalid configuration", e); } } protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { try { for (String result : worker.processTable(key.toString(), value.toString())) { context.write(new LongWritable((long)result.hashCode()), new Text(result)); } LOG.info( String.format("database %s, table %s processed", key.toString(), value.toString())); } catch (HiveMetastoreException e) { throw new IOException( String.format( "database %s, table %s got exception", key.toString(), value.toString()), e); } } protected void cleanup(Context context) throws IOException, InterruptedException { worker.cleanup(); } } public static class Stage1ProcessTableMapperWithTextInput extends Mapper<LongWritable, Text, LongWritable, Text> { private TableCompareWorker worker = new TableCompareWorker(); protected void setup(Context context) throws IOException, InterruptedException { try { worker.setup(context); } catch (ConfigurationException e) { throw new IOException("Invalid configuration", e); } } protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { try { String [] columns = value.toString().split("\\."); if (columns.length != 2) { LOG.error(String.format("invalid input at line %d: %s", key.get(), value.toString())); return; } for (String result : worker.processTable(columns[0], columns[1])) { context.write(new LongWritable((long)result.hashCode()), new Text(result)); } LOG.info( String.format("database %s, table %s processed", key.toString(), value.toString())); } catch (HiveMetastoreException e) { throw new IOException( String.format( "database %s, table %s got exception", key.toString(), value.toString()), e); } } protected void cleanup(Context context) throws IOException, InterruptedException { worker.cleanup(); } } }
fix a typo
main/src/main/java/com/airbnb/di/hive/batchreplication/hivecopy/MetastoreReplicationJob.java
fix a typo
<ide><path>ain/src/main/java/com/airbnb/di/hive/batchreplication/hivecopy/MetastoreReplicationJob.java <ide> DeployConfigurationKeys.BATCH_JOB_CLUSTER_FACTORY_CLASS, <ide> DeployConfigurationKeys.BATCH_JOB_OUTPUT_DIR, <ide> DeployConfigurationKeys.BATCH_JOB_INPUT_LIST, <del> DeployConfigurationKeys.BATCH_JOB_PARALLELISM, <del> DeployConfigurationKeys.BATCH_JOB_POOL <add> DeployConfigurationKeys.BATCH_JOB_PARALLELISM <ide> ); <ide> <ide> for (String key : mergeKeys) {
Java
mit
1a15553ed001541f449dd452d053d43a5fa60ecc
0
cristianmtr/tracker-java
package tracker_java.Utilities; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import redis.clients.jedis.Jedis; import tracker_java.Models.HibernateUtil; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.util.regex.Pattern; import static tracker_java.Models.HibernateUtil.getOneItemFromQuery; /** * Created by cristian on 11/11/15. */ public final class PermissionsChecker { private boolean userIsAdmin(Integer memberId) { Session s = HibernateUtil.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); Query isAdminQuery = s.createQuery("select admin from MemberEntity where memberid = :memberid").setParameter("memberid", memberId); boolean isAdmin = false; try { isAdmin = (boolean) isAdminQuery.list().get(0); } catch (Exception e) { e.printStackTrace(); } s.flush(); tx.commit(); s.close(); return isAdmin; } private static Integer getUserIdFromToken(String token) { Integer userid = null; try { Jedis redis = JedisPoolInstance.pool.getResource(); userid = Integer.parseInt(redis.get(token)); } catch (Exception e) { e.printStackTrace(); } if (userid==null) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } return userid; } private static String getTokenFromHeader(String bareHeader) { String token = null; try { String[] typeAndToken = bareHeader.split(Pattern.quote(" ")); if (typeAndToken[0].equals("Bearer") && typeAndToken[1].length() > 0) { token = typeAndToken[1]; } } catch (Exception e) { e.printStackTrace(); throw new WebApplicationException(Response.Status.UNAUTHORIZED); } if (token==null) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } return token; } public static int getUserIdFromAuthorization(String authorization){ return getUserIdFromToken(getTokenFromHeader(authorization)); } /* get userid from token get projectid from itemid get memberproject junction entry >= 2 */ public static boolean checkPermissionComment(Integer itemid, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",itemid)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId)); return permission >= 2; } /* get userid from token get projectid from taskid get memberproject entry == 3 */ public static boolean checkPermissionWrite(int taskId, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId)); return permission == 3; } /* get userid from token get projectid from taskid get memberproject entry >= 1 */ public static boolean checkPermissionRead(int taskId, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId)); return permission >= 1; } public static boolean checkWritePermissionToProject(Integer projectid, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectid)); return permission >= 3; } }
src/main/java/tracker_java/Utilities/PermissionsChecker.java
package tracker_java.Utilities; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import redis.clients.jedis.Jedis; import tracker_java.Models.HibernateUtil; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.util.regex.Pattern; import static tracker_java.Models.HibernateUtil.getOneItemFromQuery; /** * Created by cristian on 11/11/15. */ public final class PermissionsChecker { private boolean userIsAdmin(Integer memberId) { Session s = HibernateUtil.getSessionFactory().openSession(); Transaction tx = s.beginTransaction(); Query isAdminQuery = s.createQuery("select admin from MemberEntity where memberid = :memberid").setParameter("memberid", memberId); boolean isAdmin = false; try { isAdmin = (boolean) isAdminQuery.list().get(0); } catch (Exception e) { e.printStackTrace(); } s.flush(); tx.commit(); s.close(); return isAdmin; } private static Integer getUserIdFromToken(String token) { Integer userid = null; try { Jedis redis = JedisPoolInstance.pool.getResource(); userid = Integer.parseInt(redis.get(token)); if (userid==null) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } catch (Exception e) { e.printStackTrace(); } return userid; } private static String getTokenFromHeader(String bareHeader) { try { String[] typeAndToken = bareHeader.split(Pattern.quote(" ")); if (typeAndToken[0].equals("Bearer") && typeAndToken[1].length() > 0) { return typeAndToken[1]; } } catch (Exception e) { e.printStackTrace(); throw new WebApplicationException(Response.Status.UNAUTHORIZED); } return null; } public static int getUserIdFromAuthorization(String authorization){ return getUserIdFromToken(getTokenFromHeader(authorization)); } /* get userid from token get projectid from itemid get memberproject junction entry >= 2 */ public static boolean checkPermissionComment(Integer itemid, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",itemid)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId)); return permission >= 2; } /* get userid from token get projectid from taskid get memberproject entry == 3 */ public static boolean checkPermissionWrite(int taskId, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId)); return permission == 3; } /* get userid from token get projectid from taskid get memberproject entry >= 1 */ public static boolean checkPermissionRead(int taskId, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectId)); return permission >= 1; } public static boolean checkWritePermissionToProject(Integer projectid, String authorization) { Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); Integer permission = (Integer) getOneItemFromQuery(String.format("SELECT position FROM MemberprojectEntity WHERE memberid = '%s' AND projectid = '%s'", userid, projectid)); return permission >= 3; } }
check for null on userid from redis and auth header contents;
src/main/java/tracker_java/Utilities/PermissionsChecker.java
check for null on userid from redis and auth header contents;
<ide><path>rc/main/java/tracker_java/Utilities/PermissionsChecker.java <ide> try { <ide> Jedis redis = JedisPoolInstance.pool.getResource(); <ide> userid = Integer.parseInt(redis.get(token)); <del> if (userid==null) { <del> throw new WebApplicationException(Response.Status.UNAUTHORIZED); <del> } <ide> } catch (Exception e) { <ide> e.printStackTrace(); <ide> } <add> if (userid==null) { <add> throw new WebApplicationException(Response.Status.UNAUTHORIZED); <add> } <ide> return userid; <ide> } <ide> <ide> private static String getTokenFromHeader(String bareHeader) { <add> String token = null; <ide> try { <ide> String[] typeAndToken = bareHeader.split(Pattern.quote(" ")); <ide> if (typeAndToken[0].equals("Bearer") && typeAndToken[1].length() > 0) { <del> return typeAndToken[1]; <add> token = typeAndToken[1]; <ide> } <ide> } <ide> catch (Exception e) { <ide> e.printStackTrace(); <ide> throw new WebApplicationException(Response.Status.UNAUTHORIZED); <ide> } <del> return null; <add> if (token==null) { <add> throw new WebApplicationException(Response.Status.UNAUTHORIZED); <add> } <add> return token; <ide> } <ide> <ide> public static int getUserIdFromAuthorization(String authorization){ <ide> } <ide> <ide> /* <del> get userid from token <del> get projectid from itemid <del> get memberproject junction entry <del> >= 2 <del> */ <add> get userid from token <add> get projectid from itemid <add> get memberproject junction entry <add> >= 2 <add> */ <ide> public static boolean checkPermissionComment(Integer itemid, String authorization) { <ide> Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); <ide> Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",itemid)); <ide> } <ide> <ide> /* <del> get userid from token <del> get projectid from taskid <del> get memberproject entry <del> == 3 <del> */ <add> get userid from token <add> get projectid from taskid <add> get memberproject entry <add> == 3 <add> */ <ide> public static boolean checkPermissionWrite(int taskId, String authorization) { <ide> Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); <ide> Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId)); <ide> } <ide> <ide> /* <del> get userid from token <del> get projectid from taskid <del> get memberproject entry <del> >= 1 <del> */ <add> get userid from token <add> get projectid from taskid <add> get memberproject entry <add> >= 1 <add> */ <ide> public static boolean checkPermissionRead(int taskId, String authorization) { <ide> Integer userid = getUserIdFromToken(getTokenFromHeader(authorization)); <ide> Integer projectId = (Integer) getOneItemFromQuery(String.format("SELECT projectid FROM ItemEntity WHERE id = '%s'",taskId));
Java
mit
52ecd0f29a8b70da05d27c288bc17e6bd3fc018c
0
david-crowder/github-oauth-plugin,jenkinsci/github-oauth-plugin,jenkinsci/github-oauth-plugin,david-crowder/github-oauth-plugin
/** The MIT License Copyright (c) 2011 Michael O'Cleirigh 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 org.jenkinsci.plugins; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import hudson.security.SecurityRealm; import jenkins.model.Jenkins; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.providers.AbstractAuthenticationToken; import org.kohsuke.github.GHMyself; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHPersonSet; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GHTeam; import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.kohsuke.github.RateLimitHandler; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * @author mocleiri * * to hold the authentication token from the github oauth process. * */ public class GithubAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = 2L; private final String accessToken; private final String githubServer; private final String userName; private transient GitHub gh; private transient GHMyself me; private transient GithubSecurityRealm myRealm = null; public static final TimeUnit CACHE_EXPIRY = TimeUnit.HOURS; /** * Cache for faster organization based security */ private static final Cache<String, Set<String>> userOrganizationCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, Set<String>> repositoryCollaboratorsCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, Set<String>> repositoriesByUserCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, Boolean> publicRepositoryCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, GithubUser> usersByIdCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); private static final GithubUser UNKNOWN_USER = new GithubUser(null); /** Wrapper for cache **/ static class GithubUser { public final GHUser user; public GithubUser(GHUser user) { this.user = user; } } public GithubAuthenticationToken(final String accessToken, final String githubServer) throws IOException { super(new GrantedAuthority[] {}); this.accessToken = accessToken; this.githubServer = githubServer; this.me = getGitHub().getMyself(); assert this.me!=null; setAuthenticated(true); this.userName = this.me.getLogin(); authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY); Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins not started"); } if(jenkins.getSecurityRealm() instanceof GithubSecurityRealm) { if(myRealm == null) { myRealm = (GithubSecurityRealm) jenkins.getSecurityRealm(); } //Search for scopes that allow fetching team membership. This is documented online. //https://developer.github.com/v3/orgs/#list-your-organizations //https://developer.github.com/v3/orgs/teams/#list-user-teams if(myRealm.hasScope("read:org") || myRealm.hasScope("admin:org") || myRealm.hasScope("user") || myRealm.hasScope("repo")) { Map<String, GHOrganization> myOrgs = getGitHub().getMyOrganizations(); Map<String, Set<GHTeam>> myTeams = getGitHub().getMyTeams(); //fetch organization-only memberships (i.e.: groups without teams) for(String orgLogin : myOrgs.keySet()){ if(!myTeams.containsKey(orgLogin)){ myTeams.put(orgLogin, Collections.<GHTeam>emptySet()); } } for (Map.Entry<String, Set<GHTeam>> teamEntry : myTeams.entrySet()) { String orgLogin = teamEntry.getKey(); LOGGER.log(Level.FINE, "Fetch teams for user " + userName + " in organization " + orgLogin); authorities.add(new GrantedAuthorityImpl(orgLogin)); for (GHTeam team : teamEntry.getValue()) { authorities.add(new GrantedAuthorityImpl(orgLogin + GithubOAuthGroupDetails.ORG_TEAM_SEPARATOR + team.getName())); } } } } } /** * Necessary for testing */ public static void clearCaches() { userOrganizationCache.invalidateAll(); repositoryCollaboratorsCache.invalidateAll(); repositoriesByUserCache.invalidateAll(); usersByIdCache.invalidateAll(); } /** * Gets the OAuth access token, so that it can be persisted and used elsewhere. * @return accessToken */ public String getAccessToken() { return accessToken; } /** * Gets the Github server used for this token * @return githubServer */ public String getGithubServer() { return githubServer; } public GitHub getGitHub() throws IOException { if (this.gh == null) { this.gh = GitHubBuilder.fromEnvironment() .withEndpoint(this.githubServer) .withOAuthToken(this.accessToken) .withRateLimitHandler(RateLimitHandler.FAIL) .build(); } return gh; } @Override public GrantedAuthority[] getAuthorities() { return authorities.toArray(new GrantedAuthority[authorities.size()]); } public Object getCredentials() { return ""; // do not expose the credential } /** * Returns the login name in GitHub. * @return principal */ public String getPrincipal() { return this.userName; } /** * Returns the GHMyself object from this instance. * @return myself */ public GHMyself getMyself() throws IOException { if (me == null) { me = getGitHub().getMyself(); } return me; } /** * For some reason I can't get the github api to tell me for the current * user the groups to which he belongs. * * So this is a slightly larger consideration. If the authenticated user is * part of any team within the organization then they have permission. * * It caches user organizations for 24 hours for faster web navigation. * * @param candidateName name of the candidate * @param organization name of the organization * @return has organization permission */ public boolean hasOrganizationPermission(String candidateName, String organization) { try { Set<String> v = userOrganizationCache.get(candidateName,new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { return getGitHub().getMyOrganizations().keySet(); } }); return v.contains(organization); } catch (ExecutionException e) { throw new RuntimeException("authorization failed for user = " + candidateName, e); } } public boolean hasRepositoryPermission(final String repositoryName) { return myRepositories().contains(repositoryName); } public Set<String> myRepositories() { try { return repositoriesByUserCache.get(getName(), new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { List<GHRepository> userRepositoryList = getMyself().listRepositories().asList(); Set<String> repositoryNames = listToNames(userRepositoryList); GHPersonSet<GHOrganization> organizations = getMyself().getAllOrganizations(); for (GHOrganization organization : organizations) { List<GHRepository> orgRepositoryList = organization.listRepositories().asList(); Set<String> orgRepositoryNames = listToNames(orgRepositoryList); repositoryNames.addAll(orgRepositoryNames); } return repositoryNames; } } ); } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "an exception was thrown", e); throw new RuntimeException("authorization failed for user = " + getName(), e); } } public Set<String> listToNames(Collection<GHRepository> respositories) throws IOException { Set<String> names = new HashSet<String>(); for (GHRepository repository : respositories) { String ownerName = repository.getOwner().getLogin(); String repoName = repository.getName(); names.add(ownerName + "/" + repoName); } return names; } public boolean isPublicRepository(final String repositoryName) { try { return publicRepositoryCache.get(repositoryName, new Callable<Boolean>() { @Override public Boolean call() throws Exception { GHRepository repository = loadRepository(repositoryName); // We don't have access so it must not be public (it could be non-existant) return repository != null && !repository.isPrivate(); } } ); } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "an exception was thrown", e); throw new RuntimeException("authorization failed for user = " + getName(), e); } } private static final Logger LOGGER = Logger .getLogger(GithubAuthenticationToken.class.getName()); public GHUser loadUser(String username) throws IOException { GithubUser user; try { user = usersByIdCache.getIfPresent(username); if (gh != null && user == null && isAuthenticated()) { GHUser ghUser = getGitHub().getUser(username); user = new GithubUser(ghUser); usersByIdCache.put(username, user); } } catch (IOException e) { LOGGER.log(Level.FINEST, e.getMessage(), e); user = UNKNOWN_USER; usersByIdCache.put(username, UNKNOWN_USER); } return user != null ? user.user : null; } public GHOrganization loadOrganization(String organization) { try { if (gh != null && isAuthenticated()) return getGitHub().getOrganization(organization); } catch (IOException | RuntimeException e) { LOGGER.log(Level.FINEST, e.getMessage(), e); } return null; } public GHRepository loadRepository(String repositoryName) { try { if (gh != null && isAuthenticated()) { return getGitHub().getRepository(repositoryName); } } catch (IOException e) { LOGGER.log(Level.WARNING, "Looks like a bad GitHub URL OR the Jenkins user does not have access to the repository{0}", repositoryName); } return null; } public GHTeam loadTeam(String organization, String team) { try { GHOrganization org = loadOrganization(organization); if (org != null) { return org.getTeamByName(team); } } catch (IOException e) { LOGGER.log(Level.FINEST, e.getMessage(), e); } return null; } public GithubOAuthUserDetails getUserDetails(String username) throws IOException { GHUser user = loadUser(username); if (user != null) { return new GithubOAuthUserDetails(user.getLogin(), this); } return null; } public GrantedAuthority[] getGrantedAuthorities(GHUser user) { List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); try { GHPersonSet<GHOrganization> orgs; if(myRealm == null) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins not started"); } myRealm = (GithubSecurityRealm) jenkins.getSecurityRealm(); } //Search for scopes that allow fetching team membership. This is documented online. //https://developer.github.com/v3/orgs/#list-your-organizations //https://developer.github.com/v3/orgs/teams/#list-user-teams if(this.userName.equals(user.getLogin()) && (myRealm.hasScope("read:org") || myRealm.hasScope("admin:org") || myRealm.hasScope("user") || myRealm.hasScope("repo"))) { //This allows us to search for private organization membership. orgs = getMyself().getAllOrganizations(); } else { //This searches for public organization membership. orgs = user.getOrganizations(); } for (GHOrganization ghOrganization : orgs) { String orgLogin = ghOrganization.getLogin(); LOGGER.log(Level.FINE, "Fetch teams for user " + user.getLogin() + " in organization " + orgLogin); groups.add(new GrantedAuthorityImpl(orgLogin)); try { if (!getMyself().isMemberOf(ghOrganization)) { continue; } Map<String, GHTeam> teams = ghOrganization.getTeams(); for (Map.Entry<String, GHTeam> entry : teams.entrySet()) { GHTeam team = entry.getValue(); if (team.hasMember(user)) { groups.add(new GrantedAuthorityImpl(orgLogin + GithubOAuthGroupDetails.ORG_TEAM_SEPARATOR + team)); } } } catch (IOException | Error ignore) { LOGGER.log(Level.FINEST, "not enough rights to list teams from " + orgLogin, ignore); } } } catch(IOException e) { LOGGER.log(Level.FINE, e.getMessage(), e); } return groups.toArray(new GrantedAuthority[groups.size()]); } }
src/main/java/org/jenkinsci/plugins/GithubAuthenticationToken.java
/** The MIT License Copyright (c) 2011 Michael O'Cleirigh 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 org.jenkinsci.plugins; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import hudson.security.SecurityRealm; import jenkins.model.Jenkins; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.providers.AbstractAuthenticationToken; import org.kohsuke.github.GHMyself; import org.kohsuke.github.GHOrganization; import org.kohsuke.github.GHPersonSet; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GHTeam; import org.kohsuke.github.GHUser; import org.kohsuke.github.GitHub; import org.kohsuke.github.GitHubBuilder; import org.kohsuke.github.RateLimitHandler; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * @author mocleiri * * to hold the authentication token from the github oauth process. * */ public class GithubAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = 2L; private final String accessToken; private final String githubServer; private final String userName; private transient GitHub gh; private transient GHMyself me; private transient GithubSecurityRealm myRealm = null; public static final TimeUnit CACHE_EXPIRY = TimeUnit.HOURS; /** * Cache for faster organization based security */ private static final Cache<String, Set<String>> userOrganizationCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, Set<String>> repositoryCollaboratorsCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, Set<String>> repositoriesByUserCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, Boolean> publicRepositoryCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private static final Cache<String, GithubUser> usersByIdCache = CacheBuilder.newBuilder().expireAfterWrite(1, CACHE_EXPIRY).build(); private final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); private static final GithubUser UNKNOWN_USER = new GithubUser(null); /** Wrapper for cache **/ static class GithubUser { public final GHUser user; public GithubUser(GHUser user) { this.user = user; } } public GithubAuthenticationToken(final String accessToken, final String githubServer) throws IOException { super(new GrantedAuthority[] {}); this.accessToken = accessToken; this.githubServer = githubServer; this.me = getGitHub().getMyself(); assert this.me!=null; setAuthenticated(true); this.userName = this.me.getLogin(); authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY); Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins not started"); } if(jenkins.getSecurityRealm() instanceof GithubSecurityRealm) { if(myRealm == null) { myRealm = (GithubSecurityRealm) jenkins.getSecurityRealm(); } //Search for scopes that allow fetching team membership. This is documented online. //https://developer.github.com/v3/orgs/#list-your-organizations //https://developer.github.com/v3/orgs/teams/#list-user-teams if(myRealm.hasScope("read:org") || myRealm.hasScope("admin:org") || myRealm.hasScope("user") || myRealm.hasScope("repo")) { Map<String, GHOrganization> myOrgs = getGitHub().getMyOrganizations(); Map<String, Set<GHTeam>> myTeams = getGitHub().getMyTeams(); //fetch organization-only memberships (i.e.: groups without teams) for(String orgLogin : myOrgs.keySet()){ if(!myTeams.containsKey(orgLogin)){ myTeams.put(orgLogin, Collections.<GHTeam>emptySet()); } } for (Map.Entry<String, Set<GHTeam>> teamEntry : myTeams.entrySet()) { String orgLogin = teamEntry.getKey(); LOGGER.log(Level.FINE, "Fetch teams for user " + userName + " in organization " + orgLogin); authorities.add(new GrantedAuthorityImpl(orgLogin)); for (GHTeam team : teamEntry.getValue()) { authorities.add(new GrantedAuthorityImpl(orgLogin + GithubOAuthGroupDetails.ORG_TEAM_SEPARATOR + team.getName())); } } } } } /** * Necessary for testing */ public static void clearCaches() { userOrganizationCache.invalidateAll(); repositoryCollaboratorsCache.invalidateAll(); repositoriesByUserCache.invalidateAll(); usersByIdCache.invalidateAll(); } /** * Gets the OAuth access token, so that it can be persisted and used elsewhere. * @return accessToken */ public String getAccessToken() { return accessToken; } /** * Gets the Github server used for this token * @return githubServer */ public String getGithubServer() { return githubServer; } public GitHub getGitHub() throws IOException { if (this.gh == null) { this.gh = GitHubBuilder.fromEnvironment() .withEndpoint(this.githubServer) .withOAuthToken(this.accessToken) .withRateLimitHandler(RateLimitHandler.FAIL) .build(); } return gh; } @Override public GrantedAuthority[] getAuthorities() { return authorities.toArray(new GrantedAuthority[authorities.size()]); } public Object getCredentials() { return ""; // do not expose the credential } /** * Returns the login name in GitHub. * @return principal */ public String getPrincipal() { return this.userName; } /** * Returns the GHMyself object from this instance. * @return myself */ public GHMyself getMyself() throws IOException { if (me == null) { me = getGitHub().getMyself(); } return me; } /** * For some reason I can't get the github api to tell me for the current * user the groups to which he belongs. * * So this is a slightly larger consideration. If the authenticated user is * part of any team within the organization then they have permission. * * It caches user organizations for 24 hours for faster web navigation. * * @param candidateName name of the candidate * @param organization name of the organization * @return has organization permission */ public boolean hasOrganizationPermission(String candidateName, String organization) { try { Set<String> v = userOrganizationCache.get(candidateName,new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { return getGitHub().getMyOrganizations().keySet(); } }); return v.contains(organization); } catch (ExecutionException e) { throw new RuntimeException("authorization failed for user = " + candidateName, e); } } public boolean hasRepositoryPermission(final String repositoryName) { return myRepositories().contains(repositoryName); } public Set<String> myRepositories() { try { return repositoriesByUserCache.get(getName(), new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { List<GHRepository> userRepositoryList = getMyself().listRepositories().asList(); Set<String> repositoryNames = listToNames(userRepositoryList); GHPersonSet<GHOrganization> organizations = getMyself().getAllOrganizations(); for (GHOrganization organization : organizations) { List<GHRepository> orgRepositoryList = organization.listRepositories().asList(); Set<String> orgRepositoryNames = listToNames(orgRepositoryList); repositoryNames.addAll(orgRepositoryNames); } return repositoryNames; } } ); } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "an exception was thrown", e); throw new RuntimeException("authorization failed for user = " + getName(), e); } } public Set<String> listToNames(Collection<GHRepository> respositories) throws IOException { Set<String> names = new HashSet<String>(); for (GHRepository repository : respositories) { String ownerName = repository.getOwner().getLogin(); String repoName = repository.getName(); names.add(ownerName + "/" + repoName); } return names; } public boolean isPublicRepository(final String repositoryName) { try { return publicRepositoryCache.get(repositoryName, new Callable<Boolean>() { @Override public Boolean call() throws Exception { GHRepository repository = loadRepository(repositoryName); // We don't have access so it must not be public (it could be non-existant) return repository != null && !repository.isPrivate(); } } ); } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "an exception was thrown", e); throw new RuntimeException("authorization failed for user = " + getName(), e); } } private static final Logger LOGGER = Logger .getLogger(GithubAuthenticationToken.class.getName()); public GHUser loadUser(String username) throws IOException { GithubUser user; try { user = usersByIdCache.get(username); if (gh != null && user == null && isAuthenticated()) { GHUser ghUser = getGitHub().getUser(username); user = new GithubUser(ghUser); usersByIdCache.put(username, user); } } catch (IOException | ExecutionException e) { LOGGER.log(Level.FINEST, e.getMessage(), e); user = UNKNOWN_USER; usersByIdCache.put(username, UNKNOWN_USER); } return user != null ? user.user : null; } public GHOrganization loadOrganization(String organization) { try { if (gh != null && isAuthenticated()) return getGitHub().getOrganization(organization); } catch (IOException | RuntimeException e) { LOGGER.log(Level.FINEST, e.getMessage(), e); } return null; } public GHRepository loadRepository(String repositoryName) { try { if (gh != null && isAuthenticated()) { return getGitHub().getRepository(repositoryName); } } catch (IOException e) { LOGGER.log(Level.WARNING, "Looks like a bad GitHub URL OR the Jenkins user does not have access to the repository{0}", repositoryName); } return null; } public GHTeam loadTeam(String organization, String team) { try { GHOrganization org = loadOrganization(organization); if (org != null) { return org.getTeamByName(team); } } catch (IOException e) { LOGGER.log(Level.FINEST, e.getMessage(), e); } return null; } public GithubOAuthUserDetails getUserDetails(String username) throws IOException { GHUser user = loadUser(username); if (user != null) { return new GithubOAuthUserDetails(user.getLogin(), this); } return null; } public GrantedAuthority[] getGrantedAuthorities(GHUser user) { List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>(); try { GHPersonSet<GHOrganization> orgs; if(myRealm == null) { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins not started"); } myRealm = (GithubSecurityRealm) jenkins.getSecurityRealm(); } //Search for scopes that allow fetching team membership. This is documented online. //https://developer.github.com/v3/orgs/#list-your-organizations //https://developer.github.com/v3/orgs/teams/#list-user-teams if(this.userName.equals(user.getLogin()) && (myRealm.hasScope("read:org") || myRealm.hasScope("admin:org") || myRealm.hasScope("user") || myRealm.hasScope("repo"))) { //This allows us to search for private organization membership. orgs = getMyself().getAllOrganizations(); } else { //This searches for public organization membership. orgs = user.getOrganizations(); } for (GHOrganization ghOrganization : orgs) { String orgLogin = ghOrganization.getLogin(); LOGGER.log(Level.FINE, "Fetch teams for user " + user.getLogin() + " in organization " + orgLogin); groups.add(new GrantedAuthorityImpl(orgLogin)); try { if (!getMyself().isMemberOf(ghOrganization)) { continue; } Map<String, GHTeam> teams = ghOrganization.getTeams(); for (Map.Entry<String, GHTeam> entry : teams.entrySet()) { GHTeam team = entry.getValue(); if (team.hasMember(user)) { groups.add(new GrantedAuthorityImpl(orgLogin + GithubOAuthGroupDetails.ORG_TEAM_SEPARATOR + team)); } } } catch (IOException | Error ignore) { LOGGER.log(Level.FINEST, "not enough rights to list teams from " + orgLogin, ignore); } } } catch(IOException e) { LOGGER.log(Level.FINE, e.getMessage(), e); } return groups.toArray(new GrantedAuthority[groups.size()]); } }
[JENKINS-40201] Fix cached users breaking authz for GitHub organizations being used as a group in Jenkins. Fixed bug introduced by #64.
src/main/java/org/jenkinsci/plugins/GithubAuthenticationToken.java
[JENKINS-40201] Fix cached users breaking authz
<ide><path>rc/main/java/org/jenkinsci/plugins/GithubAuthenticationToken.java <ide> public GHUser loadUser(String username) throws IOException { <ide> GithubUser user; <ide> try { <del> user = usersByIdCache.get(username); <add> user = usersByIdCache.getIfPresent(username); <ide> if (gh != null && user == null && isAuthenticated()) { <ide> GHUser ghUser = getGitHub().getUser(username); <ide> user = new GithubUser(ghUser); <ide> usersByIdCache.put(username, user); <ide> } <del> } catch (IOException | ExecutionException e) { <add> } catch (IOException e) { <ide> LOGGER.log(Level.FINEST, e.getMessage(), e); <ide> user = UNKNOWN_USER; <ide> usersByIdCache.put(username, UNKNOWN_USER);
Java
mit
ddbbbfcfaa6edce54e11e1ac6b8f65fa252e20e2
0
mozack/abra2,mozack/abra2,mozack/abra2,mozack/abra2
package abra; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Manages threading * * @author Lisle E. Mose (lmose at unc dot edu) */ public class ThreadManager { private static final int MAX_PENDING = 100; private int numThreads; private List<AbraRunnable> threads = new ArrayList<AbraRunnable>(); private ExecutorService executor; public ThreadManager(int numThreads) { this.numThreads = numThreads; executor = Executors.newFixedThreadPool(numThreads); } public void spawnThread(AbraRunnable runnable) { try { waitForAvailableThread(); } catch (InterruptedException e) {} addThread(runnable); executor.submit(runnable); } private synchronized void addThread(AbraRunnable thread) { threads.add(thread); } public synchronized void removeThread(AbraRunnable thread) { threads.remove(thread); } private synchronized int activeThreads() { return threads.size(); } private void waitForAvailableThread() throws InterruptedException { while (activeThreads() >= MAX_PENDING) { Thread.sleep(50); } } public void waitForAllThreadsToComplete() throws InterruptedException, IOException { executor.shutdown(); while (!executor.awaitTermination(1, TimeUnit.SECONDS)) { Runtime runtime = Runtime.getRuntime(); Logger.info("Waiting on %d queued threads.\tmax_mem\t%d\ttotal_mem\t%d\tfree_mem\t%d", threads.size(), runtime.maxMemory()/1024, runtime.totalMemory()/1024, runtime.freeMemory()/1024); } } public int getNumThreads() { return numThreads; } }
src/main/java/abra/ThreadManager.java
package abra; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Manages threading * * @author Lisle E. Mose (lmose at unc dot edu) */ public class ThreadManager { private static final int MAX_PENDING = 100; private int numThreads; private List<AbraRunnable> threads = new ArrayList<AbraRunnable>(); private ExecutorService executor; public ThreadManager(int numThreads) { this.numThreads = numThreads; executor = Executors.newFixedThreadPool(numThreads); } public void spawnThread(AbraRunnable runnable) { try { waitForAvailableThread(); } catch (InterruptedException e) {} addThread(runnable); executor.submit(runnable); } private synchronized void addThread(AbraRunnable thread) { threads.add(thread); } public synchronized void removeThread(AbraRunnable thread) { threads.remove(thread); } private synchronized int activeThreads() { return threads.size(); } private void waitForAvailableThread() throws InterruptedException { while (activeThreads() >= MAX_PENDING) { Thread.sleep(50); } } public void waitForAllThreadsToComplete() throws InterruptedException, IOException { executor.shutdown(); while (!executor.awaitTermination(300, TimeUnit.SECONDS)) { Logger.info("Waiting on " + threads.size() + " queued threads."); } } public int getNumThreads() { return numThreads; } }
Record JVM memory stats.
src/main/java/abra/ThreadManager.java
Record JVM memory stats.
<ide><path>rc/main/java/abra/ThreadManager.java <ide> <ide> public void waitForAllThreadsToComplete() throws InterruptedException, IOException { <ide> executor.shutdown(); <del> while (!executor.awaitTermination(300, TimeUnit.SECONDS)) { <del> Logger.info("Waiting on " + threads.size() + " queued threads."); <add> while (!executor.awaitTermination(1, TimeUnit.SECONDS)) { <add> Runtime runtime = Runtime.getRuntime(); <add> <add> Logger.info("Waiting on %d queued threads.\tmax_mem\t%d\ttotal_mem\t%d\tfree_mem\t%d", threads.size(), <add> runtime.maxMemory()/1024, runtime.totalMemory()/1024, runtime.freeMemory()/1024); <ide> } <ide> } <ide>
JavaScript
apache-2.0
03b42868468cfef36c215ac8277b96e5457dce83
0
WisapeAgency/WisapeAndroid,WisapeAgency/WisapeAndroid,WisapeAgency/WisapeAndroid,WisapeAgency/WisapeAndroid,WisapeAgency/WisapeAndroid
var WisapeEditer = WisapeEditer || {}; WisapeEditer = { currentTplData : '<div class="stage-content edit-area pages-img" style="background: url(/mnt/sdcard/wisape/com.wisape.android/data/template/dddddddddddd/img/bg.jpg);background-size: 100% 100%;width:100%;height:100%;"> <div class="symbol" style="z-index: 2;"> <div class="pages-img edit-area"><img data-name="img1" style="" src="/mnt/sdcard/wisape/com.wisape.android/data/template/dddddddddddd/img/icon-earth.png"/> </div> </div> <div class="symbol" style="z-index: 3;"> <div class="pages-txt edit-area" style="margin:70px auto;width:150px;color:#fff;text-align: center;">As c update of the classictranslation corpus, the combination of network technology and language essence </div> </div> </div>', selectedStagetIndex : 1, stageData : [], storyData : [], initial : function(){ //获取模板分类 WisapeEditer.GetNativeData("getStageCategory", [],function(data){ var menuScroll = $("#menu-scroll"); console.info("getStageCategory"); console.info(JSON.stringify(data)); var source = '<ul class="tabcon-item">' + '{{each list as value i}}' + '<li class="tabnav-item" data-id="{{value.id}}"> {{value.name}} </li>' + '{{/each}}' + '</ul>'; var render = template.compile(source); var html = render({ list: data }); document.getElementById('menu-scroll').innerHTML = html; menuScroll.iScroll( { eventPassthrough: true,scrollX: true, scrollY: false, preventDefault: false }); //获取默认模板模板列表 console.info("获取默认模板模板列表:" + parseInt(menuScroll.find("li").data("id"))); WisapeEditer.LoadTplList(parseInt(menuScroll.find("li").data("id"))); menuScroll.find("li").eq(0).addClass("active"); //默认加载的stage,需入口传递 WisapeEditer.storyData.push(WisapeEditer.currentTplData); }); }, event : function(){ //模板分类事件 var menuScroll = $("#menu-scroll"); console.info("menu-scroll length:" + menuScroll.length); menuScroll.delegate("li","click",function(){ var _me = $(this); console.info("menu-scroll click"); console.info("id:" + _me.data("id")); _me.addClass("active").siblings().removeClass("active"); WisapeEditer.LoadTplList(parseInt(_me.data("id"))); }); //显示隐藏分类 $("#toggleCat").click(function(){ $(".tpl-page-cat").toggle(); }) //模板列表事件 var catScroll = $("#cat-scroll"); catScroll.delegate("li","click",function() { var _me = $(this); _me.addClass("active").siblings().removeClass("active"); console.info(!_me.hasClass("tpl-exist")); //if (!_me.hasClass("tpl-exist")) { console.info("down"); WisapeEditer.GetNativeData("start", [parseInt(_me.data("id")), parseInt(_me.data("type"))], function (data) { console.info("down data:"); console.info(data); _me.removeClass("tpl-exist"); }); //} else { console.info("read:"); WisapeEditer.GetNativeData("read", ["/mnt/sdcard/wisape/com.wisape.android/data/template/" + _me.data("name") + "/stage.html"], function (data) { console.info("read data:"); console.info(data); WisapeEditer.currentTplData = data; pageScroll.find("ul li.active").html(data); WisapeEditer.storyData[WisapeEditer.selectedStagetIndex-1] = data; }); //} }); //stage列表事件 var pageScroll = $("#pages-scroll"); pageScroll.delegate("li","click",function(){ var _me = $(this); WisapeEditer.selectedStagetIndex = _me.index()+1; _me.addClass("active").siblings().removeClass("active").find(".pages-img,.pages-txt").removeClass("active"); }); pageScroll.delegate("li.active .pages-img ","click",function(event){ var _me = $(this); if(!_me.hasClass("active")) { console.info(pageScroll.find(".edit-area").length); pageScroll.find(".edit-area").removeClass("active"); _me.addClass("active"); if(_me.find(".ico-acitve").length == 0) _me.append('<i class="ico-acitve"></i>'); return false; } WisapeEditer.ShowView('main','editorImage'); cordova.exec(function(retval) { console.info("PhotoSelector:" + retval); }, function(e) { alert("Error: "+e); }, "PhotoSelector", "execute", "action"); event.stopPropagation(); }); function startPhotoSelector(url, opts, className){ cordova.exec(function(url) { console.log("Image URL:" + url); var imgID = new Image(); imgID.src=url; imgID.onload = function(){ document.getElementById("img_logo").innerHTML = "<img src="+imgID.src+" />"; } }, function(e) {console.log("Error: "+e);}, "PhotoSelector", "story", [className, url, opts || {}]); }; pageScroll.delegate("li.active .pages-txt ","click",function(event){ var _me = $(this); if(!_me.hasClass("active")) { console.info(pageScroll.find(".edit-area").length); pageScroll.find(".edit-area").removeClass("active"); _me.addClass("active"); return false; }; WisapeEditer.UpdateSelectedStage(WisapeEditer.selectedStagetIndex,_me.parents(".stage-content").find(".symbol.active").index()); WisapeEditer.ShowView('main','editorText'); event.stopPropagation(); }); //新建stage事件 var AddNewStage = $("#AddNewStage"); AddNewStage.click(function(){ var target = pageScroll.find("li.active"), pageScrollLi = pageScroll.find("li"); if(pageScrollLi.length > 0 ){ pageScroll.find("li").removeClass("active").find(".pages-img,.pages-txt").removeClass("active"); target.after('<li class="active">' + WisapeEditer.currentTplData + '</li>'); } else { target.find("ul").html('<li class="active">' + WisapeEditer.currentTplData + '</li>'); } WisapeEditer.selectedStagetIndex++; pageScroll.iScroll( {scrollX: true, scrollY: false, preventDefault: false }); }) //文本编辑事件 $("#editorText .backToMain").click(function(){//返回主界面,并保存 var pagesScroll = $("#pages-scroll li").eq(WisapeEditer.selectedStagetIndex-1); var eidtPage = $("#editorText .pages"); eidtPage.find(".pages-txt").removeAttr("contenteditable"); pagesScroll.html( eidtPage.html()); WisapeEditer.ShowView('editorText','main'); if($("#TextEditerOpt").hasClass("active")) { $("#TextEditerOpt").click(); } $(".pop-editer-opt i,.pop-editer-animation i").removeClass("active"); $(".input-href").val("http://"); }) $("#TextEditerOpt").click(function(){ var me = $(this); var parent = $("#editorText"); var target = $("#editorText .pop-editer-opt"); if(me.hasClass("active")) { me.removeClass("active"); parent.removeClass("pop-active"); target.hide(); } else { me.addClass("active"); parent.addClass("pop-active"); target.show(); } }); $("#setFontWeight").click(function(){ var me = $(this); var target = $("#editorText .pages-txt.active"); if(me.hasClass("active")) { me.removeClass("active"); target.css({"font-weight":"normal"}); } else { me.addClass("active"); target.css({"font-weight":"bolder"}) } console.info(target.attr("style")); }); $("#setFontStyle").click(function(){ var me = $(this); var target = $("#editorText .pages-txt.active"); if(me.hasClass("active")) { me.removeClass("active"); target.css({"font-style":"normal"}) } else { me.addClass("active"); target.css({"font-style":"italic"}) } }); $("#setFontLink").click(function(){ var me = $(this); var target = $("#editorText .pages-txt.active"); var tmpText = target.text(); var mask = $(".ui-mask"); var link = ""; var hrefDialog = $(".href-dialog"); if(me.hasClass("active")) { me.removeClass("active"); hrefDialog.find(".input-href input").val("http://"); target.html(tmpText); } else { mask.show(); hrefDialog.show(); hrefDialog.find(".btn-cancle").click(function(){ mask.hide(); hrefDialog.hide(); }); hrefDialog.find(".btn-submit").click(function(){ link = hrefDialog.find(".input-href input").val(); mask.hide(); hrefDialog.hide(); if(link == "http://" || link == "") return false; me.addClass("active"); target.html("<a href='" + link + "'>" + tmpText +"</a>"); }); } }); $("#setFontAlign").click(function($event){ var me = $(this); var target = $("#editorText .pages-txt.active"); if(me.hasClass("icon-align-left")) { me.removeClass("icon-align-left").addClass("icon-align-center"); target.css({"text-align":"center"}); } else if(me.hasClass("icon-align-center")) { me.removeClass("icon-align-center").addClass("icon-align-right"); target.css({"text-align":"right"}); } else if(me.hasClass("icon-align-right")) { me.removeClass("icon-align-right").addClass("icon-align-left"); target.css({"text-align":"left"}); } }); $(".pop-editer-opt .item").click(function(){ var popLayers = $("#editorText .pop-layer"); var me = $(this); popLayers.hide().parent().find("."+me.data("name")).show(); }); $(".backPopLayerOpt").click(function(){ var popLayers = $("#editorText .pop-layer"); popLayers.hide().parent().find(".pop-editer-opt").show(); }); //动画事件 $(".pop-editer-animation .anim-item").click(function(){ var me = $(this).find("i"); if(me.hasClass("active")) { me.removeClass("active") } else { me.addClass("active"); me.parent().siblings().find("i").removeClass("active"); } }) }, //加载模板列表 LoadTplList : function(id){ WisapeEditer.GetNativeData("getStageList", [id],function(data){ console.info("getStageList"); console.info(JSON.stringify(data)); var catScroll = $("#cat-scroll"); var source = '<ul class="tpl-page-item">' + '{{each list as value i}}' + '<li class="tpl-page-item {{if value.exists}}tpl-exist{{/if}}" data-id="{{value.id}}" data-exists="{{value.exists}}" data-type="{{value.type}}" data-name="{{value.temp_name}}">' + '<i style="display: none" class="icon-tags-hot"></i>' + '{{if !value.exists}} <span class="icon-download"></span> {{/if}}<div style="display:none;" class="download-progress-bar"><div class="download-progress-percent"></div></div>' + '<img class="stage-thumb" src="{{value.temp_img_local}}" alt="{{value.temp_name}}"/>' + '<div class="tpl-page-item-name">{{value.temp_name}}</div>' + ' </li>' + '{{/each}}' + '</ul>'; var render = template.compile(source); var html = render({ list: JSON.parse(data) }); document.getElementById('cat-scroll').innerHTML = html; catScroll.iScroll( { eventPassthrough: true,scrollX: true, scrollY: false, preventDefault: false }); catScroll.find("li").eq(0).addClass("active"); }); }, //加载,更新stages LoadStage : function(){ }, //更新选中的主界面的stage UpdateSelectedStage : function(tplIndex,symbolInex){ var pagesScroll = $("#pages-scroll li").eq(tplIndex-1); var eidtPage = $("#editorText .pages"); var curPagesTxt = eidtPage.find(".symbol").eq(symbolInex).find(".pages-txt"); console.info("symbolInex:" + eidtPage.find(".symbol").eq(symbolInex).html()); eidtPage.html(pagesScroll.html()).find(".symbol").eq(symbolInex).addClass("active").find(".pages-txt").attr({"contenteditable":"true"}); //初始化编辑菜单 eidtPage.find(".opt-val-color").css({"color":curPagesTxt.css("color")}); }, //加载stagelist的stages LoadStageList : function(){}, //生成发布,保存的story GenerateStory : function(){}, ShowView : function(from,to){ console.info(from + " to " + to); $("#" + from).hide(); $("#" + to).show(); }, GetNativeData : function(fn,params,cb){ cordova.exec(function(retval) { console.info(fn + "exec: " + retval); cb(retval); }, function(e) { console.info(fn + " Error: "+e); }, "StoryTemplate", fn, params); console.info("fn:" + fn); console.info("params:"); console.info(params); } }; var browser = { versions : function() { var u = navigator.userAgent, app = navigator.appVersion; return {//移动终端浏览器版本信息 trident : u.indexOf('Trident') > -1, //IE内核 presto : u.indexOf('Presto') > -1, //opera内核 webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 mobile : !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端 ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp : u.indexOf('Safari') == -1,//是否web应该程序,没有头部与底部 google:u.indexOf('Chrome')>-1 }; }(), language : (navigator.browserLanguage || navigator.language).toLowerCase() };
app/src/main/assets/www/public/js/app-main.js
var WisapeEditer = WisapeEditer || {}; WisapeEditer = { currentTplData : '<div class="stage-content edit-area pages-img" style="background: url(/mnt/sdcard/wisape/com.wisape.android/data/template/dddddddddddd/img/bg.jpg);background-size: 100% 100%;width:100%;height:100%;"> <div class="symbol" style="z-index: 2;"> <div class="pages-img edit-area"><img data-name="img1" style="" src="/mnt/sdcard/wisape/com.wisape.android/data/template/dddddddddddd/img/icon-earth.png"/> </div> </div> <div class="symbol" style="z-index: 3;"> <div class="pages-txt edit-area" style="margin:70px auto;width:150px;color:#fff;text-align: center;">As c update of the classictranslation corpus, the combination of network technology and language essence </div> </div> </div>', selectedStagetIndex : 1, stageData : [], storyData : [], initial : function(){ //获取模板分类 WisapeEditer.GetNativeData("getStageCategory", [],function(data){ var menuScroll = $("#menu-scroll"); console.info("getStageCategory"); console.info(JSON.stringify(data)); var source = '<ul class="tabcon-item">' + '{{each list as value i}}' + '<li class="tabnav-item" data-id="{{value.id}}"> {{value.name}} </li>' + '{{/each}}' + '</ul>'; var render = template.compile(source); var html = render({ list: data }); document.getElementById('menu-scroll').innerHTML = html; menuScroll.iScroll( { eventPassthrough: true,scrollX: true, scrollY: false, preventDefault: false }); //获取默认模板模板列表 console.info("获取默认模板模板列表:" + parseInt(menuScroll.find("li").data("id"))); WisapeEditer.LoadTplList(parseInt(menuScroll.find("li").data("id"))); menuScroll.find("li").eq(0).addClass("active"); //默认加载的stage,需入口传递 WisapeEditer.storyData.push(WisapeEditer.currentTplData); }); }, event : function(){ //模板分类事件 var menuScroll = $("#menu-scroll"); console.info("menu-scroll length:" + menuScroll.length); menuScroll.delegate("li","click",function(){ var _me = $(this); console.info("menu-scroll click"); console.info("id:" + _me.data("id")); _me.addClass("active").siblings().removeClass("active"); WisapeEditer.LoadTplList(parseInt(_me.data("id"))); }); //显示隐藏分类 $("#toggleCat").click(function(){ $(".tpl-page-cat").toggle(); }) //模板列表事件 var catScroll = $("#cat-scroll"); catScroll.delegate("li","click",function() { var _me = $(this); _me.addClass("active").siblings().removeClass("active"); console.info(!_me.hasClass("tpl-exist")); //if (!_me.hasClass("tpl-exist")) { console.info("down"); WisapeEditer.GetNativeData("start", [parseInt(_me.data("id")), parseInt(_me.data("type"))], function (data) { console.info("down data:"); console.info(data); _me.removeClass("tpl-exist"); }); //} else { console.info("read:"); WisapeEditer.GetNativeData("read", ["/mnt/sdcard/wisape/com.wisape.android/data/template/" + _me.data("name") + "/stage.html"], function (data) { console.info("read data:"); console.info(data); WisapeEditer.currentTplData = data; pageScroll.find("ul li.active").html(data); WisapeEditer.storyData[WisapeEditer.selectedStagetIndex-1] = data; }); //} }); //stage列表事件 var pageScroll = $("#pages-scroll"); pageScroll.delegate("li","click",function(){ var _me = $(this); WisapeEditer.selectedStagetIndex = _me.index()+1; _me.addClass("active").siblings().removeClass("active").find(".pages-img,.pages-txt").removeClass("active"); }); pageScroll.delegate("li.active .pages-img ","click",function(event){ var _me = $(this); if(!_me.hasClass("active")) { console.info(pageScroll.find(".edit-area").length); pageScroll.find(".edit-area").removeClass("active"); _me.addClass("active"); if(_me.find(".ico-acitve").length == 0) _me.append('<i class="ico-acitve"></i>'); return false; } WisapeEditer.ShowView('main','editorImage'); cordova.exec(function(retval) { console.info("PhotoSelector:" + retval); }, function(e) { alert("Error: "+e); }, "PhotoSelector", "execute", "action"); event.stopPropagation(); }); function startPhotoSelector(url, opts, className){ cordova.exec(function(url) { console.log("Image URL:" + url); var imgID = new Image(); imgID.src=url; imgID.onload = function(){ document.getElementById("img_logo").innerHTML = "<img src="+imgID.src+" />"; } }, function(e) {console.log("Error: "+e);}, "PhotoSelector", "story", [className, url, opts || {}]); }; pageScroll.delegate("li.active .pages-txt ","click",function(event){ var _me = $(this); if(!_me.hasClass("active")) { console.info(pageScroll.find(".edit-area").length); pageScroll.find(".edit-area").removeClass("active"); _me.addClass("active"); return false; }; WisapeEditer.UpdateSelectedStage(WisapeEditer.selectedStagetIndex,_me.parents(".stage-content").find(".symbol.active").index()); WisapeEditer.ShowView('main','editorText'); event.stopPropagation(); }); //新建stage事件 var AddNewStage = $("#AddNewStage"); AddNewStage.click(function(){ var target = pageScroll.find("li.active"), pageScrollLi = pageScroll.find("li"); if(pageScrollLi.length > 0 ){ pageScroll.find("li").removeClass("active").find(".pages-img,.pages-txt").removeClass("active"); target.after('<li class="active">' + WisapeEditer.currentTplData + '</li>'); } else { target.find("ul").html('<li class="active">' + WisapeEditer.currentTplData + '</li>'); } WisapeEditer.selectedStagetIndex++; pageScroll.iScroll( {scrollX: true, scrollY: false, preventDefault: false }); }) //文本编辑事件 $("#editorText .backToMain").click(function(){//返回主界面,并保存 var pagesScroll = $("#pages-scroll li").eq(WisapeEditer.selectedStagetIndex-1); var eidtPage = $("#editorText .pages"); eidtPage.find(".pages-txt").removeAttr("contenteditable"); pagesScroll.html( eidtPage.html()); WisapeEditer.ShowView('editorText','main'); if($("#TextEditerOpt").hasClass("active")) { $("#TextEditerOpt").click(); } $(".pop-editer-opt i,.pop-editer-animation i").removeClass("active"); $(".input-href").val("http://"); }) $("#TextEditerOpt").click(function(){ var me = $(this); var parent = $("#editorText"); var target = $("#editorText .pop-editer-opt"); if(me.hasClass("active")) { me.removeClass("active"); parent.removeClass("pop-active"); target.hide(); } else { me.addClass("active"); parent.addClass("pop-active"); target.show(); } }); $("#setFontWeight").click(function(){ var me = $(this); var target = $("#editorText .pages-txt.active"); if(me.hasClass("active")) { me.removeClass("active"); target.css({"font-weight":"normal"}); } else { me.addClass("active"); target.css({"font-weight":"bolder"}) } console.info(target.attr("style")); }); $("#setFontStyle").click(function(){ var me = $(this); var target = $("#editorText .pages-txt.active"); if(me.hasClass("active")) { me.removeClass("active"); target.css({"font-style":"normal"}) } else { me.addClass("active"); target.css({"font-style":"italic"}) } }); $("#setFontLink").click(function(){ var me = $(this); var target = $("#editorText .pages-txt.active"); var tmpText = target.text(); var mask = $(".ui-mask"); var link = ""; var hrefDialog = $(".href-dialog"); if(me.hasClass("active")) { me.removeClass("active"); hrefDialog.find(".input-href input").val("http://"); target.html(tmpText); } else { mask.show(); hrefDialog.show(); hrefDialog.find(".btn-cancle").click(function(){ mask.hide(); hrefDialog.hide(); }); hrefDialog.find(".btn-submit").click(function(){ link = hrefDialog.find(".input-href input").val(); mask.hide(); hrefDialog.hide(); if(link == "http://" || link == "") return false; me.addClass("active"); target.html("<a href='" + link + "'>" + tmpText +"</a>"); }); } }); $("#setFontAlign").click(function($event){ var me = $(this); var target = $("#editorText .pages-txt.active"); if(me.hasClass("icon-align-left")) { me.removeClass("icon-align-left").addClass("icon-align-center"); target.css({"text-align":"center"}); } else if(me.hasClass("icon-align-center")) { me.removeClass("icon-align-center").addClass("icon-align-right"); target.css({"text-align":"right"}); } else if(me.hasClass("icon-align-right")) { me.removeClass("icon-align-right").addClass("icon-align-left"); target.css({"text-align":"left"}); } }); $(".pop-editer-opt .item").click(function(){ var popLayers = $("#editorText .pop-layer"); var me = $(this); popLayers.hide().parent().find("."+me.data("name")).show(); }); $(".backPopLayerOpt").click(function(){ var popLayers = $("#editorText .pop-layer"); popLayers.hide().parent().find(".pop-editer-opt").show(); }); //动画事件 $(".pop-editer-animation .anim-item").click(function(){ var me = $(this).find("i"); if(me.hasClass("active")) { me.removeClass("active") } else { me.addClass("active"); me.parent().siblings().find("i").removeClass("active"); } }) }, //加载模板列表 LoadTplList : function(id){ WisapeEditer.GetNativeData("getStageList", [id],function(data){ console.info("getStageList"); console.info(JSON.stringify(data)); var catScroll = $("#cat-scroll"); var source = '<ul class="tpl-page-item">' + '{{each list as value i}}' + '<li class="tpl-page-item {{if value.exists}}tpl-exist{{/if}}" data-id="{{value.id}}" data-exists="{{value.exists}}" data-type="{{value.type}}" data-name="{{value.temp_name}}">' + '<i style="display: none" class="icon-tags-hot"></i>' + '{{if !value.exists}} <span class="icon-download"></span> {{/if}}<div style="display:none;" class="download-progress-bar"><div class="download-progress-percent"></div></div>' + '<img class="stage-thumb" src="{{value.temp_img_local}}" alt="{{value.temp_name}}"/>' + '<div class="tpl-page-item-name">{{value.temp_name}}</div>' + ' </li>' + '{{/each}}' + '</ul>'; var render = template.compile(source); var html = render({ list: JSON.parse(data) }); document.getElementById('cat-scroll').innerHTML = html; catScroll.iScroll( { eventPassthrough: true,scrollX: true, scrollY: false, preventDefault: false }); catScroll.find("li").eq(0).addClass("active"); }); }, //加载,更新stages LoadStage : function(){ }, //更新选中的主界面的stage UpdateSelectedStage : function(tplIndex,symbolInex){ var pagesScroll = $("#pages-scroll li").eq(tplIndex-1); var eidtPage = $("#editorText .pages"); var curPagesTxt = eidtPage.find(".symbol").eq(symbolInex).find(".pages-txt"); console.info("symbolInex:" + eidtPage.find(".symbol").eq(symbolInex).html()); eidtPage.html(pagesScroll.html()).find(".symbol").eq(symbolInex).addClass("active").find(".pages-txt").attr({"contenteditable":"true"}); //初始化编辑菜单 eidtPage.find(".opt-val-color").css({"color":curPagesTxt.css("color")}); }, //加载stagelist的stages LoadStageList : function(){}, //生成发布,保存的story GenerateStory : function(){}, ShowView : function(from,to){ console.info(from + " to " + to); $("#" + from).hide(); $("#" + to).show(); }, GetNativeData : function(fn,params,cb){ cordova.exec(function(retval) { console.info(fn + "exec: " + retval); cb(retval); }, function(e) { console.info(fn + " Error: "+e); }, "StoryTemplate", fn, params); console.info("fn:" + fn); console.info("params:"); console.info(params); } }; var browser = { versions : function() { var u = navigator.userAgent, app = navigator.appVersion; return {//移动终端浏览器版本信息 trident : u.indexOf('Trident') > -1, //IE内核 presto : u.indexOf('Presto') > -1, //opera内核 webKit : u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核 mobile : !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端 ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp : u.indexOf('Safari') == -1,//是否web应该程序,没有头部与底部 google:u.indexOf('Chrome')>-1 }; }(), language : (navigator.browserLanguage || navigator.language).toLowerCase() };
img cut
app/src/main/assets/www/public/js/app-main.js
img cut
<ide><path>pp/src/main/assets/www/public/js/app-main.js <ide> //初始化编辑菜单 <ide> eidtPage.find(".opt-val-color").css({"color":curPagesTxt.css("color")}); <ide> }, <del> <ide> <ide> //加载stagelist的stages <ide> LoadStageList : function(){},
JavaScript
apache-2.0
47d9dc65a6d486320ac93294d0001d3c89e66aff
0
mattlo/assets-to-pdf
var sizeOf = require('image-size'), Q = require('q'), http = require('http'), exec = require('child_process').exec, fs = require('fs'), path = require('path'), Base62 = require('base62'), port = 8080; // spawn server http.createServer(function (req, res) { // argument stream: /fetch/filename hash/file name to download as var pdfExp = /^\/fetch\/(.*)\/(.*)/; // resolve route if (req.url === '/create-pdf') { // request validation validateRequest(req) // parse body stream and convert to JSON .then(getJsonRequestBody) // prepare files and merge .then(responseHandler(req, res)) // success handler .then(function (data) { outputResponse(res, 200, { url: 'http://' + req.headers.host + '/fetch/' + data.hash + '/' + encodeURIComponent(data.name) }); }) // fail handler .catch(function (e) { outputResponse(res, 500, {data: e.toString()}); }); } else if (pdfExp.test(req.url)) { // get path and stream out data pdfExists(req.url.match(pdfExp)[1]) .then(function (path) { // get file stat var stat = fs.statSync(path); // headers res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Length': stat.size, // force download the file 'Content-Disposition': 'attachment; filename="' + (req.url.match(pdfExp)[2]) + '.pdf"' }); // stream out file fs.createReadStream(path).pipe(res); }) .catch(function (e) { outputResponse(res, 500, {data: e.toString()}); }); } else { outputResponse(res, 404, {data: 'page does not exist'}); } }).listen(port, '0.0.0.0'); /** * Validates PDF * @todo probably overkill to use a defer for this, but I may need to do additional checks * in the future if files are off loaded to external server * @param {String} fileName * @return {Object} promise */ function pdfExists(fileName) { var deferred = Q.defer(), // construct path filePath = path.join(__dirname, 'output', fileName + '.pdf'); try { // check if file exists if (!fs.existsSync(filePath)) { throw new Error('PDF does not exist'); } deferred.resolve(filePath); } catch (e) { deferred.reject(e); } return deferred.promise; } /** * Outputs HTTP response * @param {Object} res * @param {Number} status * @param {Object} data * @return {undefined} */ function outputResponse(res, status, data) { res.writeHead(status, { 'Content-Type': 'application/json' }); // resolve to provided response, if non provide generic res.end(JSON.stringify(data || {'data': 'OK'})); } /** * Validates Request * @param {Object} req * @return {Object} */ function validateRequest(req) { var deferred = Q.defer(); try { // post check if (req.method !== 'POST') { throw new Error('HTTP method must be a POST'); } deferred.resolve(req); } catch (e) { deferred.reject(e); } return deferred.promise; } /** * Parses raw body stream into JSON * @param {Object} req * @return {Function} */ function getJsonRequestBody(req) { var deferred = Q.defer(); var responseBody = ''; req.on('data', function (data) { responseBody += data; }); req.on('end', function () { deferred.resolve(JSON.parse(responseBody)); }); return deferred.promise; } /** * Handles executing PDF actions * @param {Object} req * @param {Object} res * @return {Function} */ function responseHandler(req, res) { return function (data) { return prepareFiles(data.inputFiles) .then(mergePdfs) .then(function (hash) { return { "name": data.uniquePkgName, "hash": hash } }); }; } /** * Execute PhantomJS to PDF service * Arguments are forwarded onto execution args * * @return {Object} promise */ function phantom() { var deferred = Q.defer(); exec(['phantomjs', __dirname + '/rasterize.js'].concat([].slice.call(arguments)).join(' '), function (err) { // error handler if (err) { console.log('endpoint failed to translate to PDF'); deferred.reject(err); } deferred.resolve(arguments[0]); // return output path }); return deferred.promise; } /** * Translates all files to individual PDFs then moves them to `tmp` * @todo abstract out PDFer and let this resolve moving files * @param {Array} files * @return {Object} promise */ function prepareFiles(files) { var deferred = Q.defer(), preparedFiles = [], n = 0; console.log('...preparing files for normalization'); function basename(file) { return file.substr(0, file.lastIndexOf('.')); } function isPdf(file) { return file.substr(-4) === '.pdf'; } function isHttpProtocol(file) { return file.substr(0, 7) === 'http://' || file.substr(0, 8) === 'https://'; } function resolve(inputPath) { preparedFiles.push(inputPath); if (preparedFiles.length === files.length) { deferred.resolve(preparedFiles); } } files.every(function (file) { // PDF a website if (isHttpProtocol(file)) { var ouputFilename = 'fieldnote.pdf'; phantom(file, ouputFilename, '2000px*3000px').then(function () { resolve(ouputFilename); }); // if its a PDF, skip it // we are assuming all input files are JPG or PNG } else if (!isPdf(file)) { // configurations var sourcePath = __dirname + '/input/' + file, outputBase = __dirname + '/tmp/' + basename(file), size = sizeOf(sourcePath), xAxisLarger = size.width > size.height, scale = 2000, aspectRatio = xAxisLarger ? (size.width / size.height) : (size.height / size.width), errorPx = 5, width = (xAxisLarger ? scale : scale / aspectRatio) + errorPx, height = (xAxisLarger ? scale / aspectRatio : scale) + errorPx; // validate path if (!fs.existsSync(sourcePath)) { deferred.reject(sourcePath + ' does not exist!'); // break loop return false; } // create PDF phantom(sourcePath, outputBase + '.pdf', width +'px*' + height + 'px').then(function () { exec(['pdftk', outputBase + '.pdf', 'cat', '1-1', 'output', outputBase + 'x.pdf'].join (' '), function (err) { // ignore errors for this one, pdftk will fail if there isn't 2 pages if (err) { resolve(outputBase + '.pdf'); } else { resolve(outputBase + 'x.pdf'); fs.unlinkSync(outputBase + '.pdf'); } }); }); } else { // copy it to tmp directory fs.createReadStream(__dirname + '/input/' + file) .pipe(fs.createWriteStream(__dirname + '/tmp/' + file)); resolve(__dirname + '/tmp/' + file); } // continuation of the loop return true; }); return deferred.promise; } /** * Merges PDFs into a single PDF from given list * @param {Array} pdfList * @return {Object} promise */ function mergePdfs(pdfList) { var deferred = Q.defer(), fileName = Base62.encode((new Date).getTime()), outputFile = __dirname + '/output/' + fileName + '.pdf'; console.log('preparing to merge PDFs') pdfList.forEach(function (sourcePath) { if (!fs.existsSync(sourcePath)) { console.log('... ' + sourcePath + ' does not exist!'); } else { console.log('... ' + sourcePath + ' exists!'); } }); // merge PDFs exec(['pdftk', pdfList.join(' '), 'cat', 'output', outputFile].join(' '), function (err) { if (err) { console.log(''); console.log(err); deferred.reject(err); } else { // removes files in tmp pdfList.forEach(function (file) { fs.unlinkSync(file); }); console.log('...PDFs merged: ' + outputFile); // return hash deferred.resolve(fileName); } }); return deferred.promise; }
src/main.js
var sizeOf = require('image-size'), Q = require('q'), http = require('http'), exec = require('child_process').exec, fs = require('fs'), path = require('path'), Base62 = require('base62'), port = 8080; // spawn server http.createServer(function (req, res) { // argument stream: /fetch/filename hash/file name to download as var pdfExp = /^\/fetch\/(.*)\/(.*)/; // resolve route if (req.url === '/create-pdf') { // request validation validateRequest(req) // parse body stream and convert to JSON .then(getJsonRequestBody) // prepare files and merge .then(responseHandler(req, res)) // success handler .then(function (data) { outputResponse(res, 200, { url: 'http://' + req.headers.host + '/fetch/' + data.hash + '/' + encodeURIComponent(data.name) }); }) // fail handler .catch(function (e) { outputResponse(res, 500, {data: e.toString()}); }); } else if (pdfExp.test(req.url)) { // get path and stream out data pdfExists(req.url.match(pdfExp)[1]) .then(function (path) { // get file stat var stat = fs.statSync(path); // headers res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Length': stat.size, // force download the file 'Content-Disposition': 'attachment; filename="' + (req.url.match(pdfExp)[2]) + '.pdf"' }); // stream out file fs.createReadStream(path).pipe(res); }) .catch(function (e) { outputResponse(res, 500, {data: e.toString()}); }); } else { outputResponse(res, 404, {data: 'page does not exist'}); } }).listen(port, '0.0.0.0'); /** * Validates PDF * @todo probably overkill to use a defer for this, but I may need to do additional checks * in the future if files are off loaded to external server * @param {String} fileName * @return {Object} promise */ function pdfExists(fileName) { var deferred = Q.defer(), // construct path filePath = path.join(__dirname, 'output', fileName + '.pdf'); try { // check if file exists if (!fs.existsSync(filePath)) { throw new Error('PDF does not exist'); } deferred.resolve(filePath); } catch (e) { deferred.reject(e); } return deferred.promise; } /** * Outputs HTTP response * @param {Object} res * @param {Number} status * @param {Object} data * @return {undefined} */ function outputResponse(res, status, data) { res.writeHead(status, { 'Content-Type': 'application/json' }); // resolve to provided response, if non provide generic res.end(JSON.stringify(data || {'data': 'OK'})); } /** * Validates Request * @param {Object} req * @return {Object} */ function validateRequest(req) { var deferred = Q.defer(); try { // post check if (req.method !== 'POST') { throw new Error('HTTP method must be a POST'); } deferred.resolve(req); } catch (e) { deferred.reject(e); } return deferred.promise; } /** * Parses raw body stream into JSON * @param {Object} req * @return {Function} */ function getJsonRequestBody(req) { var deferred = Q.defer(); var responseBody = ''; req.on('data', function (data) { responseBody += data; }); req.on('end', function () { deferred.resolve(JSON.parse(responseBody)); }); return deferred.promise; } /** * Handles executing PDF actions * @param {Object} req * @param {Object} res * @return {Function} */ function responseHandler(req, res) { return function (data) { return prepareFiles(data.inputFiles) .then(mergePdfs) .then(function (hash) { return { "name": data.uniquePkgName, "hash": hash } }); }; } /** * Translates all files to individual PDFs then moves them to `tmp` * @todo abstract out PDFer and let this resolve moving files * @param {Array} files * @return {Object} promise */ function prepareFiles(files) { var deferred = Q.defer(), preparedFiles = [], n = 0; console.log('...preparing files for normalization'); function basename(file) { return file.substr(0, file.lastIndexOf('.')); } function isPdf(file) { return file.substr(-4) === '.pdf'; } function resolve(inputPath) { preparedFiles.push(inputPath); if (preparedFiles.length === files.length) { deferred.resolve(preparedFiles); } } files.every(function (file) { // if its a PDF, skip it // we are assuming all input files are JPG or PNG if (!isPdf(file)) { // configurations var sourcePath = __dirname + '/input/' + file, outputBase = __dirname + '/tmp/' + basename(file), size = sizeOf(sourcePath), xAxisLarger = size.width > size.height, scale = 2000, aspectRatio = xAxisLarger ? (size.width / size.height) : (size.height / size.width), errorPx = 5, width = (xAxisLarger ? scale : scale / aspectRatio) + errorPx, height = (xAxisLarger ? scale / aspectRatio : scale) + errorPx; // validate path if (!fs.existsSync(sourcePath)) { deferred.reject(sourcePath + ' does not exist!'); // break loop return false; } // create PDF // @TODO abstract out all these commands into promises exec(['phantomjs', __dirname + '/rasterize.js', sourcePath, outputBase + '.pdf', width +'px*' + height + 'px'].join(' '), function (err) { // error handler if (err) { console.log('file failed to translate to PDF'); deferred.reject(err); } // remove second page exec(['pdftk', outputBase + '.pdf', 'cat', '1-1', 'output', outputBase + 'x.pdf'].join (' '), function (err) { // ignore errors for this one, pdftk will fail if there isn't 2 pages if (err) { resolve(outputBase + '.pdf'); } else { resolve(outputBase + 'x.pdf'); fs.unlinkSync(outputBase + '.pdf'); } }); }); } else { // copy it to tmp directory fs.createReadStream(__dirname + '/input/' + file) .pipe(fs.createWriteStream(__dirname + '/tmp/' + file)); resolve( __dirname + '/tmp/' + file); } // continuation of the loop return true; }); return deferred.promise; } /** * Merges PDFs into a single PDF from given list * @param {Array} pdfList * @return {Object} promise */ function mergePdfs(pdfList) { var deferred = Q.defer(), fileName = Base62.encode((new Date).getTime()), outputFile = __dirname + '/output/' + fileName + '.pdf'; console.log('preparing to merge PDFs') pdfList.forEach(function (sourcePath) { if (!fs.existsSync(sourcePath)) { console.log('... ' + sourcePath + ' does not exist!'); } else { console.log('... ' + sourcePath + ' exists!'); } }); // merge PDFs exec(['pdftk', pdfList.join(' '), 'cat', 'output', outputFile].join(' '), function (err) { if (err) { console.log(''); console.log(err); deferred.reject(err); } else { // removes files in tmp pdfList.forEach(function (file) { fs.unlinkSync(file); }); console.log('...PDFs merged: ' + outputFile); // return hash deferred.resolve(fileName); } }); return deferred.promise; }
added webpage support
src/main.js
added webpage support
<ide><path>rc/main.js <ide> } <ide> <ide> /** <add> * Execute PhantomJS to PDF service <add> * Arguments are forwarded onto execution args <add> * <add> * @return {Object} promise <add> */ <add>function phantom() { <add> var deferred = Q.defer(); <add> <add> exec(['phantomjs', __dirname + '/rasterize.js'].concat([].slice.call(arguments)).join(' '), function (err) { <add> // error handler <add> if (err) { <add> console.log('endpoint failed to translate to PDF'); <add> deferred.reject(err); <add> } <add> <add> deferred.resolve(arguments[0]); // return output path <add> }); <add> <add> return deferred.promise; <add>} <add> <add>/** <ide> * Translates all files to individual PDFs then moves them to `tmp` <ide> * @todo abstract out PDFer and let this resolve moving files <ide> * @param {Array} files <ide> return file.substr(-4) === '.pdf'; <ide> } <ide> <add> function isHttpProtocol(file) { <add> return file.substr(0, 7) === 'http://' || file.substr(0, 8) === 'https://'; <add> } <add> <ide> function resolve(inputPath) { <ide> preparedFiles.push(inputPath); <ide> <ide> } <ide> <ide> files.every(function (file) { <add> // PDF a website <add> if (isHttpProtocol(file)) { <add> var ouputFilename = 'fieldnote.pdf'; <add> <add> phantom(file, ouputFilename, '2000px*3000px').then(function () { <add> resolve(ouputFilename); <add> }); <add> <ide> // if its a PDF, skip it <ide> // we are assuming all input files are JPG or PNG <del> if (!isPdf(file)) { <add> } else if (!isPdf(file)) { <ide> // configurations <ide> var sourcePath = __dirname + '/input/' + file, <ide> outputBase = __dirname + '/tmp/' + basename(file), <ide> } <ide> <ide> // create PDF <del> // @TODO abstract out all these commands into promises <del> exec(['phantomjs', __dirname + '/rasterize.js', sourcePath, outputBase + '.pdf', width +'px*' + height + 'px'].join(' '), function (err) { <del> // error handler <del> if (err) { <del> console.log('file failed to translate to PDF'); <del> deferred.reject(err); <del> } <del> <del> // remove second page <add> phantom(sourcePath, outputBase + '.pdf', width +'px*' + height + 'px').then(function () { <ide> exec(['pdftk', outputBase + '.pdf', 'cat', '1-1', 'output', outputBase + 'x.pdf'].join (' '), function (err) { <ide> // ignore errors for this one, pdftk will fail if there isn't 2 pages <ide> if (err) { <ide> fs.createReadStream(__dirname + '/input/' + file) <ide> .pipe(fs.createWriteStream(__dirname + '/tmp/' + file)); <ide> <del> resolve( __dirname + '/tmp/' + file); <add> resolve(__dirname + '/tmp/' + file); <ide> } <ide> <ide> // continuation of the loop
Java
mit
96a5d8424a12344f1415a61a34ffa2d579aa2eea
0
bounswe/bounswe2015group7,bounswe/bounswe2015group7,bounswe/bounswe2015group7,bounswe/bounswe2015group7
package sculture.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.core.io.Resource; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; import sculture.Utils; import sculture.dao.*; import sculture.exceptions.*; import sculture.lucene.SearchEngine; import sculture.models.requests.*; import sculture.models.response.*; import sculture.models.tables.Comment; import sculture.models.tables.Story; import sculture.models.tables.Tag; import sculture.models.tables.User; import sculture.models.tables.relations.TagStory; import javax.persistence.NoResultException; import java.io.FileOutputStream; import java.util.*; import static sculture.Utils.*; @RestController public class SCultureRest { @Autowired private UserDao userDao; @Autowired private VoteStoryDao voteStoryDao; @Autowired private StoryDao storyDao; @Autowired private CommentDao commentDao; @Autowired private TagDao tagDao; @Autowired private TagStoryDao tagStoryDao; @Autowired private FollowUserDao followUserDao; @Autowired private ReportStoryDao reportStoryDao; @RequestMapping(method = RequestMethod.POST, value = "/user/register") public LoginResponse user_register(@RequestBody RegisterRequestBody requestBody) { String email = requestBody.getEmail(); String username = requestBody.getUsername(); String password = requestBody.getPassword(); String fullname = requestBody.getFullname(); long facebook_id = requestBody.getFacebook_id(); String facebook_token = requestBody.getFacebook_token(); if (!checkEmailSyntax(email)) throw new InvalidEmailException(); if (!checkUsernameSyntax(username)) throw new InvalidUsernameException(); if (!checkPasswordSyntax(password)) throw new InvalidPasswordException(); User u = new User(); u.setEmail(email); u.setUsername(username); u.setPassword_hash(Utils.password_hash(password)); if (requestBody.getFullname() != null) u.setFullname(fullname); if (requestBody.getFacebook_id() != 0) u.setFacebook_id(facebook_id); if (requestBody.getFacebook_token() != null) u.setFacebook_token(facebook_token); u.setAccess_token(Utils.access_token_generate()); try { userDao.create(u); } catch (org.springframework.dao.DataIntegrityViolationException e) { throw new UserAlreadyExistsException(); } return new LoginResponse(u); } @RequestMapping(method = RequestMethod.POST, value = "/user/update") public LoginResponse user_update(@RequestBody UserUpdateRequestBody requestBody, @RequestHeader HttpHeaders headers) { User u = getCurrentUser(headers, true); String email = requestBody.getEmail(); String username = requestBody.getUsername(); String old_password = requestBody.getOld_password(); String new_password = requestBody.getNew_password(); String fullname = requestBody.getFullname(); if (!checkEmailSyntax(email)) throw new InvalidEmailException(); if (!checkUsernameSyntax(username)) throw new InvalidUsernameException(); if (!checkPasswordSyntax(old_password)) throw new InvalidPasswordException(); if (!checkPasswordSyntax(new_password)) throw new InvalidPasswordException(); if (u.getPassword_hash().equals(Utils.password_hash(old_password))) { u.setEmail(email); u.setUsername(username); u.setPassword_hash(Utils.password_hash(new_password)); if (fullname != null) u.setFullname(fullname); userDao.update(u); return new LoginResponse(u); } else throw new WrongPasswordException(); } @RequestMapping(method = RequestMethod.POST, value = "/user/get") public UserGetResponse user_get(@RequestBody UserGetRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); long id = requestBody.getUserId(); User u; try { u = userDao.getById(id); } catch (org.springframework.dao.EmptyResultDataAccessException e) { throw new UserNotExistException(); } UserGetResponse response = new UserGetResponse(); response.setEmail(u.getEmail()); response.setUser_id(u.getUser_id()); response.setUsername(u.getUsername()); if (current_user != null) response.setIs_following(followUserDao.get(current_user.getUser_id(), u.getUser_id()).is_follow()); else response.setIs_following(false); return response; } @RequestMapping(method = RequestMethod.POST, value = "/search/all") public SearchResponse user_get(@RequestBody SearchAllRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; SearchResponse response = new SearchResponse(); List<StoryResponse> storyResponses = new ArrayList<>(); response.setResult(storyResponses); List<Story> stories = storyDao.getAll(page, size); for (Story story : stories) { storyResponses.add(new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao)); } response.setResult(storyResponses); return response; } @RequestMapping(method = RequestMethod.POST, value = "/tag/get") public TagResponse user_get(@RequestBody TagGetRequestBody requestBody) { String title = requestBody.getTag_title(); Tag tag; try { tag = tagDao.getByTitle(title); } catch (org.springframework.dao.EmptyResultDataAccessException e) { throw new UserNotExistException(); } return new TagResponse(tag, userDao.getById(tag.getLast_editor_id()).getUsername()); } @RequestMapping(method = RequestMethod.POST, value = "/tag/edit") public TagResponse tag_edit(@RequestBody TagEditRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Tag tag = new Tag(); tag.setTag_title(requestBody.getTag_title()); tag.setIs_location(false); tag.setTag_description(requestBody.getTag_description()); tag.setLast_editor_id(current_user.getUser_id()); tag.setLast_edit_date(new Date()); tagDao.update(tag); return new TagResponse(tag, userDao.getById(tag.getLast_editor_id()).getUsername()); } @RequestMapping(method = RequestMethod.POST, value = "/user/stories") public SearchResponse user_get(@RequestBody StoriesGetRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); //TODO Exception handling int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; long id = requestBody.getId(); List<Story> storyList = storyDao.getByOwner(id, page, size); SearchResponse searchResponse = new SearchResponse(); List<StoryResponse> responses = new ArrayList<>(); for (Story story : storyList) { responses.add(new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao)); } searchResponse.setResult(responses); return searchResponse; } final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890"; final java.util.Random rand = new java.util.Random(); // consider using a Map<String,Boolean> to say whether the identifier is being used or not final Set<String> identifiers = new HashSet<String>(); public String randomIdentifier() { StringBuilder builder = new StringBuilder(); while (builder.toString().length() == 0) { int length = rand.nextInt(5) + 5; for (int i = 0; i < length; i++) builder.append(lexicon.charAt(rand.nextInt(lexicon.length()))); if (identifiers.contains(builder.toString())) builder = new StringBuilder(); } return builder.toString(); } @RequestMapping(value = "/image/upload", method = RequestMethod.POST) public @ResponseBody ImageResponse handleFileUpload( @RequestBody byte[] file) throws Exception { String randomIdentifier = randomIdentifier(); FileOutputStream fos = new FileOutputStream("/image/" + randomIdentifier + ".jpg"); fos.write(file); fos.close(); ImageResponse imageResponse = new ImageResponse(); imageResponse.setId(randomIdentifier); return imageResponse; } private FileSystemResourceLoader resourceLoader = new FileSystemResourceLoader(); @RequestMapping(method = RequestMethod.GET, value = "/image/get/{id}", produces = "image/jpg") public Resource image_get(@PathVariable String id) { return resourceLoader.getResource("file:/image/" + id + ".jpg"); } @RequestMapping(method = RequestMethod.POST, value = "/user/login") public LoginResponse user_login(@RequestBody LoginRequestBody requestBody) { String email = requestBody.getEmail(); String password = requestBody.getPassword(); String username = requestBody.getUsername(); if (!checkEmailSyntax(email) && username == null) throw new InvalidEmailException(); if (!checkPasswordSyntax(password)) throw new InvalidPasswordException(); User u; try { if (email != null) { u = userDao.getByEmail(email); } else u = userDao.getByUsername(username); } catch (org.springframework.dao.EmptyResultDataAccessException e) { throw new UserNotExistException(); } if (u.getPassword_hash().equals(Utils.password_hash(password))) { return new LoginResponse(u); } else throw new WrongPasswordException(); } @RequestMapping(method = RequestMethod.POST, value = "/user/follow") public UserFollowResponse user_follow(@RequestBody UserFollowRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); followUserDao.follow_user(current_user.getUser_id(), requestBody.getUser_id(), requestBody.is_follow()); return new UserFollowResponse(requestBody.is_follow()); } @RequestMapping(method = RequestMethod.POST, value = "/story/create") public StoryResponse story_create(@RequestBody StoryCreateRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); //TODO Exception handling Date date = new Date(); Story story = new Story(); story.setTitle(requestBody.getTitle()); story.setContent(requestBody.getContent()); story.setOwner_id(current_user.getUser_id()); story.setCreate_date(date); story.setLast_edit_date(date); story.setLast_editor_id(current_user.getUser_id()); if (requestBody.getMedia() != null) { String str = ""; for (String media : requestBody.getMedia()) { str += media; str += ","; } story.setMedia(str.substring(0, str.length() - 1)); } storyDao.create(story); List<String> tags = requestBody.getTags(); String tag_index = ""; for (String tag : tags) { TagStory tagStory = new TagStory(); tagStory.setTag_title(tag); tagStory.setStory_id(story.getStory_id()); tag_index += tag + ", "; tagStoryDao.update(tagStory); } SearchEngine.addDoc(story.getStory_id(), story.getTitle(), story.getContent(), tag_index); return new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao); } @RequestMapping(method = RequestMethod.POST, value = "/story/edit") public StoryResponse story_edit(@RequestBody StoryEditRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Story story = storyDao.getById(requestBody.getStory_id()); if (current_user.getUser_id() != story.getOwner_id()) { throw new NotOwnerException(); } //TODO Exception handling Date date = new Date(); story.setStory_id(requestBody.getStory_id()); story.setTitle(requestBody.getTitle()); story.setContent(requestBody.getContent()); story.setOwner_id(current_user.getUser_id()); story.setCreate_date(date); story.setLast_edit_date(date); story.setLast_editor_id(current_user.getUser_id()); if (requestBody.getMedia() != null) { String str = ""; for (String media : requestBody.getMedia()) { str += media; str += ","; } story.setMedia(str.substring(0, str.length() - 1)); } storyDao.edit(story); String tag_index = ""; if (requestBody.getTags() != null) { List<String> tags = requestBody.getTags(); for (String tag : tags) { tag_index += tag + ", "; TagStory tagStory = new TagStory(); tagStory.setTag_title(tag); tagStory.setStory_id(story.getStory_id()); tagStoryDao.update(tagStory); } } SearchEngine.removeDoc(story.getStory_id()); SearchEngine.addDoc(story.getStory_id(), story.getTitle(), story.getContent(), tag_index); return new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao); } @RequestMapping("/story/get") public StoryResponse storyGet(@RequestBody StoryGetRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); Story story = storyDao.getById(requestBody.getId()); return new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao); } @RequestMapping("/search") public SearchResponse search(@RequestBody SearchRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); //TODO Exception handling int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; List<Long> story_ids = SearchEngine.search(requestBody.getQuery(), page, size); List<StoryResponse> responses = new LinkedList<>(); for (long id : story_ids) { Story story = storyDao.getById(id); System.out.println(id); responses.add(new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao)); } SearchResponse searchResponse = new SearchResponse(); searchResponse.setResult(responses); return searchResponse; } @RequestMapping("/comment/get") public CommentResponse commentGet(@RequestBody CommentGetRequestBody requestBody) { Comment comment = commentDao.getById(requestBody.getCommentId()); return new CommentResponse(comment, userDao); } @RequestMapping("/comment/new") public CommentResponse commentGet(@RequestBody CommentNewRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user; try { String access_token; access_token = headers.get("access-token").get(0); current_user = userDao.getByAccessToken(access_token); } catch (NullPointerException | org.springframework.dao.EmptyResultDataAccessException e) { throw new InvalidAccessTokenException(); } Comment comment = new Comment(); Date date = new Date(); comment.setContent(requestBody.getContent()); comment.setCreate_date(date); comment.setOwner_id(current_user.getUser_id()); comment.setStory_id(requestBody.getStoryId()); comment.setLast_edit_date(date); commentDao.create(comment); return new CommentResponse(comment, userDao); } @RequestMapping("/story/report") public StoryReportResponse storyReport(@RequestBody StoryReportRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Story story = storyDao.getById(requestBody.getStory_id()); reportStoryDao.reportStory(current_user, story); return new StoryReportResponse(story.getReport_count()); } @RequestMapping(method = RequestMethod.POST, value = "/story/vote") public VoteResponse storyVote(@RequestBody StoryVoteRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Story story = voteStoryDao.vote(current_user.getUser_id(), requestBody.getStory_id(), requestBody.getVote()); return new VoteResponse(requestBody.getVote(), story); } @RequestMapping("/comment/list") public CommentListResponse commentList(@RequestBody CommentListRequestBody requestBody) { int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; List<Comment> comments = commentDao.retrieveByStory(requestBody.getStory_id(), page, size); List<CommentResponse> responses = new LinkedList<>(); for (Comment comment : comments) { responses.add(new CommentResponse(comment, userDao)); } CommentListResponse commentListResponse = new CommentListResponse(); commentListResponse.setResult(responses); return commentListResponse; } @RequestMapping("/admin/search/reindex") public void admin_search_reindex() { SearchEngine.removeAll(); for (int i = 1; ; i++) { List<Story> stories = storyDao.getAllPaged(i, 20); for (Story story : stories) { List<String> tags = tagStoryDao.getTagTitlesByStoryId(story.getStory_id()); String tag_index = ""; for (String tag : tags) tag_index += tag + ", "; SearchEngine.addDoc(story.getStory_id(), story.getTitle(), story.getContent(), tag_index); } if (stories.size() == 0) break; } } @RequestMapping("/admin/clear") public void admin_clear(@RequestBody AdminClearRequest requestBody) { for (String email : requestBody.getEmails()) { User user; try { user = userDao.getByEmail(email); } catch (EmptyResultDataAccessException e) { continue; } for (; ; ) { List<Story> stories = storyDao.getByOwner(user.getUser_id(), 1, 10); if (stories.size() == 0) break; for (Story story : stories) { commentDao.deleteByStoryId(story.getStory_id()); tagStoryDao.deleteByStoryId(story.getStory_id()); reportStoryDao.deleteByStoryId(story.getStory_id()); voteStoryDao.deleteByStoryId(story.getStory_id()); storyDao.delete(story); } } commentDao.deleteByUserId(user.getUser_id()); tagDao.deleteByUserId(user.getUser_id()); reportStoryDao.deleteByUserId(user.getUser_id()); voteStoryDao.deleteByUserId(user.getUser_id()); followUserDao.deleteByUserId(user.getUser_id()); userDao.delete(user); System.out.println("User " + user.getUsername() + " is deleted"); } admin_search_reindex(); } @RequestMapping("/admin/orphan") public void admin_clear_orphan() { List<Story> stories = storyDao.getAll(1, 1000); for (Story story : stories) { User u = userDao.getById(story.getOwner_id()); if (u == null) storyDao.delete(story); } admin_search_reindex(); } /** * Returns current user by using access-token * * @param headers The headers which contains access-token * @param notnull Whether the current_user can be null or not, if true it will not return null instead throw an exception * @return Current user */ private User getCurrentUser(HttpHeaders headers, boolean notnull) { User current_user = null; try { String access_token; access_token = headers.get("access-token").get(0); current_user = userDao.getByAccessToken(access_token); } catch (NullPointerException | org.springframework.dao.EmptyResultDataAccessException ignored) { if (notnull) throw new InvalidAccessTokenException(); } return current_user; } }
sculture-rest/src/main/java/sculture/controllers/SCultureRest.java
package sculture.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.core.io.Resource; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; import sculture.Utils; import sculture.dao.*; import sculture.exceptions.*; import sculture.lucene.SearchEngine; import sculture.models.requests.*; import sculture.models.response.*; import sculture.models.tables.Comment; import sculture.models.tables.Story; import sculture.models.tables.Tag; import sculture.models.tables.User; import sculture.models.tables.relations.TagStory; import javax.persistence.NoResultException; import java.io.FileOutputStream; import java.util.*; import static sculture.Utils.*; @RestController public class SCultureRest { @Autowired private UserDao userDao; @Autowired private VoteStoryDao voteStoryDao; @Autowired private StoryDao storyDao; @Autowired private CommentDao commentDao; @Autowired private TagDao tagDao; @Autowired private TagStoryDao tagStoryDao; @Autowired private FollowUserDao followUserDao; @Autowired private ReportStoryDao reportStoryDao; @RequestMapping(method = RequestMethod.POST, value = "/user/register") public LoginResponse user_register(@RequestBody RegisterRequestBody requestBody) { String email = requestBody.getEmail(); String username = requestBody.getUsername(); String password = requestBody.getPassword(); String fullname = requestBody.getFullname(); long facebook_id = requestBody.getFacebook_id(); String facebook_token = requestBody.getFacebook_token(); if (!checkEmailSyntax(email)) throw new InvalidEmailException(); if (!checkUsernameSyntax(username)) throw new InvalidUsernameException(); if (!checkPasswordSyntax(password)) throw new InvalidPasswordException(); User u = new User(); u.setEmail(email); u.setUsername(username); u.setPassword_hash(Utils.password_hash(password)); if (requestBody.getFullname() != null) u.setFullname(fullname); if (requestBody.getFacebook_id() != 0) u.setFacebook_id(facebook_id); if (requestBody.getFacebook_token() != null) u.setFacebook_token(facebook_token); u.setAccess_token(Utils.access_token_generate()); try { userDao.create(u); } catch (org.springframework.dao.DataIntegrityViolationException e) { throw new UserAlreadyExistsException(); } return new LoginResponse(u); } @RequestMapping(method = RequestMethod.POST, value = "/user/update") public LoginResponse user_update(@RequestBody UserUpdateRequestBody requestBody, @RequestHeader HttpHeaders headers) { User u = getCurrentUser(headers, true); String email = requestBody.getEmail(); String username = requestBody.getUsername(); String old_password = requestBody.getOld_password(); String new_password = requestBody.getNew_password(); String fullname = requestBody.getFullname(); if (!checkEmailSyntax(email)) throw new InvalidEmailException(); if (!checkUsernameSyntax(username)) throw new InvalidUsernameException(); if (!checkPasswordSyntax(old_password)) throw new InvalidPasswordException(); if (!checkPasswordSyntax(new_password)) throw new InvalidPasswordException(); if (u.getPassword_hash().equals(Utils.password_hash(old_password))) { u.setEmail(email); u.setUsername(username); u.setPassword_hash(Utils.password_hash(new_password)); if (fullname != null) u.setFullname(fullname); userDao.update(u); return new LoginResponse(u); } else throw new WrongPasswordException(); } @RequestMapping(method = RequestMethod.POST, value = "/user/get") public UserGetResponse user_get(@RequestBody UserGetRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); long id = requestBody.getUserId(); User u; try { u = userDao.getById(id); } catch (org.springframework.dao.EmptyResultDataAccessException e) { throw new UserNotExistException(); } UserGetResponse response = new UserGetResponse(); response.setEmail(u.getEmail()); response.setUser_id(u.getUser_id()); response.setUsername(u.getUsername()); if (current_user != null) response.setIs_following(followUserDao.get(current_user.getUser_id(), u.getUser_id()).is_follow()); else response.setIs_following(false); return response; } @RequestMapping(method = RequestMethod.POST, value = "/search/all") public SearchResponse user_get(@RequestBody SearchAllRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; SearchResponse response = new SearchResponse(); List<StoryResponse> storyResponses = new ArrayList<>(); response.setResult(storyResponses); List<Story> stories = storyDao.getAll(page, size); for (Story story : stories) { storyResponses.add(new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao)); } response.setResult(storyResponses); return response; } @RequestMapping(method = RequestMethod.POST, value = "/tag/get") public TagResponse user_get(@RequestBody TagGetRequestBody requestBody) { String title = requestBody.getTag_title(); Tag tag; try { tag = tagDao.getByTitle(title); } catch (org.springframework.dao.EmptyResultDataAccessException e) { throw new UserNotExistException(); } return new TagResponse(tag, userDao.getById(tag.getLast_editor_id()).getUsername()); } @RequestMapping(method = RequestMethod.POST, value = "/tag/edit") public TagResponse tag_edit(@RequestBody TagEditRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Tag tag = new Tag(); tag.setTag_title(requestBody.getTag_title()); tag.setIs_location(false); tag.setTag_description(requestBody.getTag_description()); tag.setLast_editor_id(current_user.getUser_id()); tag.setLast_edit_date(new Date()); tagDao.update(tag); return new TagResponse(tag, userDao.getById(tag.getLast_editor_id()).getUsername()); } @RequestMapping(method = RequestMethod.POST, value = "/user/stories") public SearchResponse user_get(@RequestBody StoriesGetRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); //TODO Exception handling int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; long id = requestBody.getId(); List<Story> storyList = storyDao.getByOwner(id, page, size); SearchResponse searchResponse = new SearchResponse(); List<StoryResponse> responses = new ArrayList<>(); for (Story story : storyList) { responses.add(new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao)); } searchResponse.setResult(responses); return searchResponse; } final String lexicon = "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345674890"; final java.util.Random rand = new java.util.Random(); // consider using a Map<String,Boolean> to say whether the identifier is being used or not final Set<String> identifiers = new HashSet<String>(); public String randomIdentifier() { StringBuilder builder = new StringBuilder(); while (builder.toString().length() == 0) { int length = rand.nextInt(5) + 5; for (int i = 0; i < length; i++) builder.append(lexicon.charAt(rand.nextInt(lexicon.length()))); if (identifiers.contains(builder.toString())) builder = new StringBuilder(); } return builder.toString(); } @RequestMapping(value = "/image/upload", method = RequestMethod.POST) public @ResponseBody ImageResponse handleFileUpload( @RequestBody byte[] file) throws Exception { String randomIdentifier = randomIdentifier(); FileOutputStream fos = new FileOutputStream("/image/" + randomIdentifier + ".jpg"); fos.write(file); fos.close(); ImageResponse imageResponse = new ImageResponse(); imageResponse.setId(randomIdentifier); return imageResponse; } private FileSystemResourceLoader resourceLoader = new FileSystemResourceLoader(); @RequestMapping(method = RequestMethod.GET, value = "/image/get/{id}", produces = "image/jpg") public Resource image_get(@PathVariable String id) { return resourceLoader.getResource("file:/image/" + id + ".jpg"); } @RequestMapping(method = RequestMethod.POST, value = "/user/login") public LoginResponse user_login(@RequestBody LoginRequestBody requestBody) { String email = requestBody.getEmail(); String password = requestBody.getPassword(); String username = requestBody.getUsername(); if (!checkEmailSyntax(email) && username == null) throw new InvalidEmailException(); if (!checkPasswordSyntax(password)) throw new InvalidPasswordException(); User u; try { if (email != null) { u = userDao.getByEmail(email); } else u = userDao.getByUsername(username); } catch (org.springframework.dao.EmptyResultDataAccessException e) { throw new UserNotExistException(); } if (u.getPassword_hash().equals(Utils.password_hash(password))) { return new LoginResponse(u); } else throw new WrongPasswordException(); } @RequestMapping(method = RequestMethod.POST, value = "/user/follow") public UserFollowResponse user_follow(@RequestBody UserFollowRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); followUserDao.follow_user(current_user.getUser_id(), requestBody.getUser_id(), requestBody.is_follow()); return new UserFollowResponse(requestBody.is_follow()); } @RequestMapping(method = RequestMethod.POST, value = "/story/create") public StoryResponse story_create(@RequestBody StoryCreateRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); //TODO Exception handling Date date = new Date(); Story story = new Story(); story.setTitle(requestBody.getTitle()); story.setContent(requestBody.getContent()); story.setOwner_id(current_user.getUser_id()); story.setCreate_date(date); story.setLast_edit_date(date); story.setLast_editor_id(current_user.getUser_id()); if (requestBody.getMedia() != null) { String str = ""; for (String media : requestBody.getMedia()) { str += media; str += ","; } story.setMedia(str.substring(0, str.length() - 1)); } storyDao.create(story); List<String> tags = requestBody.getTags(); String tag_index = ""; for (String tag : tags) { TagStory tagStory = new TagStory(); tagStory.setTag_title(tag); tagStory.setStory_id(story.getStory_id()); tag_index += tag + ", "; tagStoryDao.update(tagStory); } SearchEngine.addDoc(story.getStory_id(), story.getTitle(), story.getContent(), tag_index); return new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao); } @RequestMapping(method = RequestMethod.POST, value = "/story/edit") public StoryResponse story_edit(@RequestBody StoryEditRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Story story = storyDao.getById(requestBody.getStory_id()); if (current_user.getUser_id() != story.getOwner_id()) { throw new NotOwnerException(); } //TODO Exception handling Date date = new Date(); story.setStory_id(requestBody.getStory_id()); story.setTitle(requestBody.getTitle()); story.setContent(requestBody.getContent()); story.setOwner_id(current_user.getUser_id()); story.setCreate_date(date); story.setLast_edit_date(date); story.setLast_editor_id(current_user.getUser_id()); if (requestBody.getMedia() != null) { String str = ""; for (String media : requestBody.getMedia()) { str += media; str += ","; } story.setMedia(str.substring(0, str.length() - 1)); } storyDao.edit(story); String tag_index = ""; if (requestBody.getTags() != null) { List<String> tags = requestBody.getTags(); for (String tag : tags) { tag_index += tag + ", "; TagStory tagStory = new TagStory(); tagStory.setTag_title(tag); tagStory.setStory_id(story.getStory_id()); tagStoryDao.update(tagStory); } } SearchEngine.removeDoc(story.getStory_id()); SearchEngine.addDoc(story.getStory_id(), story.getTitle(), story.getContent(), tag_index); return new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao); } @RequestMapping("/story/get") public StoryResponse storyGet(@RequestBody StoryGetRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); Story story = storyDao.getById(requestBody.getId()); return new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao); } @RequestMapping("/search") public SearchResponse search(@RequestBody SearchRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, false); //TODO Exception handling int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; List<Long> story_ids = SearchEngine.search(requestBody.getQuery(), page, size); List<StoryResponse> responses = new LinkedList<>(); for (long id : story_ids) { Story story = storyDao.getById(id); System.out.println(id); responses.add(new StoryResponse(story, current_user, tagStoryDao, userDao, voteStoryDao)); } SearchResponse searchResponse = new SearchResponse(); searchResponse.setResult(responses); return searchResponse; } @RequestMapping("/comment/get") public CommentResponse commentGet(@RequestBody CommentGetRequestBody requestBody) { Comment comment = commentDao.getById(requestBody.getCommentId()); return new CommentResponse(comment, userDao); } @RequestMapping("/comment/new") public CommentResponse commentGet(@RequestBody CommentNewRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user; try { String access_token; access_token = headers.get("access-token").get(0); current_user = userDao.getByAccessToken(access_token); } catch (NullPointerException | org.springframework.dao.EmptyResultDataAccessException e) { throw new InvalidAccessTokenException(); } Comment comment = new Comment(); Date date = new Date(); comment.setContent(requestBody.getContent()); comment.setCreate_date(date); comment.setOwner_id(current_user.getUser_id()); comment.setStory_id(requestBody.getStoryId()); comment.setLast_edit_date(date); commentDao.create(comment); return new CommentResponse(comment, userDao); } @RequestMapping("/story/report") public StoryReportResponse storyReport(@RequestBody StoryReportRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Story story = storyDao.getById(requestBody.getStory_id()); reportStoryDao.reportStory(current_user, story); return new StoryReportResponse(story.getReport_count()); } @RequestMapping(method = RequestMethod.POST, value = "/story/vote") public VoteResponse storyVote(@RequestBody StoryVoteRequestBody requestBody, @RequestHeader HttpHeaders headers) { User current_user = getCurrentUser(headers, true); Story story = voteStoryDao.vote(current_user.getUser_id(), requestBody.getStory_id(), requestBody.getVote()); return new VoteResponse(requestBody.getVote(), story); } @RequestMapping("/comment/list") public CommentListResponse commentList(@RequestBody CommentListRequestBody requestBody) { int page = requestBody.getPage(); int size = requestBody.getSize(); if (size < 1) size = 10; if (page < 1) page = 1; List<Comment> comments = commentDao.retrieveByStory(requestBody.getStory_id(), page, size); List<CommentResponse> responses = new LinkedList<>(); for (Comment comment : comments) { responses.add(new CommentResponse(comment, userDao)); } CommentListResponse commentListResponse = new CommentListResponse(); commentListResponse.setResult(responses); return commentListResponse; } @RequestMapping("/admin/search/reindex") public void admin_search_reindex() { SearchEngine.removeAll(); for (int i = 1; ; i++) { List<Story> stories = storyDao.getAllPaged(i, 20); for (Story story : stories) { List<String> tags = tagStoryDao.getTagTitlesByStoryId(story.getStory_id()); String tag_index = ""; for (String tag : tags) tag_index += tag + ", "; SearchEngine.addDoc(story.getStory_id(), story.getTitle(), story.getContent(), tag_index); } if (stories.size() == 0) break; } } @RequestMapping("/admin/clear") public void admin_clear(@RequestBody AdminClearRequest requestBody) { for (String email : requestBody.getEmails()) { User user; try { user = userDao.getByEmail(email); } catch (EmptyResultDataAccessException e) { continue; } for (; ; ) { List<Story> stories = storyDao.getByOwner(user.getUser_id(), 1, 10); if (stories.size() == 0) break; for (Story story : stories) { commentDao.deleteByStoryId(story.getStory_id()); tagStoryDao.deleteByStoryId(story.getStory_id()); reportStoryDao.deleteByStoryId(story.getStory_id()); voteStoryDao.deleteByStoryId(story.getStory_id()); storyDao.delete(story); } } commentDao.deleteByUserId(user.getUser_id()); tagDao.deleteByUserId(user.getUser_id()); reportStoryDao.deleteByUserId(user.getUser_id()); voteStoryDao.deleteByUserId(user.getUser_id()); followUserDao.deleteByUserId(user.getUser_id()); userDao.delete(user); System.out.println("User " + user.getUsername() + " is deleted"); } admin_search_reindex(); } @RequestMapping("/admin/clear/orphan") public void admin_clear_orphan(@RequestBody AdminClearRequest requestBody) { List<Story> stories = storyDao.getAll(1, 1000); for (Story story : stories) { User u = userDao.getById(story.getOwner_id()); if (u == null) storyDao.delete(story); } admin_search_reindex(); } /** * Returns current user by using access-token * * @param headers The headers which contains access-token * @param notnull Whether the current_user can be null or not, if true it will not return null instead throw an exception * @return Current user */ private User getCurrentUser(HttpHeaders headers, boolean notnull) { User current_user = null; try { String access_token; access_token = headers.get("access-token").get(0); current_user = userDao.getByAccessToken(access_token); } catch (NullPointerException | org.springframework.dao.EmptyResultDataAccessException ignored) { if (notnull) throw new InvalidAccessTokenException(); } return current_user; } }
Fix delete methods
sculture-rest/src/main/java/sculture/controllers/SCultureRest.java
Fix delete methods
<ide><path>culture-rest/src/main/java/sculture/controllers/SCultureRest.java <ide> } <ide> <ide> <del> @RequestMapping("/admin/clear/orphan") <del> public void admin_clear_orphan(@RequestBody AdminClearRequest requestBody) { <add> @RequestMapping("/admin/orphan") <add> public void admin_clear_orphan() { <ide> List<Story> stories = storyDao.getAll(1, 1000); <ide> <ide> for (Story story : stories) {
Java
apache-2.0
ef49f81fd484261e564f3eac1f2c19fa02f509e9
0
archit47/seaglass,khuxtable/seaglass
/* * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr. * * This file is part of the SeaGlass Pluggable Look and Feel. * * 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. * * $Id$ */ package com.seaglasslookandfeel.painter; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Paint; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode; /** * ToolBarToggleButtonPainter implementation. */ public final class ToolBarToggleButtonPainter extends AbstractRegionPainter { public static enum Which { BACKGROUND_ENABLED, BACKGROUND_FOCUSED, BACKGROUND_PRESSED, BACKGROUND_PRESSED_FOCUSED, BACKGROUND_SELECTED, BACKGROUND_SELECTED_FOCUSED, BACKGROUND_PRESSED_SELECTED, BACKGROUND_PRESSED_SELECTED_FOCUSED, BACKGROUND_DISABLED_SELECTED, } private static final Color END_INNER_COLOR = new Color(0x00000000, true); private static final Color MID_INNER_COLOR = new Color(0x20000000, true); private static final Color END_INNER_EDGE_COLOR = new Color(0x00000000, true); private static final Color MID_INNER_EDGE_COLOR = new Color(0x20000000, true); private static final Color END_OUTER_EDGE_COLOR = new Color(0x10000000, true); private static final Color MID_OUTER_EDGE_COLOR = new Color(0x40000000, true); private static final Insets insets = new Insets(5, 5, 5, 5); private static final Dimension dimension = new Dimension(104, 34); private static final CacheMode cacheMode = CacheMode.FIXED_SIZES; private static final Double maxH = Double.POSITIVE_INFINITY; private static final Double maxV = Double.POSITIVE_INFINITY; private Rectangle rect = new Rectangle(); private Which state; private PaintContext ctx; public ToolBarToggleButtonPainter(Which state) { super(); this.state = state; ctx = new PaintContext(insets, dimension, false, cacheMode, maxH, maxV); } @Override protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) { switch (state) { case BACKGROUND_SELECTED: case BACKGROUND_SELECTED_FOCUSED: case BACKGROUND_PRESSED_SELECTED: case BACKGROUND_PRESSED_SELECTED_FOCUSED: case BACKGROUND_DISABLED_SELECTED: paintSelectedBackground(g, width, height); } } @Override protected PaintContext getPaintContext() { return ctx; } private void paintSelectedBackground(Graphics2D g, int width, int height) { paintRectangle(g, 0, height, END_INNER_COLOR, MID_INNER_COLOR); paintRectangle(g, 1, height, END_INNER_EDGE_COLOR, MID_INNER_EDGE_COLOR); paintRectangle(g, width - 2, height, END_INNER_EDGE_COLOR, MID_INNER_EDGE_COLOR); paintRectangle(g, 0, height, END_OUTER_EDGE_COLOR, MID_OUTER_EDGE_COLOR); paintRectangle(g, width - 1, height, END_OUTER_EDGE_COLOR, MID_OUTER_EDGE_COLOR); } private void paintRectangle(Graphics2D g, int x, int height, Color endColor, Color midColor) { rect.setBounds(x, 0, 1, height); g.setPaint(decodeGradient(rect, endColor, midColor)); g.fill(rect); } /** * Create the gradient for the background of the button. This creates the * border. * * @param s * @param color1 * @param color2 * @return */ Paint decodeGradient(Shape s, Color endColor, Color middleColor) { Rectangle2D bounds = s.getBounds2D(); float x = (float) bounds.getX(); float y = (float) bounds.getY(); float w = (float) bounds.getWidth(); float h = (float) bounds.getHeight(); return decodeGradient((0.5f * w) + x, y, (0.5f * w) + x, h + y, new float[] { 0f, 0.5f, 1f }, new Color[] { endColor, middleColor, endColor }); } }
seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/ToolBarToggleButtonPainter.java
/* * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr. * * This file is part of the SeaGlass Pluggable Look and Feel. * * 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. * * $Id$ */ package com.seaglasslookandfeel.painter; import java.awt.Dimension; import java.awt.Insets; import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode; /** * ToolBarToggleButtonPainter implementation. */ public final class ToolBarToggleButtonPainter extends AbstractImagePainter<ToolBarToggleButtonPainter.Which> { public static enum Which { BACKGROUND_ENABLED, BACKGROUND_FOCUSED, BACKGROUND_PRESSED, BACKGROUND_PRESSED_FOCUSED, BACKGROUND_SELECTED, BACKGROUND_SELECTED_FOCUSED, BACKGROUND_PRESSED_SELECTED, BACKGROUND_PRESSED_SELECTED_FOCUSED, BACKGROUND_DISABLED_SELECTED, } private static final Insets insets = new Insets(5, 5, 5, 5); private static final Dimension dimension = new Dimension(104, 34); private static final CacheMode cacheMode = CacheMode.NINE_SQUARE_SCALE; private static final Double maxH = 2.0; private static final Double maxV = Double.POSITIVE_INFINITY; public ToolBarToggleButtonPainter(Which state) { super(state); PaintContext ctx = new PaintContext(insets, dimension, false, cacheMode, maxH, maxV); setPaintContext(ctx); } protected String getImageName(Which state) { switch (state) { case BACKGROUND_FOCUSED: return "toolbar_button_focused"; case BACKGROUND_PRESSED: return "toolbar_button_pressed"; case BACKGROUND_PRESSED_FOCUSED: return "toolbar_button_focused_pressed"; case BACKGROUND_SELECTED: return "toolbar_button_selected"; case BACKGROUND_SELECTED_FOCUSED: return "toolbar_button_selected_focused"; case BACKGROUND_PRESSED_SELECTED: return "toolbar_button_selected"; case BACKGROUND_PRESSED_SELECTED_FOCUSED: return "toolbar_button_selected_focused"; case BACKGROUND_DISABLED_SELECTED: return "toolbar_button_selected"; } return null; } }
Paint toggle button using Graphics2D and use the current Mac look for selected button.
seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/ToolBarToggleButtonPainter.java
Paint toggle button using Graphics2D and use the current Mac look for selected button.
<ide><path>eaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/ToolBarToggleButtonPainter.java <ide> */ <ide> package com.seaglasslookandfeel.painter; <ide> <add>import java.awt.Color; <ide> import java.awt.Dimension; <add>import java.awt.Graphics2D; <ide> import java.awt.Insets; <add>import java.awt.Paint; <add>import java.awt.Rectangle; <add>import java.awt.Shape; <add>import java.awt.geom.Rectangle2D; <add> <add>import javax.swing.JComponent; <ide> <ide> import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode; <ide> <ide> /** <ide> * ToolBarToggleButtonPainter implementation. <ide> */ <del>public final class ToolBarToggleButtonPainter extends AbstractImagePainter<ToolBarToggleButtonPainter.Which> { <add>public final class ToolBarToggleButtonPainter extends AbstractRegionPainter { <ide> public static enum Which { <ide> BACKGROUND_ENABLED, <ide> BACKGROUND_FOCUSED, <ide> BACKGROUND_DISABLED_SELECTED, <ide> } <ide> <del> private static final Insets insets = new Insets(5, 5, 5, 5); <del> private static final Dimension dimension = new Dimension(104, 34); <del> private static final CacheMode cacheMode = CacheMode.NINE_SQUARE_SCALE; <del> private static final Double maxH = 2.0; <del> private static final Double maxV = Double.POSITIVE_INFINITY; <add> private static final Color END_INNER_COLOR = new Color(0x00000000, true); <add> private static final Color MID_INNER_COLOR = new Color(0x20000000, true); <add> <add> private static final Color END_INNER_EDGE_COLOR = new Color(0x00000000, true); <add> private static final Color MID_INNER_EDGE_COLOR = new Color(0x20000000, true); <add> <add> private static final Color END_OUTER_EDGE_COLOR = new Color(0x10000000, true); <add> private static final Color MID_OUTER_EDGE_COLOR = new Color(0x40000000, true); <add> <add> private static final Insets insets = new Insets(5, 5, 5, 5); <add> private static final Dimension dimension = new Dimension(104, 34); <add> private static final CacheMode cacheMode = CacheMode.FIXED_SIZES; <add> private static final Double maxH = Double.POSITIVE_INFINITY; <add> private static final Double maxV = Double.POSITIVE_INFINITY; <add> <add> private Rectangle rect = new Rectangle(); <add> <add> private Which state; <add> private PaintContext ctx; <ide> <ide> public ToolBarToggleButtonPainter(Which state) { <del> super(state); <del> PaintContext ctx = new PaintContext(insets, dimension, false, cacheMode, maxH, maxV); <del> setPaintContext(ctx); <add> super(); <add> this.state = state; <add> ctx = new PaintContext(insets, dimension, false, cacheMode, maxH, maxV); <ide> } <ide> <del> protected String getImageName(Which state) { <add> @Override <add> protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) { <ide> switch (state) { <del> case BACKGROUND_FOCUSED: <del> return "toolbar_button_focused"; <del> case BACKGROUND_PRESSED: <del> return "toolbar_button_pressed"; <del> case BACKGROUND_PRESSED_FOCUSED: <del> return "toolbar_button_focused_pressed"; <ide> case BACKGROUND_SELECTED: <del> return "toolbar_button_selected"; <ide> case BACKGROUND_SELECTED_FOCUSED: <del> return "toolbar_button_selected_focused"; <ide> case BACKGROUND_PRESSED_SELECTED: <del> return "toolbar_button_selected"; <ide> case BACKGROUND_PRESSED_SELECTED_FOCUSED: <del> return "toolbar_button_selected_focused"; <ide> case BACKGROUND_DISABLED_SELECTED: <del> return "toolbar_button_selected"; <add> paintSelectedBackground(g, width, height); <ide> } <del> return null; <add> } <add> <add> @Override <add> protected PaintContext getPaintContext() { <add> return ctx; <add> } <add> <add> private void paintSelectedBackground(Graphics2D g, int width, int height) { <add> paintRectangle(g, 0, height, END_INNER_COLOR, MID_INNER_COLOR); <add> <add> paintRectangle(g, 1, height, END_INNER_EDGE_COLOR, MID_INNER_EDGE_COLOR); <add> paintRectangle(g, width - 2, height, END_INNER_EDGE_COLOR, MID_INNER_EDGE_COLOR); <add> <add> paintRectangle(g, 0, height, END_OUTER_EDGE_COLOR, MID_OUTER_EDGE_COLOR); <add> paintRectangle(g, width - 1, height, END_OUTER_EDGE_COLOR, MID_OUTER_EDGE_COLOR); <add> } <add> <add> private void paintRectangle(Graphics2D g, int x, int height, Color endColor, Color midColor) { <add> rect.setBounds(x, 0, 1, height); <add> g.setPaint(decodeGradient(rect, endColor, midColor)); <add> g.fill(rect); <add> } <add> <add> /** <add> * Create the gradient for the background of the button. This creates the <add> * border. <add> * <add> * @param s <add> * @param color1 <add> * @param color2 <add> * @return <add> */ <add> Paint decodeGradient(Shape s, Color endColor, Color middleColor) { <add> Rectangle2D bounds = s.getBounds2D(); <add> float x = (float) bounds.getX(); <add> float y = (float) bounds.getY(); <add> float w = (float) bounds.getWidth(); <add> float h = (float) bounds.getHeight(); <add> return decodeGradient((0.5f * w) + x, y, (0.5f * w) + x, h + y, new float[] { 0f, 0.5f, 1f }, new Color[] { <add> endColor, <add> middleColor, <add> endColor }); <ide> } <ide> }
Java
apache-2.0
9f64e0d9579f714339d1f528de736b4092ae0950
0
chat-sdk/chat-sdk-android,chat-sdk/chat-sdk-android
package co.chatsdk.core.session; import android.content.Context; import android.content.SharedPreferences; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import co.chatsdk.core.base.BaseNetworkAdapter; import co.chatsdk.core.dao.DaoCore; import co.chatsdk.core.dao.Message; import co.chatsdk.core.dao.User; import co.chatsdk.core.error.ChatSDKException; import co.chatsdk.core.events.EventType; import co.chatsdk.core.events.NetworkEvent; import co.chatsdk.core.handlers.AudioMessageHandler; import co.chatsdk.core.handlers.AuthenticationHandler; import co.chatsdk.core.handlers.BlockingHandler; import co.chatsdk.core.handlers.ContactHandler; import co.chatsdk.core.handlers.CoreHandler; import co.chatsdk.core.handlers.EventHandler; import co.chatsdk.core.handlers.FileMessageHandler; import co.chatsdk.core.handlers.HookHandler; import co.chatsdk.core.handlers.ImageMessageHandler; import co.chatsdk.core.handlers.LastOnlineHandler; import co.chatsdk.core.handlers.LocationMessageHandler; import co.chatsdk.core.handlers.PublicThreadHandler; import co.chatsdk.core.handlers.PushHandler; import co.chatsdk.core.handlers.ReadReceiptHandler; import co.chatsdk.core.handlers.SearchHandler; import co.chatsdk.core.handlers.SocialLoginHandler; import co.chatsdk.core.handlers.StickerMessageHandler; import co.chatsdk.core.handlers.ThreadHandler; import co.chatsdk.core.handlers.TypingIndicatorHandler; import co.chatsdk.core.handlers.UploadHandler; import co.chatsdk.core.handlers.VideoMessageHandler; import co.chatsdk.core.interfaces.InterfaceAdapter; import co.chatsdk.core.interfaces.LocalNotificationHandler; import co.chatsdk.core.interfaces.ThreadType; import co.chatsdk.core.types.ReadStatus; import co.chatsdk.core.utils.AppBackgroundMonitor; import co.chatsdk.core.utils.NotificationUtils; import co.chatsdk.core.dao.Thread; import io.reactivex.disposables.Disposable; import timber.log.Timber; /** * Created by ben on 9/5/17. */ public class ChatSDK { public static String Preferences = "chat_sdk_preferences"; private static final ChatSDK instance = new ChatSDK(); public WeakReference<Context> context; public Configuration config; public Disposable localNotificationDisposable; protected ChatSDK () { } private void setContext (Context context) { this.context = new WeakReference<>(context); } public static ChatSDK initialize (Configuration config) throws ChatSDKException { return initialize(config, null, null); } public static ChatSDK initialize (Configuration config, InterfaceAdapter interfaceAdapter, BaseNetworkAdapter networkAdapter) throws ChatSDKException { shared().setContext(config.context.get()); shared().config = config; DaoCore.init(shared().context()); if(interfaceAdapter != null) { InterfaceManager.shared().a = interfaceAdapter; } else { shared().activateModule("UserInterfaceModule", "activate", new MethodArgument(Context.class, shared().context())); } if (networkAdapter != null) { NetworkManager.shared().a = networkAdapter; } else { shared().activateModule("FirebaseModule", "activate"); } shared().handleLocalNotifications(); // Monitor the app so if it goes into the background we know AppBackgroundMonitor.shared().setEnabled(true); if (config().debug) { Timber.plant(new Timber.DebugTree()); } return shared(); } public void activateModule (String moduleName, String methodName, MethodArgument... arguments) throws ChatSDKException { try { ArrayList<Class<?>> classes = new ArrayList<>(); ArrayList<Object> values = new ArrayList<>(); for(MethodArgument a : arguments) { classes.add(a.type); values.add(a.value); } Class<?> interfaceModule = Class.forName(moduleName); Method method = interfaceModule.getMethod(methodName, classes.toArray(new Class<?>[0])); method.invoke(null, values.toArray(new Object[0])); } catch (ClassNotFoundException e) { throw new ChatSDKException("Module: " + moduleName + "Not found"); } catch (NoSuchMethodException e) { throw new ChatSDKException("Activate method not found for module"); } catch (IllegalAccessException e) { throw new ChatSDKException("Activate method not found for module"); } catch (InvocationTargetException e) { throw new ChatSDKException("Activate method not found for module"); } } public void handleLocalNotifications () { if (localNotificationDisposable != null) { localNotificationDisposable.dispose(); } // TODO: Check this localNotificationDisposable = ChatSDK.events().sourceOnMain() .filter(NetworkEvent.filterType(EventType.MessageAdded)) .subscribe(networkEvent -> { Message message = networkEvent.message; Thread thread = networkEvent.thread; if(message != null && !AppBackgroundMonitor.shared().inBackground()) { if (thread.typeIs(ThreadType.Private) || (thread.typeIs(ThreadType.Public) && ChatSDK.config().pushNotificationsForPublicChatRoomsEnabled)) { if(!message.getSender().isMe() && ChatSDK.ui().showLocalNotifications(message.getThread())) { ReadStatus status = message.readStatusForUser(ChatSDK.currentUser()); if (!message.isRead() && !status.is(ReadStatus.delivered())) { // Only show the alert if we'recyclerView not on the private threads tab NotificationUtils.createMessageNotification(message); } } } } }); } public void setLocalNotificationHandler (LocalNotificationHandler handler) { } public static ChatSDK shared () { return instance; } public SharedPreferences getPreferences () { return context.get().getSharedPreferences(Preferences, Context.MODE_PRIVATE); } public Context context () { return context.get(); } public static Configuration config () { return shared().config; } public static void logError (Throwable t) { logError(new Exception(t)); } public static void logError (Exception e) { if (config().debug) { e.printStackTrace(); } if (config().crashHandler != null) { config().crashHandler.log(e); } } /** * Shortcut to return the interface adapter * @return InterfaceAdapter */ public static InterfaceAdapter ui () { return InterfaceManager.shared().a; } public void setInterfaceAdapter (InterfaceAdapter interfaceAdapter) { InterfaceManager.shared().a = interfaceAdapter; } public static CoreHandler core () { return a().core; } public static AuthenticationHandler auth () { return a().auth; } public static ThreadHandler thread () { return a().thread; } public static PublicThreadHandler publicThread () { return a().publicThread; } public static PushHandler push () { return a().push; } public static UploadHandler upload () { return a().upload; } public static EventHandler events () { return a().events; } public static User currentUser () { return ChatSDK.core().currentUserModel(); } public static SearchHandler search () { return a().search; } public static ContactHandler contact () { return a().contact; } public static BlockingHandler blocking () { return a().blocking; } public static LastOnlineHandler lastOnline () { return a().lastOnline; } public static AudioMessageHandler audioMessage () { return a().audioMessage; } public static VideoMessageHandler videoMessage () { return a().videoMessage; } public static HookHandler hook () { return a().hook; } public static SocialLoginHandler socialLogin () { return a().socialLogin; } public static StickerMessageHandler stickerMessage () { return a().stickerMessage; } public static FileMessageHandler fileMessage () { return a().fileMessage; } public static ImageMessageHandler imageMessage () { return a().imageMessage; } public static LocationMessageHandler locationMessage () { return a().locationMessage; } public static ReadReceiptHandler readReceipts () { return a().readReceipts; } public static TypingIndicatorHandler typingIndicator () { return a().typingIndicator; } public static BaseNetworkAdapter a() { return NetworkManager.shared().a; } }
chat-sdk-core/src/main/java/co/chatsdk/core/session/ChatSDK.java
package co.chatsdk.core.session; import android.content.Context; import android.content.SharedPreferences; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import co.chatsdk.core.base.BaseNetworkAdapter; import co.chatsdk.core.dao.DaoCore; import co.chatsdk.core.dao.Message; import co.chatsdk.core.dao.User; import co.chatsdk.core.error.ChatSDKException; import co.chatsdk.core.events.EventType; import co.chatsdk.core.events.NetworkEvent; import co.chatsdk.core.handlers.AudioMessageHandler; import co.chatsdk.core.handlers.AuthenticationHandler; import co.chatsdk.core.handlers.BlockingHandler; import co.chatsdk.core.handlers.ContactHandler; import co.chatsdk.core.handlers.CoreHandler; import co.chatsdk.core.handlers.EventHandler; import co.chatsdk.core.handlers.FileMessageHandler; import co.chatsdk.core.handlers.HookHandler; import co.chatsdk.core.handlers.ImageMessageHandler; import co.chatsdk.core.handlers.LastOnlineHandler; import co.chatsdk.core.handlers.LocationMessageHandler; import co.chatsdk.core.handlers.PublicThreadHandler; import co.chatsdk.core.handlers.PushHandler; import co.chatsdk.core.handlers.ReadReceiptHandler; import co.chatsdk.core.handlers.SearchHandler; import co.chatsdk.core.handlers.SocialLoginHandler; import co.chatsdk.core.handlers.StickerMessageHandler; import co.chatsdk.core.handlers.ThreadHandler; import co.chatsdk.core.handlers.TypingIndicatorHandler; import co.chatsdk.core.handlers.UploadHandler; import co.chatsdk.core.handlers.VideoMessageHandler; import co.chatsdk.core.interfaces.InterfaceAdapter; import co.chatsdk.core.interfaces.LocalNotificationHandler; import co.chatsdk.core.interfaces.ThreadType; import co.chatsdk.core.types.ReadStatus; import co.chatsdk.core.utils.AppBackgroundMonitor; import co.chatsdk.core.utils.NotificationUtils; import co.chatsdk.core.dao.Thread; import io.reactivex.disposables.Disposable; import timber.log.Timber; /** * Created by ben on 9/5/17. */ public class ChatSDK { public static String Preferences = "chat_sdk_preferences"; private static final ChatSDK instance = new ChatSDK(); public WeakReference<Context> context; public Configuration config; public Disposable localNotificationDisposable; protected ChatSDK () { } private void setContext (Context context) { this.context = new WeakReference<>(context); } public static ChatSDK initialize (Configuration config) throws ChatSDKException { return initialize(config, null, null); } public static ChatSDK initialize (Configuration config, InterfaceAdapter interfaceAdapter, BaseNetworkAdapter networkAdapter) throws ChatSDKException { shared().setContext(config.context.get()); shared().config = config; DaoCore.init(shared().context()); if(interfaceAdapter != null) { InterfaceManager.shared().a = interfaceAdapter; } else { shared().activateModule("UserInterfaceModule", "activate", new MethodArgument(Context.class, shared().context())); } if (networkAdapter != null) { NetworkManager.shared().a = networkAdapter; } else { shared().activateModule("FirebaseModule", "activate"); } shared().handleLocalNotifications(); // Monitor the app so if it goes into the background we know AppBackgroundMonitor.shared().setEnabled(true); // if (debug) { // TODO: Update this Timber.plant(new Timber.DebugTree()); // } else { // Timber.plant(new Timber.Tree()); // } return shared(); } public void activateModule (String moduleName, String methodName, MethodArgument... arguments) throws ChatSDKException { try { ArrayList<Class<?>> classes = new ArrayList<>(); ArrayList<Object> values = new ArrayList<>(); for(MethodArgument a : arguments) { classes.add(a.type); values.add(a.value); } Class<?> interfaceModule = Class.forName(moduleName); Method method = interfaceModule.getMethod(methodName, classes.toArray(new Class<?>[0])); method.invoke(null, values.toArray(new Object[0])); } catch (ClassNotFoundException e) { throw new ChatSDKException("Module: " + moduleName + "Not found"); } catch (NoSuchMethodException e) { throw new ChatSDKException("Activate method not found for module"); } catch (IllegalAccessException e) { throw new ChatSDKException("Activate method not found for module"); } catch (InvocationTargetException e) { throw new ChatSDKException("Activate method not found for module"); } } public void handleLocalNotifications () { if (localNotificationDisposable != null) { localNotificationDisposable.dispose(); } // TODO: Check this localNotificationDisposable = ChatSDK.events().sourceOnMain() .filter(NetworkEvent.filterType(EventType.MessageAdded)) .subscribe(networkEvent -> { Message message = networkEvent.message; Thread thread = networkEvent.thread; if(message != null && !AppBackgroundMonitor.shared().inBackground()) { if (thread.typeIs(ThreadType.Private) || (thread.typeIs(ThreadType.Public) && ChatSDK.config().pushNotificationsForPublicChatRoomsEnabled)) { if(!message.getSender().isMe() && ChatSDK.ui().showLocalNotifications(message.getThread())) { ReadStatus status = message.readStatusForUser(ChatSDK.currentUser()); if (!message.isRead() && !status.is(ReadStatus.delivered())) { // Only show the alert if we'recyclerView not on the private threads tab NotificationUtils.createMessageNotification(message); } } } } }); } public void setLocalNotificationHandler (LocalNotificationHandler handler) { } public static ChatSDK shared () { return instance; } public SharedPreferences getPreferences () { return context.get().getSharedPreferences(Preferences, Context.MODE_PRIVATE); } public Context context () { return context.get(); } public static Configuration config () { return shared().config; } public static void logError (Throwable t) { logError(new Exception(t)); } public static void logError (Exception e) { if (config().debug) { e.printStackTrace(); } if (config().crashHandler != null) { config().crashHandler.log(e); } } /** * Shortcut to return the interface adapter * @return InterfaceAdapter */ public static InterfaceAdapter ui () { return InterfaceManager.shared().a; } public void setInterfaceAdapter (InterfaceAdapter interfaceAdapter) { InterfaceManager.shared().a = interfaceAdapter; } public static CoreHandler core () { return a().core; } public static AuthenticationHandler auth () { return a().auth; } public static ThreadHandler thread () { return a().thread; } public static PublicThreadHandler publicThread () { return a().publicThread; } public static PushHandler push () { return a().push; } public static UploadHandler upload () { return a().upload; } public static EventHandler events () { return a().events; } public static User currentUser () { return ChatSDK.core().currentUserModel(); } public static SearchHandler search () { return a().search; } public static ContactHandler contact () { return a().contact; } public static BlockingHandler blocking () { return a().blocking; } public static LastOnlineHandler lastOnline () { return a().lastOnline; } public static AudioMessageHandler audioMessage () { return a().audioMessage; } public static VideoMessageHandler videoMessage () { return a().videoMessage; } public static HookHandler hook () { return a().hook; } public static SocialLoginHandler socialLogin () { return a().socialLogin; } public static StickerMessageHandler stickerMessage () { return a().stickerMessage; } public static FileMessageHandler fileMessage () { return a().fileMessage; } public static ImageMessageHandler imageMessage () { return a().imageMessage; } public static LocationMessageHandler locationMessage () { return a().locationMessage; } public static ReadReceiptHandler readReceipts () { return a().readReceipts; } public static TypingIndicatorHandler typingIndicator () { return a().typingIndicator; } public static BaseNetworkAdapter a() { return NetworkManager.shared().a; } }
Do not logging in non-debug build types as recommended by Google and Timber
chat-sdk-core/src/main/java/co/chatsdk/core/session/ChatSDK.java
Do not logging in non-debug build types as recommended by Google and Timber
<ide><path>hat-sdk-core/src/main/java/co/chatsdk/core/session/ChatSDK.java <ide> // Monitor the app so if it goes into the background we know <ide> AppBackgroundMonitor.shared().setEnabled(true); <ide> <del>// if (debug) { <del> // TODO: Update this <add> if (config().debug) { <ide> Timber.plant(new Timber.DebugTree()); <del>// } else { <del>// Timber.plant(new Timber.Tree()); <del>// } <add> } <ide> <ide> return shared(); <ide> }
Java
apache-2.0
584b24e9e4c1b09f09092b51b4f9baddd67c81e5
0
hongsudt/server,HaiJiaoXinHeng/server-1,HaiJiaoXinHeng/server-1,hongsudt/server,HaiJiaoXinHeng/server-1,hongsudt/server
package org.ohmage.service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.Map; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.cache.PreferenceCache; import org.ohmage.exception.CacheMissException; import org.ohmage.exception.ServiceException; /** * This class contains the services for visualization requests. * * @author John Jenkins */ public class VisualizationServices { private static final String APPLICATION_PATH = "/app"; /** * The token parameter key for the visualization server. */ private static final String PARAMETER_KEY_TOKEN = "token"; /** * The server parameter key for the visualization server. */ private static final String PARAMETER_KEY_SERVER = "server"; /** * The campaign ID parameter key for the visualization server. */ private static final String PARAMETER_KEY_CAMPAIGN_ID = "campaign_urn"; /** * The width parameter key for the visualization server. */ private static final String PARAMETER_KEY_WIDTH = "!width"; /** * The height parameter key for the visualization server. */ private static final String PARAMETER_KEY_HEIGHT = "!height"; /** * The start date which limits the range of visible survey responses to * those on or after this date. */ public static final String PARAMETER_KEY_START_DATE = "start_date"; /** * The end date which limits the range of visible survey responses to those * on or before this date. */ public static final String PARAMETER_KEY_END_DATE = "end_date"; /** * The privacy state which limits the survey responses to only those whose * privacy state matches this privacy state. */ public static final String PARAMETER_KEY_PRIVACY_STATE = "privacy_state"; /** * The single prompt ID parameter key for the visualization server. */ public static final String PARAMETER_KEY_PROMPT_ID = "prompt_id"; /** * The second prompt ID parameter key for the visualization server. */ public static final String PARAMETER_KEY_PROMPT2_ID = "prompt2_id"; /** * The username parameter key for the visualization server. */ public static final String PARAMETER_KEY_USERNAME = "user_id"; /** * Default constructor. Made private so that it cannot be instantiated. */ private VisualizationServices() {} /** * Sends a request to the visualization server and returns the image as a * byte array that was returned by the visualization server. * * @param requestPath The additional path beyond the base URI that is * stored in the database. An example would be, if the * database stored the visualization server's address as * "https://viz.server.com/R/visualzations" then this * parameter could be "survey_response_count" which * would result in a URL of * "https://viz.server/com/R/visualizations/survey_response_count?param1=...". * * @param userToken The authentication token for the requesting user that * will be passed on to the visualization server to * perform subsequent requests on our behalf. * * @param campaignId The unique identifier for the campaign whose * information will be used in conjunction with this * request and any subsequent parameters. * * @param width The desired width of the resulting visualization. * * @param height The desired height of the resulting visualization. * * @param parameters Any additional parameters that should be passed to the * visualization server. Their key values will be used as * the key in the HTTP parameter and their actual value * will be their single-quoted HTTP parameter value. * * @return Returns a byte[] representation of the visualization image. * * @throws ServiceException Thrown if there is an error. */ public static byte[] sendVisualizationRequest(final String requestPath, final String userToken, final String campaignId, final int width, final int height, final Map<String, String> parameters) throws ServiceException { // Build the request. StringBuilder urlBuilder = new StringBuilder(); try { String serverUrl = PreferenceCache.instance().lookup(PreferenceCache.KEY_VISUALIZATION_SERVER); urlBuilder.append(serverUrl); if(! serverUrl.endsWith("/")) { urlBuilder.append("/"); } } catch(CacheMissException e) { throw new ServiceException( "Cache doesn't know about 'known' key: " + PreferenceCache.KEY_VISUALIZATION_SERVER, e); } urlBuilder.append(requestPath).append("?"); // Get this machine's hostname. String hostname; try { hostname = InetAddress.getLocalHost().getHostName(); } catch(UnknownHostException e) { throw new ServiceException( "The sky is falling! Oh, and our own hostname is unknown.", e); } // Get the protocol string based on SSL being enabled. String httpString = "http"; try { String sslEnabled = PreferenceCache.instance().lookup(PreferenceCache.KEY_SSL_ENABLED); if((sslEnabled != null) && (sslEnabled.equals("true"))) { httpString = "https"; } } catch(CacheMissException e) { throw new ServiceException( "Cache doesn't know about 'known' key: " + PreferenceCache.KEY_PROPERTIES_FILE, e); } // Add the required parameters. urlBuilder.append(PARAMETER_KEY_TOKEN).append("='").append(userToken).append("'"); urlBuilder.append("&").append(PARAMETER_KEY_SERVER).append("='").append(httpString).append("://").append(hostname).append(APPLICATION_PATH).append("'"); urlBuilder.append("&").append(PARAMETER_KEY_CAMPAIGN_ID).append("='").append(campaignId).append("'"); urlBuilder.append("&").append(PARAMETER_KEY_WIDTH).append("=").append(width); urlBuilder.append("&").append(PARAMETER_KEY_HEIGHT).append("=").append(height); // Add all of the non-required, request-specific parameters. for(String key : parameters.keySet()) { urlBuilder.append("&").append(key).append("='").append(parameters.get(key)).append("'"); } // Generate the URL String. String urlString = urlBuilder.toString(); try { // Connect to the visualization server. URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); // Check that the response code was 200. if(urlConnection instanceof HttpURLConnection) { HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection; // If a non-200 response was returned, get the text from the // response. if(httpUrlConnection.getResponseCode() != 200) { // Get the error text. ByteArrayOutputStream errorByteStream = new ByteArrayOutputStream(); InputStream errorStream = httpUrlConnection.getErrorStream(); byte[] chunk = new byte[4096]; int amountRead; while((amountRead = errorStream.read(chunk)) != -1) { errorByteStream.write(chunk, 0, amountRead); } // Echo the error. throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "There was an error. Please, try again later.", "The server returned the HTTP error code '" + httpUrlConnection.getResponseCode() + "' with the error '" + errorByteStream.toString() + "': " + urlString); } } // Build the response. InputStream reader = urlConnection.getInputStream(); // Generate the byte array. ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead = 0; while((amountRead = reader.read(chunk)) != -1) { byteArrayStream.write(chunk, 0, amountRead); } return byteArrayStream.toByteArray(); } catch(MalformedURLException e) { throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "Built a malformed URL: " + urlString, e); } catch(IOException e) { throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "Error while communicating with the visualization server.", e); } } }
src/org/ohmage/service/VisualizationServices.java
package org.ohmage.service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.Map; import org.ohmage.annotator.Annotator.ErrorCode; import org.ohmage.cache.PreferenceCache; import org.ohmage.exception.CacheMissException; import org.ohmage.exception.ServiceException; /** * This class contains the services for visualization requests. * * @author John Jenkins */ public class VisualizationServices { private static final String APPLICATION_PATH = "/app"; /** * The token parameter key for the visualization server. */ private static final String PARAMETER_KEY_TOKEN = "token"; /** * The server parameter key for the visualization server. */ private static final String PARAMETER_KEY_SERVER = "server"; /** * The campaign ID parameter key for the visualization server. */ private static final String PARAMETER_KEY_CAMPAIGN_ID = "campaign_urn"; /** * The width parameter key for the visualization server. */ private static final String PARAMETER_KEY_WIDTH = "!width"; /** * The height parameter key for the visualization server. */ private static final String PARAMETER_KEY_HEIGHT = "!height"; /** * The start date which limits the range of visible survey responses to * those on or after this date. */ public static final String PARAMETER_KEY_START_DATE = "start_date"; /** * The end date which limits the range of visible survey responses to those * on or before this date. */ public static final String PARAMETER_KEY_END_DATE = "end_date"; /** * The privacy state which limits the survey responses to only those whose * privacy state matches this privacy state. */ public static final String PARAMETER_KEY_PRIVACY_STATE = "privacy_state"; /** * The single prompt ID parameter key for the visualization server. */ public static final String PARAMETER_KEY_PROMPT_ID = "prompt_id"; /** * The second prompt ID parameter key for the visualization server. */ public static final String PARAMETER_KEY_PROMPT2_ID = "prompt2_id"; /** * The username parameter key for the visualization server. */ public static final String PARAMETER_KEY_USERNAME = "user_id"; /** * Default constructor. Made private so that it cannot be instantiated. */ private VisualizationServices() {} /** * Sends a request to the visualization server and returns the image as a * byte array that was returned by the visualization server. * * @param requestPath The additional path beyond the base URI that is * stored in the database. An example would be, if the * database stored the visualization server's address as * "https://viz.server.com/R/visualzations" then this * parameter could be "survey_response_count" which * would result in a URL of * "https://viz.server/com/R/visualizations/survey_response_count?param1=...". * * @param userToken The authentication token for the requesting user that * will be passed on to the visualization server to * perform subsequent requests on our behalf. * * @param campaignId The unique identifier for the campaign whose * information will be used in conjunction with this * request and any subsequent parameters. * * @param width The desired width of the resulting visualization. * * @param height The desired height of the resulting visualization. * * @param parameters Any additional parameters that should be passed to the * visualization server. Their key values will be used as * the key in the HTTP parameter and their actual value * will be their single-quoted HTTP parameter value. * * @return Returns a byte[] representation of the visualization image. * * @throws ServiceException Thrown if there is an error. */ public static byte[] sendVisualizationRequest(final String requestPath, final String userToken, final String campaignId, final int width, final int height, final Map<String, String> parameters) throws ServiceException { // Build the request. StringBuilder urlBuilder = new StringBuilder(); try { String serverUrl = PreferenceCache.instance().lookup(PreferenceCache.KEY_VISUALIZATION_SERVER); urlBuilder.append(serverUrl); if(! serverUrl.endsWith("/")) { urlBuilder.append("/"); } } catch(CacheMissException e) { throw new ServiceException( "Cache doesn't know about 'known' key: " + PreferenceCache.KEY_VISUALIZATION_SERVER, e); } urlBuilder.append(requestPath).append("?"); // Get this machine's hostname. String hostname; try { hostname = InetAddress.getLocalHost().getHostName(); } catch(UnknownHostException e) { throw new ServiceException( "The sky is falling! Oh, and our own hostname is unknown.", e); } // Get the protocol string based on SSL being enabled. String httpString = "http"; try { String sslEnabled = PreferenceCache.instance().lookup(PreferenceCache.KEY_SSL_ENABLED); if((sslEnabled != null) && (sslEnabled.equals("true"))) { httpString = "https"; } } catch(CacheMissException e) { throw new ServiceException( "Cache doesn't know about 'known' key: " + PreferenceCache.KEY_PROPERTIES_FILE, e); } // Add the required parameters. urlBuilder.append(PARAMETER_KEY_TOKEN).append("='").append(userToken).append("'"); urlBuilder.append("&").append(PARAMETER_KEY_SERVER).append("='").append(httpString).append("://").append(hostname).append(APPLICATION_PATH).append("'"); urlBuilder.append("&").append(PARAMETER_KEY_CAMPAIGN_ID).append("='").append(campaignId).append("'"); urlBuilder.append("&").append(PARAMETER_KEY_WIDTH).append("=").append(width); urlBuilder.append("&").append(PARAMETER_KEY_HEIGHT).append("=").append(height); // Add all of the non-required, request-specific parameters. for(String key : parameters.keySet()) { urlBuilder.append("&").append(key).append("='").append(parameters.get(key)).append("'"); } // Generate the URL String. String urlString = urlBuilder.toString(); try { // Connect to the visualization server. URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); // Check that the response code was 200. if(urlConnection instanceof HttpURLConnection) { HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection; // If a non-200 response was returned, get the text from the // response. if(httpUrlConnection.getResponseCode() != 200) { // Get the error text. ByteArrayOutputStream errorByteStream = new ByteArrayOutputStream(); InputStream errorStream = httpUrlConnection.getErrorStream(); byte[] chunk = new byte[4096]; int amountRead; while((amountRead = errorStream.read(chunk)) != -1) { errorByteStream.write(chunk, 0, amountRead); } // Trim the first line. String[] errorContentArray = errorByteStream.toString().split("\n", 2); // If we didn't end up with two lines, then this is an // unknown error response. if(errorContentArray.length == 2) { throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "There was an error. Please, try again later.", "The server returned the HTTP error code '" + httpUrlConnection.getResponseCode() + "' with the error '" + errorContentArray[1].trim() + "': " + urlString); } else { throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "The server returned a non-200 response: " + urlString); } } } // Build the response. InputStream reader = urlConnection.getInputStream(); // Generate the byte array. ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead = 0; while((amountRead = reader.read(chunk)) != -1) { byteArrayStream.write(chunk, 0, amountRead); } return byteArrayStream.toByteArray(); } catch(MalformedURLException e) { throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "Built a malformed URL: " + urlString, e); } catch(IOException e) { throw new ServiceException( ErrorCode.VISUALIZATION_GENERAL_ERROR, "Error while communicating with the visualization server.", e); } } }
Updated the output for visualization requests to include the entire error message when it fails.
src/org/ohmage/service/VisualizationServices.java
Updated the output for visualization requests to include the entire error message when it fails.
<ide><path>rc/org/ohmage/service/VisualizationServices.java <ide> errorByteStream.write(chunk, 0, amountRead); <ide> } <ide> <del> // Trim the first line. <del> String[] errorContentArray = errorByteStream.toString().split("\n", 2); <del> <del> // If we didn't end up with two lines, then this is an <del> // unknown error response. <del> if(errorContentArray.length == 2) { <del> throw new ServiceException( <del> ErrorCode.VISUALIZATION_GENERAL_ERROR, <del> "There was an error. Please, try again later.", <del> "The server returned the HTTP error code '" + <del> httpUrlConnection.getResponseCode() + <del> "' with the error '" + <del> errorContentArray[1].trim() + <del> "': " + <del> urlString); <del> } <del> else { <del> throw new ServiceException( <del> ErrorCode.VISUALIZATION_GENERAL_ERROR, <del> "The server returned a non-200 response: " + <del> urlString); <del> } <add> // Echo the error. <add> throw new ServiceException( <add> ErrorCode.VISUALIZATION_GENERAL_ERROR, <add> "There was an error. Please, try again later.", <add> "The server returned the HTTP error code '" + <add> httpUrlConnection.getResponseCode() + <add> "' with the error '" + <add> errorByteStream.toString() + <add> "': " + <add> urlString); <ide> } <ide> } <ide>
Java
apache-2.0
5f013a1e3b351c7966c2b99c89b1e83d6ee09d28
0
webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno
/******************************************************************************* * Copyright 2012 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.clarin.webanno.api; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.NoResultException; import org.apache.uima.UIMAException; import org.apache.uima.cas.CAS; import org.apache.uima.jcas.JCas; import org.springframework.security.access.prepost.PreAuthorize; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.Authority; import de.tudarmstadt.ukp.clarin.webanno.model.ConstraintSet; import de.tudarmstadt.ukp.clarin.webanno.model.CrowdJob; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.PermissionLevel; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.ProjectPermission; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.User; /** * This interface contains methods that are related to accessing/creating/deleting... documents, * Users, and Projects for the annotation system. while meta data about documents and projects and * users are stored in the database, source and annotation documents are stored in a file system * * */ public interface RepositoryService { // -------------------------------------------------------------------------------------------- // Methods related to permissions // -------------------------------------------------------------------------------------------- /** * Returns a role of a user, globally we will have ROLE_ADMIN and ROLE_USER * * @param user * the {@link User} object * @return the roles. */ List<Authority> listAuthorities(User user); /** * creates a project permission, adding permission level for the user in the given project * * @param permission * the permission * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER', 'ROLE_REMOTE')") void createProjectPermission(ProjectPermission permission) throws IOException; /** * Check if a user have at least one {@link PermissionLevel } for this {@link Project} * * @param user * the user. * @param project * the project. * * @return if the project permission exists. */ boolean existsProjectPermission(User user, Project project); /** * Check if there is already a {@link PermissionLevel} on a given {@link Project} for a given * {@link User} * * @param user * the user. * @param project * the project. * @param level * the permission level. * * @return if the permission exists. */ boolean existsProjectPermissionLevel(User user, Project project, PermissionLevel level); /** * Get a {@link ProjectPermission }objects where a project is member of. We need to get them, for * example if the associated {@link Project} is deleted, the {@link ProjectPermission } objects * too. * * @param project * The project contained in a projectPermision * @return the {@link ProjectPermission } list to be analysed. */ List<ProjectPermission> getProjectPermisions(Project project); /** * Get list of permissions a user have in a given project * * @param user * the user. * @param project * the project. * * @return the permissions. */ List<ProjectPermission> listProjectPermisionLevel(User user, Project project); /** * List Users those with some {@link PermissionLevel}s in the project * * @param project * the project. * @return the users. */ List<User> listProjectUsersWithPermissions(Project project); /** * List of users with the a given {@link PermissionLevel} * * @param project * The {@link Project} * @param permissionLevel * The {@link PermissionLevel} * @return the users. */ List<User> listProjectUsersWithPermissions(Project project, PermissionLevel permissionLevel); /** * remove a user permission from the project * * @param projectPermission * The ProjectPermission to be removed * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void removeProjectPermission(ProjectPermission projectPermission) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to SourceDocuments // -------------------------------------------------------------------------------------------- /** * Creates a {@link SourceDocument} in a database. The source document is created by ROLE_ADMIN * or Project admins. Source documents are created per project and it should have a unique name * in the {@link Project} it belongs. renaming a a source document is not possible, rather the * administrator should delete and re create it. * * @param document * {@link SourceDocument} to be created * @param user * The User who perform this operation * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") void createSourceDocument(SourceDocument document, User user) throws IOException; /** * Check if a Source document with this same name exist in the project. The caller method then * can decide to override or throw an exception/message to the client * * @param project * the project. * @param fileName * the source document name. * @return if the source document exists. */ boolean existsSourceDocument(Project project, String fileName); /** * Get meta data information about {@link SourceDocument} from the database. This method is * called either for {@link AnnotationDocument} object creation or * {@link RepositoryService#createSourceDocument(SourceDocument, User)} * * @param project * the {@link Project} where the {@link SourceDocument} belongs * @param documentName * the name of the {@link SourceDocument} * @return the source document. */ SourceDocument getSourceDocument(Project project, String documentName); /** * Get meta data information about {@link SourceDocument} from the database. * * @param projectId * the id for the {@link Project} * @param documentId * the id for the {@link SourceDocument} * @return the source document */ SourceDocument getSourceDocument(long projectId, long documentId); /** * Return the Master TCF file Directory path. For the first time, all available TCF layers will * be read and converted to CAS object. subsequent accesses will be to the annotated document * unless and otherwise the document is removed from the project. * * @param document * The {@link SourceDocument} to be examined * @return the Directory path of the source document */ File getSourceDocumentFile(SourceDocument document); /** * List all source documents in a project. The source documents are the original TCF documents * imported. * * @param aProject * The Project we are looking for source documents * @return list of source documents */ List<SourceDocument> listSourceDocuments(Project aProject); /** * ROLE_ADMINs or project admins can remove source documents from a project. removing a a source * document also removes an annotation document related to that document * * @param document * the source document to be deleted * @throws IOException * If the source document searched for deletion is not available */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER', 'ROLE_REMOTE')") void removeSourceDocument(SourceDocument document) throws IOException; @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") void uploadSourceDocument(File file, SourceDocument document) throws IOException, UIMAException; /** * Upload a SourceDocument, obtained as Inputstream, such as from remote API Zip folder to a * repository directory. This way we don't need to create the file to a temporary folder * * @param file * the file. * @param document * the source document. * @throws IOException * if an I/O error occurs. * @throws UIMAException * if a conversion error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") void uploadSourceDocument(InputStream file, SourceDocument document) throws IOException, UIMAException; /** * Get the directory of this {@link SourceDocument} usually to read the content of the document * * @param aDocument * the source document. * @return the source document folder. * @throws IOException * if an I/O error occurs. */ File getDocumentFolder(SourceDocument aDocument) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to AnnotationDocuments // -------------------------------------------------------------------------------------------- /** * creates the {@link AnnotationDocument } object in the database. * * @param annotationDocument * {@link AnnotationDocument} comprises of the the name of the {@link SourceDocument} * , id of {@link SourceDocument}, id of the {@link Project}, and id of {@link User} * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void createAnnotationDocument(AnnotationDocument annotationDocument) throws IOException; /** * Creates an annotation document. The {@link AnnotationDocument} is stored in the * webanno.home/project/Project.id/document/document.id/annotation/username.ser. annotated * documents are stored per project, user and document * * @param jCas * the JCas. * @param document * the source document. * @param user * The User who perform this operation * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void writeAnnotationCas(JCas jCas, SourceDocument document, User user) throws IOException; /** * A Method that checks if there is already an annotation document created for the source * document * * @param document * the source document. * @param user * the user. * @return if an annotation document metadata exists for the user. */ boolean existsAnnotationDocument(SourceDocument document, User user); /** * A method to check if there exist a correction document already. Base correction document * should be the same for all users * * @param document * the source document. * @return if a correction document exists. */ boolean existsCorrectionDocument(SourceDocument document); /** * check if the JCAS for the {@link User} and {@link SourceDocument} in this {@link Project} * exists It is important as {@link AnnotationDocument} entry can be populated as * {@link AnnotationDocumentState#NEW} from the MonitoringPage before the user actually open the * document for annotation. * * @param sourceDocument * the source document. * @param username * the username. * @return if an annotation document file exists. * @throws IOException * if an I/O error occurs. */ boolean existsCas(SourceDocument sourceDocument, String username) throws IOException; /** * check if there is an already automated document. This is important as automated document * should appear the same among users * * @param sourceDocument * the source document. * @return if an automation document exists. */ boolean existsCorrectionCas(SourceDocument sourceDocument); /** * Exports an {@link AnnotationDocument } CAS Object as TCF/TXT/XMI... file formats. * * @param document * The {@link SourceDocument} where we get the id which hosts both the source * Document and the annotated document * @param user * the {@link User} who annotates the document. * @param writer * the DKPro Core writer. * @param fileName * the file name. * @param mode * the mode. * @return a temporary file. * @throws UIMAException * if there was a conversion error. * @throws IOException * if there was an I/O error. * @throws ClassNotFoundException * if the DKPro Core writer could not be found. */ @SuppressWarnings("rawtypes") File exportAnnotationDocument(SourceDocument document, String user, Class writer, String fileName, Mode mode) throws UIMAException, IOException, ClassNotFoundException; @SuppressWarnings("rawtypes") File exportAnnotationDocument(SourceDocument document, String user, Class writer, String fileName, Mode mode, boolean stripExtension) throws UIMAException, IOException, ClassNotFoundException; /** * Export a Serialized CAS annotation document from the file system * * @param document * the source document. * @param user * the username. * @return the serialized CAS file. */ File getCasFile(SourceDocument document, String user); /** * Get the annotation document. * * @param document * the source document. * @param user * the user. * @return the annotation document. * @throws NoResultException * if no annotation document exists for the given source/user. */ AnnotationDocument getAnnotationDocument(SourceDocument document, User user); /** * Gets the CAS for the given annotation document. Converts it form the source document if * necessary. * * @param annotationDocument * the annotation document. * @return the JCas. * @throws IOException * if there was an I/O error. */ JCas readAnnotationCas(AnnotationDocument annotationDocument) throws IOException; /** * Gets the CAS for the given annotation document. Converts it form the source document if * necessary. If necessary, no annotation document exists, one is created. The source document * is set into state {@link SourceDocumentState#ANNOTATION_IN_PROGRESS}. * * @param document * the source document. * @param user * the user. * @return the JCas. * @throws IOException * if there was an I/O error. * @deprecated use {@link #createOrGetAnnotationDocument(SourceDocument, User)} and * {@link #readAnnotationCas(AnnotationDocument)} instead and manually set source * document status manually if desired. */ @Deprecated JCas readAnnotationCas(SourceDocument document, User user) throws IOException; /** * List all the {@link AnnotationDocument}s, if available for a given {@link SourceDocument} in * the {@link Project}. Returns list of {@link AnnotationDocument}s for all {@link User}s in the * {@link Project} that has already annotated the {@link SourceDocument} * * @param document * the {@link SourceDocument} * @return {@link AnnotationDocument} */ List<AnnotationDocument> listAnnotationDocuments(SourceDocument document); /** * Number of expected annotation documents in this project (numUser X document - Ignored) * * @param project * the project. * @return the number of annotation documents. */ int numberOfExpectedAnnotationDocuments(Project project); /** * List all annotation Documents in a project that are already closed. used to compute overall * project progress * * @param project * the project. * @return the annotation documents. */ List<AnnotationDocument> listFinishedAnnotationDocuments(Project project); /** * List all annotation documents for this source document (including in active and delted user * annotation and those created by project admins or super admins for Test purpose. This method * is called when a source document (or Project) is deleted so that associated annotation * documents also get removed. * * @param document * the source document. * @return the annotation documents. */ List<AnnotationDocument> listAllAnnotationDocuments(SourceDocument document); /** * Check if the user finished annotating the {@link SourceDocument} in this {@link Project} * * @param document * the source document. * @param user * the user. * @return if the user has finished annotation. */ boolean isAnnotationFinished(SourceDocument document, User user); /** * Check if at least one annotation document is finished for this {@link SourceDocument} in the * project * * @param document * the source document. * @return if any finished annotation exists. */ boolean existsFinishedAnnotation(SourceDocument document); /** * If at least one {@link AnnotationDocument} is finished in this project */ boolean existsFinishedAnnotation(Project project); /** * list Projects which contain with those annotation documents state is finished */ List<Project> listProjectsWithFinishedAnnos(); /** * Remove an annotation document, for example, when a user is removed from a project * * @param annotationDocument * the {@link AnnotationDocument} to be removed */ void removeAnnotationDocument(AnnotationDocument annotationDocument); // -------------------------------------------------------------------------------------------- // Methods related to correction // -------------------------------------------------------------------------------------------- /** * Create an annotation document under a special user named "CORRECTION_USER" * * @param jCas * the JCas. * @param document * the source document. * @param user * the user. * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void writeCorrectionCas(JCas jCas, SourceDocument document, User user) throws IOException; JCas readCorrectionCas(SourceDocument document) throws UIMAException, IOException, ClassNotFoundException; // -------------------------------------------------------------------------------------------- // Methods related to curation // -------------------------------------------------------------------------------------------- /** * Create a curation annotation document under a special user named as "CURATION_USER" * * @param jCas * the JCas. * @param document * the source document. * @param user * the user. * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void writeCurationCas(JCas jCas, SourceDocument document, User user) throws IOException; /** * Get a curation document for the given {@link SourceDocument} * * @param document * the source document. * @return the curation JCas. * @throws UIMAException * if a conversion error occurs. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if the DKPro Core reader/writer cannot be loaded. */ JCas readCurationCas(SourceDocument document) throws UIMAException, IOException, ClassNotFoundException; /** * Remove a curation annotation document from the file system, for this {@link SourceDocument} * * @param sourceDocument * the source document. * @param username * the username. * @throws IOException * if an I/O error occurs. */ void removeCurationDocumentContent(SourceDocument sourceDocument, String username) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to Projects // -------------------------------------------------------------------------------------------- /** * Creates a {@code Project}. Creating a project needs a global ROLE_ADMIN role. For the first * time the project is created, an associated project path will be created on the file system as * {@code webanno.home/project/Project.id } * * @param project * The {@link Project} object to be created. * @param user * The User who perform this operation * @throws IOException * If the specified webanno.home directory is not available no write permission */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_REMOTE','ROLE_PROJECT_CREATOR')") void createProject(Project project, User user) throws IOException; /** * A method that check is a project exists with the same name already. getSingleResult() fails * if the project is not created, hence existProject returns false. * * @param name * the project name. * @return if the project exists. */ boolean existsProject(String name); /** * Check if there exists an project timestamp for this user and {@link Project}. * * @param project * the project. * @param username * the username. * @return if a timestamp exists. */ boolean existsProjectTimeStamp(Project project, String username); /** * check if there exists a timestamp for at least one source document in aproject (add when a * curator start curating) * * @param project * the project. * @return if a timestamp exists. */ boolean existsProjectTimeStamp(Project project); /** * Export the associated project log for this {@link Project} while copying a project * * @param project * the project. * @return the log file. */ File getProjectLogFile(Project project); File getMetaInfFolder(Project project); /** * Save some properties file associated to a project, such as meta-data.properties * * @param project * The project for which the user save some properties file. * @param is * the properties file. * @param fileName * the file name. * @throws IOException * if an I/O error occurs. */ void savePropertiesFile(Project project, InputStream is, String fileName) throws IOException; /** * Get a timestamp of for this {@link Project} of this username * * @param project * the project. * @param username * the username. * @return the timestamp. */ Date getProjectTimeStamp(Project project, String username); /** * get the timestamp, of the curator, if exist * * @param project * the project. * @return the timestamp. */ Date getProjectTimeStamp(Project project); /** * Get a {@link Project} from the database the name of the Project * * @param name * name of the project * @return {@link Project} object from the database or an error if the project is not found. * Exception is handled from the calling method. */ Project getProject(String name); /** * Get a project by its id. * * @param id * the ID. * @return the project. */ Project getProject(long id); /** * Determine if the project is created using the remote API webanno service or not TODO: For * now, it checks if the project consists of META-INF folder!! * * @param project * the project. * @return if it was created using the remote API. */ boolean isRemoteProject(Project project); /** * List all Projects. If the user logged have a ROLE_ADMIN, he can see all the projects. * Otherwise, a user will see projects only he is member of. * * @return the projects */ List<Project> listProjects(); /** * Remove a project. A ROLE_ADMIN or project admin can remove a project. removing a project will * remove associated source documents and annotation documents. * * @param project * the project to be deleted * @param user * The User who perform this operation * @throws IOException * if the project to be deleted is not available in the file system */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void removeProject(Project project, User user) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to guidelines // -------------------------------------------------------------------------------------------- /** * Write this {@code content} of the guideline file in the project; * * @param project * the project. * @param content * the guidelines. * @param fileName * the filename. * @param username * the username. * @throws IOException * if an I/O error occurs. */ void createGuideline(Project project, File content, String fileName, String username) throws IOException; /** * get the annotation guideline document from the file system * * @param project * the project. * @param fileName * the filename. * @return the file. */ File getGuideline(Project project, String fileName); /** * Export the associated project guideline for this {@link Project} while copying a project * * @param project * the project. * @return the file. */ File getGuidelinesFile(Project project); /** * List annotation guideline document already uploaded * * @param project * the project. * @return the filenames. */ List<String> listGuidelines(Project project); /** * Remove an annotation guideline document from the file system * * @param project * the project. * @param fileName * the filename. * @param username * the username. * @throws IOException * if an I/O error occurs. */ void removeGuideline(Project project, String fileName, String username) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to CrowdJobs // -------------------------------------------------------------------------------------------- /** * Create a crowd Project which contains some source document. A crowd project contains source * documents from {@link Project}(s), a {@link SourceDocument} belongs at most to one * {@link CrowdJob}. * * @param crowdProject * the job. * @throws IOException * if an I/O error occurs. */ void createCrowdJob(CrowdJob crowdProject) throws IOException; /** * Check if a crowd job already exist or not with its name * * @param name * the name. * @return if the job exists. */ boolean existsCrowdJob(String name); /** * Get a {@link CrowdJob} by its name in a {@link Project} * * @param name * the name. * @param project * the project. * @return the job. */ CrowdJob getCrowdJob(String name, Project project); /** * Get a crowdFlower Template from the WebAnno root directory * * @param fileName * the name. * @return the template. * @throws IOException * if an I/O error occurs. */ File getTemplate(String fileName) throws IOException; /** * List {@link CrowdJob}s/Crowd Tasks in the system * * @return the jobs. */ List<CrowdJob> listCrowdJobs(); List<CrowdJob> listCrowdJobs(Project project); /** * remove a crowd project * * @param crowdProject * the job. */ void removeCrowdJob(CrowdJob crowdProject); // -------------------------------------------------------------------------------------------- // Methods related to import/export data formats // -------------------------------------------------------------------------------------------- /** * Returns the labels on the UI for the format of the {@link SourceDocument} to be read from a * properties File * * @return labels of readable formats. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ List<String> getReadableFormatLabels() throws IOException, ClassNotFoundException; /** * Returns the Id of the format for the {@link SourceDocument} to be read from a properties File * * @param label * the label. * * @return the ID. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ String getReadableFormatId(String label) throws IOException, ClassNotFoundException; /** * Returns formats of the {@link SourceDocument} to be read from a properties File * * @return the formats. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ @SuppressWarnings("rawtypes") Map<String, Class> getReadableFormats() throws IOException, ClassNotFoundException; /** * Returns the labels on the UI for the format of {@link AnnotationDocument} while exporting * * @return the labels. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ List<String> getWritableFormatLabels() throws IOException, ClassNotFoundException; /** * Returns the Id of the format for {@link AnnotationDocument} while exporting * * @param label * the label. * @return the ID. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ String getWritableFormatId(String label) throws IOException, ClassNotFoundException; /** * Returns formats of {@link AnnotationDocument} while exporting * * @return the formats. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ @SuppressWarnings("rawtypes") Map<String, Class> getWritableFormats() throws IOException, ClassNotFoundException; // -------------------------------------------------------------------------------------------- // Methods related to user settings // -------------------------------------------------------------------------------------------- /** * Load annotation preferences such as {@code BratAnnotator#windowSize} from a property file * * @param username * the username. * @param project * the project where the user is working on. * @return the properties. * @throws IOException * if an I/O error occurs. */ Properties loadUserSettings(String username, Project project) throws IOException; /** * Save annotation references, such as {@code BratAnnotator#windowSize}..., in a properties file * so that they are not required to configure every time they open the document. * * @param <T> * object type to save * @param username * the user name * @param subject * differentiate the setting, either it is for {@code AnnotationPage} or * {@code CurationPage} * @param configurationObject * The Object to be saved as preference in the properties file. * @param project * The project where the user is working on. * @throws IOException * if an I/O error occurs. */ <T> void saveUserSettings(String username, Project project, Mode subject, T configurationObject) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to anything else // -------------------------------------------------------------------------------------------- /** * The Directory where the {@link SourceDocument}s and {@link AnnotationDocument}s stored * * @return the directory. */ File getDir(); /** * Load the CAS for the specified source document and user, upgrade it, and save it again. * Depending on the mode parameter, the automation/correction and curation CASes are also * upgraded. * * @param aDocument * the source document. * @param aMode * the mode. * @param username * the username. * @throws IOException * if an I/O error occurs. * @deprecated Read CAS e.g. using {@link #readAnnotationCas(SourceDocument, User)} then use  * {@link #upgradeCas(CAS, AnnotationDocument)} and then write the CAS e.g. using * {@link #writeAnnotationCas(JCas, SourceDocument, User)} */ @Deprecated void upgradeCasAndSave(SourceDocument aDocument, Mode aMode, String username) throws IOException; /** * Save the modified CAS in the file system as Serialized CAS * * @param mode * the mode. * @param document * the source document. * @param user * the user. * @param jCas * the JCas. * @throws IOException * if an I/O error occurs. */ void writeCas(Mode mode, SourceDocument document, User user, JCas jCas) throws IOException; /** * Get the name of the database driver in use. * * @return the driver name. */ String getDatabaseDriverName(); /** * For 1.0.0 release, the settings.properties file contains a key that is indicates if * crowdsourcing is enabled or not (0 disabled, 1 enabled) * * @return if crowdsourcing is enabled. */ int isCrowdSourceEnabled(); void upgradeCas(CAS aCurCas, AnnotationDocument annotationDocument) throws UIMAException, IOException; void upgradeCorrectionCas(CAS aCurCas, SourceDocument document) throws UIMAException, IOException; /** * List project accessible by current user * * @return list of projects accessible by the user. */ List<Project> listAccessibleProjects(); /** * If any of the users finised one annotation document */ boolean existFinishedDocument(SourceDocument aSourceDocument, Project aProject); AnnotationDocument createOrGetAnnotationDocument(SourceDocument aDocument, User aUser) throws IOException; /** * Get default number of sentences to display per page, set by administrator, which is read from * settings.properties file * * @return */ int getNumberOfSentences(); // -------------------------------------------------------------------------------------------- // Methods related to Constraints // -------------------------------------------------------------------------------------------- /** * Creates Constraint Set * @param aSet */ void createConstraintSet(ConstraintSet aSet); /** * Returns list of ConstraintSets in a project * @param aProject The project * @return List of Constraints in a project */ List<ConstraintSet> listConstraintSets(Project aProject); /** * Remove a constraint * @param aSet */ void removeConstraintSet(ConstraintSet aSet); String readConstrainSet(ConstraintSet aSet) throws IOException; void writeConstraintSet(ConstraintSet aSet, InputStream aContent) throws IOException; /** * Returns Constraint as a file * @param aSet The Constraint Set * @return File pointing to Constraint * @throws IOException */ File exportConstraintAsFile(ConstraintSet aSet) throws IOException; /** * Checks if there's a constraint set already with the name * @param constraintSetName The name of constraint set * @return true if exists */ boolean existConstraintSet(String constraintSetName, Project aProject); }
webanno-api/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/RepositoryService.java
/******************************************************************************* * Copyright 2012 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.clarin.webanno.api; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import javax.persistence.NoResultException; import org.apache.uima.UIMAException; import org.apache.uima.cas.CAS; import org.apache.uima.jcas.JCas; import org.springframework.security.access.prepost.PreAuthorize; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.Authority; import de.tudarmstadt.ukp.clarin.webanno.model.ConstraintSet; import de.tudarmstadt.ukp.clarin.webanno.model.CrowdJob; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.PermissionLevel; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.ProjectPermission; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.User; /** * This interface contains methods that are related to accessing/creating/deleting... documents, * Users, and Projects for the annotation system. while meta data about documents and projects and * users are stored in the database, source and annotation documents are stored in a file system * * */ public interface RepositoryService { // -------------------------------------------------------------------------------------------- // Methods related to permissions // -------------------------------------------------------------------------------------------- /** * Returns a role of a user, globally we will have ROLE_ADMIN and ROLE_USER * * @param user * the {@link User} object * @return the roles. */ List<Authority> listAuthorities(User user); /** * creates a project permission, adding permission level for the user in the given project * * @param permission * the permission * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER', 'ROLE_REMOTE')") void createProjectPermission(ProjectPermission permission) throws IOException; /** * Check if a user have at least one {@link PermissionLevel } for this {@link Project} * * @param user * the user. * @param project * the project. * * @return if the project permission exists. */ boolean existsProjectPermission(User user, Project project); /** * Check if there is already a {@link PermissionLevel} on a given {@link Project} for a given * {@link User} * * @param user * the user. * @param project * the project. * @param level * the permission level. * * @return if the permission exists. */ boolean existsProjectPermissionLevel(User user, Project project, PermissionLevel level); /** * Get a {@link ProjectPermission }objects where a project is member of. We need to get them, for * example if the associated {@link Project} is deleted, the {@link ProjectPermission } objects * too. * * @param project * The project contained in a projectPermision * @return the {@link ProjectPermission } list to be analysed. */ List<ProjectPermission> getProjectPermisions(Project project); /** * Get list of permissions a user have in a given project * * @param user * the user. * @param project * the project. * * @return the permissions. */ List<ProjectPermission> listProjectPermisionLevel(User user, Project project); /** * List Users those with some {@link PermissionLevel}s in the project * * @param project * the project. * @return the users. */ List<User> listProjectUsersWithPermissions(Project project); /** * List of users with the a given {@link PermissionLevel} * * @param project * The {@link Project} * @param permissionLevel * The {@link PermissionLevel} * @return the users. */ List<User> listProjectUsersWithPermissions(Project project, PermissionLevel permissionLevel); /** * remove a user permission from the project * * @param projectPermission * The ProjectPermission to be removed * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void removeProjectPermission(ProjectPermission projectPermission) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to SourceDocuments // -------------------------------------------------------------------------------------------- /** * Creates a {@link SourceDocument} in a database. The source document is created by ROLE_ADMIN * or Project admins. Source documents are created per project and it should have a unique name * in the {@link Project} it belongs. renaming a a source document is not possible, rather the * administrator should delete and re create it. * * @param document * {@link SourceDocument} to be created * @param user * The User who perform this operation * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") void createSourceDocument(SourceDocument document, User user) throws IOException; /** * Check if a Source document with this same name exist in the project. The caller method then * can decide to override or throw an exception/message to the client * * @param project * the project. * @param fileName * the source document name. * @return if the source document exists. */ boolean existsSourceDocument(Project project, String fileName); /** * Get meta data information about {@link SourceDocument} from the database. This method is * called either for {@link AnnotationDocument} object creation or * {@link RepositoryService#createSourceDocument(SourceDocument, User)} * * @param project * the {@link Project} where the {@link SourceDocument} belongs * @param documentName * the name of the {@link SourceDocument} * @return the source document. */ SourceDocument getSourceDocument(Project project, String documentName); /** * Get meta data information about {@link SourceDocument} from the database. * * @param projectId * the id for the {@link Project} * @param documentId * the id for the {@link SourceDocument} * @return the source document */ SourceDocument getSourceDocument(long projectId, long documentId); /** * Return the Master TCF file Directory path. For the first time, all available TCF layers will * be read and converted to CAS object. subsequent accesses will be to the annotated document * unless and otherwise the document is removed from the project. * * @param document * The {@link SourceDocument} to be examined * @return the Directory path of the source document */ File getSourceDocumentFile(SourceDocument document); /** * List all source documents in a project. The source documents are the original TCF documents * imported. * * @param aProject * The Project we are looking for source documents * @return list of source documents */ List<SourceDocument> listSourceDocuments(Project aProject); /** * ROLE_ADMINs or project admins can remove source documents from a project. removing a a source * document also removes an annotation document related to that document * * @param document * the source document to be deleted * @throws IOException * If the source document searched for deletion is not available */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER', 'ROLE_REMOTE')") void removeSourceDocument(SourceDocument document) throws IOException; @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") void uploadSourceDocument(File file, SourceDocument document) throws IOException, UIMAException; /** * Upload a SourceDocument, obtained as Inputstream, such as from remote API Zip folder to a * repository directory. This way we don't need to create the file to a temporary folder * * @param file * the file. * @param document * the source document. * @throws IOException * if an I/O error occurs. * @throws UIMAException * if a conversion error occurs. * @deprecated Use {@link #uploadSourceDocument(File, SourceDocument)} with a temporary file * instead. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") @Deprecated void uploadSourceDocument(InputStream file, SourceDocument document) throws IOException, UIMAException; /** * Get the directory of this {@link SourceDocument} usually to read the content of the document * * @param aDocument * the source document. * @return the source document folder. * @throws IOException * if an I/O error occurs. */ File getDocumentFolder(SourceDocument aDocument) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to AnnotationDocuments // -------------------------------------------------------------------------------------------- /** * creates the {@link AnnotationDocument } object in the database. * * @param annotationDocument * {@link AnnotationDocument} comprises of the the name of the {@link SourceDocument} * , id of {@link SourceDocument}, id of the {@link Project}, and id of {@link User} * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void createAnnotationDocument(AnnotationDocument annotationDocument) throws IOException; /** * Creates an annotation document. The {@link AnnotationDocument} is stored in the * webanno.home/project/Project.id/document/document.id/annotation/username.ser. annotated * documents are stored per project, user and document * * @param jCas * the JCas. * @param document * the source document. * @param user * The User who perform this operation * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void writeAnnotationCas(JCas jCas, SourceDocument document, User user) throws IOException; /** * A Method that checks if there is already an annotation document created for the source * document * * @param document * the source document. * @param user * the user. * @return if an annotation document metadata exists for the user. */ boolean existsAnnotationDocument(SourceDocument document, User user); /** * A method to check if there exist a correction document already. Base correction document * should be the same for all users * * @param document * the source document. * @return if a correction document exists. */ boolean existsCorrectionDocument(SourceDocument document); /** * check if the JCAS for the {@link User} and {@link SourceDocument} in this {@link Project} * exists It is important as {@link AnnotationDocument} entry can be populated as * {@link AnnotationDocumentState#NEW} from the MonitoringPage before the user actually open the * document for annotation. * * @param sourceDocument * the source document. * @param username * the username. * @return if an annotation document file exists. * @throws IOException * if an I/O error occurs. */ boolean existsCas(SourceDocument sourceDocument, String username) throws IOException; /** * check if there is an already automated document. This is important as automated document * should appear the same among users * * @param sourceDocument * the source document. * @return if an automation document exists. */ boolean existsCorrectionCas(SourceDocument sourceDocument); /** * Exports an {@link AnnotationDocument } CAS Object as TCF/TXT/XMI... file formats. * * @param document * The {@link SourceDocument} where we get the id which hosts both the source * Document and the annotated document * @param user * the {@link User} who annotates the document. * @param writer * the DKPro Core writer. * @param fileName * the file name. * @param mode * the mode. * @return a temporary file. * @throws UIMAException * if there was a conversion error. * @throws IOException * if there was an I/O error. * @throws ClassNotFoundException * if the DKPro Core writer could not be found. */ @SuppressWarnings("rawtypes") File exportAnnotationDocument(SourceDocument document, String user, Class writer, String fileName, Mode mode) throws UIMAException, IOException, ClassNotFoundException; @SuppressWarnings("rawtypes") File exportAnnotationDocument(SourceDocument document, String user, Class writer, String fileName, Mode mode, boolean stripExtension) throws UIMAException, IOException, ClassNotFoundException; /** * Export a Serialized CAS annotation document from the file system * * @param document * the source document. * @param user * the username. * @return the serialized CAS file. */ File getCasFile(SourceDocument document, String user); /** * Get the annotation document. * * @param document * the source document. * @param user * the user. * @return the annotation document. * @throws NoResultException * if no annotation document exists for the given source/user. */ AnnotationDocument getAnnotationDocument(SourceDocument document, User user); /** * Gets the CAS for the given annotation document. Converts it form the source document if * necessary. * * @param annotationDocument * the annotation document. * @return the JCas. * @throws IOException * if there was an I/O error. */ JCas readAnnotationCas(AnnotationDocument annotationDocument) throws IOException; /** * Gets the CAS for the given annotation document. Converts it form the source document if * necessary. If necessary, no annotation document exists, one is created. The source document * is set into state {@link SourceDocumentState#ANNOTATION_IN_PROGRESS}. * * @param document * the source document. * @param user * the user. * @return the JCas. * @throws IOException * if there was an I/O error. * @deprecated use {@link #createOrGetAnnotationDocument(SourceDocument, User)} and * {@link #readAnnotationCas(AnnotationDocument)} instead and manually set source * document status manually if desired. */ @Deprecated JCas readAnnotationCas(SourceDocument document, User user) throws IOException; /** * List all the {@link AnnotationDocument}s, if available for a given {@link SourceDocument} in * the {@link Project}. Returns list of {@link AnnotationDocument}s for all {@link User}s in the * {@link Project} that has already annotated the {@link SourceDocument} * * @param document * the {@link SourceDocument} * @return {@link AnnotationDocument} */ List<AnnotationDocument> listAnnotationDocuments(SourceDocument document); /** * Number of expected annotation documents in this project (numUser X document - Ignored) * * @param project * the project. * @return the number of annotation documents. */ int numberOfExpectedAnnotationDocuments(Project project); /** * List all annotation Documents in a project that are already closed. used to compute overall * project progress * * @param project * the project. * @return the annotation documents. */ List<AnnotationDocument> listFinishedAnnotationDocuments(Project project); /** * List all annotation documents for this source document (including in active and delted user * annotation and those created by project admins or super admins for Test purpose. This method * is called when a source document (or Project) is deleted so that associated annotation * documents also get removed. * * @param document * the source document. * @return the annotation documents. */ List<AnnotationDocument> listAllAnnotationDocuments(SourceDocument document); /** * Check if the user finished annotating the {@link SourceDocument} in this {@link Project} * * @param document * the source document. * @param user * the user. * @return if the user has finished annotation. */ boolean isAnnotationFinished(SourceDocument document, User user); /** * Check if at least one annotation document is finished for this {@link SourceDocument} in the * project * * @param document * the source document. * @return if any finished annotation exists. */ boolean existsFinishedAnnotation(SourceDocument document); /** * If at least one {@link AnnotationDocument} is finished in this project */ boolean existsFinishedAnnotation(Project project); /** * list Projects which contain with those annotation documents state is finished */ List<Project> listProjectsWithFinishedAnnos(); /** * Remove an annotation document, for example, when a user is removed from a project * * @param annotationDocument * the {@link AnnotationDocument} to be removed */ void removeAnnotationDocument(AnnotationDocument annotationDocument); // -------------------------------------------------------------------------------------------- // Methods related to correction // -------------------------------------------------------------------------------------------- /** * Create an annotation document under a special user named "CORRECTION_USER" * * @param jCas * the JCas. * @param document * the source document. * @param user * the user. * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void writeCorrectionCas(JCas jCas, SourceDocument document, User user) throws IOException; JCas readCorrectionCas(SourceDocument document) throws UIMAException, IOException, ClassNotFoundException; // -------------------------------------------------------------------------------------------- // Methods related to curation // -------------------------------------------------------------------------------------------- /** * Create a curation annotation document under a special user named as "CURATION_USER" * * @param jCas * the JCas. * @param document * the source document. * @param user * the user. * @throws IOException * if an I/O error occurs. */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void writeCurationCas(JCas jCas, SourceDocument document, User user) throws IOException; /** * Get a curation document for the given {@link SourceDocument} * * @param document * the source document. * @return the curation JCas. * @throws UIMAException * if a conversion error occurs. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if the DKPro Core reader/writer cannot be loaded. */ JCas readCurationCas(SourceDocument document) throws UIMAException, IOException, ClassNotFoundException; /** * Remove a curation annotation document from the file system, for this {@link SourceDocument} * * @param sourceDocument * the source document. * @param username * the username. * @throws IOException * if an I/O error occurs. */ void removeCurationDocumentContent(SourceDocument sourceDocument, String username) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to Projects // -------------------------------------------------------------------------------------------- /** * Creates a {@code Project}. Creating a project needs a global ROLE_ADMIN role. For the first * time the project is created, an associated project path will be created on the file system as * {@code webanno.home/project/Project.id } * * @param project * The {@link Project} object to be created. * @param user * The User who perform this operation * @throws IOException * If the specified webanno.home directory is not available no write permission */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_REMOTE','ROLE_PROJECT_CREATOR')") void createProject(Project project, User user) throws IOException; /** * A method that check is a project exists with the same name already. getSingleResult() fails * if the project is not created, hence existProject returns false. * * @param name * the project name. * @return if the project exists. */ boolean existsProject(String name); /** * Check if there exists an project timestamp for this user and {@link Project}. * * @param project * the project. * @param username * the username. * @return if a timestamp exists. */ boolean existsProjectTimeStamp(Project project, String username); /** * check if there exists a timestamp for at least one source document in aproject (add when a * curator start curating) * * @param project * the project. * @return if a timestamp exists. */ boolean existsProjectTimeStamp(Project project); /** * Export the associated project log for this {@link Project} while copying a project * * @param project * the project. * @return the log file. */ File getProjectLogFile(Project project); File getMetaInfFolder(Project project); /** * Save some properties file associated to a project, such as meta-data.properties * * @param project * The project for which the user save some properties file. * @param is * the properties file. * @param fileName * the file name. * @throws IOException * if an I/O error occurs. */ void savePropertiesFile(Project project, InputStream is, String fileName) throws IOException; /** * Get a timestamp of for this {@link Project} of this username * * @param project * the project. * @param username * the username. * @return the timestamp. */ Date getProjectTimeStamp(Project project, String username); /** * get the timestamp, of the curator, if exist * * @param project * the project. * @return the timestamp. */ Date getProjectTimeStamp(Project project); /** * Get a {@link Project} from the database the name of the Project * * @param name * name of the project * @return {@link Project} object from the database or an error if the project is not found. * Exception is handled from the calling method. */ Project getProject(String name); /** * Get a project by its id. * * @param id * the ID. * @return the project. */ Project getProject(long id); /** * Determine if the project is created using the remote API webanno service or not TODO: For * now, it checks if the project consists of META-INF folder!! * * @param project * the project. * @return if it was created using the remote API. */ boolean isRemoteProject(Project project); /** * List all Projects. If the user logged have a ROLE_ADMIN, he can see all the projects. * Otherwise, a user will see projects only he is member of. * * @return the projects */ List<Project> listProjects(); /** * Remove a project. A ROLE_ADMIN or project admin can remove a project. removing a project will * remove associated source documents and annotation documents. * * @param project * the project to be deleted * @param user * The User who perform this operation * @throws IOException * if the project to be deleted is not available in the file system */ @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") void removeProject(Project project, User user) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to guidelines // -------------------------------------------------------------------------------------------- /** * Write this {@code content} of the guideline file in the project; * * @param project * the project. * @param content * the guidelines. * @param fileName * the filename. * @param username * the username. * @throws IOException * if an I/O error occurs. */ void createGuideline(Project project, File content, String fileName, String username) throws IOException; /** * get the annotation guideline document from the file system * * @param project * the project. * @param fileName * the filename. * @return the file. */ File getGuideline(Project project, String fileName); /** * Export the associated project guideline for this {@link Project} while copying a project * * @param project * the project. * @return the file. */ File getGuidelinesFile(Project project); /** * List annotation guideline document already uploaded * * @param project * the project. * @return the filenames. */ List<String> listGuidelines(Project project); /** * Remove an annotation guideline document from the file system * * @param project * the project. * @param fileName * the filename. * @param username * the username. * @throws IOException * if an I/O error occurs. */ void removeGuideline(Project project, String fileName, String username) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to CrowdJobs // -------------------------------------------------------------------------------------------- /** * Create a crowd Project which contains some source document. A crowd project contains source * documents from {@link Project}(s), a {@link SourceDocument} belongs at most to one * {@link CrowdJob}. * * @param crowdProject * the job. * @throws IOException * if an I/O error occurs. */ void createCrowdJob(CrowdJob crowdProject) throws IOException; /** * Check if a crowd job already exist or not with its name * * @param name * the name. * @return if the job exists. */ boolean existsCrowdJob(String name); /** * Get a {@link CrowdJob} by its name in a {@link Project} * * @param name * the name. * @param project * the project. * @return the job. */ CrowdJob getCrowdJob(String name, Project project); /** * Get a crowdFlower Template from the WebAnno root directory * * @param fileName * the name. * @return the template. * @throws IOException * if an I/O error occurs. */ File getTemplate(String fileName) throws IOException; /** * List {@link CrowdJob}s/Crowd Tasks in the system * * @return the jobs. */ List<CrowdJob> listCrowdJobs(); List<CrowdJob> listCrowdJobs(Project project); /** * remove a crowd project * * @param crowdProject * the job. */ void removeCrowdJob(CrowdJob crowdProject); // -------------------------------------------------------------------------------------------- // Methods related to import/export data formats // -------------------------------------------------------------------------------------------- /** * Returns the labels on the UI for the format of the {@link SourceDocument} to be read from a * properties File * * @return labels of readable formats. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ List<String> getReadableFormatLabels() throws IOException, ClassNotFoundException; /** * Returns the Id of the format for the {@link SourceDocument} to be read from a properties File * * @param label * the label. * * @return the ID. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ String getReadableFormatId(String label) throws IOException, ClassNotFoundException; /** * Returns formats of the {@link SourceDocument} to be read from a properties File * * @return the formats. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ @SuppressWarnings("rawtypes") Map<String, Class> getReadableFormats() throws IOException, ClassNotFoundException; /** * Returns the labels on the UI for the format of {@link AnnotationDocument} while exporting * * @return the labels. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ List<String> getWritableFormatLabels() throws IOException, ClassNotFoundException; /** * Returns the Id of the format for {@link AnnotationDocument} while exporting * * @param label * the label. * @return the ID. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ String getWritableFormatId(String label) throws IOException, ClassNotFoundException; /** * Returns formats of {@link AnnotationDocument} while exporting * * @return the formats. * @throws IOException * if an I/O error occurs. * @throws ClassNotFoundException * if a DKPro Core reader/writer cannot be loaded. */ @SuppressWarnings("rawtypes") Map<String, Class> getWritableFormats() throws IOException, ClassNotFoundException; // -------------------------------------------------------------------------------------------- // Methods related to user settings // -------------------------------------------------------------------------------------------- /** * Load annotation preferences such as {@code BratAnnotator#windowSize} from a property file * * @param username * the username. * @param project * the project where the user is working on. * @return the properties. * @throws IOException * if an I/O error occurs. */ Properties loadUserSettings(String username, Project project) throws IOException; /** * Save annotation references, such as {@code BratAnnotator#windowSize}..., in a properties file * so that they are not required to configure every time they open the document. * * @param <T> * object type to save * @param username * the user name * @param subject * differentiate the setting, either it is for {@code AnnotationPage} or * {@code CurationPage} * @param configurationObject * The Object to be saved as preference in the properties file. * @param project * The project where the user is working on. * @throws IOException * if an I/O error occurs. */ <T> void saveUserSettings(String username, Project project, Mode subject, T configurationObject) throws IOException; // -------------------------------------------------------------------------------------------- // Methods related to anything else // -------------------------------------------------------------------------------------------- /** * The Directory where the {@link SourceDocument}s and {@link AnnotationDocument}s stored * * @return the directory. */ File getDir(); /** * Load the CAS for the specified source document and user, upgrade it, and save it again. * Depending on the mode parameter, the automation/correction and curation CASes are also * upgraded. * * @param aDocument * the source document. * @param aMode * the mode. * @param username * the username. * @throws IOException * if an I/O error occurs. * @deprecated Read CAS e.g. using {@link #readAnnotationCas(SourceDocument, User)} then use  * {@link #upgradeCas(CAS, AnnotationDocument)} and then write the CAS e.g. using * {@link #writeAnnotationCas(JCas, SourceDocument, User)} */ @Deprecated void upgradeCasAndSave(SourceDocument aDocument, Mode aMode, String username) throws IOException; /** * Save the modified CAS in the file system as Serialized CAS * * @param mode * the mode. * @param document * the source document. * @param user * the user. * @param jCas * the JCas. * @throws IOException * if an I/O error occurs. */ void writeCas(Mode mode, SourceDocument document, User user, JCas jCas) throws IOException; /** * Get the name of the database driver in use. * * @return the driver name. */ String getDatabaseDriverName(); /** * For 1.0.0 release, the settings.properties file contains a key that is indicates if * crowdsourcing is enabled or not (0 disabled, 1 enabled) * * @return if crowdsourcing is enabled. */ int isCrowdSourceEnabled(); void upgradeCas(CAS aCurCas, AnnotationDocument annotationDocument) throws UIMAException, IOException; void upgradeCorrectionCas(CAS aCurCas, SourceDocument document) throws UIMAException, IOException; /** * List project accessible by current user * * @return list of projects accessible by the user. */ List<Project> listAccessibleProjects(); /** * If any of the users finised one annotation document */ boolean existFinishedDocument(SourceDocument aSourceDocument, Project aProject); AnnotationDocument createOrGetAnnotationDocument(SourceDocument aDocument, User aUser) throws IOException; /** * Get default number of sentences to display per page, set by administrator, which is read from * settings.properties file * * @return */ int getNumberOfSentences(); // -------------------------------------------------------------------------------------------- // Methods related to Constraints // -------------------------------------------------------------------------------------------- /** * Creates Constraint Set * @param aSet */ void createConstraintSet(ConstraintSet aSet); /** * Returns list of ConstraintSets in a project * @param aProject The project * @return List of Constraints in a project */ List<ConstraintSet> listConstraintSets(Project aProject); /** * Remove a constraint * @param aSet */ void removeConstraintSet(ConstraintSet aSet); String readConstrainSet(ConstraintSet aSet) throws IOException; void writeConstraintSet(ConstraintSet aSet, InputStream aContent) throws IOException; /** * Returns Constraint as a file * @param aSet The Constraint Set * @return File pointing to Constraint * @throws IOException */ File exportConstraintAsFile(ConstraintSet aSet) throws IOException; /** * Checks if there's a constraint set already with the name * @param constraintSetName The name of constraint set * @return true if exists */ boolean existConstraintSet(String constraintSetName, Project aProject); }
Removed deprecated annotation from "uploadSourceDocument"
webanno-api/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/RepositoryService.java
Removed deprecated annotation from "uploadSourceDocument"
<ide><path>ebanno-api/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/RepositoryService.java <ide> * @throws IOException <ide> * if an I/O error occurs. <ide> * @throws UIMAException <del> * if a conversion error occurs. <del> * @deprecated Use {@link #uploadSourceDocument(File, SourceDocument)} with a temporary file <del> * instead. <del> */ <del> @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") <del> @Deprecated <add> * if a conversion error occurs. <add> */ <add> @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER','ROLE_REMOTE')") <ide> void uploadSourceDocument(InputStream file, SourceDocument document) <ide> throws IOException, UIMAException; <ide>
Java
apache-2.0
74a1ed6cde1e008b76f828dedf4064ea7bd898d4
0
acton393/incubator-weex,leoward/incubator-weex,houfeng0923/weex,Hanks10100/weex,acton393/incubator-weex,xiayun200825/weex,zzyhappyzzy/weex,MrRaindrop/weex,KalicyZhou/incubator-weex,yuguitao/incubator-weex,zhangquan/weex,lvscar/weex,acton393/incubator-weex,erha19/incubator-weex,cxfeng1/weex,xiayun200825/weex,erha19/incubator-weex,MrRaindrop/weex,weexteam/incubator-weex,zzyhappyzzy/weex,cxfeng1/weex,acton393/weex,lvscar/weex,KalicyZhou/incubator-weex,cxfeng1/incubator-weex,Tancy/weex,acton393/weex,HomHomLin/weex,namedlock/weex,Hanks10100/weex,lvscar/weex,lzyzsd/weex,lvscar/weex,weexteam/incubator-weex,zhangquan/weex,leoward/incubator-weex,acton393/weex,Hanks10100/incubator-weex,miomin/incubator-weex,weexteam/incubator-weex,namedlock/weex,namedlock/weex,erha19/incubator-weex,Neeeo/incubator-weex,Tancy/weex,xiayun200825/weex,kfeagle/weex,acton393/weex,erha19/incubator-weex,alibaba/weex,yuguitao/incubator-weex,leoward/incubator-weex,bigconvience/weex,MrRaindrop/incubator-weex,alibaba/weex,cxfeng1/incubator-weex,zzyhappyzzy/weex,KalicyZhou/incubator-weex,boboning/weex,Tancy/weex,boboning/weex,zzyhappyzzy/weex,Hanks10100/incubator-weex,lzyzsd/weex,miomin/incubator-weex,dianwodaMobile/DWeex,Tancy/weex,kfeagle/weex,acton393/weex,houfeng0923/weex,LeeJay0226/weex,lzyzsd/weex,xiayun200825/weex,yuguitao/incubator-weex,MrRaindrop/incubator-weex,namedlock/weex,Hanks10100/incubator-weex,LeeJay0226/weex,acton393/incubator-weex,yuguitao/incubator-weex,boboning/weex,zhangquan/weex,LeeJay0226/weex,houfeng0923/weex,Tancy/weex,kfeagle/weex,MrRaindrop/incubator-weex,Hanks10100/weex,miomin/incubator-weex,Hanks10100/incubator-weex,miomin/incubator-weex,HomHomLin/weex,zzyhappyzzy/weex,leoward/incubator-weex,xiayun200825/weex,MrRaindrop/weex,zzyhappyzzy/weex,zhangquan/weex,Hanks10100/incubator-weex,Tancy/weex,bigconvience/weex,misakuo/incubator-weex,HomHomLin/weex,yuguitao/incubator-weex,KalicyZhou/incubator-weex,MrRaindrop/weex,cxfeng1/weex,misakuo/incubator-weex,cxfeng1/incubator-weex,misakuo/incubator-weex,bigconvience/weex,kfeagle/weex,Hanks10100/incubator-weex,Hanks10100/weex,dianwodaMobile/DWeex,acton393/incubator-weex,misakuo/incubator-weex,LeeJay0226/weex,leoward/incubator-weex,acton393/incubator-weex,lvscar/weex,miomin/incubator-weex,MrRaindrop/incubator-weex,dianwodaMobile/DWeex,LeeJay0226/weex,Hanks10100/incubator-weex,KalicyZhou/incubator-weex,houfeng0923/weex,bigconvience/weex,namedlock/weex,Neeeo/incubator-weex,yuguitao/incubator-weex,Neeeo/incubator-weex,cxfeng1/incubator-weex,kfeagle/weex,Neeeo/incubator-weex,KalicyZhou/incubator-weex,alibaba/weex,cxfeng1/weex,bigconvience/weex,cxfeng1/weex,cxfeng1/incubator-weex,erha19/incubator-weex,alibaba/weex,MrRaindrop/weex,Hanks10100/weex,Hanks10100/incubator-weex,alibaba/weex,cxfeng1/incubator-weex,LeeJay0226/weex,HomHomLin/weex,weexteam/incubator-weex,houfeng0923/weex,zhangquan/weex,boboning/weex,Hanks10100/weex,bigconvience/weex,MrRaindrop/incubator-weex,HomHomLin/weex,leoward/incubator-weex,erha19/incubator-weex,misakuo/incubator-weex,dianwodaMobile/DWeex,alibaba/weex,boboning/weex,miomin/incubator-weex,boboning/weex,acton393/weex,namedlock/weex,erha19/incubator-weex,HomHomLin/weex,Neeeo/incubator-weex,erha19/incubator-weex,MrRaindrop/incubator-weex,xiayun200825/weex,dianwodaMobile/DWeex,Neeeo/incubator-weex,acton393/incubator-weex,weexteam/incubator-weex,lzyzsd/weex,dianwodaMobile/DWeex,miomin/incubator-weex,lzyzsd/weex,lzyzsd/weex,zhangquan/weex,miomin/incubator-weex,misakuo/incubator-weex,alibaba/weex,MrRaindrop/weex,weexteam/incubator-weex,cxfeng1/weex,kfeagle/weex,lvscar/weex,acton393/incubator-weex,houfeng0923/weex
/** * Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * 1. Definitions. * "License" shall mean the terms and conditions for use, reproduction, and distribution as defined * by Sections 1 through 9 of this document. * "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is * granting the License. * "Legal Entity" shall mean the union of the acting entity and all other entities that control, are * controlled by, or are under common control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the direction or management of such * entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this * License. * "Source" form shall mean the preferred form for making modifications, including but not limited * to software source code, documentation source, and configuration files. * "Object" form shall mean any form resulting from mechanical transformation or translation of a * Source form, including but not limited to compiled object code, generated documentation, and * conversions to other media types. * "Work" shall mean the work of authorship, whether in Source or Object form, made available under * the License, as indicated by a copyright notice that is included in or attached to the work (an * example is provided in the Appendix below). * "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or * derived from) the Work and for which the editorial revisions, annotations, elaborations, or other * modifications represent, as a whole, an original work of authorship. For the purposes of this * License, Derivative Works shall not include works that remain separable from, or merely link (or * bind by name) to the interfaces of, the Work and Derivative Works thereof. * "Contribution" shall mean any work of authorship, including the original version of the Work and * any modifications or additions to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or * Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this * definition, "submitted" means any form of electronic, verbal, or written communication sent to * the Licensor or its representatives, including but not limited to communication on electronic * mailing lists, source code control systems, and issue tracking systems that are managed by, or on * behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding * communication that is conspicuously marked or otherwise designated in writing by the copyright * owner as "Not a Contribution." * "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a * Contribution has been received by Licensor and subsequently incorporated within the Work. * 2. Grant of Copyright License. Subject to the terms and conditions of this License, each * Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, * irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, * publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or * Object form. * 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor * hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, use, offer to sell, sell, * import, and otherwise transfer the Work, where such license applies only to those patent claims * licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or * by combination of their Contribution(s) with the Work to which such Contribution(s) was * submitted. If You institute patent litigation against any entity (including a cross-claim or * counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work * constitutes direct or contributory patent infringement, then any patent licenses granted to You * under this License for that Work shall terminate as of the date such litigation is filed. * 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works * thereof in any medium, with or without modifications, and in Source or Object form, provided that * You meet the following conditions: * (a) You must give any other recipients of the Work or Derivative Works a copy of this License; * and * (b) You must cause any modified files to carry prominent notices stating that You changed the * files; and * (c) You must retain, in the Source form of any Derivative Works that You distribute, all * copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding * those notices that do not pertain to any part of the Derivative Works; and * (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative * Works that You distribute must include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not pertain to any part of the * Derivative Works, in at least one of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or documentation, if provided along with * the Derivative Works; or, within a display generated by the Derivative Works, if and wherever * such third-party notices normally appear. The contents of the NOTICE file are for informational * purposes only and do not modify the License. You may add Your own attribution notices within * Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the * Work, provided that such additional attribution notices cannot be construed as modifying the * License. * You may add Your own copyright statement to Your modifications and may provide additional or * different license terms and conditions for use, reproduction, or distribution of Your * modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and * distribution of the Work otherwise complies with the conditions stated in this License. * 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution * intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms * and conditions of this License, without any additional terms or conditions. Notwithstanding the * above, nothing herein shall supersede or modify the terms of any separate license agreement you * may have executed with Licensor regarding such Contributions. * 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service * marks, or product names of the Licensor, except as required for reasonable and customary use in * describing the origin of the Work and reproducing the content of the NOTICE file. * 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor * provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, * any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or * redistributing the Work and assume any risks associated with Your exercise of permissions under * this License. * 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including * negligence), contract, or otherwise, unless required by applicable law (such as deliberate and * grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for * damages, including any direct, indirect, special, incidental, or consequential damages of any * character arising as a result of this License or out of the use or inability to use the Work * (including but not limited to damages for loss of goodwill, work stoppage, computer failure or * malfunction, or any and all other commercial damages or losses), even if such Contributor has * been advised of the possibility of such damages. * 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works * thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, * indemnity, or other liability obligations and/or rights consistent with this License. However, in * accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, * not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each * Contributor harmless for any liability incurred by, or claims asserted against, such Contributor * by reason of your accepting any such warranty or additional liability. * END OF TERMS AND CONDITIONS * APPENDIX: How to apply the Apache License to your work. * To apply the Apache License to your work, attach the following boilerplate notice, with the * fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate comment syntax for the file * format. We also recommend that a file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier identification within third-party * archives. * Copyright 2016 Alibaba Group * 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.taobao.weex.ui.component; import android.content.Context; import android.graphics.PointF; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ScrollView; import com.taobao.weex.IWXActivityStateListener; import com.taobao.weex.WXEnvironment; import com.taobao.weex.WXSDKInstance; import com.taobao.weex.WXSDKManager; import com.taobao.weex.bridge.Invoker; import com.taobao.weex.bridge.WXBridgeManager; import com.taobao.weex.common.IWXObject; import com.taobao.weex.common.WXDomPropConstant; import com.taobao.weex.common.WXRuntimeException; import com.taobao.weex.dom.WXDomObject; import com.taobao.weex.dom.flex.CSSLayout; import com.taobao.weex.dom.flex.Spacing; import com.taobao.weex.ui.IFComponentHolder; import com.taobao.weex.ui.component.list.WXListComponent; import com.taobao.weex.ui.view.WXBackgroundDrawable; import com.taobao.weex.ui.view.WXCircleIndicator; import com.taobao.weex.ui.view.gesture.WXGesture; import com.taobao.weex.ui.view.gesture.WXGestureObservable; import com.taobao.weex.ui.view.gesture.WXGestureType; import com.taobao.weex.ui.view.refresh.wrapper.BounceRecyclerView; import com.taobao.weex.utils.WXLogUtils; import com.taobao.weex.utils.WXReflectionUtils; import com.taobao.weex.utils.WXResourceUtils; import com.taobao.weex.utils.WXUtils; import com.taobao.weex.utils.WXViewUtils; import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * abstract component * */ public abstract class WXComponent implements IWXObject, IWXActivityStateListener { public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; public static int mComponentNum = 0; public View mHost; public volatile WXVContainer mParent; public volatile WXDomObject mDomObj; public String mInstanceId; public boolean registerAppearEvent=false; public boolean appearState=false; protected int mOrientation = VERTICAL; protected WXSDKInstance mInstance; protected Context mContext; protected int mAbsoluteY = 0; protected int mAbsoluteX = 0; protected Set<String> mGestureType; private WXBorder mBorder; private boolean mLazy; private int mPreRealWidth = 0; private int mPreRealHeight = 0; private int mPreRealLeft = 0; private int mPreRealTop = 0; private WXGesture wxGesture; private IFComponentHolder mHolder; private boolean isUsing = false; @Deprecated public WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy) { this(instance,dom,parent,isLazy); } public WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy) { mInstance = instance; mContext = mInstance.getContext(); mParent = parent; mDomObj = dom.clone(); mInstanceId = instance.getInstanceId(); mLazy = isLazy; mGestureType = new HashSet<>(); ++mComponentNum; } public void bindHolder(IFComponentHolder holder){ mHolder = holder; } /** * The view is created as needed * @return true for lazy */ public boolean isLazy() { return mLazy; } public void lazy(boolean lazy) { mLazy = lazy; } public void applyLayoutAndEvent(WXComponent component) { if(!isLazy()) { if (component == null) { component = this; } getOrCreateBorder().attachView(mHost); setLayout(component.mDomObj); setPadding(component.mDomObj.getPadding(), component.mDomObj.getBorder()); addEvents(); } } public void bindData(WXComponent component){ if(!isLazy()) { if (component == null) { component = this; } updateProperties(component.mDomObj.style); updateProperties(component.mDomObj.attr); updateExtra(component.mDomObj.getExtra()); } } protected WXBorder getOrCreateBorder() { if (mBorder == null) { mBorder = new WXBorder(); } return mBorder; } /** * layout view */ public final void setLayout(WXDomObject domObject) { if (mParent == null || domObject == null || TextUtils.isEmpty(mDomObj.ref)) { return; } mDomObj = domObject; if (this instanceof WXRefresh && mParent instanceof WXRefreshableContainer && isOuterRefreshableContainer(mParent)) { mInstance.setRefreshMargin(mDomObj.csslayout.dimensions[CSSLayout.DIMENSION_HEIGHT]); } if ((this instanceof WXBaseRefresh && mParent instanceof WXRefreshableContainer)) { return; } if (mParent instanceof WXRefreshableContainer && isOuterRefreshableContainer(mParent)) { if (!(this instanceof WXBaseRefresh)) { CSSLayout newLayout = new CSSLayout(); newLayout.copy(mDomObj.csslayout); newLayout.position[CSSLayout.POSITION_TOP] = mDomObj.csslayout.position[CSSLayout .POSITION_TOP] - mInstance.getRefreshMargin(); mDomObj.csslayout.copy(newLayout); } } Spacing parentPadding = mParent.getDomObject().getPadding(); Spacing parentBorder = mParent.getDomObject().getBorder(); Spacing margin = mDomObj.getMargin(); int realWidth = (int) mDomObj.getLayoutWidth(); int realHeight = (int) mDomObj.getLayoutHeight(); int realLeft = (int) (mDomObj.getLayoutX() - parentPadding.get(Spacing.LEFT) - parentBorder.get(Spacing.LEFT)); int realTop = (int) (mDomObj.getLayoutY() - parentPadding.get(Spacing.TOP) - parentBorder.get(Spacing.TOP)); int realRight = (int) margin.get(Spacing.RIGHT); int realBottom = (int) margin.get(Spacing.BOTTOM); if (mPreRealWidth == realWidth && mPreRealHeight == realHeight && mPreRealLeft == realLeft && mPreRealTop == realTop) { return; } if (mParent != null) { mAbsoluteY = (int) (mParent.mAbsoluteY + mDomObj.getLayoutY()); mAbsoluteX = (int) (mParent.mAbsoluteX + mDomObj.getLayoutX()); } //calculate first screen time if (!mInstance.mEnd && mAbsoluteY >= mInstance.getWeexHeight()) { mInstance.firstScreenRenderFinished(); } if (mHost == null) { return; } MeasureOutput measureOutput = measure(realWidth, realHeight); realWidth = measureOutput.width; realHeight = measureOutput.height; if (mHost instanceof WXCircleIndicator) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); return; } //fixed style if (mDomObj.isFixed() && mInstance.getRootView() != null) { if (mHost.getParent() instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) mHost.getParent(); viewGroup.removeView(mHost); } FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.width = realWidth; params.height = realHeight; params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); mInstance.getRootView().addView(mHost); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Weex_Fixed_Style", "WXComponent:setLayout :" + realLeft + " " + realTop + " " + realWidth + " " + realHeight); WXLogUtils.d("Weex_Fixed_Style", "WXComponent:setLayout Left:" + mDomObj.style.getLeft() + " " + (int) mDomObj.style.getTop()); } return; } if (mParent.getRealView() instanceof ViewPager ) { // ViewPager.LayoutParams params = new ViewPager.LayoutParams(); // params.width = realWidth; // params.height = realHeight; // mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof FrameLayout) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof LinearLayout) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof ScrollView) { ScrollView.LayoutParams params = new ScrollView.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof BounceRecyclerView) { // RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(realWidth, realHeight); // params.setMargins(realLeft, 0, realRight, 0); // mHost.setLayoutParams(params); } mPreRealWidth = realWidth; mPreRealHeight = realHeight; mPreRealLeft = realLeft; mPreRealTop = realTop; } public void setPadding(Spacing padding, Spacing border) { int left = (int) (padding.get(Spacing.LEFT) + border.get(Spacing.LEFT)); int top = (int) (padding.get(Spacing.TOP) + border.get(Spacing.TOP)); int right = (int) (padding.get(Spacing.RIGHT) + border.get(Spacing.RIGHT)); int bottom = (int) (padding.get(Spacing.BOTTOM) + border.get(Spacing.BOTTOM)); if (mHost == null) { return; } mHost.setPadding(left, top, right, bottom); } // private void updateProperties() { // if (mDomObj.attr != null && mDomObj.attr.size() > 0) { // updateProperties(mDomObj.attr); // } // if (mDomObj.style != null && mDomObj.style.size() > 0) { // updateProperties(mDomObj.style); // } // } private void addEvents() { int count = mDomObj.event == null ? 0 : mDomObj.event.size(); for (int i = 0; i < count; ++i) { addEvent(mDomObj.event.get(i)); } } public void updateExtra(Object extra) { } public WXDomObject getDomObject() { return mDomObj; } /** * measure */ protected MeasureOutput measure(int width, int height) { MeasureOutput measureOutput = new MeasureOutput(); measureOutput.width = width; measureOutput.height = height; return measureOutput; } public void updateProperties(Map<String, Object> props) { if (props == null||props.isEmpty() || mHost == null) { return; } Iterator<Entry<String, Object>> iterator = props.entrySet().iterator(); while (iterator.hasNext()) { String key = iterator.next().getKey(); Invoker invoker = mHolder.getMethod(key); if (invoker != null) { try { Type[] paramClazzs = invoker.getParameterTypes(); if (paramClazzs.length != 1) { WXLogUtils.e("[WXComponent] setX method only one parameter:" + invoker); return; } Object param; param = WXReflectionUtils.parseArgument(paramClazzs[0],props.get(key)); invoker.invoke(this, param); } catch (Exception e) { WXLogUtils.e("[WXComponent] updateProperties :" + "class:" + getClass() + "method:" + invoker.toString() + " function " + WXLogUtils.getStackTrace(e)); } } } } public void addEvent(String type) { if (TextUtils.isEmpty(type)) { return; } mDomObj.addEvent(type); if (type.equals(WXEventType.CLICK) && getRealView() != null) { mHost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Map<String, Object> params = new HashMap<>(); WXSDKManager.getInstance().fireEvent(mInstanceId, mDomObj.ref, WXEventType.CLICK, params); } }); } else if ((type.equals(WXEventType.FOCUS) || type.equals(WXEventType.BLUR)) && getRealView() != null) { getRealView().setFocusable(true); getRealView().setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { Map<String, Object> params = new HashMap<>(); params.put("timeStamp", System.currentTimeMillis()); WXSDKManager.getInstance().fireEvent(mInstanceId, mDomObj.ref, hasFocus ? WXEventType.FOCUS : WXEventType.BLUR, params); } }); } else if (getRealView() != null && needGestureDetector(type)) { if (getRealView() instanceof WXGestureObservable) { if (wxGesture == null) { wxGesture = new WXGesture(this, mContext); } mGestureType.add(type); ((WXGestureObservable) getRealView()).registerGestureListener(wxGesture); } else { WXLogUtils.e(getRealView().getClass().getSimpleName() + " don't implement " + "WXGestureObservable, so no gesture is supported."); } } else { WXScroller scroller = getParentScroller(); if (type.equals(WXEventType.APPEAR) && scroller != null) { scroller.bindAppearEvent(this); } if (type.equals(WXEventType.DISAPPEAR) && scroller != null) { scroller.bindDisappearEvent(this); } if(type.equals(WXEventType.APPEAR) && getParent() instanceof WXListComponent){ registerAppearEvent=true; } if(type.equals(WXEventType.DISAPPEAR) && getParent() instanceof WXListComponent){ registerAppearEvent=true; } } } public View getRealView() { return mHost; } /** * Judge whether need to set an onTouchListener.<br> * As there is only one onTouchListener in each view, so all the gesture that use onTouchListener should put there. * * @param type eventType {@link WXEventType} * @return true for set an onTouchListener, otherwise false */ private boolean needGestureDetector(String type) { if (mHost != null) { for (WXGestureType gesture : WXGestureType.LowLevelGesture.values()) { if (type.equals(gesture.toString())) { return true; } } for (WXGestureType gesture : WXGestureType.HighLevelGesture.values()) { if (type.equals(gesture.toString())) { return true; } } } return false; } /** * get Scroller components */ public WXScroller getParentScroller() { WXComponent component = this; WXVContainer container; WXScroller scroller; for (; ; ) { container = component.getParent(); if (container == null) { return null; } if (container instanceof WXScroller) { scroller = (WXScroller) container; return scroller; } if (container.getRef().equals(WXDomObject.ROOT)) { return null; } component = container; } } public WXVContainer getParent() { return mParent; } public String getRef() { if (mDomObj == null) { return null; } return mDomObj.ref; } /** * create view * * @param parent * @param index */ public final void createView(WXVContainer parent, int index) { if(!isLazy()) { createViewImpl(parent, index); } } protected void createViewImpl(WXVContainer parent, int index) { initView(); if (parent != null) { parent.addSubView(mHost, index); } getOrCreateBorder().attachView(mHost); } protected void initView() { if(mContext!=null) { mHost = new FrameLayout(mContext); } } public View getView() { return mHost; } public int getAbsoluteY() { return mAbsoluteY; } public int getAbsoluteX() { return mAbsoluteX; } public void updateDom(WXDomObject dom) { if (dom == null) { return; } mDomObj = dom; } public final void removeEvent(String type) { if (TextUtils.isEmpty(type)) { return; } mDomObj.removeEvent(type); mGestureType.remove(type); removeEventFromView(type); } protected void removeEventFromView(String type) { if (type.equals(WXEventType.CLICK) && getRealView() != null) { getRealView().setOnClickListener(null); } WXScroller scroller = getParentScroller(); if (type.equals(WXEventType.APPEAR) && scroller != null) { scroller.unbindAppearEvent(this); } if (type.equals(WXEventType.DISAPPEAR) && scroller != null) { scroller.unbindDisappearEvent(this); } if(type.equals(WXEventType.APPEAR) && getParent() instanceof WXListComponent){ ((WXListComponent)getParent()).unbindAppearComponents(this); registerAppearEvent=false; } if(type.equals(WXEventType.DISAPPEAR) && getParent() instanceof WXListComponent){ ((WXListComponent)getParent()).unbindAppearComponents(this); registerAppearEvent=false; } } public final void removeAllEvent() { if (mDomObj == null || mDomObj.event == null || mDomObj.event.size() < 1) { return; } for (String event : mDomObj.event) { removeEventFromView(event); } mDomObj.event.clear(); mGestureType.clear(); wxGesture = null; if (getRealView() != null && getRealView() instanceof WXGestureObservable) { ((WXGestureObservable) getRealView()).registerGestureListener(null); } } public final void removeStickyStyle() { if (mDomObj == null || mDomObj.style == null) { return; } if (mDomObj.isSticky()) { WXScroller scroller = getParentScroller(); if (scroller != null) { scroller.unbindStickStyle(this); } } } @WXComponentProp(name = WXDomPropConstant.WX_ATTR_DISABLED) public void setDisabled(boolean disabled) { if (mHost == null) { return; } mHost.setEnabled(!disabled); } @WXComponentProp(name = WXDomPropConstant.WX_POSITION) public void setSticky(String sticky) { if (!TextUtils.isEmpty(sticky) && sticky.equals(WXDomPropConstant.WX_POSITION_STICKY)) { WXScroller waScroller = getParentScroller(); if (waScroller != null) { waScroller.bindStickStyle(this); } } } @WXComponentProp(name = WXDomPropConstant.WX_BACKGROUNDCOLOR) public void setBackgroundColor(String color) { if (!TextUtils.isEmpty(color)) { int colorInt = WXResourceUtils.getColor(color); if (colorInt != Integer.MIN_VALUE) { getOrCreateBorder().setBackgroundColor(colorInt); } } } @WXComponentProp(name = WXDomPropConstant.WX_OPACITY) public void setOpacity(float opacity) { if (opacity >= 0 && opacity <= 1 && mHost.getAlpha() != opacity) { mHost.setAlpha(opacity); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDERRADIUS) public void setBorderRadius(float borderRadius) { if (borderRadius >= 0) { getOrCreateBorder().setBorderRadius(WXViewUtils.getRealPxByWidth(borderRadius)); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_LEFT_RADIUS) public void setBorderTopLeftRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_TOP_LEFT_RADIUS, borderRadius); } private void setBorderRadius(int position, float borderRadius) { if (borderRadius >= 0) { getOrCreateBorder().setBorderRadius(position, WXViewUtils.getRealPxByWidth(borderRadius)); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_RIGHT_RADIUS) public void setBorderTopRightRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_TOP_RIGHT_RADIUS, borderRadius); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_RIGHT_RADIUS) public void setBorderBottomRightRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_BOTTOM_RIGHT_RADIUS, borderRadius); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_LEFT_RADIUS) public void setBorderBottoLeftRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_BOTTOM_LEFT_RADIUS, borderRadius); } @WXComponentProp(name = WXDomPropConstant.WX_BORDERWIDTH) public void setBorderWidth(float borderWidth) { setBorderWidth(Spacing.ALL, borderWidth); } private void setBorderWidth(int position, float borderWidth) { if (borderWidth >= 0) { getOrCreateBorder().setBorderWidth(position, WXViewUtils.getRealPxByWidth(borderWidth)); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_WIDTH) public void setBorderTopWidth(float borderWidth) { setBorderWidth(Spacing.TOP, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_RIGHT_WIDTH) public void setBorderRightWidth(float borderWidth) { setBorderWidth(Spacing.RIGHT, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_WIDTH) public void setBorderBottomWidth(float borderWidth) { setBorderWidth(Spacing.BOTTOM, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_LEFT_WIDTH) public void setBorderLeftWidth(float borderWidth) { setBorderWidth(Spacing.LEFT, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDERSTYLE) public void setBorderStyle(String borderStyle) { getOrCreateBorder().setBorderStyle(borderStyle); } @WXComponentProp(name = WXDomPropConstant.WX_BORDERCOLOR) public void setBorderColor(String borderColor) { setBorderColor(Spacing.ALL, borderColor); } private void setBorderColor(int position, String borderColor) { if (!TextUtils.isEmpty(borderColor)) { int colorInt = WXResourceUtils.getColor(borderColor); if (colorInt != Integer.MIN_VALUE) { getOrCreateBorder().setBorderColor(position, colorInt); } } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_COLOR) public void setBorderTopColor(String borderColor) { setBorderColor(Spacing.TOP, borderColor); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_RIGHT_COLOR) public void setBorderRightColor(String borderColor) { setBorderColor(Spacing.RIGHT, borderColor); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_COLOR) public void setBorderBottomColor(String borderColor) { setBorderColor(Spacing.BOTTOM, borderColor); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_LEFT_COLOR) public void setBorderLeftColor(String borderColor) { setBorderColor(Spacing.LEFT, borderColor); } public @Nullable String getVisibility() { try { return (String) getDomObject().style.get(WXDomPropConstant.WX_VISIBILITY); } catch (Exception e) { return WXDomPropConstant.WX_VISIBILITY_VISIBLE; } } @WXComponentProp(name = WXDomPropConstant.WX_VISIBILITY) public void setVisibility(String visibility) { View view; if ((view = getRealView()) != null) { if (TextUtils.equals(visibility, WXDomPropConstant.WX_VISIBILITY_VISIBLE)) { view.setVisibility(View.VISIBLE); } else if (TextUtils.equals(visibility, WXDomPropConstant.WX_VISIBILITY_HIDDEN)) { view.setVisibility(View.GONE); } } } public void registerActivityStateListener() { if (mInstance != null) { mInstance.registerActivityStateListener(this); } } @Override public void onActivityCreate() { } @Override public void onActivityStart() { } @Override public void onActivityPause() { } @Override public void onActivityResume() { } @Override public void onActivityStop() { } @Override public void onActivityDestroy() { } @Override public boolean onActivityBack() { return false; } public void destroy() { if (WXEnvironment.isApkDebugable() && !WXUtils.isUiThread()) { throw new WXRuntimeException("[WXComponent] destroy can only be called in main thread"); } removeAllEvent(); removeStickyStyle(); if (mDomObj != null) { mDomObj.destroy(); } } /** * Detach view from its component. Components, * which have difference between getView and getRealView or have temp calculation results, * must<strong> override</strong> this method with their own implementation. * * @return the original View */ public View detachViewAndClearPreInfo() { View original = mHost; if (mBorder != null) { mBorder.detachView(); } mPreRealLeft = 0; mPreRealWidth = 0; mPreRealHeight = 0; mPreRealTop = 0; // mHost = null; return original; } /** * This method computes user visible left-top point in view's coordinate. * The default implementation uses the scrollX and scrollY of the view as the result, * and put the value in the parameter pointer. * Components with different computation algorithm * (e.g. {@link WXListComponent#computeVisiblePointInViewCoordinate(PointF)} ) * <strong> should override </strong> this method. * * @param pointF the user visible left-top point in view's coordinate. */ public void computeVisiblePointInViewCoordinate(PointF pointF) { View view = getRealView(); pointF.set(view.getScrollX(), view.getScrollY()); } public boolean containsGesture(WXGestureType WXGestureType) { return mGestureType != null && mGestureType.contains(WXGestureType.toString()); } public void notifyAppearStateChange(String wxEventType,String direction){ if(getDomObject().containsEvent(WXEventType.APPEAR) || getDomObject().containsEvent(WXEventType.DISAPPEAR)) { Map<String, Object> params = new HashMap<>(); params.put("direction", direction); WXBridgeManager.getInstance().fireEvent(mInstanceId, getRef(), wxEventType, params,null); } } public boolean isUsing() { return isUsing; } public void setUsing(boolean using) { isUsing = using; } public static class MeasureOutput { public int width; public int height; } public boolean isOuterRefreshableContainer(WXComponent component) { if (component.getParent() == null) { return true; } else if (component.getParent() instanceof WXRefreshableContainer) { return false; } else { return isOuterRefreshableContainer(component.getParent()); } } }
android/sdk/src/main/java/com/taobao/weex/ui/component/WXComponent.java
/** * Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * 1. Definitions. * "License" shall mean the terms and conditions for use, reproduction, and distribution as defined * by Sections 1 through 9 of this document. * "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is * granting the License. * "Legal Entity" shall mean the union of the acting entity and all other entities that control, are * controlled by, or are under common control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the direction or management of such * entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this * License. * "Source" form shall mean the preferred form for making modifications, including but not limited * to software source code, documentation source, and configuration files. * "Object" form shall mean any form resulting from mechanical transformation or translation of a * Source form, including but not limited to compiled object code, generated documentation, and * conversions to other media types. * "Work" shall mean the work of authorship, whether in Source or Object form, made available under * the License, as indicated by a copyright notice that is included in or attached to the work (an * example is provided in the Appendix below). * "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or * derived from) the Work and for which the editorial revisions, annotations, elaborations, or other * modifications represent, as a whole, an original work of authorship. For the purposes of this * License, Derivative Works shall not include works that remain separable from, or merely link (or * bind by name) to the interfaces of, the Work and Derivative Works thereof. * "Contribution" shall mean any work of authorship, including the original version of the Work and * any modifications or additions to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or * Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this * definition, "submitted" means any form of electronic, verbal, or written communication sent to * the Licensor or its representatives, including but not limited to communication on electronic * mailing lists, source code control systems, and issue tracking systems that are managed by, or on * behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding * communication that is conspicuously marked or otherwise designated in writing by the copyright * owner as "Not a Contribution." * "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a * Contribution has been received by Licensor and subsequently incorporated within the Work. * 2. Grant of Copyright License. Subject to the terms and conditions of this License, each * Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, * irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, * publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or * Object form. * 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor * hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, use, offer to sell, sell, * import, and otherwise transfer the Work, where such license applies only to those patent claims * licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or * by combination of their Contribution(s) with the Work to which such Contribution(s) was * submitted. If You institute patent litigation against any entity (including a cross-claim or * counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work * constitutes direct or contributory patent infringement, then any patent licenses granted to You * under this License for that Work shall terminate as of the date such litigation is filed. * 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works * thereof in any medium, with or without modifications, and in Source or Object form, provided that * You meet the following conditions: * (a) You must give any other recipients of the Work or Derivative Works a copy of this License; * and * (b) You must cause any modified files to carry prominent notices stating that You changed the * files; and * (c) You must retain, in the Source form of any Derivative Works that You distribute, all * copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding * those notices that do not pertain to any part of the Derivative Works; and * (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative * Works that You distribute must include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not pertain to any part of the * Derivative Works, in at least one of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or documentation, if provided along with * the Derivative Works; or, within a display generated by the Derivative Works, if and wherever * such third-party notices normally appear. The contents of the NOTICE file are for informational * purposes only and do not modify the License. You may add Your own attribution notices within * Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the * Work, provided that such additional attribution notices cannot be construed as modifying the * License. * You may add Your own copyright statement to Your modifications and may provide additional or * different license terms and conditions for use, reproduction, or distribution of Your * modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and * distribution of the Work otherwise complies with the conditions stated in this License. * 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution * intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms * and conditions of this License, without any additional terms or conditions. Notwithstanding the * above, nothing herein shall supersede or modify the terms of any separate license agreement you * may have executed with Licensor regarding such Contributions. * 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service * marks, or product names of the Licensor, except as required for reasonable and customary use in * describing the origin of the Work and reproducing the content of the NOTICE file. * 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor * provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, * any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or * redistributing the Work and assume any risks associated with Your exercise of permissions under * this License. * 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including * negligence), contract, or otherwise, unless required by applicable law (such as deliberate and * grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for * damages, including any direct, indirect, special, incidental, or consequential damages of any * character arising as a result of this License or out of the use or inability to use the Work * (including but not limited to damages for loss of goodwill, work stoppage, computer failure or * malfunction, or any and all other commercial damages or losses), even if such Contributor has * been advised of the possibility of such damages. * 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works * thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, * indemnity, or other liability obligations and/or rights consistent with this License. However, in * accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, * not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each * Contributor harmless for any liability incurred by, or claims asserted against, such Contributor * by reason of your accepting any such warranty or additional liability. * END OF TERMS AND CONDITIONS * APPENDIX: How to apply the Apache License to your work. * To apply the Apache License to your work, attach the following boilerplate notice, with the * fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate comment syntax for the file * format. We also recommend that a file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier identification within third-party * archives. * Copyright 2016 Alibaba Group * 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.taobao.weex.ui.component; import android.content.Context; import android.graphics.PointF; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ScrollView; import com.taobao.weex.IWXActivityStateListener; import com.taobao.weex.WXEnvironment; import com.taobao.weex.WXSDKInstance; import com.taobao.weex.WXSDKManager; import com.taobao.weex.bridge.Invoker; import com.taobao.weex.bridge.WXBridgeManager; import com.taobao.weex.common.IWXObject; import com.taobao.weex.common.WXDomPropConstant; import com.taobao.weex.common.WXRuntimeException; import com.taobao.weex.dom.WXDomObject; import com.taobao.weex.dom.flex.CSSLayout; import com.taobao.weex.dom.flex.Spacing; import com.taobao.weex.ui.IFComponentHolder; import com.taobao.weex.ui.component.list.WXListComponent; import com.taobao.weex.ui.view.WXBackgroundDrawable; import com.taobao.weex.ui.view.WXCircleIndicator; import com.taobao.weex.ui.view.gesture.WXGesture; import com.taobao.weex.ui.view.gesture.WXGestureObservable; import com.taobao.weex.ui.view.gesture.WXGestureType; import com.taobao.weex.ui.view.refresh.wrapper.BounceRecyclerView; import com.taobao.weex.utils.WXLogUtils; import com.taobao.weex.utils.WXReflectionUtils; import com.taobao.weex.utils.WXResourceUtils; import com.taobao.weex.utils.WXUtils; import com.taobao.weex.utils.WXViewUtils; import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * abstract component * */ public abstract class WXComponent implements IWXObject, IWXActivityStateListener { public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; public static int mComponentNum = 0; public View mHost; public volatile WXVContainer mParent; public volatile WXDomObject mDomObj; public String mInstanceId; public boolean registerAppearEvent=false; public boolean appearState=false; protected int mOrientation = VERTICAL; protected WXSDKInstance mInstance; protected Context mContext; protected int mAbsoluteY = 0; protected int mAbsoluteX = 0; protected Set<String> mGestureType; private WXBorder mBorder; private boolean mLazy; private int mPreRealWidth = 0; private int mPreRealHeight = 0; private int mPreRealLeft = 0; private int mPreRealTop = 0; private WXGesture wxGesture; private IFComponentHolder mHolder; private boolean isUsing = false; @Deprecated public WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy) { this(instance,dom,parent,isLazy); } public WXComponent(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy) { mInstance = instance; mContext = mInstance.getContext(); mParent = parent; mDomObj = dom.clone(); mInstanceId = instance.getInstanceId(); mLazy = isLazy; mGestureType = new HashSet<>(); ++mComponentNum; } public void bindHolder(IFComponentHolder holder){ mHolder = holder; } /** * The view is created as needed * @return true for lazy */ public boolean isLazy() { return mLazy; } public void lazy(boolean lazy) { mLazy = lazy; } public void applyLayoutAndEvent(WXComponent component) { if(!isLazy()) { if (component == null) { component = this; } getOrCreateBorder().attachView(mHost); setLayout(component.mDomObj); setPadding(component.mDomObj.getPadding(), component.mDomObj.getBorder()); addEvents(); } } public void bindData(WXComponent component){ if(!isLazy()) { if (component == null) { component = this; } updateProperties(component.mDomObj.style); updateProperties(component.mDomObj.attr); updateExtra(component.mDomObj.getExtra()); } } protected WXBorder getOrCreateBorder() { if (mBorder == null) { mBorder = new WXBorder(); } return mBorder; } /** * layout view */ public final void setLayout(WXDomObject domObject) { if (mParent == null || domObject == null || TextUtils.isEmpty(mDomObj.ref)) { return; } mDomObj = domObject; if (this instanceof WXRefresh && mParent instanceof WXRefreshableContainer && isOuterRefreshableContainer(mParent)) { mInstance.setRefreshMargin(mDomObj.csslayout.dimensions[CSSLayout.DIMENSION_HEIGHT]); } if ((this instanceof WXBaseRefresh && mParent instanceof WXRefreshableContainer)) { return; } if (mParent instanceof WXRefreshableContainer && isOuterRefreshableContainer(mParent)) { if (!(this instanceof WXBaseRefresh)) { CSSLayout newLayout = new CSSLayout(); newLayout.copy(mDomObj.csslayout); newLayout.position[CSSLayout.POSITION_TOP] = mDomObj.csslayout.position[CSSLayout .POSITION_TOP] - mInstance.getRefreshMargin(); mDomObj.csslayout.copy(newLayout); } } Spacing parentPadding = mParent.getDomObject().getPadding(); Spacing parentBorder = mParent.getDomObject().getBorder(); Spacing margin = mDomObj.getMargin(); int realWidth = (int) mDomObj.getLayoutWidth(); int realHeight = (int) mDomObj.getLayoutHeight(); int realLeft = (int) (mDomObj.getLayoutX() - parentPadding.get(Spacing.LEFT) - parentBorder.get(Spacing.LEFT)); int realTop = (int) (mDomObj.getLayoutY() - parentPadding.get(Spacing.TOP) - parentBorder.get(Spacing.TOP)); int realRight = (int) margin.get(Spacing.RIGHT); int realBottom = (int) margin.get(Spacing.BOTTOM); if (mPreRealWidth == realWidth && mPreRealHeight == realHeight && mPreRealLeft == realLeft && mPreRealTop == realTop) { return; } if (mParent != null) { mAbsoluteY = (int) (mParent.mAbsoluteY + mDomObj.getLayoutY()); mAbsoluteX = (int) (mParent.mAbsoluteX + mDomObj.getLayoutX()); } //calculate first screen time if (!mInstance.mEnd && mAbsoluteY >= mInstance.getWeexHeight()) { mInstance.firstScreenRenderFinished(); } if (mHost == null) { return; } MeasureOutput measureOutput = measure(realWidth, realHeight); realWidth = measureOutput.width; realHeight = measureOutput.height; if (mHost instanceof WXCircleIndicator) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); return; } //fixed style if (mDomObj.isFixed() && mInstance.getRootView() != null) { if (mHost.getParent() instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) mHost.getParent(); viewGroup.removeView(mHost); } FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.width = realWidth; params.height = realHeight; params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); mInstance.getRootView().addView(mHost); if (WXEnvironment.isApkDebugable()) { WXLogUtils.d("Weex_Fixed_Style", "WXComponent:setLayout :" + realLeft + " " + realTop + " " + realWidth + " " + realHeight); WXLogUtils.d("Weex_Fixed_Style", "WXComponent:setLayout Left:" + mDomObj.style.getLeft() + " " + (int) mDomObj.style.getTop()); } return; } if (mParent.getRealView() instanceof ViewPager ) { // ViewPager.LayoutParams params = new ViewPager.LayoutParams(); // params.width = realWidth; // params.height = realHeight; // mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof FrameLayout) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof LinearLayout) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, realTop, realRight, realBottom); mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof ScrollView) { // ScrollView.LayoutParams params = new ScrollView.LayoutParams(realWidth, realHeight); // params.setMargins(realLeft, realTop, realRight, realBottom); // mHost.setLayoutParams(params); } else if (mParent.getRealView() instanceof BounceRecyclerView) { RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(realWidth, realHeight); params.setMargins(realLeft, 0, realRight, 0); mHost.setLayoutParams(params); } mPreRealWidth = realWidth; mPreRealHeight = realHeight; mPreRealLeft = realLeft; mPreRealTop = realTop; } public void setPadding(Spacing padding, Spacing border) { int left = (int) (padding.get(Spacing.LEFT) + border.get(Spacing.LEFT)); int top = (int) (padding.get(Spacing.TOP) + border.get(Spacing.TOP)); int right = (int) (padding.get(Spacing.RIGHT) + border.get(Spacing.RIGHT)); int bottom = (int) (padding.get(Spacing.BOTTOM) + border.get(Spacing.BOTTOM)); if (mHost == null) { return; } mHost.setPadding(left, top, right, bottom); } // private void updateProperties() { // if (mDomObj.attr != null && mDomObj.attr.size() > 0) { // updateProperties(mDomObj.attr); // } // if (mDomObj.style != null && mDomObj.style.size() > 0) { // updateProperties(mDomObj.style); // } // } private void addEvents() { int count = mDomObj.event == null ? 0 : mDomObj.event.size(); for (int i = 0; i < count; ++i) { addEvent(mDomObj.event.get(i)); } } public void updateExtra(Object extra) { } public WXDomObject getDomObject() { return mDomObj; } /** * measure */ protected MeasureOutput measure(int width, int height) { MeasureOutput measureOutput = new MeasureOutput(); measureOutput.width = width; measureOutput.height = height; return measureOutput; } public void updateProperties(Map<String, Object> props) { if (props == null||props.isEmpty() || mHost == null) { return; } Iterator<Entry<String, Object>> iterator = props.entrySet().iterator(); while (iterator.hasNext()) { String key = iterator.next().getKey(); Invoker invoker = mHolder.getMethod(key); if (invoker != null) { try { Type[] paramClazzs = invoker.getParameterTypes(); if (paramClazzs.length != 1) { WXLogUtils.e("[WXComponent] setX method only one parameter:" + invoker); return; } Object param; param = WXReflectionUtils.parseArgument(paramClazzs[0],props.get(key)); invoker.invoke(this, param); } catch (Exception e) { WXLogUtils.e("[WXComponent] updateProperties :" + "class:" + getClass() + "method:" + invoker.toString() + " function " + WXLogUtils.getStackTrace(e)); } } } } public void addEvent(String type) { if (TextUtils.isEmpty(type)) { return; } mDomObj.addEvent(type); if (type.equals(WXEventType.CLICK) && getRealView() != null) { mHost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Map<String, Object> params = new HashMap<>(); WXSDKManager.getInstance().fireEvent(mInstanceId, mDomObj.ref, WXEventType.CLICK, params); } }); } else if ((type.equals(WXEventType.FOCUS) || type.equals(WXEventType.BLUR)) && getRealView() != null) { getRealView().setFocusable(true); getRealView().setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { Map<String, Object> params = new HashMap<>(); params.put("timeStamp", System.currentTimeMillis()); WXSDKManager.getInstance().fireEvent(mInstanceId, mDomObj.ref, hasFocus ? WXEventType.FOCUS : WXEventType.BLUR, params); } }); } else if (getRealView() != null && needGestureDetector(type)) { if (getRealView() instanceof WXGestureObservable) { if (wxGesture == null) { wxGesture = new WXGesture(this, mContext); } mGestureType.add(type); ((WXGestureObservable) getRealView()).registerGestureListener(wxGesture); } else { WXLogUtils.e(getRealView().getClass().getSimpleName() + " don't implement " + "WXGestureObservable, so no gesture is supported."); } } else { WXScroller scroller = getParentScroller(); if (type.equals(WXEventType.APPEAR) && scroller != null) { scroller.bindAppearEvent(this); } if (type.equals(WXEventType.DISAPPEAR) && scroller != null) { scroller.bindDisappearEvent(this); } if(type.equals(WXEventType.APPEAR) && getParent() instanceof WXListComponent){ registerAppearEvent=true; } if(type.equals(WXEventType.DISAPPEAR) && getParent() instanceof WXListComponent){ registerAppearEvent=true; } } } public View getRealView() { return mHost; } /** * Judge whether need to set an onTouchListener.<br> * As there is only one onTouchListener in each view, so all the gesture that use onTouchListener should put there. * * @param type eventType {@link WXEventType} * @return true for set an onTouchListener, otherwise false */ private boolean needGestureDetector(String type) { if (mHost != null) { for (WXGestureType gesture : WXGestureType.LowLevelGesture.values()) { if (type.equals(gesture.toString())) { return true; } } for (WXGestureType gesture : WXGestureType.HighLevelGesture.values()) { if (type.equals(gesture.toString())) { return true; } } } return false; } /** * get Scroller components */ public WXScroller getParentScroller() { WXComponent component = this; WXVContainer container; WXScroller scroller; for (; ; ) { container = component.getParent(); if (container == null) { return null; } if (container instanceof WXScroller) { scroller = (WXScroller) container; return scroller; } if (container.getRef().equals(WXDomObject.ROOT)) { return null; } component = container; } } public WXVContainer getParent() { return mParent; } public String getRef() { if (mDomObj == null) { return null; } return mDomObj.ref; } /** * create view * * @param parent * @param index */ public final void createView(WXVContainer parent, int index) { if(!isLazy()) { createViewImpl(parent, index); } } protected void createViewImpl(WXVContainer parent, int index) { initView(); if (parent != null) { parent.addSubView(mHost, index); } getOrCreateBorder().attachView(mHost); } protected void initView() { if(mContext!=null) { mHost = new FrameLayout(mContext); } } public View getView() { return mHost; } public int getAbsoluteY() { return mAbsoluteY; } public int getAbsoluteX() { return mAbsoluteX; } public void updateDom(WXDomObject dom) { if (dom == null) { return; } mDomObj = dom; } public final void removeEvent(String type) { if (TextUtils.isEmpty(type)) { return; } mDomObj.removeEvent(type); mGestureType.remove(type); removeEventFromView(type); } protected void removeEventFromView(String type) { if (type.equals(WXEventType.CLICK) && getRealView() != null) { getRealView().setOnClickListener(null); } WXScroller scroller = getParentScroller(); if (type.equals(WXEventType.APPEAR) && scroller != null) { scroller.unbindAppearEvent(this); } if (type.equals(WXEventType.DISAPPEAR) && scroller != null) { scroller.unbindDisappearEvent(this); } if(type.equals(WXEventType.APPEAR) && getParent() instanceof WXListComponent){ ((WXListComponent)getParent()).unbindAppearComponents(this); registerAppearEvent=false; } if(type.equals(WXEventType.DISAPPEAR) && getParent() instanceof WXListComponent){ ((WXListComponent)getParent()).unbindAppearComponents(this); registerAppearEvent=false; } } public final void removeAllEvent() { if (mDomObj == null || mDomObj.event == null || mDomObj.event.size() < 1) { return; } for (String event : mDomObj.event) { removeEventFromView(event); } mDomObj.event.clear(); mGestureType.clear(); wxGesture = null; if (getRealView() != null && getRealView() instanceof WXGestureObservable) { ((WXGestureObservable) getRealView()).registerGestureListener(null); } } public final void removeStickyStyle() { if (mDomObj == null || mDomObj.style == null) { return; } if (mDomObj.isSticky()) { WXScroller scroller = getParentScroller(); if (scroller != null) { scroller.unbindStickStyle(this); } } } @WXComponentProp(name = WXDomPropConstant.WX_ATTR_DISABLED) public void setDisabled(boolean disabled) { if (mHost == null) { return; } mHost.setEnabled(!disabled); } @WXComponentProp(name = WXDomPropConstant.WX_POSITION) public void setSticky(String sticky) { if (!TextUtils.isEmpty(sticky) && sticky.equals(WXDomPropConstant.WX_POSITION_STICKY)) { WXScroller waScroller = getParentScroller(); if (waScroller != null) { waScroller.bindStickStyle(this); } } } @WXComponentProp(name = WXDomPropConstant.WX_BACKGROUNDCOLOR) public void setBackgroundColor(String color) { if (!TextUtils.isEmpty(color)) { int colorInt = WXResourceUtils.getColor(color); if (colorInt != Integer.MIN_VALUE) { getOrCreateBorder().setBackgroundColor(colorInt); } } } @WXComponentProp(name = WXDomPropConstant.WX_OPACITY) public void setOpacity(float opacity) { if (opacity >= 0 && opacity <= 1 && mHost.getAlpha() != opacity) { mHost.setAlpha(opacity); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDERRADIUS) public void setBorderRadius(float borderRadius) { if (borderRadius >= 0) { getOrCreateBorder().setBorderRadius(WXViewUtils.getRealPxByWidth(borderRadius)); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_LEFT_RADIUS) public void setBorderTopLeftRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_TOP_LEFT_RADIUS, borderRadius); } private void setBorderRadius(int position, float borderRadius) { if (borderRadius >= 0) { getOrCreateBorder().setBorderRadius(position, WXViewUtils.getRealPxByWidth(borderRadius)); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_RIGHT_RADIUS) public void setBorderTopRightRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_TOP_RIGHT_RADIUS, borderRadius); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_RIGHT_RADIUS) public void setBorderBottomRightRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_BOTTOM_RIGHT_RADIUS, borderRadius); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_LEFT_RADIUS) public void setBorderBottoLeftRadius(float borderRadius) { setBorderRadius(WXBackgroundDrawable.BORDER_BOTTOM_LEFT_RADIUS, borderRadius); } @WXComponentProp(name = WXDomPropConstant.WX_BORDERWIDTH) public void setBorderWidth(float borderWidth) { setBorderWidth(Spacing.ALL, borderWidth); } private void setBorderWidth(int position, float borderWidth) { if (borderWidth >= 0) { getOrCreateBorder().setBorderWidth(position, WXViewUtils.getRealPxByWidth(borderWidth)); } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_WIDTH) public void setBorderTopWidth(float borderWidth) { setBorderWidth(Spacing.TOP, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_RIGHT_WIDTH) public void setBorderRightWidth(float borderWidth) { setBorderWidth(Spacing.RIGHT, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_WIDTH) public void setBorderBottomWidth(float borderWidth) { setBorderWidth(Spacing.BOTTOM, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_LEFT_WIDTH) public void setBorderLeftWidth(float borderWidth) { setBorderWidth(Spacing.LEFT, borderWidth); } @WXComponentProp(name = WXDomPropConstant.WX_BORDERSTYLE) public void setBorderStyle(String borderStyle) { getOrCreateBorder().setBorderStyle(borderStyle); } @WXComponentProp(name = WXDomPropConstant.WX_BORDERCOLOR) public void setBorderColor(String borderColor) { setBorderColor(Spacing.ALL, borderColor); } private void setBorderColor(int position, String borderColor) { if (!TextUtils.isEmpty(borderColor)) { int colorInt = WXResourceUtils.getColor(borderColor); if (colorInt != Integer.MIN_VALUE) { getOrCreateBorder().setBorderColor(position, colorInt); } } } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_TOP_COLOR) public void setBorderTopColor(String borderColor) { setBorderColor(Spacing.TOP, borderColor); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_RIGHT_COLOR) public void setBorderRightColor(String borderColor) { setBorderColor(Spacing.RIGHT, borderColor); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_BOTTOM_COLOR) public void setBorderBottomColor(String borderColor) { setBorderColor(Spacing.BOTTOM, borderColor); } @WXComponentProp(name = WXDomPropConstant.WX_BORDER_LEFT_COLOR) public void setBorderLeftColor(String borderColor) { setBorderColor(Spacing.LEFT, borderColor); } public @Nullable String getVisibility() { try { return (String) getDomObject().style.get(WXDomPropConstant.WX_VISIBILITY); } catch (Exception e) { return WXDomPropConstant.WX_VISIBILITY_VISIBLE; } } @WXComponentProp(name = WXDomPropConstant.WX_VISIBILITY) public void setVisibility(String visibility) { View view; if ((view = getRealView()) != null) { if (TextUtils.equals(visibility, WXDomPropConstant.WX_VISIBILITY_VISIBLE)) { view.setVisibility(View.VISIBLE); } else if (TextUtils.equals(visibility, WXDomPropConstant.WX_VISIBILITY_HIDDEN)) { view.setVisibility(View.GONE); } } } public void registerActivityStateListener() { if (mInstance != null) { mInstance.registerActivityStateListener(this); } } @Override public void onActivityCreate() { } @Override public void onActivityStart() { } @Override public void onActivityPause() { } @Override public void onActivityResume() { } @Override public void onActivityStop() { } @Override public void onActivityDestroy() { } @Override public boolean onActivityBack() { return false; } public void destroy() { if (WXEnvironment.isApkDebugable() && !WXUtils.isUiThread()) { throw new WXRuntimeException("[WXComponent] destroy can only be called in main thread"); } removeAllEvent(); removeStickyStyle(); if (mDomObj != null) { mDomObj.destroy(); } } /** * Detach view from its component. Components, * which have difference between getView and getRealView or have temp calculation results, * must<strong> override</strong> this method with their own implementation. * * @return the original View */ public View detachViewAndClearPreInfo() { View original = mHost; if (mBorder != null) { mBorder.detachView(); } mPreRealLeft = 0; mPreRealWidth = 0; mPreRealHeight = 0; mPreRealTop = 0; // mHost = null; return original; } /** * This method computes user visible left-top point in view's coordinate. * The default implementation uses the scrollX and scrollY of the view as the result, * and put the value in the parameter pointer. * Components with different computation algorithm * (e.g. {@link WXListComponent#computeVisiblePointInViewCoordinate(PointF)} ) * <strong> should override </strong> this method. * * @param pointF the user visible left-top point in view's coordinate. */ public void computeVisiblePointInViewCoordinate(PointF pointF) { View view = getRealView(); pointF.set(view.getScrollX(), view.getScrollY()); } public boolean containsGesture(WXGestureType WXGestureType) { return mGestureType != null && mGestureType.contains(WXGestureType.toString()); } public void notifyAppearStateChange(String wxEventType,String direction){ if(getDomObject().containsEvent(WXEventType.APPEAR) || getDomObject().containsEvent(WXEventType.DISAPPEAR)) { Map<String, Object> params = new HashMap<>(); params.put("direction", direction); WXBridgeManager.getInstance().fireEvent(mInstanceId, getRef(), wxEventType, params,null); } } public boolean isUsing() { return isUsing; } public void setUsing(boolean using) { isUsing = using; } public static class MeasureOutput { public int width; public int height; } public boolean isOuterRefreshableContainer(WXComponent component) { if (component.getParent() == null) { return true; } else if (component.getParent() instanceof WXRefreshableContainer) { return false; } else { return isOuterRefreshableContainer(component.getParent()); } } }
* [android] remove height support to cell
android/sdk/src/main/java/com/taobao/weex/ui/component/WXComponent.java
* [android] remove height support to cell
<ide><path>ndroid/sdk/src/main/java/com/taobao/weex/ui/component/WXComponent.java <ide> import android.graphics.PointF; <ide> import android.support.annotation.Nullable; <ide> import android.support.v4.view.ViewPager; <del>import android.support.v7.widget.RecyclerView; <ide> import android.text.TextUtils; <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> params.setMargins(realLeft, realTop, realRight, realBottom); <ide> mHost.setLayoutParams(params); <ide> } else if (mParent.getRealView() instanceof ScrollView) { <del>// ScrollView.LayoutParams params = new ScrollView.LayoutParams(realWidth, realHeight); <del>// params.setMargins(realLeft, realTop, realRight, realBottom); <add> ScrollView.LayoutParams params = new ScrollView.LayoutParams(realWidth, realHeight); <add> params.setMargins(realLeft, realTop, realRight, realBottom); <add> mHost.setLayoutParams(params); <add> } else if (mParent.getRealView() instanceof BounceRecyclerView) { <add>// RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(realWidth, realHeight); <add>// params.setMargins(realLeft, 0, realRight, 0); <ide> // mHost.setLayoutParams(params); <del> } else if (mParent.getRealView() instanceof BounceRecyclerView) { <del> RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(realWidth, realHeight); <del> params.setMargins(realLeft, 0, realRight, 0); <del> mHost.setLayoutParams(params); <ide> } <ide> <ide> mPreRealWidth = realWidth;
Java
apache-2.0
aae75d1fdfdccdff7af7bf7f00c34e66ec9a1c78
0
dschadow/CloudSecurity
/* * Copyright (C) 2017 Dominik Schadow, [email protected] * * This file is part of the Cloud Security 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 de.dominikschadow.configclient.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Security related configuration of the Config Client Vault application. * * @author Dominik Schadow */ @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .mvcMatchers("/admin/**").hasRole("ADMIN") .mvcMatchers("/").permitAll() .and() .csrf() .ignoringAntMatchers("/admin/h2-console/*") .and() .headers() .frameOptions().sameOrigin() .and() .formLogin(); // @formatter:on } @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("user").roles("ADMIN", "ACTUATOR"); } }
config-client-vault/src/main/java/de/dominikschadow/configclient/config/WebSecurityConfig.java
/* * Copyright (C) 2017 Dominik Schadow, [email protected] * * This file is part of the Cloud Security 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 de.dominikschadow.configclient.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Security related configuration of the Config Client Vault application. * * @author Dominik Schadow */ @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .mvcMatchers("/admin/**").hasRole("ADMIN") .mvcMatchers("/").permitAll() .and() .csrf() .ignoringAntMatchers("/admin/h2-console/*") .and() .formLogin(); // @formatter:on } @Autowired public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("user").password("user").roles("ADMIN", "ACTUATOR"); } }
Allow frames for same origin, required by h2
config-client-vault/src/main/java/de/dominikschadow/configclient/config/WebSecurityConfig.java
Allow frames for same origin, required by h2
<ide><path>onfig-client-vault/src/main/java/de/dominikschadow/configclient/config/WebSecurityConfig.java <ide> .csrf() <ide> .ignoringAntMatchers("/admin/h2-console/*") <ide> .and() <add> .headers() <add> .frameOptions().sameOrigin() <add> .and() <ide> .formLogin(); <ide> // @formatter:on <ide> }
Java
bsd-3-clause
141148dfc064ebf60d0f12a3dc5241d6c330d047
0
mikandi/apptentive-android,apptentive/apptentive-android
/* * Copyright (c) 2014, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.dev; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.apptentive.android.sdk.*; import com.apptentive.android.sdk.module.messagecenter.UnreadMessagesListener; import com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener; /** * @author Sky Kelsey */ public class MainActivity extends ApptentiveActivity { public static final String LOG_TAG = "Apptentive Dev App"; private long lastUnreadMessageCount = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // OPTIONAL: To specify a different user email than what the device was setup with. //Apptentive.setUserEmail("[email protected]"); // OPTIONAL: To send extra about the device to the server. //Apptentive.addCustomDeviceData(this, "custom_device_key", "custom_device_value"); //Apptentive.addCustomPersonData(this, "custom_person_key", "custom_person_value"); // OPTIONAL: Specify a different rating provider if your app is not served from Google Play. //Apptentive.setRatingProvider(new AmazonAppstoreRatingProvider()); // Impersonate an app for ratings. //Apptentive.putRatingProviderArg("package", "your.package.name"); // If you would like to be notified when there are unread messages available, set a listener like this. Apptentive.setUnreadMessagesListener(new UnreadMessagesListener() { public void onUnreadMessageCountChanged(final int unreadMessages) { Log.e(LOG_TAG, "There are " + unreadMessages + " unread messages."); runOnUiThread(new Runnable() { public void run() { Button messageCenterButton = (Button) findViewById(R.id.button_message_center); if (messageCenterButton != null) { messageCenterButton.setText("Message Center, unread = " + unreadMessages); } if (lastUnreadMessageCount < unreadMessages) { Toast.makeText(MainActivity.this, "You have " + unreadMessages + " unread messages.", Toast.LENGTH_SHORT).show(); } } }); lastUnreadMessageCount = unreadMessages; } }); // Ad a listener to notify you when a survey is completed. Apptentive.setOnSurveyFinishedListener(new OnSurveyFinishedListener() { @Override public void onSurveyFinished(boolean completed) { Toast.makeText(MainActivity.this, completed ? "Survey was completed." : "Survey was skipped.", Toast.LENGTH_SHORT).show(); } }); } public void launchInteractionsActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, InteractionsActivity.class)); } public void launchMessageCenterActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, MessageCenterActivity.class)); } public void launchTestsActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, TestsActivity.class)); } public void launchDataActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, DataActivity.class)); } public void showMessageCenter(@SuppressWarnings("unused") View view) { Apptentive.showMessageCenter(this); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); /* if (hasFocus) { boolean ret = Apptentive.engage(this, "init"); Log.e(LOG_TAG, "Rating flow " + (ret ? "was" : "was not") + " shown."); } */ } }
samples/apptentive-dev/src/com/apptentive/android/dev/MainActivity.java
/* * Copyright (c) 2014, Apptentive, Inc. All Rights Reserved. * Please refer to the LICENSE file for the terms and conditions * under which redistribution and use of this file is permitted. */ package com.apptentive.android.dev; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.apptentive.android.sdk.*; import com.apptentive.android.sdk.module.messagecenter.UnreadMessagesListener; import com.apptentive.android.sdk.module.survey.OnSurveyFinishedListener; /** * @author Sky Kelsey */ public class MainActivity extends ApptentiveActivity { public static final String LOG_TAG = "Apptentive Dev App"; private long lastUnreadMessageCount = 0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // OPTIONAL: To specify a different user email than what the device was setup with. //Apptentive.setUserEmail("[email protected]"); // OPTIONAL: To send extra about the device to the server. //Apptentive.addCustomDeviceData(this, "custom_device_key", "custom_device_value"); //Apptentive.addCustomPersonData(this, "custom_person_key", "custom_person_value"); // OPTIONAL: Specify a different rating provider if your app is not served from Google Play. //Apptentive.setRatingProvider(new AmazonAppstoreRatingProvider()); // Impersonate an app for ratings. //Apptentive.putRatingProviderArg("package", "your.package.name"); // If you would like to be notified when there are unread messages available, set a listener like this. Apptentive.setUnreadMessagesListener(new UnreadMessagesListener() { public void onUnreadMessageCountChanged(final int unreadMessages) { Log.e(LOG_TAG, "There are " + unreadMessages + " unread messages."); runOnUiThread(new Runnable() { public void run() { Button messageCenterButton = (Button) findViewById(R.id.button_message_center); if (messageCenterButton != null) { messageCenterButton.setText("Message Center, unread = " + unreadMessages); } if (lastUnreadMessageCount < unreadMessages) { Toast.makeText(MainActivity.this, "You have " + unreadMessages + " unread messages.", Toast.LENGTH_SHORT).show(); } } }); lastUnreadMessageCount = unreadMessages; } }); // Ad a listener to notify you when a survey is completed. Apptentive.setOnSurveyFinishedListener(new OnSurveyFinishedListener() { @Override public void onSurveyFinished(boolean completed) { Toast.makeText(MainActivity.this, completed ? "Survey was completed." : "Survey was skipped.", Toast.LENGTH_SHORT).show(); } }); } public void launchInteractionsActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, InteractionsActivity.class)); } public void launchMessageCenterActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, MessageCenterActivity.class)); } public void launchTestsActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, TestsActivity.class)); } public void launchDataActivity(@SuppressWarnings("unused") View view) { startActivity(new Intent(this, DataActivity.class)); } public void showMessageCenter(@SuppressWarnings("unused") View view) { Apptentive.showMessageCenter(this); } // Call the ratings flow. This is one way to do it: Show the ratings flow if conditions are met when the window // gains focus. @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { boolean ret = Apptentive.engage(this, "init"); Log.e(LOG_TAG, "Rating flow " + (ret ? "was" : "was not") + " shown."); } } }
Dev app: Don't always call "init" Event on main window focus.
samples/apptentive-dev/src/com/apptentive/android/dev/MainActivity.java
Dev app: Don't always call "init" Event on main window focus.
<ide><path>amples/apptentive-dev/src/com/apptentive/android/dev/MainActivity.java <ide> Apptentive.showMessageCenter(this); <ide> } <ide> <del> // Call the ratings flow. This is one way to do it: Show the ratings flow if conditions are met when the window <del> // gains focus. <ide> @Override <ide> public void onWindowFocusChanged(boolean hasFocus) { <ide> super.onWindowFocusChanged(hasFocus); <add>/* <ide> if (hasFocus) { <ide> boolean ret = Apptentive.engage(this, "init"); <ide> Log.e(LOG_TAG, "Rating flow " + (ret ? "was" : "was not") + " shown."); <ide> } <add>*/ <ide> } <ide> }
Java
mit
b6581efebb049e1c16a64e720285d0e2daea1807
0
PG85/OpenTerrainGenerator
package com.pg85.otg.customobjects.bo4; import com.pg85.otg.OTG; import com.pg85.otg.common.LocalMaterialData; import com.pg85.otg.configuration.customobjects.CustomObjectConfigFile; import com.pg85.otg.configuration.customobjects.CustomObjectConfigFunction; import com.pg85.otg.configuration.io.SettingsReaderOTGPlus; import com.pg85.otg.configuration.io.SettingsWriterOTGPlus; import com.pg85.otg.configuration.standard.PluginStandardValues; import com.pg85.otg.configuration.standard.WorldStandardValues; import com.pg85.otg.configuration.world.WorldConfig.ConfigMode; import com.pg85.otg.customobjects.CustomObject; import com.pg85.otg.customobjects.bo4.BO4Config; import com.pg85.otg.customobjects.bo4.BO4Settings; import com.pg85.otg.customobjects.bo4.bo4function.BO4BlockFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4BranchFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4EntityFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4ModDataFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4ParticleFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4RandomBlockFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4SpawnerFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4WeightedBranchFunction; import com.pg85.otg.customobjects.structures.bo4.BO4CustomStructureCoordinate; import com.pg85.otg.customobjects.bo3.BO3Settings; import com.pg85.otg.customobjects.bo3.BO3Settings.SpawnHeightEnum; import com.pg85.otg.exception.InvalidConfigException; import com.pg85.otg.logging.LogMarker; import com.pg85.otg.util.bo3.NamedBinaryTag; import com.pg85.otg.util.bo3.Rotation; import com.pg85.otg.util.helpers.StreamHelper; import com.pg85.otg.util.materials.MaterialHelper; import com.pg85.otg.util.minecraft.defaults.DefaultStructurePart; import java.io.DataOutput; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.zip.DataFormatException; public class BO4Config extends CustomObjectConfigFile { public String author; public String description; public ConfigMode settingsMode; public int frequency; private final int xSize = 16; private final int zSize = 16; public int minHeight; public int maxHeight; public SpawnHeightEnum spawnHeight; private BO4BlockFunction[][] heightMap; private boolean inheritedBO3Loaded; // These are used in CustomObjectStructure when determining the minimum area in chunks that // this branching structure needs to be able to spawn public int minimumSizeTop = -1; public int minimumSizeBottom = -1; public int minimumSizeLeft = -1; public int minimumSizeRight = -1; public int timesSpawned = 0; public int branchFrequency; // Define groups that this BO3 belongs to with a range in chunks that members of each group should have to each other private String branchFrequencyGroup; public HashMap<String, Integer> branchFrequencyGroups; private int minX; private int maxX; private int minY; private int maxY; private int minZ; private int maxZ; private ArrayList<String> inheritedBO3s; // Adjusts the height by this number before spawning. Handy when using "highestblock" for lowering BO3s that have a lot of ground under them included public int heightOffset; private Rotation inheritBO3Rotation; // If this is set to true then any air blocks in the bo3 will not be spawned private boolean removeAir; // Defaults to false. Set to true if this BO3 should spawn at the player spawn point. When the server starts one of the structures that has IsSpawnPoint set to true is selected randomly and is spawned, the others never get spawned.) public boolean isSpawnPoint; // Replaces all the non-air blocks that are above this BO3 or its smoothing area with the given block material (should be WATER or AIR or NONE), also applies to smoothing areas although it intentionally leaves some of the terrain above them intact. WATER can be used in combination with SpawnUnderWater to fill any air blocks underneath waterlevel with water (and any above waterlevel with air). public String replaceAbove; // Replaces all non-air blocks underneath the BO3 (but not its smoothing area) with the designated material until a solid block is found. public String replaceBelow; // Defaults to true. If set to true then every block in the BO3 of the materials defined in ReplaceWithGroundBlock or ReplaceWithSurfaceBlock will be replaced by the GroundBlock or SurfaceBlock materials configured for the biome the block is spawned in. public boolean replaceWithBiomeBlocks; // Replaces all the blocks of the given material in the BO3 with the GroundBlock configured for the biome it spawns in public String replaceWithGroundBlock; // Replaces all the blocks of the given material in the BO3 with the SurfaceBlock configured for the biome it spawns in public String replaceWithSurfaceBlock; // Define a group that this BO3 belongs to and a range in chunks that members of this group should have to each other private String bo3Group; public HashMap<String, Integer> bo3Groups; // If this is set to true then this BO3 can spawn on top of or inside other BO3's public boolean canOverride; // Copies the blocks and branches of an existing BO3 into this one private String inheritBO3; // Should the smoothing area go to the top or the bottom blocks in the bo3? public boolean smoothStartTop; public boolean smoothStartWood; // The size of the smoothing area public int smoothRadius; // The materials used for the smoothing area public String smoothingSurfaceBlock; public String smoothingGroundBlock; // If true then root BO3 smoothing and height settings are used for all children public boolean overrideChildSettings; public boolean overrideParentHeight; // Used to make sure that dungeons can only spawn underneath other structures public boolean mustBeBelowOther; // Used to make sure that dungeons can only spawn inside worldborders public boolean mustBeInsideWorldBorders; private String replacesBO3; public ArrayList<String> replacesBO3Branches; private String mustBeInside; public ArrayList<String> mustBeInsideBranches; private String cannotBeInside; public ArrayList<String> cannotBeInsideBranches; public int smoothHeightOffset; public boolean canSpawnOnWater; public boolean spawnOnWaterOnly; public boolean spawnUnderWater; public boolean spawnAtWaterLevel; private String worldName; // Store blocks in arrays instead of as BO4BlockFunctions, // since that gives way too much overhead memory wise. // We may have tens of millions of blocks, java doesn't handle lots of small classes well. private short[][][]blocks; private LocalMaterialData[]blocksMaterial; private String[]blocksMetaDataName; private NamedBinaryTag[]blocksMetaDataTag; private LocalMaterialData[][] randomBlocksBlocks; private byte[][] randomBlocksBlockChances; private String[][] randomBlocksMetaDataNames; private NamedBinaryTag[][] randomBlocksMetaDataTags; private byte[] randomBlocksBlockCount; // private BO4BranchFunction[] branchesOTGPlus; private BO4ModDataFunction[] modDataOTGPlus; private BO4SpawnerFunction[] spawnerDataOTGPlus; private BO4ParticleFunction[] particleDataOTGPlus; private BO4EntityFunction[] entityDataOTGPlus; private boolean isCollidable = false; private boolean isBO4Data = false; /** * Creates a BO3Config from a file. * * @param reader The settings of the BO3. * @param directory The directory the BO3 is stored in. * @param otherObjects All other loaded objects by their name. */ public BO4Config(SettingsReaderOTGPlus reader, boolean init) throws InvalidConfigException { super(reader); if(init) { init(); } } static int BO4BlocksLoadedFromBO4Data = 0; static int accumulatedTime = 0; static int accumulatedTime2 = 0; private void init() throws InvalidConfigException { this.minX = Integer.MAX_VALUE; this.maxX = Integer.MIN_VALUE; this.minY = Integer.MAX_VALUE; this.maxY = Integer.MIN_VALUE; this.minZ = Integer.MAX_VALUE; this.maxZ = Integer.MIN_VALUE; if(!this.reader.getFile().getAbsolutePath().toLowerCase().endsWith(".bo4data")) { //long startTime = System.currentTimeMillis(); readConfigSettings(); //BO4BlocksLoaded++; //long timeTaken = (System.currentTimeMillis() - startTime); //accumulatedTime += timeTaken; //OTG.log(LogMarker.INFO, "BO4's loaded: " + BO4BlocksLoaded + " in " + accumulatedTime); //OTG.log(LogMarker.INFO, ".BO4 loaded in: " + timeTaken + " " + this.getName() + ".BO4"); } else { //long startTime = System.currentTimeMillis(); this.readFromBO4DataFile(false); //BO4BlocksLoadedFromBO4Data++; //long timeTaken = (System.currentTimeMillis() - startTime); //accumulatedTime2 += timeTaken; //OTG.log(LogMarker.INFO, ".BO4Data's loaded: " + BO4BlocksLoadedFromBO4Data + " in " + accumulatedTime2); //OTG.log(LogMarker.INFO, ".BO4Data loaded in: " + timeTaken + " " + this.getName() + ".BO4Data"); } // When writing, we'll need to read some raw data from the file, // so can't flush the cache yet. Flush after writing. if(this.settingsMode == ConfigMode.WriteDisable) { this.reader.flushCache(); } } public int getXOffset() { return minX < -8 ? -minX : maxX > 7 ? -minX : 8; } public int getZOffset() { return minZ < -7 ? -minZ : maxZ > 8 ? -minZ : 7; } public int getminX() { return minX + this.getXOffset(); // + xOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getmaxX() { return maxX + this.getXOffset(); // + xOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getminY() { return minY; } public int getmaxY() { return maxY; } public int getminZ() { return minZ + this.getZOffset(); // + zOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getmaxZ() { return maxZ + this.getZOffset(); // + zOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public ArrayList<String> getInheritedBO3s() { return this.inheritedBO3s; } public BO4BlockFunction[][] getSmoothingHeightMap(BO4 start) { return getSmoothingHeightMap(start, true); } private BO4BlockFunction[][] getSmoothingHeightMap(BO4 start, boolean fromFile) { // TODO: Caching the heightmap will mean this BO4 can only be used with 1 master BO4, // it won't pick up smoothing area settings if it is also used in another structure. if(this.heightMap == null) { if(this.isBO4Data && fromFile) { BO4Config bo4Config = null; try { bo4Config = new BO4Config(this.reader, false); } catch (InvalidConfigException e) { e.printStackTrace(); } if(bo4Config != null) { bo4Config.readFromBO4DataFile(true); this.heightMap = bo4Config.getSmoothingHeightMap(start, false); return this.heightMap; } } this.heightMap = new BO4BlockFunction[16][16]; // make heightmap containing the highest or lowest blocks in this chunk int blockIndex = 0; LocalMaterialData material; boolean isSmoothAreaAnchor; boolean isRandomBlock; int y; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { if(blocks[x][z] != null) { for(int i = 0; i < blocks[x][z].length; i++) { isSmoothAreaAnchor = false; isRandomBlock = this.randomBlocksBlocks[blockIndex] != null; y = blocks[x][z][i]; if(isRandomBlock) { for(LocalMaterialData randomMaterial : this.randomBlocksBlocks[blockIndex]) { // TODO: Material should never be null, fix the code in RandomBlockFunction.load() that causes this. if(randomMaterial == null) { continue; } if(randomMaterial.isSmoothAreaAnchor(start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartWood : this.smoothStartWood, start.getConfig().spawnUnderWater)) { isSmoothAreaAnchor = true; break; } } } material = this.blocksMaterial[blockIndex]; if( isSmoothAreaAnchor || ( !isRandomBlock && material.isSmoothAreaAnchor(start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartWood : this.smoothStartWood, start.getConfig().spawnUnderWater) ) ) { if( (!(start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartTop : this.smoothStartTop) && y == getminY()) || ((start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartTop : this.smoothStartTop) && (this.heightMap[x][z] == null || y > this.heightMap[x][z].y)) ) { BO4BlockFunction blockFunction = null; if(isRandomBlock) { blockFunction = new BO4RandomBlockFunction(); ((BO4RandomBlockFunction)blockFunction).blocks = this.randomBlocksBlocks[blockIndex]; ((BO4RandomBlockFunction)blockFunction).blockChances = this.randomBlocksBlockChances[blockIndex]; ((BO4RandomBlockFunction)blockFunction).metaDataNames = this.randomBlocksMetaDataNames[blockIndex]; ((BO4RandomBlockFunction)blockFunction).metaDataTags = this.randomBlocksMetaDataTags[blockIndex]; ((BO4RandomBlockFunction)blockFunction).blockCount = this.randomBlocksBlockCount[blockIndex]; } else { blockFunction = new BO4BlockFunction(); } blockFunction.material = material; blockFunction.x = x; blockFunction.y = (short) y; blockFunction.z = z; blockFunction.metaDataName = this.blocksMetaDataName[blockIndex]; blockFunction.metaDataTag = this.blocksMetaDataTag[blockIndex]; this.heightMap[x][z] = blockFunction; } } blockIndex++; } } } } } return this.heightMap; } public BO4BlockFunction[] getBlocks() { return getBlocks(true); } private BO4BlockFunction[] getBlocks(boolean fromFile) { if(fromFile && this.isBO4Data) { BO4Config bo4Config = null; try { bo4Config = new BO4Config(this.reader, false); } catch (InvalidConfigException e) { e.printStackTrace(); } if(bo4Config != null) { bo4Config.readFromBO4DataFile(true); return bo4Config.getBlocks(false); } } BO4BlockFunction[] blocksOTGPlus = new BO4BlockFunction[this.blocksMaterial.length]; BO4BlockFunction block; int blockIndex = 0; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { if(this.blocks[x][z] != null) { for(int i = 0; i < this.blocks[x][z].length; i++) { if(this.randomBlocksBlocks[blockIndex] != null) { block = new BO4RandomBlockFunction(this); ((BO4RandomBlockFunction)block).blocks = this.randomBlocksBlocks[blockIndex]; ((BO4RandomBlockFunction)block).blockChances = this.randomBlocksBlockChances[blockIndex]; ((BO4RandomBlockFunction)block).metaDataNames = this.randomBlocksMetaDataNames[blockIndex]; ((BO4RandomBlockFunction)block).metaDataTags = this.randomBlocksMetaDataTags[blockIndex]; ((BO4RandomBlockFunction)block).blockCount = this.randomBlocksBlockCount[blockIndex]; } else { block = new BO4BlockFunction(this); } block.x = x; block.y = this.blocks[x][z][i]; block.z = z; block.material = this.blocksMaterial[blockIndex]; block.metaDataName = this.blocksMetaDataName[blockIndex]; block.metaDataTag = this.blocksMetaDataTag[blockIndex]; blocksOTGPlus[blockIndex] = block; blockIndex++; } } } } return blocksOTGPlus; } protected BO4BranchFunction[] getbranches() { return branchesOTGPlus; } public BO4ModDataFunction[] getModData() { return modDataOTGPlus; } public BO4SpawnerFunction[] getSpawnerData() { return spawnerDataOTGPlus; } public BO4ParticleFunction[] getParticleData() { return particleDataOTGPlus; } public BO4EntityFunction[] getEntityData() { return entityDataOTGPlus; } private void loadInheritedBO3() { if(this.inheritBO3 != null && this.inheritBO3.trim().length() > 0 && !inheritedBO3Loaded) { File currentFile = this.getFile().getParentFile(); this.worldName = currentFile.getName(); while(currentFile.getParentFile() != null && !currentFile.getName().toLowerCase().equals(PluginStandardValues.PresetsDirectoryName)) { this.worldName = currentFile.getName(); currentFile = currentFile.getParentFile(); if(this.worldName.toLowerCase().equals("globalobjects")) { this.worldName = null; break; } } CustomObject parentBO3 = OTG.getCustomObjectManager().getGlobalObjects().getObjectByName(this.inheritBO3, this.worldName); if(parentBO3 != null) { BO4BlockFunction[] blocks = getBlocks(); this.inheritedBO3Loaded = true; this.inheritedBO3s.addAll(((BO4)parentBO3).getConfig().getInheritedBO3s()); this.removeAir = ((BO4)parentBO3).getConfig().removeAir; this.replaceAbove = this.replaceAbove == null || this.replaceAbove.length() == 0 ? ((BO4)parentBO3).getConfig().replaceAbove : this.replaceAbove; this.replaceBelow = this.replaceBelow == null || this.replaceBelow.length() == 0 ? ((BO4)parentBO3).getConfig().replaceBelow : this.replaceBelow; BO4CustomStructureCoordinate rotatedParentMaxCoords = BO4CustomStructureCoordinate.getRotatedBO3Coords(((BO4)parentBO3).getConfig().maxX, ((BO4)parentBO3).getConfig().maxY, ((BO4)parentBO3).getConfig().maxZ, this.inheritBO3Rotation); BO4CustomStructureCoordinate rotatedParentMinCoords = BO4CustomStructureCoordinate.getRotatedBO3Coords(((BO4)parentBO3).getConfig().minX, ((BO4)parentBO3).getConfig().minY, ((BO4)parentBO3).getConfig().minZ, this.inheritBO3Rotation); int parentMaxX = rotatedParentMaxCoords.getX() > rotatedParentMinCoords.getX() ? rotatedParentMaxCoords.getX() : rotatedParentMinCoords.getX(); int parentMinX = rotatedParentMaxCoords.getX() < rotatedParentMinCoords.getX() ? rotatedParentMaxCoords.getX() : rotatedParentMinCoords.getX(); int parentMaxY = rotatedParentMaxCoords.getY() > rotatedParentMinCoords.getY() ? rotatedParentMaxCoords.getY() : rotatedParentMinCoords.getY(); int parentMinY = rotatedParentMaxCoords.getY() < rotatedParentMinCoords.getY() ? rotatedParentMaxCoords.getY() : rotatedParentMinCoords.getY(); int parentMaxZ = rotatedParentMaxCoords.getZ() > rotatedParentMinCoords.getZ() ? rotatedParentMaxCoords.getZ() : rotatedParentMinCoords.getZ(); int parentMinZ = rotatedParentMaxCoords.getZ() < rotatedParentMinCoords.getZ() ? rotatedParentMaxCoords.getZ() : rotatedParentMinCoords.getZ(); if(parentMaxX > this.maxX) { this.maxX = parentMaxX; } if(parentMinX < this.minX) { this.minX = parentMinX; } if(parentMaxY > this.maxY) { this.maxY = parentMaxY; } if(parentMinY < this.minY) { this.minY = parentMinY; } if(parentMaxZ > this.maxZ) { this.maxZ = parentMaxZ; } if(parentMinZ < this.minZ) { this.minZ = parentMinZ; } BO4BlockFunction[] parentBlocks = ((BO4)parentBO3).getConfig().getBlocks(); ArrayList<BO4BlockFunction> newBlocks = new ArrayList<BO4BlockFunction>(); newBlocks.addAll(new ArrayList<BO4BlockFunction>(Arrays.asList(parentBlocks))); newBlocks.addAll(new ArrayList<BO4BlockFunction>(Arrays.asList(blocks))); short[][] columnSizes = new short[16][16]; for(BO4BlockFunction block : newBlocks) { columnSizes[block.x][block.z]++; } loadBlockArrays(newBlocks, columnSizes); this.isCollidable = newBlocks.size() > 0; ArrayList<BO4BranchFunction> newBranches = new ArrayList<BO4BranchFunction>(); if(this.branchesOTGPlus != null) { for(BO4BranchFunction branch : this.branchesOTGPlus) { newBranches.add(branch); } } for(BO4BranchFunction branch : ((BO4)parentBO3).getConfig().branchesOTGPlus) { newBranches.add(branch.rotate(this.inheritBO3Rotation)); } this.branchesOTGPlus = newBranches.toArray(new BO4BranchFunction[newBranches.size()]); ArrayList<BO4ModDataFunction> newModData = new ArrayList<BO4ModDataFunction>(); if(this.modDataOTGPlus != null) { for(BO4ModDataFunction modData : this.modDataOTGPlus) { newModData.add(modData); } } for(BO4ModDataFunction modData : ((BO4)parentBO3).getConfig().modDataOTGPlus) { newModData.add(modData.rotate(this.inheritBO3Rotation)); } this.modDataOTGPlus = newModData.toArray(new BO4ModDataFunction[newModData.size()]); ArrayList<BO4SpawnerFunction> newSpawnerData = new ArrayList<BO4SpawnerFunction>(); if(this.spawnerDataOTGPlus != null) { for(BO4SpawnerFunction spawnerData : this.spawnerDataOTGPlus) { newSpawnerData.add(spawnerData); } } for(BO4SpawnerFunction spawnerData : ((BO4)parentBO3).getConfig().spawnerDataOTGPlus) { newSpawnerData.add(spawnerData.rotate(this.inheritBO3Rotation)); } this.spawnerDataOTGPlus = newSpawnerData.toArray(new BO4SpawnerFunction[newSpawnerData.size()]); ArrayList<BO4ParticleFunction> newParticleData = new ArrayList<BO4ParticleFunction>(); if(this.particleDataOTGPlus != null) { for(BO4ParticleFunction particleData : this.particleDataOTGPlus) { newParticleData.add(particleData); } } for(BO4ParticleFunction particleData : ((BO4)parentBO3).getConfig().particleDataOTGPlus) { newParticleData.add(particleData.rotate(this.inheritBO3Rotation)); } this.particleDataOTGPlus = newParticleData.toArray(new BO4ParticleFunction[newParticleData.size()]); ArrayList<BO4EntityFunction> newEntityData = new ArrayList<BO4EntityFunction>(); if(this.entityDataOTGPlus != null) { for(BO4EntityFunction entityData : this.entityDataOTGPlus) { newEntityData.add(entityData); } } for(BO4EntityFunction entityData : ((BO4)parentBO3).getConfig().entityDataOTGPlus) { newEntityData.add(entityData.rotate(this.inheritBO3Rotation)); } this.entityDataOTGPlus = newEntityData.toArray(new BO4EntityFunction[newEntityData.size()]); this.inheritedBO3s.addAll(((BO4)parentBO3).getConfig().getInheritedBO3s()); } if(!this.inheritedBO3Loaded) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "could not load BO3 parent for InheritBO3: " + this.inheritBO3 + " in BO3 " + this.getName()); } } } } static int BO4BlocksLoaded = 0; private void readResources() throws InvalidConfigException { List<BO4BlockFunction> tempBlocksList = new ArrayList<BO4BlockFunction>(); List<BO4BranchFunction> tempBranchesList = new ArrayList<BO4BranchFunction>(); List<BO4EntityFunction> tempEntitiesList = new ArrayList<BO4EntityFunction>(); List<BO4ModDataFunction> tempModDataList = new ArrayList<BO4ModDataFunction>(); List<BO4ParticleFunction> tempParticlesList = new ArrayList<BO4ParticleFunction>(); List<BO4SpawnerFunction> tempSpawnerList = new ArrayList<BO4SpawnerFunction>(); short[][] columnSizes = new short[xSize][zSize]; BO4BlockFunction block; for (CustomObjectConfigFunction<BO4Config> res : reader.getConfigFunctions(this, true)) { if (res.isValid()) { if (res instanceof BO4BlockFunction) { this.isCollidable = true; if(res instanceof BO4RandomBlockFunction) { block = (BO4RandomBlockFunction)res; tempBlocksList.add((BO4RandomBlockFunction)res); columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; } else { if(!this.removeAir || !((BO4BlockFunction)res).material.isAir()) { tempBlocksList.add((BO4BlockFunction)res); block = (BO4BlockFunction)res; try { columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; } catch(ArrayIndexOutOfBoundsException ex) { String breakpoint = ""; } } } // Get the real size of this BO3 if(((BO4BlockFunction)res).x < this.minX) { this.minX = ((BO4BlockFunction)res).x; } if(((BO4BlockFunction)res).x > this.maxX) { this.maxX = ((BO4BlockFunction)res).x; } if(((BO4BlockFunction)res).y < this.minY) { this.minY = ((BO4BlockFunction)res).y; } if(((BO4BlockFunction)res).y > this.maxY) { this.maxY = ((BO4BlockFunction)res).y; } if(((BO4BlockFunction)res).z < this.minZ) { this.minZ = ((BO4BlockFunction)res).z; } if(((BO4BlockFunction)res).z > this.maxZ) { this.maxZ = ((BO4BlockFunction)res).z; } } else { if (res instanceof BO4WeightedBranchFunction) { tempBranchesList.add((BO4WeightedBranchFunction) res); } else if (res instanceof BO4BranchFunction) { tempBranchesList.add((BO4BranchFunction) res); } else if (res instanceof BO4ModDataFunction) { tempModDataList.add((BO4ModDataFunction) res); } else if (res instanceof BO4SpawnerFunction) { tempSpawnerList.add((BO4SpawnerFunction) res); } else if (res instanceof BO4ParticleFunction) { tempParticlesList.add((BO4ParticleFunction) res); } else if (res instanceof BO4EntityFunction) { tempEntitiesList.add((BO4EntityFunction) res); } } } } if(this.minX == Integer.MAX_VALUE) { this.minX = -8; } if(this.maxX == Integer.MIN_VALUE) { this.maxX = -8; } if(this.minY == Integer.MAX_VALUE) { this.minY = 0; } if(this.maxY == Integer.MIN_VALUE) { this.maxY = 0; } if(this.minZ == Integer.MAX_VALUE) { this.minZ = -7; } if(this.maxZ == Integer.MIN_VALUE) { this.maxZ = -7; } if(Math.abs(this.minX - this.maxX) >= 16 || Math.abs(this.minZ - this.maxZ) >= 16) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "BO4 was too large to spawn (> 16x16) " + this.getName() + " XSize " + (Math.abs(this.minX - this.maxX) + 1) + " ZSize " + (Math.abs(this.minZ - this.maxZ) + 1) + ". Use branches instead."); } } // TODO: OTG+ Doesn't do CustomObject BO3's, only check for 16x16, not 32x32? boolean illegalBlock = false; for(BO4BlockFunction block1 : tempBlocksList) { block1.x += this.getXOffset(); block1.z += this.getZOffset(); if(block1.x > 15 || block1.z > 15) { illegalBlock = true; } if(block1.x < 0 || block1.z < 0) { illegalBlock = true; } } this.blocks = new short[xSize][zSize][]; this.blocksMaterial = new LocalMaterialData[tempBlocksList.size()]; this.blocksMetaDataName = new String[tempBlocksList.size()]; this.blocksMetaDataTag = new NamedBinaryTag[tempBlocksList.size()]; this.randomBlocksBlocks = new LocalMaterialData[tempBlocksList.size()][]; this.randomBlocksBlockChances = new byte[tempBlocksList.size()][]; this.randomBlocksMetaDataNames = new String[tempBlocksList.size()][]; this.randomBlocksMetaDataTags = new NamedBinaryTag[tempBlocksList.size()][]; this.randomBlocksBlockCount = new byte[tempBlocksList.size()]; short[][] columnBlockIndex = new short[xSize][zSize]; BO4BlockFunction[] blocksSorted = new BO4BlockFunction[tempBlocksList.size()]; int blocksSortedIndex = 0; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { for(int h = 0; h < tempBlocksList.size(); h++) { if(tempBlocksList.get(h).x == x && tempBlocksList.get(h).z == z) { blocksSorted[blocksSortedIndex] = tempBlocksList.get(h); blocksSortedIndex++; } } } } for(int blockIndex = 0; blockIndex < blocksSorted.length; blockIndex++) { block = blocksSorted[blockIndex]; if(this.blocks[block.x][block.z] == null) { this.blocks[block.x][block.z] = new short[columnSizes[block.x][block.z]]; } this.blocks[block.x][block.z][columnBlockIndex[block.x][block.z]] = (short) block.y; this.blocksMaterial[blockIndex] = block.material; this.blocksMetaDataName[blockIndex] = block.metaDataName; this.blocksMetaDataTag[blockIndex] = block.metaDataTag; if(block instanceof BO4RandomBlockFunction) { this.randomBlocksBlocks[blockIndex] = ((BO4RandomBlockFunction)block).blocks; this.randomBlocksBlockChances[blockIndex] = ((BO4RandomBlockFunction)block).blockChances; this.randomBlocksMetaDataNames[blockIndex] = ((BO4RandomBlockFunction)block).metaDataNames; this.randomBlocksMetaDataTags[blockIndex] = ((BO4RandomBlockFunction)block).metaDataTags; this.randomBlocksBlockCount[blockIndex] = ((BO4RandomBlockFunction)block).blockCount; } columnBlockIndex[block.x][block.z]++; } boolean illegalModData = false; for(BO4ModDataFunction modData : tempModDataList) { modData.x += this.getXOffset(); modData.z += this.getZOffset(); if(modData.x > 15 || modData.z > 15) { illegalModData = true; } if(modData.x < 0 || modData.z < 0) { illegalModData = true; } } this.modDataOTGPlus = tempModDataList.toArray(new BO4ModDataFunction[tempModDataList.size()]); boolean illegalSpawnerData = false; for(BO4SpawnerFunction spawnerData : tempSpawnerList) { spawnerData.x += this.getXOffset(); spawnerData.z += this.getZOffset(); if(spawnerData.x > 15 || spawnerData.z > 15) { illegalSpawnerData = true; } if(spawnerData.x < 0 || spawnerData.z < 0) { illegalSpawnerData = true; } } this.spawnerDataOTGPlus = tempSpawnerList.toArray(new BO4SpawnerFunction[tempSpawnerList.size()]); boolean illegalParticleData = false; for(BO4ParticleFunction particleData : tempParticlesList) { particleData.x += this.getXOffset(); particleData.z += this.getZOffset(); if(particleData.x > 15 || particleData.z > 15) { illegalParticleData = true; } if(particleData.x < 0 || particleData.z < 0) { illegalParticleData = true; } } this.particleDataOTGPlus = tempParticlesList.toArray(new BO4ParticleFunction[tempParticlesList.size()]); boolean illegalEntityData = false; for(BO4EntityFunction entityData : tempEntitiesList) { entityData.x += this.getXOffset(); entityData.z += this.getZOffset(); if(entityData.x > 15 || entityData.z > 15) { illegalEntityData = true; } if(entityData.x < 0 || entityData.z < 0) { illegalEntityData = true; } } this.entityDataOTGPlus = tempEntitiesList.toArray(new BO4EntityFunction[tempEntitiesList.size()]); if(OTG.getPluginConfig().spawnLog) { if(illegalBlock) { OTG.log(LogMarker.WARN, "Warning: BO3 contains Blocks or RandomBlocks that are placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalModData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains ModData that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalSpawnerData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains a Spawner() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalParticleData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains a Particle() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalEntityData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains an Entity() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } } this.branchesOTGPlus = tempBranchesList.toArray(new BO4BranchFunction[tempBranchesList.size()]); if(this.branchesOTGPlus.length > 0) // If this BO3 has branches then it must be max 16x16 { if(Math.abs(this.minX - this.maxX) > 15 || Math.abs(this.minZ - this.maxZ) > 15) { OTG.log(LogMarker.INFO, "BO3 " + this.getName() + " was too large, branching BO3's can be max 16x16 blocks."); throw new InvalidConfigException("BO3 " + this.getName() + " was too large, branching BO3's can be max 16x16 blocks."); } } else { if(Math.abs(this.minX - this.maxX) > 15 || Math.abs(this.minZ - this.maxZ) > 15) // If this BO3 is larger than 16x16 then it can only be used as a customObject { OTG.log(LogMarker.INFO, "BO4 " + this.getName() + " was too large, BO4's used as CustomStructure() can be max 16x16 blocks."); throw new InvalidConfigException("BO4 " + this.getName() + " was too large, BO4's used as CustomStructure() can be max 16x16 blocks."); } } } public void setBranches(List<BO4BranchFunction> branches) { this.branchesOTGPlus = branches.toArray(new BO4BranchFunction[branches.size()]); } /** * Gets the file this config will be written to. May be null if the config * will never be written. * @return The file. */ public File getFile() { return this.reader.getFile(); } @Override protected void writeConfigSettings(SettingsWriterOTGPlus writer) throws IOException { writeSettings(writer, null, null); } public void writeWithData(SettingsWriterOTGPlus writer, List<BO4BlockFunction> blocksList, List<BO4BranchFunction> branchesList) throws IOException { writer.setConfigMode(ConfigMode.WriteAll); try { writer.open(); writeSettings(writer, blocksList, branchesList); } finally { writer.close(); } } private void writeSettings(SettingsWriterOTGPlus writer, List<BO4BlockFunction> blocksList, List<BO4BranchFunction> branchesList) throws IOException { // The object writer.bigTitle("BO4 object"); writer.comment("This is the config file of a custom object."); writer.comment("If you add this object correctly to your BiomeConfigs, it will spawn in the world."); writer.comment(""); writer.comment("This is the creator of this BO4 object"); writer.setting(BO4Settings.AUTHOR, this.author); writer.comment("A short description of this BO4 object"); writer.setting(BO4Settings.DESCRIPTION, this.description); if(writer.getFile().getName().toUpperCase().endsWith(".BO3")) { writer.comment("Legacy setting, always true for BO4's. Only used if the file has a .BO3 extension."); writer.comment("Rename your file to .BO4 and remove this setting."); writer.setting(BO4Settings.ISOTGPLUS, true); } writer.comment("The settings mode, WriteAll, WriteWithoutComments or WriteDisable. See WorldConfig."); writer.setting(WorldStandardValues.SETTINGS_MODE_BO3, this.settingsMode); // Main settings writer.bigTitle("Main settings"); writer.comment("This BO4 can only spawn at least Frequency chunks distance away from any other BO4 with the exact same name."); writer.comment("You can use this to make this BO4 spawn in groups or make sure that this BO4 only spawns once every X chunks."); writer.setting(BO4Settings.FREQUENCY, this.frequency); writer.comment("The spawn height of the BO4: randomY, highestBlock or highestSolidBlock."); writer.setting(BO3Settings.SPAWN_HEIGHT, this.spawnHeight); writer.smallTitle("Height Limits for the BO4."); writer.comment("When in randomY mode used as the minimum Y or in atMinY mode as the actual Y to spawn this BO4 at."); writer.setting(BO4Settings.MIN_HEIGHT, this.minHeight); writer.comment("When in randomY mode used as the maximum Y to spawn this BO4 at."); writer.setting(BO4Settings.MAX_HEIGHT, this.maxHeight); writer.comment("Copies the blocks and branches of an existing BO4 into this BO4. You can still add blocks and branches in this BO4, they will be added on top of the inherited blocks and branches."); writer.setting(BO4Settings.INHERITBO3, this.inheritBO3); writer.comment("Rotates the inheritedBO3's resources (blocks, spawners, checks etc) and branches, defaults to NORTH (no rotation)."); writer.setting(BO4Settings.INHERITBO3ROTATION, this.inheritBO3Rotation); writer.comment("Defaults to true, if true and this is the starting BO4 for this branching structure then this BO4's smoothing and height settings are used for all children (branches)."); writer.setting(BO4Settings.OVERRIDECHILDSETTINGS, this.overrideChildSettings); writer.comment("Defaults to false, if true then this branch uses it's own height settings (SpawnHeight, minHeight, maxHeight, spawnAtWaterLevel) instead of those defined in the starting BO4 for this branching structure."); writer.setting(BO4Settings.OVERRIDEPARENTHEIGHT, this.overrideParentHeight); writer.comment("If this is set to true then this BO4 can spawn on top of or inside an existing BO4. If this is set to false then this BO4 will use a bounding box to detect collisions with other BO4's, if a collision is detected then this BO4 won't spawn and the current branch is rolled back."); writer.setting(BO4Settings.CANOVERRIDE, this.canOverride); writer.comment("This branch can only spawn at least branchFrequency chunks (x,z) distance away from any other branch with the exact same name."); writer.setting(BO4Settings.BRANCH_FREQUENCY, this.branchFrequency); writer.comment("Define groups that this branch belongs to along with a minimum (x,z) range in chunks that this branch must have between it and any other members of this group if it is to be allowed to spawn. Syntax is \"GroupName:Frequency, GoupName2:Frequency2\" etc so for example a branch that belongs to 3 groups: \"BranchFrequencyGroup: Ships:10, Vehicles:5, FloatingThings:3\"."); writer.setting(BO4Settings.BRANCH_FREQUENCY_GROUP, this.branchFrequencyGroup); writer.comment("If this is set to true then this BO4 can only spawn underneath an existing BO4. Used to make sure that dungeons only appear underneath buildings."); writer.setting(BO4Settings.MUSTBEBELOWOTHER, this.mustBeBelowOther); writer.comment("Used with CanOverride: true. A comma-seperated list of BO4s, this BO4's bounding box must collide with one of the BO4's in the list or this BO4 fails to spawn and the current branch is rolled back. AND/OR is supported, comma is OR, space is AND, f.e: branch1, branch2 branch3, branch 4."); writer.setting(BO4Settings.MUSTBEINSIDE, this.mustBeInside); writer.comment("Used with CanOverride: true. A comma-seperated list of BO4s, this BO4's bounding box cannot collide with any of the BO4's in the list or this BO4 fails to spawn and the current branch is rolled back."); writer.setting(BO4Settings.CANNOTBEINSIDE, this.cannotBeInside); writer.comment("Used with CanOverride: true. A comma-seperated list of BO4s, if this BO4's bounding box collides with any of the BO4's in the list then those BO4's won't spawn any blocks. This does not remove or roll back any BO4's."); writer.setting(BO4Settings.REPLACESBO3, this.replacesBO3); writer.comment("If this is set to true then this BO4 can only spawn inside world borders. Used to make sure that dungeons only appear inside the world borders."); writer.setting(BO4Settings.MUSTBEINSIDEWORLDBORDERS, this.mustBeInsideWorldBorders); writer.comment("Defaults to true. Set to false if the BO4 is not allowed to spawn on a water block"); writer.setting(BO4Settings.CANSPAWNONWATER, this.canSpawnOnWater); writer.comment("Defaults to false. Set to true if the BO4 is allowed to spawn only on a water block"); writer.setting(BO4Settings.SPAWNONWATERONLY, this.spawnOnWaterOnly); writer.comment("Defaults to false. Set to true if the BO4 and its smoothing area should ignore water when looking for the highest block to spawn on. Defaults to false (things spawn on top of water)"); writer.setting(BO4Settings.SPAWNUNDERWATER, this.spawnUnderWater); writer.comment("Defaults to false. Set to true if the BO4 should spawn at water level"); writer.setting(BO4Settings.SPAWNATWATERLEVEL, this.spawnAtWaterLevel); writer.comment("Spawns the BO4 at a Y offset of this value. Handy when using highestBlock for lowering BO4s into the surrounding terrain when there are layers of ground included in the BO4, also handy when using SpawnAtWaterLevel to lower objects like ships into the water."); writer.setting(BO4Settings.HEIGHT_OFFSET, this.heightOffset); boolean removeAir = readSettings(BO4Settings.REMOVEAIR); writer.comment("If set to true removes all AIR blocks from the BO4 so that it can be flooded or buried."); writer.setting(BO4Settings.REMOVEAIR, removeAir); String replaceAbove = readSettings(BO4Settings.REPLACEABOVE); writer.comment("Replaces all the non-air blocks that are above this BO4 or its smoothing area with the given block material (should be WATER or AIR or NONE), also applies to smoothing areas although OTG intentionally leaves some of the terrain above them intact. WATER can be used in combination with SpawnUnderWater to fill any air blocks underneath waterlevel with water (and any above waterlevel with air)."); writer.setting(BO4Settings.REPLACEABOVE, replaceAbove); String replaceBelow = readSettings(BO4Settings.REPLACEBELOW); writer.comment("Replaces all air blocks underneath the BO4 (but not its smoothing area) with the specified material until a solid block is found."); writer.setting(BO4Settings.REPLACEBELOW, replaceBelow); writer.comment("Defaults to true. If set to true then every block in the BO4 of the materials defined in ReplaceWithGroundBlock or ReplaceWithSurfaceBlock will be replaced by the GroundBlock or SurfaceBlock materials configured for the biome the block is spawned in."); writer.setting(BO4Settings.REPLACEWITHBIOMEBLOCKS, this.replaceWithBiomeBlocks); writer.comment("Defaults to DIRT, Replaces all the blocks of the given material in the BO4 with the GroundBlock configured for the biome it spawns in."); writer.setting(BO4Settings.REPLACEWITHGROUNDBLOCK, this.replaceWithGroundBlock); writer.comment("Defaults to GRASS, Replaces all the blocks of the given material in the BO4 with the SurfaceBlock configured for the biome it spawns in."); writer.setting(BO4Settings.REPLACEWITHSURFACEBLOCK, this.replaceWithSurfaceBlock); writer.comment("Makes the terrain around the BO4 slope evenly towards the edges of the BO4. The given value is the distance in blocks around the BO4 from where the slope should start and can be any positive number."); writer.setting(BO4Settings.SMOOTHRADIUS, this.smoothRadius); writer.comment("Moves the smoothing area up or down relative to the BO4 (at the points where the smoothing area is connected to the BO4). Handy when using SmoothStartTop: false and the BO4 has some layers of ground included, in that case we can set the HeightOffset to a negative value to lower the BO4 into the ground and we can set the SmoothHeightOffset to a positive value to move the smoothing area starting height up."); writer.setting(BO4Settings.SMOOTH_HEIGHT_OFFSET, this.smoothHeightOffset); writer.comment("Should the smoothing area be attached at the bottom or the top of the edges of the BO4? Defaults to false (bottom). Using this setting can make things slower so try to avoid using it and use SmoothHeightOffset instead if for instance you have a BO4 with some ground layers included. The only reason you should need to use this setting is if you have a BO4 with edges that have an irregular height (like some hills)."); writer.setting(BO4Settings.SMOOTHSTARTTOP, this.smoothStartTop); writer.comment("Should the smoothing area attach itself to \"log\" block or ignore them? Defaults to false (ignore logs)."); writer.setting(BO4Settings.SMOOTHSTARTWOOD, this.smoothStartWood); writer.comment("The block used for smoothing area surface blocks, defaults to biome SurfaceBlock."); writer.setting(BO4Settings.SMOOTHINGSURFACEBLOCK, this.smoothingSurfaceBlock); writer.comment("The block used for smoothing area ground blocks, defaults to biome GroundBlock."); writer.setting(BO4Settings.SMOOTHINGGROUNDBLOCK, this.smoothingGroundBlock); writer.comment("Define groups that this BO4 belongs to along with a minimum range in chunks that this BO4 must have between it and any other members of this group if it is to be allowed to spawn. Syntax is \"GroupName:Frequency, GoupName2:Frequency2\" etc so for example a BO4 that belongs to 3 groups: \"BO4Group: Ships:10, Vehicles:5, FloatingThings:3\"."); writer.setting(BO4Settings.BO3GROUP, this.bo3Group); writer.comment("Defaults to false. Set to true if this BO4 should spawn at the player spawn point. When the server starts the spawn point is determined and the BO4's for the biome it is in are loaded, one of these BO4s that has IsSpawnPoint set to true (if any) is selected randomly and is spawned at the spawn point regardless of its rarity (so even Rarity:0, IsSpawnPoint: true BO4's can get spawned as the spawn point!)."); writer.setting(BO4Settings.ISSPAWNPOINT, this.isSpawnPoint); // Blocks and other things writeResources(writer, blocksList, branchesList); if(this.reader != null) // Can be true for BO4Creator? { this.reader.flushCache(); } } @Override protected void readConfigSettings() throws InvalidConfigException { this.branchFrequency = readSettings(BO4Settings.BRANCH_FREQUENCY); this.branchFrequencyGroup = readSettings(BO4Settings.BRANCH_FREQUENCY_GROUP); this.branchFrequencyGroups = new HashMap<String, Integer>(); if(this.branchFrequencyGroup != null && this.branchFrequencyGroup.trim().length() > 0) { String[] groupStrings = this.branchFrequencyGroup.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.branchFrequencyGroups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.heightOffset = readSettings(BO4Settings.HEIGHT_OFFSET); this.inheritBO3Rotation = readSettings(BO4Settings.INHERITBO3ROTATION); this.removeAir = readSettings(BO4Settings.REMOVEAIR); this.isSpawnPoint = readSettings(BO4Settings.ISSPAWNPOINT); this.replaceAbove = readSettings(BO4Settings.REPLACEABOVE); this.replaceBelow = readSettings(BO4Settings.REPLACEBELOW); this.replaceWithBiomeBlocks = readSettings(BO4Settings.REPLACEWITHBIOMEBLOCKS); this.replaceWithGroundBlock = readSettings(BO4Settings.REPLACEWITHGROUNDBLOCK); this.replaceWithSurfaceBlock = readSettings(BO4Settings.REPLACEWITHSURFACEBLOCK); this.bo3Group = readSettings(BO4Settings.BO3GROUP); this.bo3Groups = new HashMap<String, Integer>(); if(this.bo3Group != null && this.bo3Group.trim().length() > 0) { String[] groupStrings = this.bo3Group.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.bo3Groups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.canOverride = readSettings(BO4Settings.CANOVERRIDE); this.mustBeBelowOther = readSettings(BO4Settings.MUSTBEBELOWOTHER); this.mustBeInsideWorldBorders = readSettings(BO4Settings.MUSTBEINSIDEWORLDBORDERS); this.mustBeInside = readSettings(BO4Settings.MUSTBEINSIDE); this.mustBeInsideBranches = new ArrayList<String>(); if(this.mustBeInside != null && this.mustBeInside.trim().length() > 0) { String[] mustBeInsideStrings = this.mustBeInside.split(","); if(mustBeInsideStrings != null && mustBeInsideStrings.length > 0) { for(int i = 0; i < mustBeInsideStrings.length; i++) { String mustBeInsideString = mustBeInsideStrings[i].trim(); if(mustBeInsideString.length() > 0) { this.mustBeInsideBranches.add(mustBeInsideString); } } } } this.cannotBeInside = readSettings(BO4Settings.CANNOTBEINSIDE); this.cannotBeInsideBranches = new ArrayList<String>(); if(this.cannotBeInside != null && this.cannotBeInside.trim().length() > 0) { String[] cannotBeInsideStrings = this.cannotBeInside.split(","); if(cannotBeInsideStrings != null && cannotBeInsideStrings.length > 0) { for(int i = 0; i < cannotBeInsideStrings.length; i++) { String cannotBeInsideString = cannotBeInsideStrings[i].trim(); if(cannotBeInsideString.length() > 0) { this.cannotBeInsideBranches.add(cannotBeInsideString); } } } } this.replacesBO3 = readSettings(BO4Settings.REPLACESBO3); this.replacesBO3Branches = new ArrayList<String>(); if(this.replacesBO3 != null && this.replacesBO3.trim().length() > 0) { String[] replacesBO3Strings = replacesBO3.split(","); if(replacesBO3Strings != null && replacesBO3Strings.length > 0) { for(int i = 0; i < replacesBO3Strings.length; i++) { String replacesBO3String = replacesBO3Strings[i].trim(); if(replacesBO3String.length() > 0) { this.replacesBO3Branches.add(replacesBO3String); } } } } //smoothHeightOffset = readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET).equals("HeightOffset") ? heightOffset : Integer.parseInt(readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET)); this.smoothHeightOffset = readSettings(BO4Settings.SMOOTH_HEIGHT_OFFSET); this.canSpawnOnWater = readSettings(BO4Settings.CANSPAWNONWATER); this.spawnOnWaterOnly = readSettings(BO4Settings.SPAWNONWATERONLY); this.spawnUnderWater = readSettings(BO4Settings.SPAWNUNDERWATER); this.spawnAtWaterLevel = readSettings(BO4Settings.SPAWNATWATERLEVEL); this.inheritBO3 = readSettings(BO4Settings.INHERITBO3); this.overrideChildSettings = readSettings(BO4Settings.OVERRIDECHILDSETTINGS); this.overrideParentHeight = readSettings(BO4Settings.OVERRIDEPARENTHEIGHT); this.smoothRadius = readSettings(BO4Settings.SMOOTHRADIUS); this.smoothStartTop = readSettings(BO4Settings.SMOOTHSTARTTOP); this.smoothStartWood = readSettings(BO4Settings.SMOOTHSTARTWOOD); this.smoothingSurfaceBlock = readSettings(BO4Settings.SMOOTHINGSURFACEBLOCK); this.smoothingGroundBlock = readSettings(BO4Settings.SMOOTHINGGROUNDBLOCK); // Make sure that the BO3 wont try to spawn below Y 0 because of the height offset if(this.heightOffset < 0 && this.minHeight < -this.heightOffset) { this.minHeight = -this.heightOffset; } this.inheritedBO3s = new ArrayList<String>(); this.inheritedBO3s.add(this.getName()); // TODO: Make this cleaner? if(this.inheritBO3 != null && this.inheritBO3.trim().length() > 0) { this.inheritedBO3s.add(this.inheritBO3); } this.author = readSettings(BO4Settings.AUTHOR); this.description = readSettings(BO4Settings.DESCRIPTION); this.settingsMode = readSettings(WorldStandardValues.SETTINGS_MODE_BO3); this.frequency = readSettings(BO4Settings.FREQUENCY); this.spawnHeight = readSettings(BO3Settings.SPAWN_HEIGHT); this.minHeight = readSettings(BO4Settings.MIN_HEIGHT); this.maxHeight = readSettings(BO4Settings.MAX_HEIGHT); this.maxHeight = this.maxHeight < this.minHeight ? this.minHeight : this.maxHeight; // Read the resources readResources(); // Merge inherited resources loadInheritedBO3(); } private void writeResources(SettingsWriterOTGPlus writer, List<BO4BlockFunction> blocksList, List<BO4BranchFunction> branchesList) throws IOException { writer.bigTitle("Blocks"); writer.comment("All the blocks used in the BO4 are listed here. Possible blocks:"); writer.comment("Block(x,y,z,id[.data][,nbtfile.nbt)"); writer.comment("RandomBlock(x,y,z,id[:data][,nbtfile.nbt],chance[,id[:data][,nbtfile.nbt],chance[,...]])"); writer.comment(" So RandomBlock(0,0,0,CHEST,chest.nbt,50,CHEST,anotherchest.nbt,100) will spawn a chest at"); writer.comment(" the BO4 origin, and give it a 50% chance to have the contents of chest.nbt, or, if that"); writer.comment(" fails, a 100% percent chance to have the contents of anotherchest.nbt."); writer.comment("MinecraftObject(x,y,z,name) (TODO: This may not work anymore and needs to be tested."); writer.comment(" Spawns an object in the Mojang NBT structure format. For example, "); writer.comment(" MinecraftObject(0,0,0," + DefaultStructurePart.IGLOO_BOTTOM.getPath() + ")"); writer.comment(" spawns the bottom part of an igloo."); ArrayList<BO4ModDataFunction> modDataList = new ArrayList<BO4ModDataFunction>(); ArrayList<BO4ParticleFunction> particlesList = new ArrayList<BO4ParticleFunction>(); ArrayList<BO4SpawnerFunction> spawnerList = new ArrayList<BO4SpawnerFunction>(); ArrayList<BO4EntityFunction> entitiesList = new ArrayList<BO4EntityFunction>(); // Re-read the raw data, if no data was supplied. Don't save any loaded data, since it has been processed/transformed. if(blocksList == null || branchesList == null || entitiesList == null) { blocksList = new ArrayList<BO4BlockFunction>(); branchesList = new ArrayList<BO4BranchFunction>(); for (CustomObjectConfigFunction<BO4Config> res : reader.getConfigFunctions(this, true)) { if (res.isValid()) { if(res instanceof BO4RandomBlockFunction) { blocksList.add((BO4RandomBlockFunction)res); } else if(res instanceof BO4BlockFunction) { blocksList.add((BO4BlockFunction)res); } else if (res instanceof BO4WeightedBranchFunction) { branchesList.add((BO4WeightedBranchFunction) res); } else if (res instanceof BO4BranchFunction) { branchesList.add((BO4BranchFunction) res); } else if (res instanceof BO4ModDataFunction) { modDataList.add((BO4ModDataFunction) res); } else if (res instanceof BO4SpawnerFunction) { spawnerList.add((BO4SpawnerFunction) res); } else if (res instanceof BO4ParticleFunction) { particlesList.add((BO4ParticleFunction) res); } else if (res instanceof BO4EntityFunction) { entitiesList.add((BO4EntityFunction) res); } } } } for(BO4BlockFunction block : blocksList) { writer.function(block); } writer.bigTitle("Branches"); writer.comment("Branches are child-BO4's that spawn if this BO4 is configured to spawn as a"); writer.comment("CustomStructure resource in a biome config. Branches can have branches,"); writer.comment("making complex structures possible. See the wiki for more details."); writer.comment(""); writer.comment("Regular Branches spawn each branch with an independent chance of spawning."); writer.comment("Branch(x,y,z,isRequiredBranch,branchName,rotation,chance,branchDepth[,anotherBranchName,rotation,chance,branchDepth[,...]][IndividualChance])"); writer.comment("branchName - name of the object to spawn."); writer.comment("rotation - NORTH, SOUTH, EAST or WEST."); writer.comment("IndividualChance - The chance each branch has to spawn, assumed to be 100 when left blank"); writer.comment("isRequiredBranch - If this is set to true then at least one of the branches in this BO4 must spawn at these x,y,z coordinates. If no branch can spawn there then this BO4 fails to spawn and its branch is rolled back."); writer.comment("isRequiredBranch:true branches must spawn or the current branch is rolled back entirely. This is useful for grouping BO4's that must spawn together, for instance a single room made of multiple BO4's/branches."); writer.comment("If all parts of the room are connected together via isRequiredBranch:true branches then either the entire room will spawns or no part of it will spawn."); writer.comment("*Note: When isRequiredBranch:true only one BO4 can be added per Branch() and it will automatically have a rarity of 100.0."); writer.comment("isRequiredBranch:false branches are used to make optional parts of structures, for instance the middle section of a tunnel that has a beginning, middle and end BO4/branch and can have a variable length by repeating the middle BO4/branch."); writer.comment("By making the start and end branches isRequiredBranch:true and the middle branch isRequiredbranch:false you can make it so that either:"); writer.comment("A. A tunnel spawns with at least a beginning and end branch"); writer.comment("B. A tunnel spawns with a beginning and end branch and as many middle branches as will fit in the available space."); writer.comment("C. No tunnel spawns at all because there wasn't enough space to spawn at least a beginning and end branch."); writer.comment("branchDepth - When creating a chain of branches that contains optional (isRequiredBranch:false) branches branch depth is configured for the first BO4 in the chain to determine the maximum length of the chain."); writer.comment("branchDepth - 1 is inherited by each isRequiredBranch:false branch in the chain. When branchDepth is zero isRequiredBranch:false branches cannot spawn and the chain ends. In the case of the tunnel this means the last middle branch would be"); writer.comment("rolled back and an IsRequiredBranch:true end branch could be spawned in its place to make sure the tunnel has a proper ending."); writer.comment("Instead of inheriting branchDepth - 1 from the parent branchDepth can be overridden by child branches if it is set higher than 0 (the default value)."); writer.comment("isRequiredBranch:true branches do inherit branchDepth and pass it on to their own branches, however they cannot be prevented from spawning by it and also don't subtract 1 from branchDepth when inheriting it."); writer.comment(""); writer.comment("Weighted Branches spawn branches with a dependent chance of spawning."); writer.comment("WeightedBranch(x,y,z,isRequiredBranch,branchName,rotation,chance,branchDepth[,anotherBranchName,rotation,chance,branchDepth[,...]][MaxChanceOutOf])"); writer.comment("*Note: isRequiredBranch must be set to false. It is not possible to use isRequiredBranch:true with WeightedBranch() since isRequired:true branches must spawn and automatically have a rarity of 100.0."); writer.comment("MaxChanceOutOf - The chance all branches have to spawn out of, assumed to be 100 when left blank"); for(BO4BranchFunction func : branchesList) { writer.function(func); } writer.bigTitle("Entities"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("An EntityFunction spawns an entity instead of a block. The entity is spawned only once when the BO4 is spawned."); writer.comment("Entities are persistent by default so they don't de-spawn when no player is near, they are only unloaded."); writer.comment("Usage: Entity(x,y,z,entityName,groupSize,NameTagOrNBTFileName) or Entity(x,y,z,mobName,groupSize)"); writer.comment("Use /otg entities to get a list of entities that can be used as entityName, this includes entities added by other mods and non-living entities."); writer.comment("NameTagOrNBTFileName can be either a nametag for the mob or an .txt file with nbt data (such as myentityinfo.txt)."); writer.comment("In the text file you can use the same mob spawning parameters used with the /summon command to equip the"); writer.comment("entity and give it custom attributes etc. You can copy the DATA part of a summon command including surrounding "); writer.comment("curly braces to a .txt file, for instance for: \"/summon Skeleton x y z {DATA}\""); for(BO4EntityFunction func : entitiesList) { writer.function(func); } writer.bigTitle("Particles"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("Creates an invisible particle spawner at the given location that spawns particles every x milliseconds."); writer.comment("Usage: Particle(x,y,z,particleName,interval,velocityX,velocityY,velocityZ)"); writer.comment("velocityX, velocityY and velocityZ are optional."); writer.comment("Only vanilla particle names can be used, for 1.11.2 these are;"); writer.comment("explode, largeexplode, hugeexplosion, fireworksSpark, bubble, splash, wake, suspended"); writer.comment("depthsuspend, crit, magicCrit, smoke, largesmoke, spell, instantSpell, mobSpell"); writer.comment("mobSpellAmbient, witchMagic, dripWater, dripLava, angryVillager, happyVillager"); writer.comment("townaura, note, portal, enchantmenttable, flame, lava, footstep, cloud, reddust"); writer.comment("snowballpoof, snowshovel, slime, heart, barrier, iconcrack, blockcrack, blockdust"); writer.comment("droplet, take, mobappearance, dragonbreath, endRod, damageIndicator, sweepAttack"); writer.comment("fallingdust, totem, spit."); writer.comment("velocityX,velocityY,velocityZ - Spawn the enemy with the given velocity. If this is not filled in then a small random velocity is applied."); for(BO4ParticleFunction func : particlesList) { writer.function(func); } writer.bigTitle("Spawners"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("Creates an invisible entity spawner at the given location that spawns entities every x seconds."); writer.comment("Entities can only spawn if their spawn requirements are met (zombies/skeletons only spawn in the dark etc). Max entity count for the server is ignored, each spawner has its own maxCount setting."); writer.comment("Usage: Spawner(x,y,z,entityName,nbtFileName,groupSize,interval,spawnChance,maxCount,despawnTime,velocityX,velocityY,velocityZ,yaw,pitch)"); writer.comment("nbtFileName, despawnTime, velocityX, velocityY, velocityZ, yaw and pitch are optional"); writer.comment("Example Spawner(0, 0, 0, Villager, 1, 5, 100, 5) or Spawner(0, 0, 0, Villager, villager1.txt, 1, 5, 100, 5) or Spawner(0, 0, 0, Villager, 1, 5, 100, 5, 30, 1, 1, 1, 0, 0)"); writer.comment("entityName - Name of the entity to spawn, use /otg entities to get a list of entities that can be used as entityName, this includes entities added by other mods and non-living entities."); writer.comment("nbtFileName - A .txt file with nbt data (such as myentityinfo.txt)."); writer.comment("In the text file you can use the same mob spawning parameters used with the /summon command to equip the"); writer.comment("entity and give it custom attributes etc. You can copy the DATA part of a summon command including surrounding "); writer.comment("curly braces to a .txt file, for instance for: \"/summon Skeleton x y z {DATA}\""); writer.comment("groupSize - Number of entities that should spawn for each successful spawn attempt."); writer.comment("interval - Time in seconds between each spawn attempt."); writer.comment("spawnChance - For each spawn attempt, the chance between 0-100 that the spawn attempt will succeed."); writer.comment("maxCount - The maximum amount of this kind of entity that can exist within 32 blocks. If there are already maxCount or more entities of this type in a 32 radius this spawner will not spawn anything."); writer.comment("despawnTime - After despawnTime seconds, if there is no player within 32 blocks of the entity it will despawn.."); writer.comment("velocityX,velocityY,velocityZ,yaw,pitch - Spawn the enemy with the given velocity and angle, handy for making traps and launchers (shooting arrows and fireballs etc)."); for(BO4SpawnerFunction func : spawnerList) { writer.function(func); } // ModData writer.bigTitle("ModData"); writer.comment("Forge only."); writer.comment("Use the ModData() tag to include data that other mods can use"); writer.comment("Mod makers can use ModData and the /otg GetModData command to test IMC communications between OTG"); writer.comment("and their mod."); writer.comment("Normal users can use it to spawn some mobs and blocks on command."); writer.comment("ModData(x,y,z,\"ModName\", \"MyModDataAsText\""); writer.comment("Example: ModData(x,y,z,MyCystomNPCMod,SpawnBobHere/WithAPotato/And50Health)"); writer.comment("Try not to use exotic/reserved characters, like brackets and comma's etc, this stuff isn't fool-proof."); writer.comment("Also, use this only to store IDs/object names etc for your mod, DO NOT include things like character dialogue,"); writer.comment("messages on signs, loot lists etc in this file. As much as possible just store id's/names here and store all the data related to those id's/names in your own mod."); writer.comment("OTG has some built in ModData commands for basic mob and block spawning."); writer.comment("These are mostly just a demonstration for mod makers to show how ModData."); writer.comment("can be used by other mods."); writer.comment("For mob spawning in OTG use: ModData(x,y,z,OTG,mob/MobType/Count/Persistent/Name)"); writer.comment("mob: Makes OTG recognise this as a mob spawning command."); writer.comment("MobType: Lower-case, no spaces. Any vanilla mob like dragon, skeleton, wither, villager etc"); writer.comment("Count: The number of mobs to spawn"); writer.comment("Persistent (true/false): Should the mobs never de-spawn? If set to true the mob will get a"); writer.comment("name-tag ingame so you can recognise it."); writer.comment("Name: A name-tag for the monster/npc."); writer.comment("Example: ModData(0,0,0,OTG,villager/1/true/Bob)"); writer.comment("To spawn blocks using ModData use: ModData(x,y,z,OTG,block/material)"); writer.comment("block: Makes OTG recognise this as a block spawning command."); writer.comment("material: id or text, custom blocks can be added using ModName:MaterialName."); writer.comment("To send all ModData within a radius in chunks around the player to the specified mod"); writer.comment("use this console command: /otg GetModData ModName Radius"); writer.comment("ModName: name of the mod, for OTG commands use OTG "); writer.comment("Radius (optional): Radius in chunks around the player."); for(BO4ModDataFunction func : modDataList) { writer.function(func); } } int bo4DataVersion = 1; public void writeToStream(DataOutput stream) throws IOException { stream.writeInt(this.bo4DataVersion); stream.writeInt(this.minimumSizeTop); stream.writeInt(this.minimumSizeBottom); stream.writeInt(this.minimumSizeLeft); stream.writeInt(this.minimumSizeRight); stream.writeInt(this.minX); stream.writeInt(this.maxX); stream.writeInt(this.minY); stream.writeInt(this.maxY); stream.writeInt(this.minZ); stream.writeInt(this.maxZ); StreamHelper.writeStringToStream(stream, this.author); StreamHelper.writeStringToStream(stream, this.description); StreamHelper.writeStringToStream(stream, this.settingsMode.name()); stream.writeInt(this.frequency); StreamHelper.writeStringToStream(stream, this.spawnHeight.name()); stream.writeInt(this.minHeight); stream.writeInt(this.maxHeight); stream.writeShort(this.inheritedBO3s.size()); for(String inheritedBO3 : this.inheritedBO3s) { StreamHelper.writeStringToStream(stream, inheritedBO3); } StreamHelper.writeStringToStream(stream, this.inheritBO3); StreamHelper.writeStringToStream(stream, this.inheritBO3Rotation.name()); stream.writeBoolean(this.overrideChildSettings); stream.writeBoolean(this.overrideParentHeight); stream.writeBoolean(this.canOverride); stream.writeInt(this.branchFrequency); StreamHelper.writeStringToStream(stream, this.branchFrequencyGroup); stream.writeBoolean(this.mustBeBelowOther); stream.writeBoolean(this.mustBeInsideWorldBorders); StreamHelper.writeStringToStream(stream, this.mustBeInside); StreamHelper.writeStringToStream(stream, this.cannotBeInside); StreamHelper.writeStringToStream(stream, this.replacesBO3); stream.writeBoolean(this.canSpawnOnWater); stream.writeBoolean(this.spawnOnWaterOnly); stream.writeBoolean(this.spawnUnderWater); stream.writeBoolean(this.spawnAtWaterLevel); stream.writeInt(this.heightOffset); stream.writeBoolean(this.removeAir); StreamHelper.writeStringToStream(stream, this.replaceAbove); StreamHelper.writeStringToStream(stream, this.replaceBelow); stream.writeBoolean(this.replaceWithBiomeBlocks); StreamHelper.writeStringToStream(stream, this.replaceWithGroundBlock); StreamHelper.writeStringToStream(stream, this.replaceWithSurfaceBlock); stream.writeInt(this.smoothRadius); stream.writeInt(this.smoothHeightOffset); stream.writeBoolean(this.smoothStartTop); stream.writeBoolean(this.smoothStartWood); StreamHelper.writeStringToStream(stream, this.smoothingSurfaceBlock); StreamHelper.writeStringToStream(stream, this.smoothingGroundBlock); StreamHelper.writeStringToStream(stream, this.bo3Group); stream.writeBoolean(this.isSpawnPoint); stream.writeBoolean(this.isCollidable); ArrayList<LocalMaterialData> materials = new ArrayList<LocalMaterialData>(); ArrayList<String> metaDataNames = new ArrayList<String>(); int randomBlockCount = 0; int nonRandomBlockCount = 0; BO4BlockFunction[] blocks = getBlocks(); for(BO4BlockFunction block : blocks) { if(block instanceof BO4RandomBlockFunction) { randomBlockCount++; for(LocalMaterialData material : ((BO4RandomBlockFunction)block).blocks) { if(!materials.contains(material)) { materials.add(material); } } } else { nonRandomBlockCount++; } if(block.material != null && !materials.contains(block.material)) { materials.add(block.material); } if(block.metaDataName != null && !metaDataNames.contains(block.metaDataName)) { metaDataNames.add(block.metaDataName); } } String[] metaDataNamesArr = metaDataNames.toArray(new String[metaDataNames.size()]); LocalMaterialData[] blocksArr = materials.toArray(new LocalMaterialData[materials.size()]); stream.writeShort(metaDataNamesArr.length); for(int i = 0; i < metaDataNamesArr.length; i++) { StreamHelper.writeStringToStream(stream, metaDataNamesArr[i]); } stream.writeShort(blocksArr.length); for(int i = 0; i < blocksArr.length; i++) { StreamHelper.writeStringToStream(stream, blocksArr[i].getName()); } // TODO: This assumes that loading blocks in a different order won't matter, which may not be true? // Anything that spawns on top, entities/spawners etc, should be spawned last tho, so shouldn't be a problem? stream.writeInt(nonRandomBlockCount); int nonRandomBlockIndex = 0; ArrayList<BO4BlockFunction> blocksInColumn; if(nonRandomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { blocksInColumn = new ArrayList<BO4BlockFunction>(); for(BO4BlockFunction blockFunction : blocks) { if(!(blockFunction instanceof BO4RandomBlockFunction)) { if(blockFunction.x == x && blockFunction.z == z) { blocksInColumn.add(blockFunction); } } } stream.writeShort(blocksInColumn.size()); if(blocksInColumn.size() > 0) { for(BO4BlockFunction blockFunction : blocksInColumn) { blockFunction.writeToStream(metaDataNamesArr, blocksArr, stream); nonRandomBlockIndex++; } } if(nonRandomBlockIndex == nonRandomBlockCount) { break; } } if(nonRandomBlockIndex == nonRandomBlockCount) { break; } } } stream.writeInt(randomBlockCount); int randomBlockIndex = 0; if(randomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { blocksInColumn = new ArrayList<BO4BlockFunction>(); for(BO4BlockFunction blockFunction : blocks) { if(blockFunction instanceof BO4RandomBlockFunction) { if(blockFunction.x == x && blockFunction.z == z) { blocksInColumn.add(blockFunction); } } } stream.writeShort(blocksInColumn.size()); if(blocksInColumn.size() > 0) { for(BO4BlockFunction blockFunction : blocksInColumn) { blockFunction.writeToStream(metaDataNamesArr, blocksArr, stream); randomBlockIndex++; } } if(randomBlockIndex == randomBlockCount) { break; } } if(randomBlockIndex == randomBlockCount) { break; } } } stream.writeInt(this.branchesOTGPlus.length); for(BO4BranchFunction func : Arrays.asList(this.branchesOTGPlus)) { if(func instanceof BO4WeightedBranchFunction) { stream.writeBoolean(true); // false For BO4BranchFunction, true for BO4WeightedBranchFunction } else { stream.writeBoolean(false); // false For BO4BranchFunction, true for BO4WeightedBranchFunction } func.writeToStream(stream); } stream.writeInt(this.entityDataOTGPlus.length); for(BO4EntityFunction func : Arrays.asList(this.entityDataOTGPlus)) { func.writeToStream(stream); } stream.writeInt(this.particleDataOTGPlus.length); for(BO4ParticleFunction func : Arrays.asList(this.particleDataOTGPlus)) { func.writeToStream(stream); } stream.writeInt(this.spawnerDataOTGPlus.length); for(BO4SpawnerFunction func : Arrays.asList(this.spawnerDataOTGPlus)) { func.writeToStream(stream); } stream.writeInt(this.modDataOTGPlus.length); for(BO4ModDataFunction func : Arrays.asList(this.modDataOTGPlus)) { func.writeToStream(stream); } } public BO4Config readFromBO4DataFile(boolean getBlocks) { FileInputStream fis; try { fis = new FileInputStream(this.reader.getFile()); try { ByteBuffer buffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fis.getChannel().size()); byte[] compressedBytes = new byte[(int) fis.getChannel().size()]; buffer.get(compressedBytes); try { byte[] decompressedBytes = com.pg85.otg.util.CompressionUtils.decompress(compressedBytes); buffer = ByteBuffer.wrap(decompressedBytes); } catch (DataFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //buffer.get(data, 0, remaining); // do something with data this.isBO4Data = true; this.inheritedBO3Loaded = true; int bo4DataVersion = buffer.getInt(); this.minimumSizeTop = buffer.getInt(); this.minimumSizeBottom = buffer.getInt(); this.minimumSizeLeft = buffer.getInt(); this.minimumSizeRight = buffer.getInt(); this.minX = buffer.getInt(); this.maxX = buffer.getInt(); this.minY = buffer.getInt(); this.maxY = buffer.getInt(); this.minZ = buffer.getInt(); this.maxZ = buffer.getInt(); this.author = StreamHelper.readStringFromBuffer(buffer); this.description = StreamHelper.readStringFromBuffer(buffer); this.settingsMode = ConfigMode.valueOf(StreamHelper.readStringFromBuffer(buffer)); this.frequency = buffer.getInt(); this.spawnHeight = SpawnHeightEnum.valueOf(StreamHelper.readStringFromBuffer(buffer)); this.minHeight = buffer.getInt(); this.maxHeight = buffer.getInt(); short inheritedBO3sSize = buffer.getShort(); this.inheritedBO3s = new ArrayList<String>(); for(int i = 0; i < inheritedBO3sSize; i++) { this.inheritedBO3s.add(StreamHelper.readStringFromBuffer(buffer)); } this.inheritBO3 = StreamHelper.readStringFromBuffer(buffer); this.inheritBO3Rotation = Rotation.valueOf(StreamHelper.readStringFromBuffer(buffer)); this.overrideChildSettings = buffer.get() != 0; this.overrideParentHeight = buffer.get() != 0; this.canOverride = buffer.get() != 0; this.branchFrequency = buffer.getInt(); this.branchFrequencyGroup = StreamHelper.readStringFromBuffer(buffer); this.mustBeBelowOther = buffer.get() != 0; this.mustBeInsideWorldBorders = buffer.get() != 0; this.mustBeInside = StreamHelper.readStringFromBuffer(buffer); this.cannotBeInside = StreamHelper.readStringFromBuffer(buffer); this.replacesBO3 = StreamHelper.readStringFromBuffer(buffer); this.canSpawnOnWater = buffer.get() != 0; this.spawnOnWaterOnly = buffer.get() != 0; this.spawnUnderWater = buffer.get() != 0; this.spawnAtWaterLevel = buffer.get() != 0; this.heightOffset = buffer.getInt(); this.removeAir = buffer.get() != 0; this.replaceAbove = StreamHelper.readStringFromBuffer(buffer); this.replaceBelow = StreamHelper.readStringFromBuffer(buffer); this.replaceWithBiomeBlocks = buffer.get() != 0; this.replaceWithGroundBlock = StreamHelper.readStringFromBuffer(buffer); this.replaceWithSurfaceBlock = StreamHelper.readStringFromBuffer(buffer); this.smoothRadius = buffer.getInt(); this.smoothHeightOffset = buffer.getInt(); this.smoothStartTop = buffer.get() != 0; this.smoothStartWood = buffer.get() != 0; this.smoothingSurfaceBlock = StreamHelper.readStringFromBuffer(buffer); this.smoothingGroundBlock = StreamHelper.readStringFromBuffer(buffer); this.bo3Group = StreamHelper.readStringFromBuffer(buffer); this.isSpawnPoint = buffer.get() != 0; this.isCollidable = buffer.get() != 0; this.branchFrequencyGroups = new HashMap<String, Integer>(); if(this.branchFrequencyGroup != null && this.branchFrequencyGroup.trim().length() > 0) { String[] groupStrings = this.branchFrequencyGroup.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.branchFrequencyGroups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.bo3Groups = new HashMap<String, Integer>(); if(this.bo3Group != null && this.bo3Group.trim().length() > 0) { String[] groupStrings = this.bo3Group.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.bo3Groups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.mustBeInsideBranches = new ArrayList<String>(); if(this.mustBeInside != null && this.mustBeInside.trim().length() > 0) { String[] mustBeInsideStrings = this.mustBeInside.split(","); if(mustBeInsideStrings != null && mustBeInsideStrings.length > 0) { for(int i = 0; i < mustBeInsideStrings.length; i++) { String mustBeInsideString = mustBeInsideStrings[i].trim(); if(mustBeInsideString.length() > 0) { this.mustBeInsideBranches.add(mustBeInsideString); } } } } this.cannotBeInsideBranches = new ArrayList<String>(); if(this.cannotBeInside != null && this.cannotBeInside.trim().length() > 0) { String[] cannotBeInsideStrings = this.cannotBeInside.split(","); if(cannotBeInsideStrings != null && cannotBeInsideStrings.length > 0) { for(int i = 0; i < cannotBeInsideStrings.length; i++) { String cannotBeInsideString = cannotBeInsideStrings[i].trim(); if(cannotBeInsideString.length() > 0) { this.cannotBeInsideBranches.add(cannotBeInsideString); } } } } this.replacesBO3Branches = new ArrayList<String>(); if(this.replacesBO3 != null && this.replacesBO3.trim().length() > 0) { String[] replacesBO3Strings = replacesBO3.split(","); if(replacesBO3Strings != null && replacesBO3Strings.length > 0) { for(int i = 0; i < replacesBO3Strings.length; i++) { String replacesBO3String = replacesBO3Strings[i].trim(); if(replacesBO3String.length() > 0) { this.replacesBO3Branches.add(replacesBO3String); } } } } // Reconstruct blocks short metaDataNamesArrLength = buffer.getShort(); String[] metaDataNames = new String[metaDataNamesArrLength]; for(int i = 0; i < metaDataNamesArrLength; i++) { metaDataNames[i] = StreamHelper.readStringFromBuffer(buffer); } short blocksArrArrLength = buffer.getShort(); LocalMaterialData[] blocksArr = new LocalMaterialData[blocksArrArrLength]; for(int i = 0; i < blocksArrArrLength; i++) { String materialName = StreamHelper.readStringFromBuffer(buffer); try { blocksArr[i] = MaterialHelper.readMaterial(materialName); } catch (InvalidConfigException e) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "Could not read material \"" + materialName + "\" for BO4 \"" + this.getName() + "\""); e.printStackTrace(); } } } short[][] columnSizes = new short[xSize][zSize]; // TODO: This assumes that loading blocks in a different order won't matter, which may not be true? // Anything that spawns on top, entities/spawners etc, should be spawned last tho, so shouldn't be a problem? int nonRandomBlockCount = buffer.getInt(); int nonRandomBlockIndex = 0; ArrayList<BO4BlockFunction> nonRandomBlocks = new ArrayList<BO4BlockFunction>(); if(nonRandomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { short blocksInColumnSize = buffer.getShort(); for(int j = 0; j < blocksInColumnSize; j++) { columnSizes[x][z]++; nonRandomBlocks.add(BO4BlockFunction.fromStream(x, z, metaDataNames, blocksArr, this, buffer)); nonRandomBlockIndex++; if(nonRandomBlockCount == nonRandomBlockIndex) { break; } } if(nonRandomBlockCount == nonRandomBlockIndex) { break; } } if(nonRandomBlockCount == nonRandomBlockIndex) { break; } } } int randomBlockCount = buffer.getInt(); int randomBlockIndex = 0; ArrayList<BO4RandomBlockFunction> randomBlocks = new ArrayList<BO4RandomBlockFunction>(); if(randomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { short blocksInColumnSize = buffer.getShort(); for(int j = 0; j < blocksInColumnSize; j++) { columnSizes[x][z]++; randomBlocks.add(BO4RandomBlockFunction.fromStream(x, z, metaDataNames, blocksArr, this, buffer)); randomBlockIndex++; if(randomBlockCount == randomBlockIndex) { break; } } if(randomBlockCount == randomBlockIndex) { break; } } if(randomBlockCount == randomBlockIndex) { break; } } } ArrayList<BO4BlockFunction> newBlocks = new ArrayList<BO4BlockFunction>(); newBlocks.addAll(nonRandomBlocks); newBlocks.addAll(randomBlocks); if(getBlocks) { loadBlockArrays(newBlocks, columnSizes); } int branchesOTGPlusLength = buffer.getInt(); boolean branchType; BO4BranchFunction branch; this.branchesOTGPlus = new BO4BranchFunction[branchesOTGPlusLength]; for(int i = 0; i < branchesOTGPlusLength; i++) { branchType = buffer.get() != 0; if(branchType) { branch = BO4WeightedBranchFunction.fromStream(this, buffer); } else { branch = BO4BranchFunction.fromStream(this, buffer); } this.branchesOTGPlus[i] = branch; } int entityDataOTGPlusLength = buffer.getInt(); this.entityDataOTGPlus = new BO4EntityFunction[entityDataOTGPlusLength]; for(int i = 0; i < entityDataOTGPlusLength; i++) { this.entityDataOTGPlus[i] = BO4EntityFunction.fromStream(this, buffer); } int particleDataOTGPlusLength = buffer.getInt(); this.particleDataOTGPlus = new BO4ParticleFunction[particleDataOTGPlusLength]; for(int i = 0; i < particleDataOTGPlusLength; i++) { this.particleDataOTGPlus[i] = BO4ParticleFunction.fromStream(this, buffer); } int spawnerDataOTGPlusLength = buffer.getInt(); this.spawnerDataOTGPlus = new BO4SpawnerFunction[spawnerDataOTGPlusLength]; for(int i = 0; i < spawnerDataOTGPlusLength; i++) { this.spawnerDataOTGPlus[i] = BO4SpawnerFunction.fromStream(this, buffer); } int modDataOTGPlusLength = buffer.getInt(); this.modDataOTGPlus = new BO4ModDataFunction[modDataOTGPlusLength]; for(int i = 0; i < modDataOTGPlusLength; i++) { this.modDataOTGPlus[i] = BO4ModDataFunction.fromStream(this, buffer); } } catch (IOException e1) { e1.printStackTrace(); } // when finished try { fis.getChannel().close(); } catch (IOException e) { e.printStackTrace(); } try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e2) { e2.printStackTrace(); } return this; } private void loadBlockArrays(ArrayList<BO4BlockFunction> newBlocks, short[][] columnSizes) { // Store blocks in arrays instead of as BO4BlockFunctions, // since that gives way too much overhead memory wise. // We may have tens of millions of blocks, java doesn't handle lots of small classes well. this.blocks = new short[xSize][zSize][]; this.blocksMaterial = new LocalMaterialData[newBlocks.size()]; this.blocksMetaDataName = new String[newBlocks.size()]; this.blocksMetaDataTag = new NamedBinaryTag[newBlocks.size()]; this.randomBlocksBlocks = new LocalMaterialData[newBlocks.size()][]; this.randomBlocksBlockChances = new byte[newBlocks.size()][]; this.randomBlocksMetaDataNames = new String[newBlocks.size()][]; this.randomBlocksMetaDataTags = new NamedBinaryTag[newBlocks.size()][]; this.randomBlocksBlockCount = new byte[newBlocks.size()]; BO4BlockFunction block; short[][] columnBlockIndex = new short[xSize][zSize]; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { if(this.blocks[x][z] == null) { this.blocks[x ][z] = new short[columnSizes[x][z]]; } } } for(int i = 0; i < newBlocks.size(); i++) { block = newBlocks.get(i); this.blocks[block.x][block.z][columnBlockIndex[block.x][block.z]] = (short) block.y; int blockIndex = columnBlockIndex[block.x][block.z] + getColumnBlockIndex(columnSizes, block.x, block.z); this.blocksMaterial[blockIndex] = block.material; this.blocksMetaDataName[blockIndex] = block.metaDataName; this.blocksMetaDataTag[blockIndex] = block.metaDataTag; if(block instanceof BO4RandomBlockFunction) { this.randomBlocksBlocks[blockIndex] = ((BO4RandomBlockFunction)block).blocks; this.randomBlocksBlockChances[blockIndex] = ((BO4RandomBlockFunction)block).blockChances; this.randomBlocksMetaDataNames[blockIndex] = ((BO4RandomBlockFunction)block).metaDataNames; this.randomBlocksMetaDataTags[blockIndex] = ((BO4RandomBlockFunction)block).metaDataTags; this.randomBlocksBlockCount[blockIndex] = ((BO4RandomBlockFunction)block).blockCount; } columnBlockIndex[block.x][block.z]++; } } private int getColumnBlockIndex(short[][] columnSizes, int columnX, int columnZ) { int blockIndex = 0; for(int x = 0; x < 16; x++) { for(int z = 0; z < 16; z++) { if(columnX == x && columnZ == z) { return blockIndex; } blockIndex += columnSizes[x][z]; } } return blockIndex; } @Override protected void correctSettings() { } @Override protected void renameOldSettings() { // Stub method - there are no old setting to convert yet (: } public boolean isCollidable() { return isCollidable; } }
common/src/main/java/com/pg85/otg/customobjects/bo4/BO4Config.java
package com.pg85.otg.customobjects.bo4; import com.pg85.otg.OTG; import com.pg85.otg.common.LocalMaterialData; import com.pg85.otg.configuration.customobjects.CustomObjectConfigFile; import com.pg85.otg.configuration.customobjects.CustomObjectConfigFunction; import com.pg85.otg.configuration.io.SettingsReaderOTGPlus; import com.pg85.otg.configuration.io.SettingsWriterOTGPlus; import com.pg85.otg.configuration.standard.PluginStandardValues; import com.pg85.otg.configuration.standard.WorldStandardValues; import com.pg85.otg.configuration.world.WorldConfig.ConfigMode; import com.pg85.otg.customobjects.CustomObject; import com.pg85.otg.customobjects.bo4.BO4Config; import com.pg85.otg.customobjects.bo4.BO4Settings; import com.pg85.otg.customobjects.bo4.bo4function.BO4BlockFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4BranchFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4EntityFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4ModDataFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4ParticleFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4RandomBlockFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4SpawnerFunction; import com.pg85.otg.customobjects.bo4.bo4function.BO4WeightedBranchFunction; import com.pg85.otg.customobjects.structures.bo4.BO4CustomStructureCoordinate; import com.pg85.otg.customobjects.bo3.BO3Settings; import com.pg85.otg.customobjects.bo3.BO3Settings.SpawnHeightEnum; import com.pg85.otg.customobjects.bo3.bo3function.BO3BlockFunction; import com.pg85.otg.customobjects.bo3.bo3function.BO3BranchFunction; import com.pg85.otg.customobjects.bo3.bo3function.BO3RandomBlockFunction; import com.pg85.otg.exception.InvalidConfigException; import com.pg85.otg.logging.LogMarker; import com.pg85.otg.util.ChunkCoordinate; import com.pg85.otg.util.bo3.NamedBinaryTag; import com.pg85.otg.util.bo3.Rotation; import com.pg85.otg.util.helpers.MaterialHelper; import com.pg85.otg.util.helpers.StreamHelper; import com.pg85.otg.util.minecraft.defaults.DefaultMaterial; import com.pg85.otg.util.minecraft.defaults.DefaultStructurePart; import java.io.DataInputStream; import java.io.DataOutput; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.DataFormatException; public class BO4Config extends CustomObjectConfigFile { public String author; public String description; public ConfigMode settingsMode; public int frequency; private final int xSize = 16; private final int zSize = 16; public int minHeight; public int maxHeight; public SpawnHeightEnum spawnHeight; private BO4BlockFunction[][] heightMap; private boolean inheritedBO3Loaded; // These are used in CustomObjectStructure when determining the minimum area in chunks that // this branching structure needs to be able to spawn public int minimumSizeTop = -1; public int minimumSizeBottom = -1; public int minimumSizeLeft = -1; public int minimumSizeRight = -1; public int timesSpawned = 0; public int branchFrequency; // Define groups that this BO3 belongs to with a range in chunks that members of each group should have to each other private String branchFrequencyGroup; public HashMap<String, Integer> branchFrequencyGroups; private int minX; private int maxX; private int minY; private int maxY; private int minZ; private int maxZ; private ArrayList<String> inheritedBO3s; // Adjusts the height by this number before spawning. Handy when using "highestblock" for lowering BO3s that have a lot of ground under them included public int heightOffset; private Rotation inheritBO3Rotation; // If this is set to true then any air blocks in the bo3 will not be spawned private boolean removeAir; // Defaults to false. Set to true if this BO3 should spawn at the player spawn point. When the server starts one of the structures that has IsSpawnPoint set to true is selected randomly and is spawned, the others never get spawned.) public boolean isSpawnPoint; // Replaces all the non-air blocks that are above this BO3 or its smoothing area with the given block material (should be WATER or AIR or NONE), also applies to smoothing areas although it intentionally leaves some of the terrain above them intact. WATER can be used in combination with SpawnUnderWater to fill any air blocks underneath waterlevel with water (and any above waterlevel with air). public String replaceAbove; // Replaces all non-air blocks underneath the BO3 (but not its smoothing area) with the designated material until a solid block is found. public String replaceBelow; // Defaults to true. If set to true then every block in the BO3 of the materials defined in ReplaceWithGroundBlock or ReplaceWithSurfaceBlock will be replaced by the GroundBlock or SurfaceBlock materials configured for the biome the block is spawned in. public boolean replaceWithBiomeBlocks; // Replaces all the blocks of the given material in the BO3 with the GroundBlock configured for the biome it spawns in public String replaceWithGroundBlock; // Replaces all the blocks of the given material in the BO3 with the SurfaceBlock configured for the biome it spawns in public String replaceWithSurfaceBlock; // Define a group that this BO3 belongs to and a range in chunks that members of this group should have to each other private String bo3Group; public HashMap<String, Integer> bo3Groups; // If this is set to true then this BO3 can spawn on top of or inside other BO3's public boolean canOverride; // Copies the blocks and branches of an existing BO3 into this one private String inheritBO3; // Should the smoothing area go to the top or the bottom blocks in the bo3? public boolean smoothStartTop; public boolean smoothStartWood; // The size of the smoothing area public int smoothRadius; // The materials used for the smoothing area public String smoothingSurfaceBlock; public String smoothingGroundBlock; // If true then root BO3 smoothing and height settings are used for all children public boolean overrideChildSettings; public boolean overrideParentHeight; // Used to make sure that dungeons can only spawn underneath other structures public boolean mustBeBelowOther; // Used to make sure that dungeons can only spawn inside worldborders public boolean mustBeInsideWorldBorders; private String replacesBO3; public ArrayList<String> replacesBO3Branches; private String mustBeInside; public ArrayList<String> mustBeInsideBranches; private String cannotBeInside; public ArrayList<String> cannotBeInsideBranches; public int smoothHeightOffset; public boolean canSpawnOnWater; public boolean spawnOnWaterOnly; public boolean spawnUnderWater; public boolean spawnAtWaterLevel; private String worldName; // Store blocks in arrays instead of as BO4BlockFunctions, // since that gives way too much overhead memory wise. // We may have tens of millions of blocks, java doesn't handle lots of small classes well. private short[][][]blocks; private LocalMaterialData[]blocksMaterial; private String[]blocksMetaDataName; private NamedBinaryTag[]blocksMetaDataTag; private LocalMaterialData[][] randomBlocksBlocks; private byte[][] randomBlocksBlockChances; private String[][] randomBlocksMetaDataNames; private NamedBinaryTag[][] randomBlocksMetaDataTags; private byte[] randomBlocksBlockCount; // private BO4BranchFunction[] branchesOTGPlus; private BO4ModDataFunction[] modDataOTGPlus; private BO4SpawnerFunction[] spawnerDataOTGPlus; private BO4ParticleFunction[] particleDataOTGPlus; private BO4EntityFunction[] entityDataOTGPlus; private boolean isCollidable = false; /** * Creates a BO3Config from a file. * * @param reader The settings of the BO3. * @param directory The directory the BO3 is stored in. * @param otherObjects All other loaded objects by their name. */ public BO4Config(SettingsReaderOTGPlus reader, boolean init) throws InvalidConfigException { super(reader); if(init) { init(); } } static int BO4BlocksLoadedFromBO4Data = 0; static int accumulatedTime = 0; static int accumulatedTime2 = 0; private void init() throws InvalidConfigException { this.minX = Integer.MAX_VALUE; this.maxX = Integer.MIN_VALUE; this.minY = Integer.MAX_VALUE; this.maxY = Integer.MIN_VALUE; this.minZ = Integer.MAX_VALUE; this.maxZ = Integer.MIN_VALUE; if(!this.reader.getFile().getAbsolutePath().toLowerCase().endsWith(".bo4data")) { //long startTime = System.currentTimeMillis(); readConfigSettings(); //BO4BlocksLoaded++; //long timeTaken = (System.currentTimeMillis() - startTime); //accumulatedTime += timeTaken; //OTG.log(LogMarker.INFO, "BO4's loaded: " + BO4BlocksLoaded + " in " + accumulatedTime); //OTG.log(LogMarker.INFO, ".BO4 loaded in: " + timeTaken + " " + this.getName() + ".BO4"); } else { //long startTime = System.currentTimeMillis(); this.readFromBO4DataFile(); //BO4BlocksLoadedFromBO4Data++; //long timeTaken = (System.currentTimeMillis() - startTime); //accumulatedTime2 += timeTaken; //OTG.log(LogMarker.INFO, ".BO4Data's loaded: " + BO4BlocksLoadedFromBO4Data + " in " + accumulatedTime2); //OTG.log(LogMarker.INFO, ".BO4Data loaded in: " + timeTaken + " " + this.getName() + ".BO4Data"); } // When writing, we'll need to read some raw data from the file, // so can't flush the cache yet. Flush after writing. if(this.settingsMode == ConfigMode.WriteDisable) { this.reader.flushCache(); } } public int getXOffset() { return minX < -8 ? -minX : maxX > 7 ? -minX : 8; } public int getZOffset() { return minZ < -7 ? -minZ : maxZ > 8 ? -minZ : 7; } public int getminX() { return minX + this.getXOffset(); // + xOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getmaxX() { return maxX + this.getXOffset(); // + xOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getminY() { return minY; } public int getmaxY() { return maxY; } public int getminZ() { return minZ + this.getZOffset(); // + zOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public int getmaxZ() { return maxZ + this.getZOffset(); // + zOffset makes sure that the value returned is never negative which is necessary for the collision detection code for CustomStructures in OTG (it assumes the furthest top and left blocks are at => 0 x or >= 0 z in the BO3) } public ArrayList<String> getInheritedBO3s() { return this.inheritedBO3s; } public BO4BlockFunction[][] getSmoothingHeightMap(BO4 start) { if(this.heightMap == null) { this.heightMap = new BO4BlockFunction[16][16]; // make heightmap containing the highest or lowest blocks in this chunk int blockIndex = 0; LocalMaterialData material; boolean isSmoothAreaAnchor; boolean isRandomBlock; int y; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { if(blocks[x][z] != null) { for(int i = 0; i < blocks[x][z].length; i++) { isSmoothAreaAnchor = false; isRandomBlock = this.randomBlocksBlocks[blockIndex] != null; y = blocks[x][z][i]; if(isRandomBlock) { for(LocalMaterialData randomMaterial : this.randomBlocksBlocks[blockIndex]) { // TODO: Material should never be null, fix the code in RandomBlockFunction.load() that causes this. if(randomMaterial == null) { continue; } if(randomMaterial.isSmoothAreaAnchor(start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartWood : this.smoothStartWood, start.getConfig().spawnUnderWater)) { isSmoothAreaAnchor = true; break; } } } material = this.blocksMaterial[blockIndex]; if( isSmoothAreaAnchor || ( !isRandomBlock && material.isSmoothAreaAnchor(start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartWood : this.smoothStartWood, start.getConfig().spawnUnderWater) ) ) { if( (!(start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartTop : this.smoothStartTop) && y == getminY()) || ((start.getConfig().overrideChildSettings && this.overrideChildSettings ? start.getConfig().smoothStartTop : this.smoothStartTop) && (this.heightMap[x][z] == null || y > this.heightMap[x][z].y)) ) { BO4BlockFunction blockFunction = null; if(isRandomBlock) { blockFunction = new BO4RandomBlockFunction(); ((BO4RandomBlockFunction)blockFunction).blocks = this.randomBlocksBlocks[blockIndex]; ((BO4RandomBlockFunction)blockFunction).blockChances = this.randomBlocksBlockChances[blockIndex]; ((BO4RandomBlockFunction)blockFunction).metaDataNames = this.randomBlocksMetaDataNames[blockIndex]; ((BO4RandomBlockFunction)blockFunction).metaDataTags = this.randomBlocksMetaDataTags[blockIndex]; ((BO4RandomBlockFunction)blockFunction).blockCount = this.randomBlocksBlockCount[blockIndex]; } else { blockFunction = new BO4BlockFunction(); } blockFunction.material = material; blockFunction.x = x; blockFunction.y = (short) y; blockFunction.z = z; blockFunction.metaDataName = this.blocksMetaDataName[blockIndex]; blockFunction.metaDataTag = this.blocksMetaDataTag[blockIndex]; this.heightMap[x][z] = blockFunction; } } blockIndex++; } } } } } return this.heightMap; } public BO4BlockFunction[] getBlocks() { BO4BlockFunction[] blocksOTGPlus = new BO4BlockFunction[this.blocksMaterial.length]; BO4BlockFunction block; int blockIndex = 0; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { if(this.blocks[x][z] != null) { for(int i = 0; i < this.blocks[x][z].length; i++) { if(this.randomBlocksBlocks[blockIndex] != null) { block = new BO4RandomBlockFunction(this); ((BO4RandomBlockFunction)block).blocks = this.randomBlocksBlocks[blockIndex]; ((BO4RandomBlockFunction)block).blockChances = this.randomBlocksBlockChances[blockIndex]; ((BO4RandomBlockFunction)block).metaDataNames = this.randomBlocksMetaDataNames[blockIndex]; ((BO4RandomBlockFunction)block).metaDataTags = this.randomBlocksMetaDataTags[blockIndex]; ((BO4RandomBlockFunction)block).blockCount = this.randomBlocksBlockCount[blockIndex]; } else { block = new BO4BlockFunction(this); } block.x = x; block.y = this.blocks[x][z][i]; block.z = z; block.material = this.blocksMaterial[blockIndex]; block.metaDataName = this.blocksMetaDataName[blockIndex]; block.metaDataTag = this.blocksMetaDataTag[blockIndex]; blocksOTGPlus[blockIndex] = block; blockIndex++; } } } } return blocksOTGPlus; } protected BO4BranchFunction[] getbranches() { return branchesOTGPlus; } public BO4ModDataFunction[] getModData() { return modDataOTGPlus; } public BO4SpawnerFunction[] getSpawnerData() { return spawnerDataOTGPlus; } public BO4ParticleFunction[] getParticleData() { return particleDataOTGPlus; } public BO4EntityFunction[] getEntityData() { return entityDataOTGPlus; } private void loadInheritedBO3() { if(this.inheritBO3 != null && this.inheritBO3.trim().length() > 0 && !inheritedBO3Loaded) { File currentFile = this.getFile().getParentFile(); this.worldName = currentFile.getName(); while(currentFile.getParentFile() != null && !currentFile.getName().toLowerCase().equals(PluginStandardValues.PresetsDirectoryName)) { this.worldName = currentFile.getName(); currentFile = currentFile.getParentFile(); if(this.worldName.toLowerCase().equals("globalobjects")) { this.worldName = null; break; } } CustomObject parentBO3 = OTG.getCustomObjectManager().getGlobalObjects().getObjectByName(this.inheritBO3, this.worldName); if(parentBO3 != null) { BO4BlockFunction[] blocks = getBlocks(); this.inheritedBO3Loaded = true; this.inheritedBO3s.addAll(((BO4)parentBO3).getConfig().getInheritedBO3s()); this.removeAir = ((BO4)parentBO3).getConfig().removeAir; this.replaceAbove = this.replaceAbove == null || this.replaceAbove.length() == 0 ? ((BO4)parentBO3).getConfig().replaceAbove : this.replaceAbove; this.replaceBelow = this.replaceBelow == null || this.replaceBelow.length() == 0 ? ((BO4)parentBO3).getConfig().replaceBelow : this.replaceBelow; BO4CustomStructureCoordinate rotatedParentMaxCoords = BO4CustomStructureCoordinate.getRotatedBO3Coords(((BO4)parentBO3).getConfig().maxX, ((BO4)parentBO3).getConfig().maxY, ((BO4)parentBO3).getConfig().maxZ, this.inheritBO3Rotation); BO4CustomStructureCoordinate rotatedParentMinCoords = BO4CustomStructureCoordinate.getRotatedBO3Coords(((BO4)parentBO3).getConfig().minX, ((BO4)parentBO3).getConfig().minY, ((BO4)parentBO3).getConfig().minZ, this.inheritBO3Rotation); int parentMaxX = rotatedParentMaxCoords.getX() > rotatedParentMinCoords.getX() ? rotatedParentMaxCoords.getX() : rotatedParentMinCoords.getX(); int parentMinX = rotatedParentMaxCoords.getX() < rotatedParentMinCoords.getX() ? rotatedParentMaxCoords.getX() : rotatedParentMinCoords.getX(); int parentMaxY = rotatedParentMaxCoords.getY() > rotatedParentMinCoords.getY() ? rotatedParentMaxCoords.getY() : rotatedParentMinCoords.getY(); int parentMinY = rotatedParentMaxCoords.getY() < rotatedParentMinCoords.getY() ? rotatedParentMaxCoords.getY() : rotatedParentMinCoords.getY(); int parentMaxZ = rotatedParentMaxCoords.getZ() > rotatedParentMinCoords.getZ() ? rotatedParentMaxCoords.getZ() : rotatedParentMinCoords.getZ(); int parentMinZ = rotatedParentMaxCoords.getZ() < rotatedParentMinCoords.getZ() ? rotatedParentMaxCoords.getZ() : rotatedParentMinCoords.getZ(); if(parentMaxX > this.maxX) { this.maxX = parentMaxX; } if(parentMinX < this.minX) { this.minX = parentMinX; } if(parentMaxY > this.maxY) { this.maxY = parentMaxY; } if(parentMinY < this.minY) { this.minY = parentMinY; } if(parentMaxZ > this.maxZ) { this.maxZ = parentMaxZ; } if(parentMinZ < this.minZ) { this.minZ = parentMinZ; } BO4BlockFunction[] parentBlocks = ((BO4)parentBO3).getConfig().getBlocks(); ArrayList<BO4BlockFunction> newBlocks = new ArrayList<BO4BlockFunction>(); newBlocks.addAll(new ArrayList<BO4BlockFunction>(Arrays.asList(parentBlocks))); newBlocks.addAll(new ArrayList<BO4BlockFunction>(Arrays.asList(blocks))); short[][] columnSizes = new short[16][16]; for(BO4BlockFunction block : newBlocks) { columnSizes[block.x][block.z]++; } loadBlockArrays(newBlocks, columnSizes); this.isCollidable = newBlocks.size() > 0; ArrayList<BO4BranchFunction> newBranches = new ArrayList<BO4BranchFunction>(); if(this.branchesOTGPlus != null) { for(BO4BranchFunction branch : this.branchesOTGPlus) { newBranches.add(branch); } } for(BO4BranchFunction branch : ((BO4)parentBO3).getConfig().branchesOTGPlus) { newBranches.add(branch.rotate(this.inheritBO3Rotation)); } this.branchesOTGPlus = newBranches.toArray(new BO4BranchFunction[newBranches.size()]); ArrayList<BO4ModDataFunction> newModData = new ArrayList<BO4ModDataFunction>(); if(this.modDataOTGPlus != null) { for(BO4ModDataFunction modData : this.modDataOTGPlus) { newModData.add(modData); } } for(BO4ModDataFunction modData : ((BO4)parentBO3).getConfig().modDataOTGPlus) { newModData.add(modData.rotate(this.inheritBO3Rotation)); } this.modDataOTGPlus = newModData.toArray(new BO4ModDataFunction[newModData.size()]); ArrayList<BO4SpawnerFunction> newSpawnerData = new ArrayList<BO4SpawnerFunction>(); if(this.spawnerDataOTGPlus != null) { for(BO4SpawnerFunction spawnerData : this.spawnerDataOTGPlus) { newSpawnerData.add(spawnerData); } } for(BO4SpawnerFunction spawnerData : ((BO4)parentBO3).getConfig().spawnerDataOTGPlus) { newSpawnerData.add(spawnerData.rotate(this.inheritBO3Rotation)); } this.spawnerDataOTGPlus = newSpawnerData.toArray(new BO4SpawnerFunction[newSpawnerData.size()]); ArrayList<BO4ParticleFunction> newParticleData = new ArrayList<BO4ParticleFunction>(); if(this.particleDataOTGPlus != null) { for(BO4ParticleFunction particleData : this.particleDataOTGPlus) { newParticleData.add(particleData); } } for(BO4ParticleFunction particleData : ((BO4)parentBO3).getConfig().particleDataOTGPlus) { newParticleData.add(particleData.rotate(this.inheritBO3Rotation)); } this.particleDataOTGPlus = newParticleData.toArray(new BO4ParticleFunction[newParticleData.size()]); ArrayList<BO4EntityFunction> newEntityData = new ArrayList<BO4EntityFunction>(); if(this.entityDataOTGPlus != null) { for(BO4EntityFunction entityData : this.entityDataOTGPlus) { newEntityData.add(entityData); } } for(BO4EntityFunction entityData : ((BO4)parentBO3).getConfig().entityDataOTGPlus) { newEntityData.add(entityData.rotate(this.inheritBO3Rotation)); } this.entityDataOTGPlus = newEntityData.toArray(new BO4EntityFunction[newEntityData.size()]); this.inheritedBO3s.addAll(((BO4)parentBO3).getConfig().getInheritedBO3s()); } if(!this.inheritedBO3Loaded) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "could not load BO3 parent for InheritBO3: " + this.inheritBO3 + " in BO3 " + this.getName()); } } } } static int BO4BlocksLoaded = 0; private void readResources() throws InvalidConfigException { List<BO4BlockFunction> tempBlocksList = new ArrayList<BO4BlockFunction>(); List<BO4BranchFunction> tempBranchesList = new ArrayList<BO4BranchFunction>(); List<BO4EntityFunction> tempEntitiesList = new ArrayList<BO4EntityFunction>(); List<BO4ModDataFunction> tempModDataList = new ArrayList<BO4ModDataFunction>(); List<BO4ParticleFunction> tempParticlesList = new ArrayList<BO4ParticleFunction>(); List<BO4SpawnerFunction> tempSpawnerList = new ArrayList<BO4SpawnerFunction>(); short[][] columnSizes = new short[xSize][zSize]; BO4BlockFunction block; for (CustomObjectConfigFunction<BO4Config> res : reader.getConfigFunctions(this, true)) { if (res.isValid()) { if (res instanceof BO4BlockFunction) { this.isCollidable = true; if(res instanceof BO4RandomBlockFunction) { block = (BO4RandomBlockFunction)res; tempBlocksList.add((BO4RandomBlockFunction)res); columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; } else { if(!this.removeAir || !((BO4BlockFunction)res).material.toDefaultMaterial().equals(DefaultMaterial.AIR)) { tempBlocksList.add((BO4BlockFunction)res); block = (BO4BlockFunction)res; try { columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; } catch(ArrayIndexOutOfBoundsException ex) { String breakpoint = ""; } } } // Get the real size of this BO3 if(((BO4BlockFunction)res).x < this.minX) { this.minX = ((BO4BlockFunction)res).x; } if(((BO4BlockFunction)res).x > this.maxX) { this.maxX = ((BO4BlockFunction)res).x; } if(((BO4BlockFunction)res).y < this.minY) { this.minY = ((BO4BlockFunction)res).y; } if(((BO4BlockFunction)res).y > this.maxY) { this.maxY = ((BO4BlockFunction)res).y; } if(((BO4BlockFunction)res).z < this.minZ) { this.minZ = ((BO4BlockFunction)res).z; } if(((BO4BlockFunction)res).z > this.maxZ) { this.maxZ = ((BO4BlockFunction)res).z; } } else { if (res instanceof BO4WeightedBranchFunction) { tempBranchesList.add((BO4WeightedBranchFunction) res); } else if (res instanceof BO4BranchFunction) { tempBranchesList.add((BO4BranchFunction) res); } else if (res instanceof BO4ModDataFunction) { tempModDataList.add((BO4ModDataFunction) res); } else if (res instanceof BO4SpawnerFunction) { tempSpawnerList.add((BO4SpawnerFunction) res); } else if (res instanceof BO4ParticleFunction) { tempParticlesList.add((BO4ParticleFunction) res); } else if (res instanceof BO4EntityFunction) { tempEntitiesList.add((BO4EntityFunction) res); } } } } if(this.minX == Integer.MAX_VALUE) { this.minX = -8; } if(this.maxX == Integer.MIN_VALUE) { this.maxX = -8; } if(this.minY == Integer.MAX_VALUE) { this.minY = 0; } if(this.maxY == Integer.MIN_VALUE) { this.maxY = 0; } if(this.minZ == Integer.MAX_VALUE) { this.minZ = -7; } if(this.maxZ == Integer.MIN_VALUE) { this.maxZ = -7; } if(Math.abs(this.minX - this.maxX) >= 16 || Math.abs(this.minZ - this.maxZ) >= 16) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "BO4 was too large to spawn (> 16x16) " + this.getName() + " XSize " + (Math.abs(this.minX - this.maxX) + 1) + " ZSize " + (Math.abs(this.minZ - this.maxZ) + 1) + ". Use branches instead."); } } // TODO: OTG+ Doesn't do CustomObject BO3's, only check for 16x16, not 32x32? boolean illegalBlock = false; for(BO4BlockFunction block1 : tempBlocksList) { block1.x += this.getXOffset(); block1.z += this.getZOffset(); if(block1.x > 15 || block1.z > 15) { illegalBlock = true; } if(block1.x < 0 || block1.z < 0) { illegalBlock = true; } } this.blocks = new short[xSize][zSize][]; this.blocksMaterial = new LocalMaterialData[tempBlocksList.size()]; this.blocksMetaDataName = new String[tempBlocksList.size()]; this.blocksMetaDataTag = new NamedBinaryTag[tempBlocksList.size()]; this.randomBlocksBlocks = new LocalMaterialData[tempBlocksList.size()][]; this.randomBlocksBlockChances = new byte[tempBlocksList.size()][]; this.randomBlocksMetaDataNames = new String[tempBlocksList.size()][]; this.randomBlocksMetaDataTags = new NamedBinaryTag[tempBlocksList.size()][]; this.randomBlocksBlockCount = new byte[tempBlocksList.size()]; short[][] columnBlockIndex = new short[xSize][zSize]; BO4BlockFunction[] blocksSorted = new BO4BlockFunction[tempBlocksList.size()]; int blocksSortedIndex = 0; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { for(int h = 0; h < tempBlocksList.size(); h++) { if(tempBlocksList.get(h).x == x && tempBlocksList.get(h).z == z) { blocksSorted[blocksSortedIndex] = tempBlocksList.get(h); blocksSortedIndex++; } } } } for(int blockIndex = 0; blockIndex < blocksSorted.length; blockIndex++) { block = blocksSorted[blockIndex]; if(this.blocks[block.x][block.z] == null) { this.blocks[block.x][block.z] = new short[columnSizes[block.x][block.z]]; } this.blocks[block.x][block.z][columnBlockIndex[block.x][block.z]] = (short) block.y; this.blocksMaterial[blockIndex] = block.material; this.blocksMetaDataName[blockIndex] = block.metaDataName; this.blocksMetaDataTag[blockIndex] = block.metaDataTag; if(block instanceof BO4RandomBlockFunction) { this.randomBlocksBlocks[blockIndex] = ((BO4RandomBlockFunction)block).blocks; this.randomBlocksBlockChances[blockIndex] = ((BO4RandomBlockFunction)block).blockChances; this.randomBlocksMetaDataNames[blockIndex] = ((BO4RandomBlockFunction)block).metaDataNames; this.randomBlocksMetaDataTags[blockIndex] = ((BO4RandomBlockFunction)block).metaDataTags; this.randomBlocksBlockCount[blockIndex] = ((BO4RandomBlockFunction)block).blockCount; } columnBlockIndex[block.x][block.z]++; } boolean illegalModData = false; for(BO4ModDataFunction modData : tempModDataList) { modData.x += this.getXOffset(); modData.z += this.getZOffset(); if(modData.x > 15 || modData.z > 15) { illegalModData = true; } if(modData.x < 0 || modData.z < 0) { illegalModData = true; } } this.modDataOTGPlus = tempModDataList.toArray(new BO4ModDataFunction[tempModDataList.size()]); boolean illegalSpawnerData = false; for(BO4SpawnerFunction spawnerData : tempSpawnerList) { spawnerData.x += this.getXOffset(); spawnerData.z += this.getZOffset(); if(spawnerData.x > 15 || spawnerData.z > 15) { illegalSpawnerData = true; } if(spawnerData.x < 0 || spawnerData.z < 0) { illegalSpawnerData = true; } } this.spawnerDataOTGPlus = tempSpawnerList.toArray(new BO4SpawnerFunction[tempSpawnerList.size()]); boolean illegalParticleData = false; for(BO4ParticleFunction particleData : tempParticlesList) { particleData.x += this.getXOffset(); particleData.z += this.getZOffset(); if(particleData.x > 15 || particleData.z > 15) { illegalParticleData = true; } if(particleData.x < 0 || particleData.z < 0) { illegalParticleData = true; } } this.particleDataOTGPlus = tempParticlesList.toArray(new BO4ParticleFunction[tempParticlesList.size()]); boolean illegalEntityData = false; for(BO4EntityFunction entityData : tempEntitiesList) { entityData.x += this.getXOffset(); entityData.z += this.getZOffset(); if(entityData.x > 15 || entityData.z > 15) { illegalEntityData = true; } if(entityData.x < 0 || entityData.z < 0) { illegalEntityData = true; } } this.entityDataOTGPlus = tempEntitiesList.toArray(new BO4EntityFunction[tempEntitiesList.size()]); if(OTG.getPluginConfig().spawnLog) { if(illegalBlock) { OTG.log(LogMarker.WARN, "Warning: BO3 contains Blocks or RandomBlocks that are placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalModData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains ModData that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalSpawnerData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains a Spawner() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalParticleData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains a Particle() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } if(illegalEntityData) { OTG.log(LogMarker.WARN, "Warning: BO3 contains an Entity() that may be placed outside the chunk(s) that the BO3 will be placed in. This can slow down world generation. BO3: " + this.getName()); } } this.branchesOTGPlus = tempBranchesList.toArray(new BO4BranchFunction[tempBranchesList.size()]); if(this.branchesOTGPlus.length > 0) // If this BO3 has branches then it must be max 16x16 { if(Math.abs(this.minX - this.maxX) > 15 || Math.abs(this.minZ - this.maxZ) > 15) { OTG.log(LogMarker.INFO, "BO3 " + this.getName() + " was too large, branching BO3's can be max 16x16 blocks."); throw new InvalidConfigException("BO3 " + this.getName() + " was too large, branching BO3's can be max 16x16 blocks."); } } else { if(Math.abs(this.minX - this.maxX) > 15 || Math.abs(this.minZ - this.maxZ) > 15) // If this BO3 is larger than 16x16 then it can only be used as a customObject { OTG.log(LogMarker.INFO, "BO4 " + this.getName() + " was too large, BO4's used as CustomStructure() can be max 16x16 blocks."); throw new InvalidConfigException("BO4 " + this.getName() + " was too large, BO4's used as CustomStructure() can be max 16x16 blocks."); } } } public void setBranches(List<BO4BranchFunction> branches) { this.branchesOTGPlus = branches.toArray(new BO4BranchFunction[branches.size()]); } /** * Gets the file this config will be written to. May be null if the config * will never be written. * @return The file. */ public File getFile() { return this.reader.getFile(); } @Override protected void writeConfigSettings(SettingsWriterOTGPlus writer) throws IOException { writeSettings(writer, null, null); } public void writeWithData(SettingsWriterOTGPlus writer, List<BO4BlockFunction> blocksList, List<BO4BranchFunction> branchesList) throws IOException { writer.setConfigMode(ConfigMode.WriteAll); try { writer.open(); writeSettings(writer, blocksList, branchesList); } finally { writer.close(); } } private void writeSettings(SettingsWriterOTGPlus writer, List<BO4BlockFunction> blocksList, List<BO4BranchFunction> branchesList) throws IOException { // The object writer.bigTitle("BO4 object"); writer.comment("This is the config file of a custom object."); writer.comment("If you add this object correctly to your BiomeConfigs, it will spawn in the world."); writer.comment(""); writer.comment("This is the creator of this BO4 object"); writer.setting(BO4Settings.AUTHOR, this.author); writer.comment("A short description of this BO4 object"); writer.setting(BO4Settings.DESCRIPTION, this.description); if(writer.getFile().getName().toUpperCase().endsWith(".BO3")) { writer.comment("Legacy setting, always true for BO4's. Only used if the file has a .BO3 extension."); writer.comment("Rename your file to .BO4 and remove this setting."); writer.setting(BO4Settings.ISOTGPLUS, true); } writer.comment("The settings mode, WriteAll, WriteWithoutComments or WriteDisable. See WorldConfig."); writer.setting(WorldStandardValues.SETTINGS_MODE_BO3, this.settingsMode); // Main settings writer.bigTitle("Main settings"); writer.comment("This BO4 can only spawn at least Frequency chunks distance away from any other BO4 with the exact same name."); writer.comment("You can use this to make this BO4 spawn in groups or make sure that this BO4 only spawns once every X chunks."); writer.setting(BO4Settings.FREQUENCY, this.frequency); writer.comment("The spawn height of the BO4: randomY, highestBlock or highestSolidBlock."); writer.setting(BO3Settings.SPAWN_HEIGHT, this.spawnHeight); writer.smallTitle("Height Limits for the BO4."); writer.comment("When in randomY mode used as the minimum Y or in atMinY mode as the actual Y to spawn this BO4 at."); writer.setting(BO4Settings.MIN_HEIGHT, this.minHeight); writer.comment("When in randomY mode used as the maximum Y to spawn this BO4 at."); writer.setting(BO4Settings.MAX_HEIGHT, this.maxHeight); writer.comment("Copies the blocks and branches of an existing BO4 into this BO4. You can still add blocks and branches in this BO4, they will be added on top of the inherited blocks and branches."); writer.setting(BO4Settings.INHERITBO3, this.inheritBO3); writer.comment("Rotates the inheritedBO3's resources (blocks, spawners, checks etc) and branches, defaults to NORTH (no rotation)."); writer.setting(BO4Settings.INHERITBO3ROTATION, this.inheritBO3Rotation); writer.comment("Defaults to true, if true and this is the starting BO4 for this branching structure then this BO4's smoothing and height settings are used for all children (branches)."); writer.setting(BO4Settings.OVERRIDECHILDSETTINGS, this.overrideChildSettings); writer.comment("Defaults to false, if true then this branch uses it's own height settings (SpawnHeight, minHeight, maxHeight, spawnAtWaterLevel) instead of those defined in the starting BO4 for this branching structure."); writer.setting(BO4Settings.OVERRIDEPARENTHEIGHT, this.overrideParentHeight); writer.comment("If this is set to true then this BO4 can spawn on top of or inside an existing BO4. If this is set to false then this BO4 will use a bounding box to detect collisions with other BO4's, if a collision is detected then this BO4 won't spawn and the current branch is rolled back."); writer.setting(BO4Settings.CANOVERRIDE, this.canOverride); writer.comment("This branch can only spawn at least branchFrequency chunks (x,z) distance away from any other branch with the exact same name."); writer.setting(BO4Settings.BRANCH_FREQUENCY, this.branchFrequency); writer.comment("Define groups that this branch belongs to along with a minimum (x,z) range in chunks that this branch must have between it and any other members of this group if it is to be allowed to spawn. Syntax is \"GroupName:Frequency, GoupName2:Frequency2\" etc so for example a branch that belongs to 3 groups: \"BranchFrequencyGroup: Ships:10, Vehicles:5, FloatingThings:3\"."); writer.setting(BO4Settings.BRANCH_FREQUENCY_GROUP, this.branchFrequencyGroup); writer.comment("If this is set to true then this BO4 can only spawn underneath an existing BO4. Used to make sure that dungeons only appear underneath buildings."); writer.setting(BO4Settings.MUSTBEBELOWOTHER, this.mustBeBelowOther); writer.comment("Used with CanOverride: true. A comma-seperated list of BO4s, this BO4's bounding box must collide with one of the BO4's in the list or this BO4 fails to spawn and the current branch is rolled back. AND/OR is supported, comma is OR, space is AND, f.e: branch1, branch2 branch3, branch 4."); writer.setting(BO4Settings.MUSTBEINSIDE, this.mustBeInside); writer.comment("Used with CanOverride: true. A comma-seperated list of BO4s, this BO4's bounding box cannot collide with any of the BO4's in the list or this BO4 fails to spawn and the current branch is rolled back."); writer.setting(BO4Settings.CANNOTBEINSIDE, this.cannotBeInside); writer.comment("Used with CanOverride: true. A comma-seperated list of BO4s, if this BO4's bounding box collides with any of the BO4's in the list then those BO4's won't spawn any blocks. This does not remove or roll back any BO4's."); writer.setting(BO4Settings.REPLACESBO3, this.replacesBO3); writer.comment("If this is set to true then this BO4 can only spawn inside world borders. Used to make sure that dungeons only appear inside the world borders."); writer.setting(BO4Settings.MUSTBEINSIDEWORLDBORDERS, this.mustBeInsideWorldBorders); writer.comment("Defaults to true. Set to false if the BO4 is not allowed to spawn on a water block"); writer.setting(BO4Settings.CANSPAWNONWATER, this.canSpawnOnWater); writer.comment("Defaults to false. Set to true if the BO4 is allowed to spawn only on a water block"); writer.setting(BO4Settings.SPAWNONWATERONLY, this.spawnOnWaterOnly); writer.comment("Defaults to false. Set to true if the BO4 and its smoothing area should ignore water when looking for the highest block to spawn on. Defaults to false (things spawn on top of water)"); writer.setting(BO4Settings.SPAWNUNDERWATER, this.spawnUnderWater); writer.comment("Defaults to false. Set to true if the BO4 should spawn at water level"); writer.setting(BO4Settings.SPAWNATWATERLEVEL, this.spawnAtWaterLevel); writer.comment("Spawns the BO4 at a Y offset of this value. Handy when using highestBlock for lowering BO4s into the surrounding terrain when there are layers of ground included in the BO4, also handy when using SpawnAtWaterLevel to lower objects like ships into the water."); writer.setting(BO4Settings.HEIGHT_OFFSET, this.heightOffset); boolean removeAir = readSettings(BO4Settings.REMOVEAIR); writer.comment("If set to true removes all AIR blocks from the BO4 so that it can be flooded or buried."); writer.setting(BO4Settings.REMOVEAIR, removeAir); String replaceAbove = readSettings(BO4Settings.REPLACEABOVE); writer.comment("Replaces all the non-air blocks that are above this BO4 or its smoothing area with the given block material (should be WATER or AIR or NONE), also applies to smoothing areas although OTG intentionally leaves some of the terrain above them intact. WATER can be used in combination with SpawnUnderWater to fill any air blocks underneath waterlevel with water (and any above waterlevel with air)."); writer.setting(BO4Settings.REPLACEABOVE, replaceAbove); String replaceBelow = readSettings(BO4Settings.REPLACEBELOW); writer.comment("Replaces all air blocks underneath the BO4 (but not its smoothing area) with the specified material until a solid block is found."); writer.setting(BO4Settings.REPLACEBELOW, replaceBelow); writer.comment("Defaults to true. If set to true then every block in the BO4 of the materials defined in ReplaceWithGroundBlock or ReplaceWithSurfaceBlock will be replaced by the GroundBlock or SurfaceBlock materials configured for the biome the block is spawned in."); writer.setting(BO4Settings.REPLACEWITHBIOMEBLOCKS, this.replaceWithBiomeBlocks); writer.comment("Defaults to DIRT, Replaces all the blocks of the given material in the BO4 with the GroundBlock configured for the biome it spawns in."); writer.setting(BO4Settings.REPLACEWITHGROUNDBLOCK, this.replaceWithGroundBlock); writer.comment("Defaults to GRASS, Replaces all the blocks of the given material in the BO4 with the SurfaceBlock configured for the biome it spawns in."); writer.setting(BO4Settings.REPLACEWITHSURFACEBLOCK, this.replaceWithSurfaceBlock); writer.comment("Makes the terrain around the BO4 slope evenly towards the edges of the BO4. The given value is the distance in blocks around the BO4 from where the slope should start and can be any positive number."); writer.setting(BO4Settings.SMOOTHRADIUS, this.smoothRadius); writer.comment("Moves the smoothing area up or down relative to the BO4 (at the points where the smoothing area is connected to the BO4). Handy when using SmoothStartTop: false and the BO4 has some layers of ground included, in that case we can set the HeightOffset to a negative value to lower the BO4 into the ground and we can set the SmoothHeightOffset to a positive value to move the smoothing area starting height up."); writer.setting(BO4Settings.SMOOTH_HEIGHT_OFFSET, this.smoothHeightOffset); writer.comment("Should the smoothing area be attached at the bottom or the top of the edges of the BO4? Defaults to false (bottom). Using this setting can make things slower so try to avoid using it and use SmoothHeightOffset instead if for instance you have a BO4 with some ground layers included. The only reason you should need to use this setting is if you have a BO4 with edges that have an irregular height (like some hills)."); writer.setting(BO4Settings.SMOOTHSTARTTOP, this.smoothStartTop); writer.comment("Should the smoothing area attach itself to \"log\" block or ignore them? Defaults to false (ignore logs)."); writer.setting(BO4Settings.SMOOTHSTARTWOOD, this.smoothStartWood); writer.comment("The block used for smoothing area surface blocks, defaults to biome SurfaceBlock."); writer.setting(BO4Settings.SMOOTHINGSURFACEBLOCK, this.smoothingSurfaceBlock); writer.comment("The block used for smoothing area ground blocks, defaults to biome GroundBlock."); writer.setting(BO4Settings.SMOOTHINGGROUNDBLOCK, this.smoothingGroundBlock); writer.comment("Define groups that this BO4 belongs to along with a minimum range in chunks that this BO4 must have between it and any other members of this group if it is to be allowed to spawn. Syntax is \"GroupName:Frequency, GoupName2:Frequency2\" etc so for example a BO4 that belongs to 3 groups: \"BO4Group: Ships:10, Vehicles:5, FloatingThings:3\"."); writer.setting(BO4Settings.BO3GROUP, this.bo3Group); writer.comment("Defaults to false. Set to true if this BO4 should spawn at the player spawn point. When the server starts the spawn point is determined and the BO4's for the biome it is in are loaded, one of these BO4s that has IsSpawnPoint set to true (if any) is selected randomly and is spawned at the spawn point regardless of its rarity (so even Rarity:0, IsSpawnPoint: true BO4's can get spawned as the spawn point!)."); writer.setting(BO4Settings.ISSPAWNPOINT, this.isSpawnPoint); // Blocks and other things writeResources(writer, blocksList, branchesList); if(this.reader != null) // Can be true for BO4Creator? { this.reader.flushCache(); } } @Override protected void readConfigSettings() throws InvalidConfigException { this.branchFrequency = readSettings(BO4Settings.BRANCH_FREQUENCY); this.branchFrequencyGroup = readSettings(BO4Settings.BRANCH_FREQUENCY_GROUP); this.branchFrequencyGroups = new HashMap<String, Integer>(); if(this.branchFrequencyGroup != null && this.branchFrequencyGroup.trim().length() > 0) { String[] groupStrings = this.branchFrequencyGroup.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.branchFrequencyGroups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.heightOffset = readSettings(BO4Settings.HEIGHT_OFFSET); this.inheritBO3Rotation = readSettings(BO4Settings.INHERITBO3ROTATION); this.removeAir = readSettings(BO4Settings.REMOVEAIR); this.isSpawnPoint = readSettings(BO4Settings.ISSPAWNPOINT); this.replaceAbove = readSettings(BO4Settings.REPLACEABOVE); this.replaceBelow = readSettings(BO4Settings.REPLACEBELOW); this.replaceWithBiomeBlocks = readSettings(BO4Settings.REPLACEWITHBIOMEBLOCKS); this.replaceWithGroundBlock = readSettings(BO4Settings.REPLACEWITHGROUNDBLOCK); this.replaceWithSurfaceBlock = readSettings(BO4Settings.REPLACEWITHSURFACEBLOCK); this.bo3Group = readSettings(BO4Settings.BO3GROUP); this.bo3Groups = new HashMap<String, Integer>(); if(this.bo3Group != null && this.bo3Group.trim().length() > 0) { String[] groupStrings = this.bo3Group.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.bo3Groups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.canOverride = readSettings(BO4Settings.CANOVERRIDE); this.mustBeBelowOther = readSettings(BO4Settings.MUSTBEBELOWOTHER); this.mustBeInsideWorldBorders = readSettings(BO4Settings.MUSTBEINSIDEWORLDBORDERS); this.mustBeInside = readSettings(BO4Settings.MUSTBEINSIDE); this.mustBeInsideBranches = new ArrayList<String>(); if(this.mustBeInside != null && this.mustBeInside.trim().length() > 0) { String[] mustBeInsideStrings = this.mustBeInside.split(","); if(mustBeInsideStrings != null && mustBeInsideStrings.length > 0) { for(int i = 0; i < mustBeInsideStrings.length; i++) { String mustBeInsideString = mustBeInsideStrings[i].trim(); if(mustBeInsideString.length() > 0) { this.mustBeInsideBranches.add(mustBeInsideString); } } } } this.cannotBeInside = readSettings(BO4Settings.CANNOTBEINSIDE); this.cannotBeInsideBranches = new ArrayList<String>(); if(this.cannotBeInside != null && this.cannotBeInside.trim().length() > 0) { String[] cannotBeInsideStrings = this.cannotBeInside.split(","); if(cannotBeInsideStrings != null && cannotBeInsideStrings.length > 0) { for(int i = 0; i < cannotBeInsideStrings.length; i++) { String cannotBeInsideString = cannotBeInsideStrings[i].trim(); if(cannotBeInsideString.length() > 0) { this.cannotBeInsideBranches.add(cannotBeInsideString); } } } } this.replacesBO3 = readSettings(BO4Settings.REPLACESBO3); this.replacesBO3Branches = new ArrayList<String>(); if(this.replacesBO3 != null && this.replacesBO3.trim().length() > 0) { String[] replacesBO3Strings = replacesBO3.split(","); if(replacesBO3Strings != null && replacesBO3Strings.length > 0) { for(int i = 0; i < replacesBO3Strings.length; i++) { String replacesBO3String = replacesBO3Strings[i].trim(); if(replacesBO3String.length() > 0) { this.replacesBO3Branches.add(replacesBO3String); } } } } //smoothHeightOffset = readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET).equals("HeightOffset") ? heightOffset : Integer.parseInt(readSettings(BO3Settings.SMOOTH_HEIGHT_OFFSET)); this.smoothHeightOffset = readSettings(BO4Settings.SMOOTH_HEIGHT_OFFSET); this.canSpawnOnWater = readSettings(BO4Settings.CANSPAWNONWATER); this.spawnOnWaterOnly = readSettings(BO4Settings.SPAWNONWATERONLY); this.spawnUnderWater = readSettings(BO4Settings.SPAWNUNDERWATER); this.spawnAtWaterLevel = readSettings(BO4Settings.SPAWNATWATERLEVEL); this.inheritBO3 = readSettings(BO4Settings.INHERITBO3); this.overrideChildSettings = readSettings(BO4Settings.OVERRIDECHILDSETTINGS); this.overrideParentHeight = readSettings(BO4Settings.OVERRIDEPARENTHEIGHT); this.smoothRadius = readSettings(BO4Settings.SMOOTHRADIUS); this.smoothStartTop = readSettings(BO4Settings.SMOOTHSTARTTOP); this.smoothStartWood = readSettings(BO4Settings.SMOOTHSTARTWOOD); this.smoothingSurfaceBlock = readSettings(BO4Settings.SMOOTHINGSURFACEBLOCK); this.smoothingGroundBlock = readSettings(BO4Settings.SMOOTHINGGROUNDBLOCK); // Make sure that the BO3 wont try to spawn below Y 0 because of the height offset if(this.heightOffset < 0 && this.minHeight < -this.heightOffset) { this.minHeight = -this.heightOffset; } this.inheritedBO3s = new ArrayList<String>(); this.inheritedBO3s.add(this.getName()); // TODO: Make this cleaner? if(this.inheritBO3 != null && this.inheritBO3.trim().length() > 0) { this.inheritedBO3s.add(this.inheritBO3); } this.author = readSettings(BO4Settings.AUTHOR); this.description = readSettings(BO4Settings.DESCRIPTION); this.settingsMode = readSettings(WorldStandardValues.SETTINGS_MODE_BO3); this.frequency = readSettings(BO4Settings.FREQUENCY); this.spawnHeight = readSettings(BO3Settings.SPAWN_HEIGHT); this.minHeight = readSettings(BO4Settings.MIN_HEIGHT); this.maxHeight = readSettings(BO4Settings.MAX_HEIGHT); this.maxHeight = this.maxHeight < this.minHeight ? this.minHeight : this.maxHeight; // Read the resources readResources(); // Merge inherited resources loadInheritedBO3(); } private void writeResources(SettingsWriterOTGPlus writer, List<BO4BlockFunction> blocksList, List<BO4BranchFunction> branchesList) throws IOException { writer.bigTitle("Blocks"); writer.comment("All the blocks used in the BO4 are listed here. Possible blocks:"); writer.comment("Block(x,y,z,id[.data][,nbtfile.nbt)"); writer.comment("RandomBlock(x,y,z,id[:data][,nbtfile.nbt],chance[,id[:data][,nbtfile.nbt],chance[,...]])"); writer.comment(" So RandomBlock(0,0,0,CHEST,chest.nbt,50,CHEST,anotherchest.nbt,100) will spawn a chest at"); writer.comment(" the BO4 origin, and give it a 50% chance to have the contents of chest.nbt, or, if that"); writer.comment(" fails, a 100% percent chance to have the contents of anotherchest.nbt."); writer.comment("MinecraftObject(x,y,z,name) (TODO: This may not work anymore and needs to be tested."); writer.comment(" Spawns an object in the Mojang NBT structure format. For example, "); writer.comment(" MinecraftObject(0,0,0," + DefaultStructurePart.IGLOO_BOTTOM.getPath() + ")"); writer.comment(" spawns the bottom part of an igloo."); ArrayList<BO4ModDataFunction> modDataList = new ArrayList<BO4ModDataFunction>(); ArrayList<BO4ParticleFunction> particlesList = new ArrayList<BO4ParticleFunction>(); ArrayList<BO4SpawnerFunction> spawnerList = new ArrayList<BO4SpawnerFunction>(); ArrayList<BO4EntityFunction> entitiesList = new ArrayList<BO4EntityFunction>(); // Re-read the raw data, if no data was supplied. Don't save any loaded data, since it has been processed/transformed. if(blocksList == null || branchesList == null || entitiesList == null) { blocksList = new ArrayList<BO4BlockFunction>(); branchesList = new ArrayList<BO4BranchFunction>(); for (CustomObjectConfigFunction<BO4Config> res : reader.getConfigFunctions(this, true)) { if (res.isValid()) { if(res instanceof BO4RandomBlockFunction) { blocksList.add((BO4RandomBlockFunction)res); } else if(res instanceof BO4BlockFunction) { blocksList.add((BO4BlockFunction)res); } else if (res instanceof BO4WeightedBranchFunction) { branchesList.add((BO4WeightedBranchFunction) res); } else if (res instanceof BO4BranchFunction) { branchesList.add((BO4BranchFunction) res); } else if (res instanceof BO4ModDataFunction) { modDataList.add((BO4ModDataFunction) res); } else if (res instanceof BO4SpawnerFunction) { spawnerList.add((BO4SpawnerFunction) res); } else if (res instanceof BO4ParticleFunction) { particlesList.add((BO4ParticleFunction) res); } else if (res instanceof BO4EntityFunction) { entitiesList.add((BO4EntityFunction) res); } } } } for(BO4BlockFunction block : blocksList) { writer.function(block); } writer.bigTitle("Branches"); writer.comment("Branches are child-BO4's that spawn if this BO4 is configured to spawn as a"); writer.comment("CustomStructure resource in a biome config. Branches can have branches,"); writer.comment("making complex structures possible. See the wiki for more details."); writer.comment(""); writer.comment("Regular Branches spawn each branch with an independent chance of spawning."); writer.comment("Branch(x,y,z,isRequiredBranch,branchName,rotation,chance,branchDepth[,anotherBranchName,rotation,chance,branchDepth[,...]][IndividualChance])"); writer.comment("branchName - name of the object to spawn."); writer.comment("rotation - NORTH, SOUTH, EAST or WEST."); writer.comment("IndividualChance - The chance each branch has to spawn, assumed to be 100 when left blank"); writer.comment("isRequiredBranch - If this is set to true then at least one of the branches in this BO4 must spawn at these x,y,z coordinates. If no branch can spawn there then this BO4 fails to spawn and its branch is rolled back."); writer.comment("isRequiredBranch:true branches must spawn or the current branch is rolled back entirely. This is useful for grouping BO4's that must spawn together, for instance a single room made of multiple BO4's/branches."); writer.comment("If all parts of the room are connected together via isRequiredBranch:true branches then either the entire room will spawns or no part of it will spawn."); writer.comment("*Note: When isRequiredBranch:true only one BO4 can be added per Branch() and it will automatically have a rarity of 100.0."); writer.comment("isRequiredBranch:false branches are used to make optional parts of structures, for instance the middle section of a tunnel that has a beginning, middle and end BO4/branch and can have a variable length by repeating the middle BO4/branch."); writer.comment("By making the start and end branches isRequiredBranch:true and the middle branch isRequiredbranch:false you can make it so that either:"); writer.comment("A. A tunnel spawns with at least a beginning and end branch"); writer.comment("B. A tunnel spawns with a beginning and end branch and as many middle branches as will fit in the available space."); writer.comment("C. No tunnel spawns at all because there wasn't enough space to spawn at least a beginning and end branch."); writer.comment("branchDepth - When creating a chain of branches that contains optional (isRequiredBranch:false) branches branch depth is configured for the first BO4 in the chain to determine the maximum length of the chain."); writer.comment("branchDepth - 1 is inherited by each isRequiredBranch:false branch in the chain. When branchDepth is zero isRequiredBranch:false branches cannot spawn and the chain ends. In the case of the tunnel this means the last middle branch would be"); writer.comment("rolled back and an IsRequiredBranch:true end branch could be spawned in its place to make sure the tunnel has a proper ending."); writer.comment("Instead of inheriting branchDepth - 1 from the parent branchDepth can be overridden by child branches if it is set higher than 0 (the default value)."); writer.comment("isRequiredBranch:true branches do inherit branchDepth and pass it on to their own branches, however they cannot be prevented from spawning by it and also don't subtract 1 from branchDepth when inheriting it."); writer.comment(""); writer.comment("Weighted Branches spawn branches with a dependent chance of spawning."); writer.comment("WeightedBranch(x,y,z,isRequiredBranch,branchName,rotation,chance,branchDepth[,anotherBranchName,rotation,chance,branchDepth[,...]][MaxChanceOutOf])"); writer.comment("*Note: isRequiredBranch must be set to false. It is not possible to use isRequiredBranch:true with WeightedBranch() since isRequired:true branches must spawn and automatically have a rarity of 100.0."); writer.comment("MaxChanceOutOf - The chance all branches have to spawn out of, assumed to be 100 when left blank"); for(BO4BranchFunction func : branchesList) { writer.function(func); } writer.bigTitle("Entities"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("An EntityFunction spawns an entity instead of a block. The entity is spawned only once when the BO4 is spawned."); writer.comment("Entities are persistent by default so they don't de-spawn when no player is near, they are only unloaded."); writer.comment("Usage: Entity(x,y,z,entityName,groupSize,NameTagOrNBTFileName) or Entity(x,y,z,mobName,groupSize)"); writer.comment("Use /otg entities to get a list of entities that can be used as entityName, this includes entities added by other mods and non-living entities."); writer.comment("NameTagOrNBTFileName can be either a nametag for the mob or an .txt file with nbt data (such as myentityinfo.txt)."); writer.comment("In the text file you can use the same mob spawning parameters used with the /summon command to equip the"); writer.comment("entity and give it custom attributes etc. You can copy the DATA part of a summon command including surrounding "); writer.comment("curly braces to a .txt file, for instance for: \"/summon Skeleton x y z {DATA}\""); for(BO4EntityFunction func : entitiesList) { writer.function(func); } writer.bigTitle("Particles"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("Creates an invisible particle spawner at the given location that spawns particles every x milliseconds."); writer.comment("Usage: Particle(x,y,z,particleName,interval,velocityX,velocityY,velocityZ)"); writer.comment("velocityX, velocityY and velocityZ are optional."); writer.comment("Only vanilla particle names can be used, for 1.11.2 these are;"); writer.comment("explode, largeexplode, hugeexplosion, fireworksSpark, bubble, splash, wake, suspended"); writer.comment("depthsuspend, crit, magicCrit, smoke, largesmoke, spell, instantSpell, mobSpell"); writer.comment("mobSpellAmbient, witchMagic, dripWater, dripLava, angryVillager, happyVillager"); writer.comment("townaura, note, portal, enchantmenttable, flame, lava, footstep, cloud, reddust"); writer.comment("snowballpoof, snowshovel, slime, heart, barrier, iconcrack, blockcrack, blockdust"); writer.comment("droplet, take, mobappearance, dragonbreath, endRod, damageIndicator, sweepAttack"); writer.comment("fallingdust, totem, spit."); writer.comment("velocityX,velocityY,velocityZ - Spawn the enemy with the given velocity. If this is not filled in then a small random velocity is applied."); for(BO4ParticleFunction func : particlesList) { writer.function(func); } writer.bigTitle("Spawners"); writer.comment("Forge only (this may have changed, check for updates)."); writer.comment("Creates an invisible entity spawner at the given location that spawns entities every x seconds."); writer.comment("Entities can only spawn if their spawn requirements are met (zombies/skeletons only spawn in the dark etc). Max entity count for the server is ignored, each spawner has its own maxCount setting."); writer.comment("Usage: Spawner(x,y,z,entityName,nbtFileName,groupSize,interval,spawnChance,maxCount,despawnTime,velocityX,velocityY,velocityZ,yaw,pitch)"); writer.comment("nbtFileName, despawnTime, velocityX, velocityY, velocityZ, yaw and pitch are optional"); writer.comment("Example Spawner(0, 0, 0, Villager, 1, 5, 100, 5) or Spawner(0, 0, 0, Villager, villager1.txt, 1, 5, 100, 5) or Spawner(0, 0, 0, Villager, 1, 5, 100, 5, 30, 1, 1, 1, 0, 0)"); writer.comment("entityName - Name of the entity to spawn, use /otg entities to get a list of entities that can be used as entityName, this includes entities added by other mods and non-living entities."); writer.comment("nbtFileName - A .txt file with nbt data (such as myentityinfo.txt)."); writer.comment("In the text file you can use the same mob spawning parameters used with the /summon command to equip the"); writer.comment("entity and give it custom attributes etc. You can copy the DATA part of a summon command including surrounding "); writer.comment("curly braces to a .txt file, for instance for: \"/summon Skeleton x y z {DATA}\""); writer.comment("groupSize - Number of entities that should spawn for each successful spawn attempt."); writer.comment("interval - Time in seconds between each spawn attempt."); writer.comment("spawnChance - For each spawn attempt, the chance between 0-100 that the spawn attempt will succeed."); writer.comment("maxCount - The maximum amount of this kind of entity that can exist within 32 blocks. If there are already maxCount or more entities of this type in a 32 radius this spawner will not spawn anything."); writer.comment("despawnTime - After despawnTime seconds, if there is no player within 32 blocks of the entity it will despawn.."); writer.comment("velocityX,velocityY,velocityZ,yaw,pitch - Spawn the enemy with the given velocity and angle, handy for making traps and launchers (shooting arrows and fireballs etc)."); for(BO4SpawnerFunction func : spawnerList) { writer.function(func); } // ModData writer.bigTitle("ModData"); writer.comment("Forge only."); writer.comment("Use the ModData() tag to include data that other mods can use"); writer.comment("Mod makers can use ModData and the /otg GetModData command to test IMC communications between OTG"); writer.comment("and their mod."); writer.comment("Normal users can use it to spawn some mobs and blocks on command."); writer.comment("ModData(x,y,z,\"ModName\", \"MyModDataAsText\""); writer.comment("Example: ModData(x,y,z,MyCystomNPCMod,SpawnBobHere/WithAPotato/And50Health)"); writer.comment("Try not to use exotic/reserved characters, like brackets and comma's etc, this stuff isn't fool-proof."); writer.comment("Also, use this only to store IDs/object names etc for your mod, DO NOT include things like character dialogue,"); writer.comment("messages on signs, loot lists etc in this file. As much as possible just store id's/names here and store all the data related to those id's/names in your own mod."); writer.comment("OTG has some built in ModData commands for basic mob and block spawning."); writer.comment("These are mostly just a demonstration for mod makers to show how ModData."); writer.comment("can be used by other mods."); writer.comment("For mob spawning in OTG use: ModData(x,y,z,OTG,mob/MobType/Count/Persistent/Name)"); writer.comment("mob: Makes OTG recognise this as a mob spawning command."); writer.comment("MobType: Lower-case, no spaces. Any vanilla mob like dragon, skeleton, wither, villager etc"); writer.comment("Count: The number of mobs to spawn"); writer.comment("Persistent (true/false): Should the mobs never de-spawn? If set to true the mob will get a"); writer.comment("name-tag ingame so you can recognise it."); writer.comment("Name: A name-tag for the monster/npc."); writer.comment("Example: ModData(0,0,0,OTG,villager/1/true/Bob)"); writer.comment("To spawn blocks using ModData use: ModData(x,y,z,OTG,block/material)"); writer.comment("block: Makes OTG recognise this as a block spawning command."); writer.comment("material: id or text, custom blocks can be added using ModName:MaterialName."); writer.comment("To send all ModData within a radius in chunks around the player to the specified mod"); writer.comment("use this console command: /otg GetModData ModName Radius"); writer.comment("ModName: name of the mod, for OTG commands use OTG "); writer.comment("Radius (optional): Radius in chunks around the player."); for(BO4ModDataFunction func : modDataList) { writer.function(func); } } int bo4DataVersion = 1; public void writeToStream(DataOutput stream) throws IOException { stream.writeInt(this.bo4DataVersion); stream.writeInt(this.minimumSizeTop); stream.writeInt(this.minimumSizeBottom); stream.writeInt(this.minimumSizeLeft); stream.writeInt(this.minimumSizeRight); stream.writeInt(this.minX); stream.writeInt(this.maxX); stream.writeInt(this.minY); stream.writeInt(this.maxY); stream.writeInt(this.minZ); stream.writeInt(this.maxZ); StreamHelper.writeStringToStream(stream, this.author); StreamHelper.writeStringToStream(stream, this.description); StreamHelper.writeStringToStream(stream, this.settingsMode.name()); stream.writeInt(this.frequency); StreamHelper.writeStringToStream(stream, this.spawnHeight.name()); stream.writeInt(this.minHeight); stream.writeInt(this.maxHeight); stream.writeShort(this.inheritedBO3s.size()); for(String inheritedBO3 : this.inheritedBO3s) { StreamHelper.writeStringToStream(stream, inheritedBO3); } StreamHelper.writeStringToStream(stream, this.inheritBO3); StreamHelper.writeStringToStream(stream, this.inheritBO3Rotation.name()); stream.writeBoolean(this.overrideChildSettings); stream.writeBoolean(this.overrideParentHeight); stream.writeBoolean(this.canOverride); stream.writeInt(this.branchFrequency); StreamHelper.writeStringToStream(stream, this.branchFrequencyGroup); stream.writeBoolean(this.mustBeBelowOther); stream.writeBoolean(this.mustBeInsideWorldBorders); StreamHelper.writeStringToStream(stream, this.mustBeInside); StreamHelper.writeStringToStream(stream, this.cannotBeInside); StreamHelper.writeStringToStream(stream, this.replacesBO3); stream.writeBoolean(this.canSpawnOnWater); stream.writeBoolean(this.spawnOnWaterOnly); stream.writeBoolean(this.spawnUnderWater); stream.writeBoolean(this.spawnAtWaterLevel); stream.writeInt(this.heightOffset); stream.writeBoolean(this.removeAir); StreamHelper.writeStringToStream(stream, this.replaceAbove); StreamHelper.writeStringToStream(stream, this.replaceBelow); stream.writeBoolean(this.replaceWithBiomeBlocks); StreamHelper.writeStringToStream(stream, this.replaceWithGroundBlock); StreamHelper.writeStringToStream(stream, this.replaceWithSurfaceBlock); stream.writeInt(this.smoothRadius); stream.writeInt(this.smoothHeightOffset); stream.writeBoolean(this.smoothStartTop); stream.writeBoolean(this.smoothStartWood); StreamHelper.writeStringToStream(stream, this.smoothingSurfaceBlock); StreamHelper.writeStringToStream(stream, this.smoothingGroundBlock); StreamHelper.writeStringToStream(stream, this.bo3Group); stream.writeBoolean(this.isSpawnPoint); stream.writeBoolean(this.isCollidable); ArrayList<LocalMaterialData> materials = new ArrayList<LocalMaterialData>(); ArrayList<String> metaDataNames = new ArrayList<String>(); int randomBlockCount = 0; int nonRandomBlockCount = 0; BO4BlockFunction[] blocks = getBlocks(); for(BO4BlockFunction block : blocks) { if(block instanceof BO4RandomBlockFunction) { randomBlockCount++; for(LocalMaterialData material : ((BO4RandomBlockFunction)block).blocks) { if(!materials.contains(material)) { materials.add(material); } } } else { nonRandomBlockCount++; } if(block.material != null && !materials.contains(block.material)) { materials.add(block.material); } if(block.metaDataName != null && !metaDataNames.contains(block.metaDataName)) { metaDataNames.add(block.metaDataName); } } String[] metaDataNamesArr = metaDataNames.toArray(new String[metaDataNames.size()]); LocalMaterialData[] blocksArr = materials.toArray(new LocalMaterialData[materials.size()]); stream.writeShort(metaDataNamesArr.length); for(int i = 0; i < metaDataNamesArr.length; i++) { StreamHelper.writeStringToStream(stream, metaDataNamesArr[i]); } stream.writeShort(blocksArr.length); for(int i = 0; i < blocksArr.length; i++) { StreamHelper.writeStringToStream(stream, blocksArr[i].getName()); } // TODO: This assumes that loading blocks in a different order won't matter, which may not be true? // Anything that spawns on top, entities/spawners etc, should be spawned last tho, so shouldn't be a problem? stream.writeInt(nonRandomBlockCount); int nonRandomBlockIndex = 0; ArrayList<BO4BlockFunction> blocksInColumn; if(nonRandomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { blocksInColumn = new ArrayList<BO4BlockFunction>(); for(BO4BlockFunction blockFunction : blocks) { if(!(blockFunction instanceof BO4RandomBlockFunction)) { if(blockFunction.x == x && blockFunction.z == z) { blocksInColumn.add(blockFunction); } } } stream.writeShort(blocksInColumn.size()); if(blocksInColumn.size() > 0) { for(BO4BlockFunction blockFunction : blocksInColumn) { blockFunction.writeToStream(metaDataNamesArr, blocksArr, stream); nonRandomBlockIndex++; } } if(nonRandomBlockIndex == nonRandomBlockCount) { break; } } if(nonRandomBlockIndex == nonRandomBlockCount) { break; } } } stream.writeInt(randomBlockCount); int randomBlockIndex = 0; if(randomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { blocksInColumn = new ArrayList<BO4BlockFunction>(); for(BO4BlockFunction blockFunction : blocks) { if(blockFunction instanceof BO4RandomBlockFunction) { if(blockFunction.x == x && blockFunction.z == z) { blocksInColumn.add(blockFunction); } } } stream.writeShort(blocksInColumn.size()); if(blocksInColumn.size() > 0) { for(BO4BlockFunction blockFunction : blocksInColumn) { blockFunction.writeToStream(metaDataNamesArr, blocksArr, stream); randomBlockIndex++; } } if(randomBlockIndex == randomBlockCount) { break; } } if(randomBlockIndex == randomBlockCount) { break; } } } stream.writeInt(this.branchesOTGPlus.length); for(BO4BranchFunction func : Arrays.asList(this.branchesOTGPlus)) { if(func instanceof BO4WeightedBranchFunction) { stream.writeBoolean(true); // false For BO4BranchFunction, true for BO4WeightedBranchFunction } else { stream.writeBoolean(false); // false For BO4BranchFunction, true for BO4WeightedBranchFunction } func.writeToStream(stream); } stream.writeInt(this.entityDataOTGPlus.length); for(BO4EntityFunction func : Arrays.asList(this.entityDataOTGPlus)) { func.writeToStream(stream); } stream.writeInt(this.particleDataOTGPlus.length); for(BO4ParticleFunction func : Arrays.asList(this.particleDataOTGPlus)) { func.writeToStream(stream); } stream.writeInt(this.spawnerDataOTGPlus.length); for(BO4SpawnerFunction func : Arrays.asList(this.spawnerDataOTGPlus)) { func.writeToStream(stream); } stream.writeInt(this.modDataOTGPlus.length); for(BO4ModDataFunction func : Arrays.asList(this.modDataOTGPlus)) { func.writeToStream(stream); } } public BO4Config readFromBO4DataFile() { FileInputStream fis; try { fis = new FileInputStream(this.reader.getFile()); try { ByteBuffer buffer = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fis.getChannel().size()); byte[] compressedBytes = new byte[(int) fis.getChannel().size()]; buffer.get(compressedBytes); try { byte[] decompressedBytes = com.pg85.otg.util.CompressionUtils.decompress(compressedBytes); buffer = ByteBuffer.wrap(decompressedBytes); } catch (DataFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //buffer.get(data, 0, remaining); // do something with data this.inheritedBO3Loaded = true; int bo4DataVersion = buffer.getInt(); this.minimumSizeTop = buffer.getInt(); this.minimumSizeBottom = buffer.getInt(); this.minimumSizeLeft = buffer.getInt(); this.minimumSizeRight = buffer.getInt(); this.minX = buffer.getInt(); this.maxX = buffer.getInt(); this.minY = buffer.getInt(); this.maxY = buffer.getInt(); this.minZ = buffer.getInt(); this.maxZ = buffer.getInt(); this.author = StreamHelper.readStringFromBuffer(buffer); this.description = StreamHelper.readStringFromBuffer(buffer); this.settingsMode = ConfigMode.valueOf(StreamHelper.readStringFromBuffer(buffer)); this.frequency = buffer.getInt(); this.spawnHeight = SpawnHeightEnum.valueOf(StreamHelper.readStringFromBuffer(buffer)); this.minHeight = buffer.getInt(); this.maxHeight = buffer.getInt(); short inheritedBO3sSize = buffer.getShort(); this.inheritedBO3s = new ArrayList<String>(); for(int i = 0; i < inheritedBO3sSize; i++) { this.inheritedBO3s.add(StreamHelper.readStringFromBuffer(buffer)); } this.inheritBO3 = StreamHelper.readStringFromBuffer(buffer); this.inheritBO3Rotation = Rotation.valueOf(StreamHelper.readStringFromBuffer(buffer)); this.overrideChildSettings = buffer.get() != 0; this.overrideParentHeight = buffer.get() != 0; this.canOverride = buffer.get() != 0; this.branchFrequency = buffer.getInt(); this.branchFrequencyGroup = StreamHelper.readStringFromBuffer(buffer); this.mustBeBelowOther = buffer.get() != 0; this.mustBeInsideWorldBorders = buffer.get() != 0; this.mustBeInside = StreamHelper.readStringFromBuffer(buffer); this.cannotBeInside = StreamHelper.readStringFromBuffer(buffer); this.replacesBO3 = StreamHelper.readStringFromBuffer(buffer); this.canSpawnOnWater = buffer.get() != 0; this.spawnOnWaterOnly = buffer.get() != 0; this.spawnUnderWater = buffer.get() != 0; this.spawnAtWaterLevel = buffer.get() != 0; this.heightOffset = buffer.getInt(); this.removeAir = buffer.get() != 0; this.replaceAbove = StreamHelper.readStringFromBuffer(buffer); this.replaceBelow = StreamHelper.readStringFromBuffer(buffer); this.replaceWithBiomeBlocks = buffer.get() != 0; this.replaceWithGroundBlock = StreamHelper.readStringFromBuffer(buffer); this.replaceWithSurfaceBlock = StreamHelper.readStringFromBuffer(buffer); this.smoothRadius = buffer.getInt(); this.smoothHeightOffset = buffer.getInt(); this.smoothStartTop = buffer.get() != 0; this.smoothStartWood = buffer.get() != 0; this.smoothingSurfaceBlock = StreamHelper.readStringFromBuffer(buffer); this.smoothingGroundBlock = StreamHelper.readStringFromBuffer(buffer); this.bo3Group = StreamHelper.readStringFromBuffer(buffer); this.isSpawnPoint = buffer.get() != 0; this.isCollidable = buffer.get() != 0; this.branchFrequencyGroups = new HashMap<String, Integer>(); if(this.branchFrequencyGroup != null && this.branchFrequencyGroup.trim().length() > 0) { String[] groupStrings = this.branchFrequencyGroup.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.branchFrequencyGroups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.bo3Groups = new HashMap<String, Integer>(); if(this.bo3Group != null && this.bo3Group.trim().length() > 0) { String[] groupStrings = this.bo3Group.split(","); if(groupStrings != null && groupStrings.length > 0) { for(int i = 0; i < groupStrings.length; i++) { String[] groupString = groupStrings[i].trim().length() > 0 ? groupStrings[i].split(":") : null; if(groupString != null && groupString.length == 2) { this.bo3Groups.put(groupString[0].trim(), Integer.parseInt(groupString[1].trim())); } } } } this.mustBeInsideBranches = new ArrayList<String>(); if(this.mustBeInside != null && this.mustBeInside.trim().length() > 0) { String[] mustBeInsideStrings = this.mustBeInside.split(","); if(mustBeInsideStrings != null && mustBeInsideStrings.length > 0) { for(int i = 0; i < mustBeInsideStrings.length; i++) { String mustBeInsideString = mustBeInsideStrings[i].trim(); if(mustBeInsideString.length() > 0) { this.mustBeInsideBranches.add(mustBeInsideString); } } } } this.cannotBeInsideBranches = new ArrayList<String>(); if(this.cannotBeInside != null && this.cannotBeInside.trim().length() > 0) { String[] cannotBeInsideStrings = this.cannotBeInside.split(","); if(cannotBeInsideStrings != null && cannotBeInsideStrings.length > 0) { for(int i = 0; i < cannotBeInsideStrings.length; i++) { String cannotBeInsideString = cannotBeInsideStrings[i].trim(); if(cannotBeInsideString.length() > 0) { this.cannotBeInsideBranches.add(cannotBeInsideString); } } } } this.replacesBO3Branches = new ArrayList<String>(); if(this.replacesBO3 != null && this.replacesBO3.trim().length() > 0) { String[] replacesBO3Strings = replacesBO3.split(","); if(replacesBO3Strings != null && replacesBO3Strings.length > 0) { for(int i = 0; i < replacesBO3Strings.length; i++) { String replacesBO3String = replacesBO3Strings[i].trim(); if(replacesBO3String.length() > 0) { this.replacesBO3Branches.add(replacesBO3String); } } } } // Reconstruct blocks short metaDataNamesArrLength = buffer.getShort(); String[] metaDataNames = new String[metaDataNamesArrLength]; for(int i = 0; i < metaDataNamesArrLength; i++) { metaDataNames[i] = StreamHelper.readStringFromBuffer(buffer); } short blocksArrArrLength = buffer.getShort(); LocalMaterialData[] blocksArr = new LocalMaterialData[blocksArrArrLength]; for(int i = 0; i < blocksArrArrLength; i++) { String materialName = StreamHelper.readStringFromBuffer(buffer); try { blocksArr[i] = MaterialHelper.readMaterial(materialName); } catch (InvalidConfigException e) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "Could not read material \"" + materialName + "\" for BO4 \"" + this.getName() + "\""); e.printStackTrace(); } } } short[][] columnSizes = new short[xSize][zSize]; // TODO: This assumes that loading blocks in a different order won't matter, which may not be true? // Anything that spawns on top, entities/spawners etc, should be spawned last tho, so shouldn't be a problem? int nonRandomBlockCount = buffer.getInt(); int nonRandomBlockIndex = 0; ArrayList<BO4BlockFunction> nonRandomBlocks = new ArrayList<BO4BlockFunction>(); if(nonRandomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { short blocksInColumnSize = buffer.getShort(); for(int j = 0; j < blocksInColumnSize; j++) { columnSizes[x][z]++; nonRandomBlocks.add(BO4BlockFunction.fromStream(x, z, metaDataNames, blocksArr, this, buffer)); nonRandomBlockIndex++; if(nonRandomBlockCount == nonRandomBlockIndex) { break; } } if(nonRandomBlockCount == nonRandomBlockIndex) { break; } } if(nonRandomBlockCount == nonRandomBlockIndex) { break; } } } int randomBlockCount = buffer.getInt(); int randomBlockIndex = 0; ArrayList<BO4RandomBlockFunction> randomBlocks = new ArrayList<BO4RandomBlockFunction>(); if(randomBlockCount > 0) { for(int x = this.getminX(); x < xSize; x++) { for(int z = this.getminZ(); z < zSize; z++) { short blocksInColumnSize = buffer.getShort(); for(int j = 0; j < blocksInColumnSize; j++) { columnSizes[x][z]++; randomBlocks.add(BO4RandomBlockFunction.fromStream(x, z, metaDataNames, blocksArr, this, buffer)); randomBlockIndex++; if(randomBlockCount == randomBlockIndex) { break; } } if(randomBlockCount == randomBlockIndex) { break; } } if(randomBlockCount == randomBlockIndex) { break; } } } ArrayList<BO4BlockFunction> newBlocks = new ArrayList<BO4BlockFunction>(); newBlocks.addAll(nonRandomBlocks); newBlocks.addAll(randomBlocks); loadBlockArrays(newBlocks, columnSizes); int branchesOTGPlusLength = buffer.getInt(); boolean branchType; BO4BranchFunction branch; this.branchesOTGPlus = new BO4BranchFunction[branchesOTGPlusLength]; for(int i = 0; i < branchesOTGPlusLength; i++) { branchType = buffer.get() != 0; if(branchType) { branch = BO4WeightedBranchFunction.fromStream(this, buffer); } else { branch = BO4BranchFunction.fromStream(this, buffer); } this.branchesOTGPlus[i] = branch; } int entityDataOTGPlusLength = buffer.getInt(); this.entityDataOTGPlus = new BO4EntityFunction[entityDataOTGPlusLength]; for(int i = 0; i < entityDataOTGPlusLength; i++) { this.entityDataOTGPlus[i] = BO4EntityFunction.fromStream(this, buffer); } int particleDataOTGPlusLength = buffer.getInt(); this.particleDataOTGPlus = new BO4ParticleFunction[particleDataOTGPlusLength]; for(int i = 0; i < particleDataOTGPlusLength; i++) { this.particleDataOTGPlus[i] = BO4ParticleFunction.fromStream(this, buffer); } int spawnerDataOTGPlusLength = buffer.getInt(); this.spawnerDataOTGPlus = new BO4SpawnerFunction[spawnerDataOTGPlusLength]; for(int i = 0; i < spawnerDataOTGPlusLength; i++) { this.spawnerDataOTGPlus[i] = BO4SpawnerFunction.fromStream(this, buffer); } int modDataOTGPlusLength = buffer.getInt(); this.modDataOTGPlus = new BO4ModDataFunction[modDataOTGPlusLength]; for(int i = 0; i < modDataOTGPlusLength; i++) { this.modDataOTGPlus[i] = BO4ModDataFunction.fromStream(this, buffer); } } catch (IOException e1) { e1.printStackTrace(); } // when finished try { fis.getChannel().close(); } catch (IOException e) { e.printStackTrace(); } try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e2) { e2.printStackTrace(); } return this; } private void loadBlockArrays(ArrayList<BO4BlockFunction> newBlocks, short[][] columnSizes) { // Store blocks in arrays instead of as BO4BlockFunctions, // since that gives way too much overhead memory wise. // We may have tens of millions of blocks, java doesn't handle lots of small classes well. this.blocks = new short[xSize][zSize][]; this.blocksMaterial = new LocalMaterialData[newBlocks.size()]; this.blocksMetaDataName = new String[newBlocks.size()]; this.blocksMetaDataTag = new NamedBinaryTag[newBlocks.size()]; this.randomBlocksBlocks = new LocalMaterialData[newBlocks.size()][]; this.randomBlocksBlockChances = new byte[newBlocks.size()][]; this.randomBlocksMetaDataNames = new String[newBlocks.size()][]; this.randomBlocksMetaDataTags = new NamedBinaryTag[newBlocks.size()][]; this.randomBlocksBlockCount = new byte[newBlocks.size()]; BO4BlockFunction block; short[][] columnBlockIndex = new short[xSize][zSize]; for(int x = 0; x < xSize; x++) { for(int z = 0; z < zSize; z++) { if(this.blocks[x][z] == null) { this.blocks[x ][z] = new short[columnSizes[x][z]]; } } } for(int i = 0; i < newBlocks.size(); i++) { block = newBlocks.get(i); this.blocks[block.x][block.z][columnBlockIndex[block.x][block.z]] = (short) block.y; int blockIndex = columnBlockIndex[block.x][block.z] + getColumnBlockIndex(columnSizes, block.x, block.z); this.blocksMaterial[blockIndex] = block.material; this.blocksMetaDataName[blockIndex] = block.metaDataName; this.blocksMetaDataTag[blockIndex] = block.metaDataTag; if(block instanceof BO4RandomBlockFunction) { this.randomBlocksBlocks[blockIndex] = ((BO4RandomBlockFunction)block).blocks; this.randomBlocksBlockChances[blockIndex] = ((BO4RandomBlockFunction)block).blockChances; this.randomBlocksMetaDataNames[blockIndex] = ((BO4RandomBlockFunction)block).metaDataNames; this.randomBlocksMetaDataTags[blockIndex] = ((BO4RandomBlockFunction)block).metaDataTags; this.randomBlocksBlockCount[blockIndex] = ((BO4RandomBlockFunction)block).blockCount; } columnBlockIndex[block.x][block.z]++; } } private int getColumnBlockIndex(short[][] columnSizes, int columnX, int columnZ) { int blockIndex = 0; for(int x = 0; x < 16; x++) { for(int z = 0; z < 16; z++) { if(columnX == x && columnZ == z) { return blockIndex; } blockIndex += columnSizes[x][z]; } } return blockIndex; } @Override protected void correctSettings() { } @Override protected void renameOldSettings() { // Stub method - there are no old setting to convert yet (: } public boolean isCollidable() { return isCollidable; } }
9.0_r6: BO4Data blocks not cached - BO4Data blocks are no longer cached, they are loaded from file only when spawning a structure or calculating its height map.
common/src/main/java/com/pg85/otg/customobjects/bo4/BO4Config.java
9.0_r6: BO4Data blocks not cached
<ide><path>ommon/src/main/java/com/pg85/otg/customobjects/bo4/BO4Config.java <ide> import com.pg85.otg.customobjects.structures.bo4.BO4CustomStructureCoordinate; <ide> import com.pg85.otg.customobjects.bo3.BO3Settings; <ide> import com.pg85.otg.customobjects.bo3.BO3Settings.SpawnHeightEnum; <del>import com.pg85.otg.customobjects.bo3.bo3function.BO3BlockFunction; <del>import com.pg85.otg.customobjects.bo3.bo3function.BO3BranchFunction; <del>import com.pg85.otg.customobjects.bo3.bo3function.BO3RandomBlockFunction; <ide> import com.pg85.otg.exception.InvalidConfigException; <ide> import com.pg85.otg.logging.LogMarker; <del>import com.pg85.otg.util.ChunkCoordinate; <ide> import com.pg85.otg.util.bo3.NamedBinaryTag; <ide> import com.pg85.otg.util.bo3.Rotation; <del>import com.pg85.otg.util.helpers.MaterialHelper; <ide> import com.pg85.otg.util.helpers.StreamHelper; <del>import com.pg85.otg.util.minecraft.defaults.DefaultMaterial; <add>import com.pg85.otg.util.materials.MaterialHelper; <ide> import com.pg85.otg.util.minecraft.defaults.DefaultStructurePart; <ide> <del>import java.io.DataInputStream; <ide> import java.io.DataOutput; <ide> import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.io.FileNotFoundException; <ide> import java.io.IOException; <del>import java.io.InputStreamReader; <ide> import java.nio.ByteBuffer; <del>import java.nio.MappedByteBuffer; <ide> import java.nio.channels.FileChannel; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.HashMap; <ide> import java.util.List; <del>import java.util.Map; <ide> import java.util.zip.DataFormatException; <ide> <ide> public class BO4Config extends CustomObjectConfigFile <ide> private BO4EntityFunction[] entityDataOTGPlus; <ide> <ide> private boolean isCollidable = false; <add> private boolean isBO4Data = false; <ide> <ide> /** <ide> * Creates a BO3Config from a file. <ide> //OTG.log(LogMarker.INFO, ".BO4 loaded in: " + timeTaken + " " + this.getName() + ".BO4"); <ide> } else { <ide> //long startTime = System.currentTimeMillis(); <del> this.readFromBO4DataFile(); <add> this.readFromBO4DataFile(false); <ide> //BO4BlocksLoadedFromBO4Data++; <ide> //long timeTaken = (System.currentTimeMillis() - startTime); <ide> //accumulatedTime2 += timeTaken; <ide> <ide> public BO4BlockFunction[][] getSmoothingHeightMap(BO4 start) <ide> { <add> return getSmoothingHeightMap(start, true); <add> } <add> <add> private BO4BlockFunction[][] getSmoothingHeightMap(BO4 start, boolean fromFile) <add> { <add> // TODO: Caching the heightmap will mean this BO4 can only be used with 1 master BO4, <add> // it won't pick up smoothing area settings if it is also used in another structure. <ide> if(this.heightMap == null) <ide> { <add> if(this.isBO4Data && fromFile) <add> { <add> BO4Config bo4Config = null; <add> try <add> { <add> bo4Config = new BO4Config(this.reader, false); <add> } <add> catch (InvalidConfigException e) <add> { <add> e.printStackTrace(); <add> } <add> if(bo4Config != null) <add> { <add> bo4Config.readFromBO4DataFile(true); <add> this.heightMap = bo4Config.getSmoothingHeightMap(start, false); <add> return this.heightMap; <add> } <add> } <add> <ide> this.heightMap = new BO4BlockFunction[16][16]; <ide> <ide> // make heightmap containing the highest or lowest blocks in this chunk <ide> <ide> public BO4BlockFunction[] getBlocks() <ide> { <add> return getBlocks(true); <add> } <add> <add> private BO4BlockFunction[] getBlocks(boolean fromFile) <add> { <add> if(fromFile && this.isBO4Data) <add> { <add> BO4Config bo4Config = null; <add> try <add> { <add> bo4Config = new BO4Config(this.reader, false); <add> } <add> catch (InvalidConfigException e) <add> { <add> e.printStackTrace(); <add> } <add> if(bo4Config != null) <add> { <add> bo4Config.readFromBO4DataFile(true); <add> return bo4Config.getBlocks(false); <add> } <add> } <add> <ide> BO4BlockFunction[] blocksOTGPlus = new BO4BlockFunction[this.blocksMaterial.length]; <ide> <ide> BO4BlockFunction block; <ide> tempBlocksList.add((BO4RandomBlockFunction)res); <ide> columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; <ide> } else { <del> if(!this.removeAir || !((BO4BlockFunction)res).material.toDefaultMaterial().equals(DefaultMaterial.AIR)) <add> if(!this.removeAir || !((BO4BlockFunction)res).material.isAir()) <ide> { <ide> tempBlocksList.add((BO4BlockFunction)res); <ide> block = (BO4BlockFunction)res; <ide> try <ide> { <del> columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; <add> columnSizes[block.x + (xSize / 2)][block.z + (zSize / 2) - 1]++; <ide> } <ide> catch(ArrayIndexOutOfBoundsException ex) <ide> { <ide> } <ide> } <ide> <del> public BO4Config readFromBO4DataFile() <add> public BO4Config readFromBO4DataFile(boolean getBlocks) <ide> { <ide> FileInputStream fis; <ide> try { <ide> //buffer.get(data, 0, remaining); <ide> // do something with data <ide> <add> this.isBO4Data = true; <ide> this.inheritedBO3Loaded = true; <ide> int bo4DataVersion = buffer.getInt(); <ide> this.minimumSizeTop = buffer.getInt(); <ide> newBlocks.addAll(nonRandomBlocks); <ide> newBlocks.addAll(randomBlocks); <ide> <del> loadBlockArrays(newBlocks, columnSizes); <add> if(getBlocks) <add> { <add> loadBlockArrays(newBlocks, columnSizes); <add> } <ide> <ide> int branchesOTGPlusLength = buffer.getInt(); <ide> boolean branchType;
Java
apache-2.0
108e158aa0e9886c0d739c40f1eddbb76cfe4176
0
jswudi/alluxio,Alluxio/alluxio,Alluxio/alluxio,jsimsa/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,apc999/alluxio,apc999/alluxio,maboelhassan/alluxio,WilliamZapata/alluxio,riversand963/alluxio,maobaolong/alluxio,yuluo-ding/alluxio,madanadit/alluxio,jswudi/alluxio,calvinjia/tachyon,wwjiang007/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,apc999/alluxio,WilliamZapata/alluxio,aaudiber/alluxio,apc999/alluxio,bf8086/alluxio,Alluxio/alluxio,aaudiber/alluxio,madanadit/alluxio,bf8086/alluxio,WilliamZapata/alluxio,wwjiang007/alluxio,madanadit/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,madanadit/alluxio,jsimsa/alluxio,uronce-cc/alluxio,Reidddddd/mo-alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,PasaLab/tachyon,Reidddddd/mo-alluxio,jswudi/alluxio,calvinjia/tachyon,PasaLab/tachyon,maobaolong/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,apc999/alluxio,apc999/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,PasaLab/tachyon,ChangerYoung/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,madanadit/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,riversand963/alluxio,aaudiber/alluxio,uronce-cc/alluxio,ShailShah/alluxio,riversand963/alluxio,Alluxio/alluxio,aaudiber/alluxio,maobaolong/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,maobaolong/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,Alluxio/alluxio,Alluxio/alluxio,calvinjia/tachyon,bf8086/alluxio,maobaolong/alluxio,madanadit/alluxio,Reidddddd/alluxio,PasaLab/tachyon,calvinjia/tachyon,madanadit/alluxio,aaudiber/alluxio,riversand963/alluxio,bf8086/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,jswudi/alluxio,Reidddddd/alluxio,Alluxio/alluxio,jsimsa/alluxio,Reidddddd/alluxio,WilliamZapata/alluxio,jsimsa/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,maboelhassan/alluxio,PasaLab/tachyon,ShailShah/alluxio,ChangerYoung/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,PasaLab/tachyon,aaudiber/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,wwjiang007/alluxio,riversand963/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,WilliamZapata/alluxio,ShailShah/alluxio,jsimsa/alluxio,wwjiang007/alluxio,maobaolong/alluxio,calvinjia/tachyon,uronce-cc/alluxio,ShailShah/alluxio,Reidddddd/mo-alluxio,maobaolong/alluxio,jswudi/alluxio,apc999/alluxio,maboelhassan/alluxio,wwjiang007/alluxio,riversand963/alluxio,uronce-cc/alluxio,Alluxio/alluxio,maboelhassan/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,jsimsa/alluxio,bf8086/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,bf8086/alluxio,yuluo-ding/alluxio
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.journal; import alluxio.util.io.PathUtils; /** * Interface for factories which create {@link Journal}s. */ public interface JournalFactory { /** * @param directory the directory for the journal * @return a journal based on the given directory */ Journal get(String directory); /** * A factory which creates read-write journals. */ final class ReadWrite implements JournalFactory { private final String mBaseDirectory; /** * Creates a journal factory with the specified directory as the root. When journals are * created, their paths are appended to the base path, e.g. * *<pre> * baseDirectory * journalDirectory1 * journalDirectory2 *</pre> * * Journals created by this factory support both reading and writing. * * @param baseDirectory the base directory for journals created by this factory */ public ReadWrite(String baseDirectory) { mBaseDirectory = baseDirectory; } @Override public Journal get(String directory) { return new ReadWriteJournal(PathUtils.concatPath(mBaseDirectory, directory)); } } /** * A factory which creates read-only journals. */ final class ReadOnly implements JournalFactory { private final String mBaseDirectory; /** * Creates a journal factory with the specified directory as the root. When journals are * created, their paths are appended to the base path, e.g. * *<pre> * baseDirectory * journalDirectory1 * journalDirectory2 *</pre> * * Journals created by this factory only support reads. * * @param baseDirectory the base directory for journals created by this factory */ public ReadOnly(String baseDirectory) { mBaseDirectory = baseDirectory; } @Override public Journal get(String directory) { return new ReadOnlyJournal(PathUtils.concatPath(mBaseDirectory, directory)); } } }
core/server/src/main/java/alluxio/master/journal/JournalFactory.java
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.journal; import alluxio.util.io.PathUtils; /** * Interface for factories which create {@link Journal}s. */ public interface JournalFactory { /** * @param directory the directory for the journal * @return a journal based on the given directory */ Journal get(String directory); /** * A factory which creates read-write journals. */ final class ReadWrite implements JournalFactory{ private final String mBaseDirectory; /** * Creates a journal factory with the specified directory as the root. When journals are * created, their paths are appended to the base path, e.g. * *<pre> * baseDirectory * journalDirectory1 * journalDirectory2 *</pre> * * Journals created by this factory support both reading and writing. * * @param baseDirectory the base directory for journals created by this factory */ public ReadWrite(String baseDirectory) { mBaseDirectory = baseDirectory; } @Override public Journal get(String directory) { return new ReadWriteJournal(PathUtils.concatPath(mBaseDirectory, directory)); } } /** * A factory which creates read-only journals. */ final class ReadOnly implements JournalFactory { private final String mBaseDirectory; /** * Creates a journal factory with the specified directory as the root. When journals are * created, their paths are appended to the base path, e.g. * *<pre> * baseDirectory * journalDirectory1 * journalDirectory2 *</pre> * * Journals created by this factory only support reads. * * @param baseDirectory the base directory for journals created by this factory */ public ReadOnly(String baseDirectory) { mBaseDirectory = baseDirectory; } @Override public Journal get(String directory) { return new ReadOnlyJournal(PathUtils.concatPath(mBaseDirectory, directory)); } } }
Fix brace
core/server/src/main/java/alluxio/master/journal/JournalFactory.java
Fix brace
<ide><path>ore/server/src/main/java/alluxio/master/journal/JournalFactory.java <ide> /** <ide> * A factory which creates read-write journals. <ide> */ <del> final class ReadWrite implements JournalFactory{ <add> final class ReadWrite implements JournalFactory { <ide> private final String mBaseDirectory; <ide> <ide> /**
Java
apache-2.0
a86ea829a114cac83efcce969b69bd520cd01d18
0
dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.controls.resultset; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.graphics.Color; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.exec.trace.DBCTrace; import org.jkiss.dbeaver.model.runtime.AbstractJob; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.virtual.DBVColorOverride; import org.jkiss.dbeaver.model.virtual.DBVEntity; import org.jkiss.dbeaver.model.virtual.DBVUtils; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.util.*; /** * Result set model */ public class ResultSetModel { private static final Log log = Log.getLog(ResultSetModel.class); // Attributes private DBDAttributeBinding[] attributes = new DBDAttributeBinding[0]; private List<DBDAttributeBinding> visibleAttributes = new ArrayList<>(); private DBDAttributeBinding documentAttribute = null; private DBDDataFilter dataFilter; private DBSEntity singleSourceEntity; private DBCExecutionSource executionSource; // Data private List<ResultSetRow> curRows = new ArrayList<>(); private Long totalRowCount = null; private int changesCount = 0; private volatile boolean hasData = false; // Flag saying that edited values update is in progress private volatile boolean updateInProgress = false; // Coloring private Map<DBDAttributeBinding, List<AttributeColorSettings>> colorMapping = new HashMap<>(); private DBCStatistics statistics; private DBCTrace trace; private transient boolean metadataChanged; private transient boolean metadataDynamic; public static class AttributeColorSettings { private DBCLogicalOperator operator; private Object[] attributeValues; private Color colorForeground; private Color colorBackground; public AttributeColorSettings(DBVColorOverride co) { this.operator = co.getOperator(); this.colorForeground = UIUtils.getSharedColor(co.getColorForeground()); this.colorBackground = UIUtils.getSharedColor(co.getColorBackground()); this.attributeValues = co.getAttributeValues(); } public DBCLogicalOperator getOperator() { return operator; } public Object[] getAttributeValues() { return attributeValues; } public Color getColorForeground() { return colorForeground; } public Color getColorBackground() { return colorBackground; } public boolean evaluate(Object cellValue) { return operator.evaluate(cellValue, attributeValues); } } private final Comparator<DBDAttributeBinding> POSITION_SORTER = new Comparator<DBDAttributeBinding>() { @Override public int compare(DBDAttributeBinding o1, DBDAttributeBinding o2) { final DBDAttributeConstraint c1 = dataFilter.getConstraint(o1); final DBDAttributeConstraint c2 = dataFilter.getConstraint(o2); if (c1 == null) { log.debug("Missing constraint for " + o1); return -1; } if (c2 == null) { log.debug("Missing constraint for " + o2); return 1; } return c1.getVisualPosition() - c2.getVisualPosition(); } }; public ResultSetModel() { dataFilter = createDataFilter(); } @NotNull public DBDDataFilter createDataFilter() { fillVisibleAttributes(); List<DBDAttributeConstraint> constraints = new ArrayList<>(attributes.length); for (DBDAttributeBinding binding : attributes) { addConstraints(constraints, binding); } return new DBDDataFilter(constraints); } private void addConstraints(List<DBDAttributeConstraint> constraints, DBDAttributeBinding binding) { DBDAttributeConstraint constraint = new DBDAttributeConstraint(binding); constraint.setVisible(visibleAttributes.contains(binding) || binding.getParentObject() != null); constraints.add(constraint); List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings(); if (nestedBindings != null) { for (DBDAttributeBinding nested : nestedBindings) { addConstraints(constraints, nested); } } } public boolean isSingleSource() { return singleSourceEntity != null; } /** * Returns single source of this result set. Usually it is a table. * If result set is a result of joins or contains synthetic attributes then * single source is null. If driver doesn't support meta information * for queries then is will null. * * @return single source entity */ @Nullable public DBSEntity getSingleSource() { return singleSourceEntity; } public void resetCellValue(DBDAttributeBinding attr, ResultSetRow row) { if (row.getState() == ResultSetRow.STATE_REMOVED) { row.setState(ResultSetRow.STATE_NORMAL); } else if (row.changes != null && row.changes.containsKey(attr)) { DBUtils.resetValue(getCellValue(attr, row)); updateCellValue(attr, row, row.changes.get(attr), false); row.resetChange(attr); if (row.getState() == ResultSetRow.STATE_NORMAL) { changesCount--; } } } public void refreshChangeCount() { changesCount = 0; for (ResultSetRow row : curRows) { if (row.getState() != ResultSetRow.STATE_NORMAL) { changesCount++; } else if (row.changes != null) { changesCount += row.changes.size(); } } } public DBDAttributeBinding getDocumentAttribute() { return documentAttribute; } @NotNull public DBDAttributeBinding[] getAttributes() { return attributes; } @NotNull public DBDAttributeBinding getAttribute(int index) { return attributes[index]; } @NotNull public List<DBDAttributeBinding> getVisibleAttributes() { return visibleAttributes; } public int getVisibleAttributeCount() { return visibleAttributes.size(); } @Nullable public List<DBDAttributeBinding> getVisibleAttributes(DBDAttributeBinding parent) { final List<DBDAttributeBinding> nestedBindings = parent.getNestedBindings(); if (nestedBindings == null || nestedBindings.isEmpty()) { return null; } List<DBDAttributeBinding> result = new ArrayList<>(nestedBindings); for (Iterator<DBDAttributeBinding> iter = result.iterator(); iter.hasNext(); ) { final DBDAttributeConstraint constraint = dataFilter.getConstraint(iter.next()); if (constraint != null && !constraint.isVisible()) { iter.remove(); } } return result; } @NotNull public DBDAttributeBinding getVisibleAttribute(int index) { return visibleAttributes.get(index); } public void setAttributeVisibility(@NotNull DBDAttributeBinding attribute, boolean visible) { DBDAttributeConstraint constraint = dataFilter.getConstraint(attribute); if (constraint != null && constraint.isVisible() != visible) { constraint.setVisible(visible); if (attribute.getParentObject() == null) { if (visible) { visibleAttributes.add(attribute); } else { visibleAttributes.remove(attribute); } } } } @Nullable public DBDAttributeBinding getAttributeBinding(@Nullable DBSAttributeBase attribute) { return DBUtils.findBinding(attributes, attribute); } @Nullable DBDAttributeBinding getAttributeBinding(@Nullable DBSEntity entity, @NotNull String attrName) { for (DBDAttributeBinding attribute : visibleAttributes) { DBDRowIdentifier rowIdentifier = attribute.getRowIdentifier(); if ((entity == null || (rowIdentifier != null && rowIdentifier.getEntity() == entity)) && attribute.getName().equals(attrName)) { return attribute; } } return null; } public boolean isEmpty() { return getRowCount() <= 0 || visibleAttributes.size() <= 0; } public int getRowCount() { return curRows.size(); } @NotNull public List<ResultSetRow> getAllRows() { return curRows; } @NotNull public Object[] getRowData(int index) { return curRows.get(index).values; } @NotNull public ResultSetRow getRow(int index) { return curRows.get(index); } public Long getTotalRowCount() { return totalRowCount; } void setTotalRowCount(Long totalRowCount) { this.totalRowCount = totalRowCount; } @Nullable public Object getCellValue(@NotNull DBDAttributeBinding attribute, @NotNull ResultSetRow row) { int depth = attribute.getLevel(); if (depth == 0) { final int index = attribute.getOrdinalPosition(); if (index >= row.values.length) { log.debug("Bad attribute - index out of row values' bounds"); return null; } else { return row.values[index]; } } Object curValue = row.values[attribute.getTopParent().getOrdinalPosition()]; for (int i = 0; i < depth; i++) { if (curValue == null) { break; } DBDAttributeBinding attr = attribute.getParent(depth - i - 1); assert attr != null; try { curValue = attr.extractNestedValue(curValue); } catch (DBCException e) { log.debug("Error reading nested value of [" + attr.getName() + "]", e); curValue = null; break; } } return curValue; } /** * Updates cell value. Saves previous value. * * @param attr Attribute * @param row row index * @param value new value * @return true on success */ public boolean updateCellValue(@NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, @Nullable Object value) { return updateCellValue(attr, row, value, true); } public boolean updateCellValue(@NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, @Nullable Object value, boolean updateChanges) { int depth = attr.getLevel(); int rootIndex; if (depth == 0) { rootIndex = attr.getOrdinalPosition(); } else { rootIndex = attr.getTopParent().getOrdinalPosition(); } Object rootValue = row.values[rootIndex]; Object ownerValue = depth > 0 ? rootValue : null; { // Obtain owner value and create all intermediate values for (int i = 0; i < depth; i++) { if (ownerValue == null) { // Create new owner object log.warn("Null owner value"); return false; } if (i == depth - 1) { break; } DBDAttributeBinding ownerAttr = attr.getParent(depth - i - 1); assert ownerAttr != null; try { ownerValue = ownerAttr.extractNestedValue(ownerValue); } catch (DBCException e) { log.warn("Error getting field [" + ownerAttr.getName() + "] value", e); return false; } } } // Get old value Object oldValue = rootValue; if (ownerValue != null) { try { oldValue = attr.extractNestedValue(ownerValue); } catch (DBCException e) { log.error("Error getting [" + attr.getName() + "] value", e); } } if ((value instanceof DBDValue && value == oldValue && ((DBDValue) value).isModified()) || !CommonUtils.equalObjects(oldValue, value)) { // If DBDValue was updated (kind of CONTENT?) or actual value was changed if (ownerValue == null && DBUtils.isNullValue(oldValue) && DBUtils.isNullValue(value)) { // Both nulls - nothing to update return false; } // Check composite type if (ownerValue != null) { if (!(ownerValue instanceof DBDComposite)) { log.warn("Value [" + ownerValue + "] edit is not supported"); return false; } } // Do not add edited cell for new/deleted rows if (row.getState() == ResultSetRow.STATE_NORMAL) { boolean cellWasEdited = row.changes != null && row.changes.containsKey(attr); Object oldOldValue = !cellWasEdited ? null : row.changes.get(attr); if (cellWasEdited && !CommonUtils.equalObjects(oldValue, oldOldValue) && !CommonUtils.equalObjects(oldValue, value)) { // Value rewrite - release previous stored old value DBUtils.releaseValue(oldValue); } else if (updateChanges) { if (value instanceof DBDValue || !CommonUtils.equalObjects(value, oldValue)) { row.addChange(attr, oldValue); } else { updateChanges = false; } } if (updateChanges && row.getState() == ResultSetRow.STATE_NORMAL && !cellWasEdited) { changesCount++; } } if (ownerValue != null) { ((DBDComposite) ownerValue).setAttributeValue(attr.getAttribute(), value); } else { row.values[rootIndex] = value; } return true; } return false; } boolean isDynamicMetadata() { return metadataDynamic; } boolean isMetadataChanged() { return metadataChanged; } /** * Sets new metadata of result set * * @param resultSet resultset * @param newAttributes attributes metadata */ public void setMetaData(@NotNull DBCResultSet resultSet, @NotNull DBDAttributeBinding[] newAttributes) { boolean update = false; DBCStatement sourceStatement = resultSet.getSourceStatement(); if (sourceStatement != null) { this.executionSource = sourceStatement.getStatementSource(); } else { this.executionSource = null; } if (resultSet instanceof DBCResultSetTrace) { this.trace = ((DBCResultSetTrace) resultSet).getExecutionTrace(); } else { this.trace = null; } if (this.attributes == null || this.attributes.length == 0 || this.attributes.length != newAttributes.length || isDynamicMetadata()) { update = true; } else { for (int i = 0; i < this.attributes.length; i++) { if (!ResultSetUtils.equalAttributes(this.attributes[i].getMetaAttribute(), newAttributes[i].getMetaAttribute())) { update = true; break; } } } this.metadataChanged = update; if (update) { if (!ArrayUtils.isEmpty(this.attributes) && !ArrayUtils.isEmpty(newAttributes) && isDynamicMetadata() && this.attributes[0].getTopParent().getMetaAttribute().getSource() == newAttributes[0].getTopParent().getMetaAttribute().getSource()) { // the same source metadataChanged = false; } else { metadataChanged = true; } } this.clearData(); this.attributes = newAttributes; this.documentAttribute = null; metadataDynamic = this.attributes.length > 0 && this.attributes[0].getTopParent().getDataSource().getInfo().isDynamicMetadata(); { // Detect document attribute // It has to be only one attribute in list (excluding pseudo attributes). DBDAttributeBinding realAttr = null; if (attributes.length == 1) { realAttr = attributes[0]; } else { for (DBDAttributeBinding attr : attributes) { if (!attr.isPseudoAttribute()) { if (realAttr != null) { // more than one realAttr = null; break; } realAttr = attr; } } } if (realAttr != null) { if (realAttr.getDataKind() == DBPDataKind.DOCUMENT || realAttr.getDataKind() == DBPDataKind.CONTENT) { documentAttribute = realAttr; } } updateColorMapping(); } } public void setData(@NotNull List<Object[]> rows) { // Clear previous data this.clearData(); { // Extract nested attributes from single top-level attribute if (attributes.length == 1) { DBDAttributeBinding topAttr = attributes[0]; if (topAttr.getDataKind() == DBPDataKind.DOCUMENT || topAttr.getDataKind() == DBPDataKind.STRUCT) { List<DBDAttributeBinding> nested = topAttr.getNestedBindings(); if (nested != null && !nested.isEmpty()) { attributes = nested.toArray(new DBDAttributeBinding[nested.size()]); fillVisibleAttributes(); } } } } // Add new data appendData(rows); // Init data filter if (metadataChanged) { this.dataFilter = createDataFilter(); } else { DBDDataFilter prevFilter = dataFilter; this.dataFilter = createDataFilter(); updateDataFilter(prevFilter); } this.visibleAttributes.sort(POSITION_SORTER); { // Check single source flag DBSEntity sourceTable = null; for (DBDAttributeBinding attribute : visibleAttributes) { if (attribute.isPseudoAttribute()) { continue; } DBDRowIdentifier rowIdentifier = attribute.getRowIdentifier(); if (rowIdentifier != null) { if (sourceTable == null) { sourceTable = rowIdentifier.getEntity(); } else if (sourceTable != rowIdentifier.getEntity()) { sourceTable = null; break; } } else { // Do not mark it a multi-source. // It is just some column without identifier, probably a constant or an expression //singleSourceCells = false; //break; } } singleSourceEntity = sourceTable; updateColorMapping(); } hasData = true; } boolean hasColorMapping(DBDAttributeBinding binding) { return colorMapping.containsKey(binding); } boolean hasColorMapping(DBSEntity entity) { DBVEntity virtualEntity = DBVUtils.findVirtualEntity(entity, false); return virtualEntity != null && !CommonUtils.isEmpty(virtualEntity.getColorOverrides()); } void updateColorMapping() { colorMapping.clear(); DBSEntity entity = getSingleSource(); if (entity == null) { return; } DBVEntity virtualEntity = DBVUtils.findVirtualEntity(entity, false); if (virtualEntity != null) { List<DBVColorOverride> coList = virtualEntity.getColorOverrides(); if (!CommonUtils.isEmpty(coList)) { for (DBVColorOverride co : coList) { DBDAttributeBinding binding = getAttributeBinding(entity, co.getAttributeName()); if (binding != null) { List<AttributeColorSettings> cmList = colorMapping.computeIfAbsent(binding, k -> new ArrayList<>()); cmList.add(new AttributeColorSettings(co)); } } } } updateRowColors(curRows); } private void updateRowColors(List<ResultSetRow> rows) { if (colorMapping.isEmpty()) { for (ResultSetRow row : rows) { row.foreground = null; row.background = null; } } else { for (Map.Entry<DBDAttributeBinding, List<AttributeColorSettings>> entry : colorMapping.entrySet()) { for (ResultSetRow row : rows) { final DBDAttributeBinding binding = entry.getKey(); final Object cellValue = getCellValue(binding, row); //final String cellStringValue = binding.getValueHandler().getValueDisplayString(binding, cellValue, DBDDisplayFormat.NATIVE); for (AttributeColorSettings acs : entry.getValue()) { if (acs.evaluate(cellValue)) { row.foreground = acs.colorForeground; row.background = acs.colorBackground; break; } } } } } } public void appendData(@NotNull List<Object[]> rows) { int rowCount = rows.size(); int firstRowNum = curRows.size(); List<ResultSetRow> newRows = new ArrayList<>(rowCount); for (int i = 0; i < rowCount; i++) { newRows.add( new ResultSetRow(firstRowNum + i, rows.get(i))); } curRows.addAll(newRows); updateRowColors(newRows); } void clearData() { // Refresh all rows this.releaseAll(); hasData = false; } public boolean hasData() { return hasData; } public boolean isDirty() { return changesCount != 0; } public boolean isAttributeReadOnly(@NotNull DBDAttributeBinding attribute) { // if (!isSingleSource()) { // return true; // } if (attribute == null || attribute.getMetaAttribute().isReadOnly()) { return true; } DBDRowIdentifier rowIdentifier = attribute.getRowIdentifier(); if (rowIdentifier == null || !(rowIdentifier.getEntity() instanceof DBSDataManipulator)) { return true; } DBSDataManipulator dataContainer = (DBSDataManipulator) rowIdentifier.getEntity(); return (dataContainer.getSupportedFeatures() & DBSDataManipulator.DATA_UPDATE) == 0; } public boolean isUpdateInProgress() { return updateInProgress; } void setUpdateInProgress(boolean updateInProgress) { this.updateInProgress = updateInProgress; } @NotNull ResultSetRow addNewRow(int rowNum, @NotNull Object[] data) { ResultSetRow newRow = new ResultSetRow(curRows.size(), data); newRow.setVisualNumber(rowNum); newRow.setState(ResultSetRow.STATE_ADDED); shiftRows(newRow, 1); curRows.add(rowNum, newRow); changesCount++; return newRow; } /** * Removes row with specified index from data * * @param row row * @return true if row was physically removed (only in case if this row was previously added) * or false if it just marked as deleted */ boolean deleteRow(@NotNull ResultSetRow row) { if (row.getState() == ResultSetRow.STATE_ADDED) { cleanupRow(row); return true; } else { // Mark row as deleted row.setState(ResultSetRow.STATE_REMOVED); changesCount++; return false; } } void cleanupRow(@NotNull ResultSetRow row) { row.release(); this.curRows.remove(row.getVisualNumber()); this.shiftRows(row, -1); } boolean cleanupRows(Collection<ResultSetRow> rows) { if (rows != null && !rows.isEmpty()) { // Remove rows (in descending order to prevent concurrent modification errors) List<ResultSetRow> rowsToRemove = new ArrayList<>(rows); rowsToRemove.sort(Comparator.comparingInt(ResultSetRow::getVisualNumber)); for (ResultSetRow row : rowsToRemove) { cleanupRow(row); } return true; } else { return false; } } private void shiftRows(@NotNull ResultSetRow relative, int delta) { for (ResultSetRow row : curRows) { if (row.getVisualNumber() >= relative.getVisualNumber()) { row.setVisualNumber(row.getVisualNumber() + delta); } if (row.getRowNumber() >= relative.getRowNumber()) { row.setRowNumber(row.getRowNumber() + delta); } } } private void releaseAll() { final List<ResultSetRow> oldRows = curRows; this.curRows = new ArrayList<>(); this.totalRowCount = null; // Cleanup in separate job. // Sometimes model cleanup takes much time (e.g. freeing LOB values) // So let's do it in separate job to avoid UI locking new AbstractJob("Cleanup model") { { setSystem(true); } @Override protected IStatus run(DBRProgressMonitor monitor) { for (ResultSetRow row : oldRows) { row.release(); } return Status.OK_STATUS; } }.schedule(); } public DBDDataFilter getDataFilter() { return dataFilter; } /** * Sets new data filter * * @param dataFilter data filter * @return true if visible attributes were changed. Spreadsheet has to be refreshed */ boolean setDataFilter(DBDDataFilter dataFilter) { this.dataFilter = dataFilter; // Check if filter misses some attributes List<DBDAttributeConstraint> newConstraints = new ArrayList<>(); for (DBDAttributeBinding binding : attributes) { if (dataFilter.getConstraint(binding) == null) { addConstraints(newConstraints, binding); } } if (!newConstraints.isEmpty()) { dataFilter.addConstraints(newConstraints); } List<DBDAttributeBinding> newBindings = new ArrayList<>(); for (DBSAttributeBase attr : this.dataFilter.getOrderedVisibleAttributes()) { DBDAttributeBinding binding = getAttributeBinding(attr); if (binding != null) { newBindings.add(binding); } } if (!newBindings.equals(visibleAttributes)) { visibleAttributes = newBindings; return true; } return false; } void updateDataFilter(DBDDataFilter filter) { this.visibleAttributes.clear(); Collections.addAll(this.visibleAttributes, this.attributes); for (DBDAttributeConstraint constraint : filter.getConstraints()) { DBDAttributeConstraint filterConstraint = this.dataFilter.getConstraint(constraint.getAttribute(), true); if (filterConstraint == null) { //log.warn("Constraint for attribute [" + constraint.getAttribute().getName() + "] not found"); continue; } if (constraint.getOperator() != null) { filterConstraint.setOperator(constraint.getOperator()); filterConstraint.setReverseOperator(constraint.isReverseOperator()); filterConstraint.setValue(constraint.getValue()); } else { filterConstraint.setCriteria(constraint.getCriteria()); } filterConstraint.setOrderPosition(constraint.getOrderPosition()); filterConstraint.setOrderDescending(constraint.isOrderDescending()); filterConstraint.setVisible(constraint.isVisible()); filterConstraint.setVisualPosition(constraint.getVisualPosition()); if (filterConstraint.getAttribute() instanceof DBDAttributeBinding) { if (!constraint.isVisible()) { visibleAttributes.remove(filterConstraint.getAttribute()); } else { if (!visibleAttributes.contains(filterConstraint.getAttribute())) { DBDAttributeBinding attribute = (DBDAttributeBinding) filterConstraint.getAttribute(); if (attribute.getParentObject() == null) { // Add only root attributes visibleAttributes.add(attribute); } } } } } if (filter.getConstraints().size() != attributes.length) { // Update visibility for (Iterator<DBDAttributeBinding> iter = visibleAttributes.iterator(); iter.hasNext(); ) { final DBDAttributeBinding attr = iter.next(); if (filter.getConstraint(attr, true) == null) { // No constraint for this attribute: use default visibility if (!isVisibleByDefault(attr)) { iter.remove(); } } } } this.visibleAttributes.sort(POSITION_SORTER); this.dataFilter.setWhere(filter.getWhere()); this.dataFilter.setOrder(filter.getOrder()); this.dataFilter.setAnyConstraint(filter.isAnyConstraint()); } public void resetOrdering() { final boolean hasOrdering = dataFilter.hasOrdering(); // Sort locally final List<DBDAttributeConstraint> orderConstraints = dataFilter.getOrderConstraints(); curRows.sort((row1, row2) -> { if (!hasOrdering) { return row1.getRowNumber() - row2.getRowNumber(); } int result = 0; for (DBDAttributeConstraint co : orderConstraints) { final DBDAttributeBinding binding = getAttributeBinding(co.getAttribute()); if (binding == null) { continue; } Object cell1 = getCellValue(binding, row1); Object cell2 = getCellValue(binding, row2); if (cell1 == cell2) { result = 0; } else if (DBUtils.isNullValue(cell1)) { result = 1; } else if (DBUtils.isNullValue(cell2)) { result = -1; } else if (cell1 instanceof Number && cell2 instanceof Number) { // Actual data type for the same column may differ (e.g. partially read from server, partially added on client side) double numDiff = ((Number) cell1).doubleValue() - ((Number) cell2).doubleValue(); result = numDiff < 0 ? -1 : (numDiff > 0 ? 1 : 0); } else if (cell1 instanceof Comparable) { result = ((Comparable) cell1).compareTo(cell2); } else { String str1 = String.valueOf(cell1); String str2 = String.valueOf(cell2); result = str1.compareTo(str2); } if (co.isOrderDescending()) { result = -result; } if (result != 0) { break; } } return result; }); for (int i = 0; i < curRows.size(); i++) { curRows.get(i).setVisualNumber(i); } } private void fillVisibleAttributes() { this.visibleAttributes.clear(); boolean entityDataView = executionSource != null && executionSource.getDataContainer() instanceof DBSEntity; DBSObjectFilter columnFilter = null; if (entityDataView) { // Detect column filter DBSEntity entity = (DBSEntity) executionSource.getDataContainer(); DBPDataSourceContainer container = entity.getDataSource().getContainer(); if (container.getPreferenceStore().getBoolean(ResultSetPreferences.RESULT_SET_USE_NAVIGATOR_FILTERS) && attributes.length > 0) { DBSEntityAttribute entityAttribute = attributes[0].getEntityAttribute(); if (entityAttribute != null) { columnFilter = container.getObjectFilter(entityAttribute.getClass(), entity, false); } } } // Filter pseudo attributes if we query single entity for (DBDAttributeBinding binding : this.attributes) { if (!entityDataView || isVisibleByDefault(binding)) { // Make visible "real" attributes if (columnFilter != null && !columnFilter.matches(binding.getName())) { // Filtered out by column filter continue; } this.visibleAttributes.add(binding); } } } private static boolean isVisibleByDefault(DBDAttributeBinding binding) { return !binding.isPseudoAttribute(); } public DBCStatistics getStatistics() { return statistics; } public void setStatistics(DBCStatistics statistics) { this.statistics = statistics; } public DBCTrace getTrace() { return trace; } }
plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetModel.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.controls.resultset; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.graphics.Color; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPDataKind; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.exec.*; import org.jkiss.dbeaver.model.exec.trace.DBCTrace; import org.jkiss.dbeaver.model.runtime.AbstractJob; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.virtual.DBVColorOverride; import org.jkiss.dbeaver.model.virtual.DBVEntity; import org.jkiss.dbeaver.model.virtual.DBVUtils; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.util.*; /** * Result set model */ public class ResultSetModel { private static final Log log = Log.getLog(ResultSetModel.class); // Attributes private DBDAttributeBinding[] attributes = new DBDAttributeBinding[0]; private List<DBDAttributeBinding> visibleAttributes = new ArrayList<>(); private DBDAttributeBinding documentAttribute = null; private DBDDataFilter dataFilter; private DBSEntity singleSourceEntity; private DBCExecutionSource executionSource; // Data private List<ResultSetRow> curRows = new ArrayList<>(); private Long totalRowCount = null; private int changesCount = 0; private volatile boolean hasData = false; // Flag saying that edited values update is in progress private volatile boolean updateInProgress = false; // Coloring private Map<DBDAttributeBinding, List<AttributeColorSettings>> colorMapping = new HashMap<>(); private DBCStatistics statistics; private DBCTrace trace; private transient boolean metadataChanged; private transient boolean metadataDynamic; public static class AttributeColorSettings { private DBCLogicalOperator operator; private Object[] attributeValues; private Color colorForeground; private Color colorBackground; public AttributeColorSettings(DBVColorOverride co) { this.operator = co.getOperator(); this.colorForeground = UIUtils.getSharedColor(co.getColorForeground()); this.colorBackground = UIUtils.getSharedColor(co.getColorBackground()); this.attributeValues = co.getAttributeValues(); } public DBCLogicalOperator getOperator() { return operator; } public Object[] getAttributeValues() { return attributeValues; } public Color getColorForeground() { return colorForeground; } public Color getColorBackground() { return colorBackground; } public boolean evaluate(Object cellValue) { return operator.evaluate(cellValue, attributeValues); } } private final Comparator<DBDAttributeBinding> POSITION_SORTER = new Comparator<DBDAttributeBinding>() { @Override public int compare(DBDAttributeBinding o1, DBDAttributeBinding o2) { final DBDAttributeConstraint c1 = dataFilter.getConstraint(o1); final DBDAttributeConstraint c2 = dataFilter.getConstraint(o2); if (c1 == null) { log.debug("Missing constraint for " + o1); return -1; } if (c2 == null) { log.debug("Missing constraint for " + o2); return 1; } return c1.getVisualPosition() - c2.getVisualPosition(); } }; public ResultSetModel() { dataFilter = createDataFilter(); } @NotNull public DBDDataFilter createDataFilter() { fillVisibleAttributes(); List<DBDAttributeConstraint> constraints = new ArrayList<>(attributes.length); for (DBDAttributeBinding binding : attributes) { addConstraints(constraints, binding); } return new DBDDataFilter(constraints); } private void addConstraints(List<DBDAttributeConstraint> constraints, DBDAttributeBinding binding) { DBDAttributeConstraint constraint = new DBDAttributeConstraint(binding); constraint.setVisible(visibleAttributes.contains(binding) || binding.getParentObject() != null); constraints.add(constraint); List<DBDAttributeBinding> nestedBindings = binding.getNestedBindings(); if (nestedBindings != null) { for (DBDAttributeBinding nested : nestedBindings) { addConstraints(constraints, nested); } } } public boolean isSingleSource() { return singleSourceEntity != null; } /** * Returns single source of this result set. Usually it is a table. * If result set is a result of joins or contains synthetic attributes then * single source is null. If driver doesn't support meta information * for queries then is will null. * * @return single source entity */ @Nullable public DBSEntity getSingleSource() { return singleSourceEntity; } public void resetCellValue(DBDAttributeBinding attr, ResultSetRow row) { if (row.getState() == ResultSetRow.STATE_REMOVED) { row.setState(ResultSetRow.STATE_NORMAL); } else if (row.changes != null && row.changes.containsKey(attr)) { DBUtils.resetValue(getCellValue(attr, row)); updateCellValue(attr, row, row.changes.get(attr), false); row.resetChange(attr); if (row.getState() == ResultSetRow.STATE_NORMAL) { changesCount--; } } } public void refreshChangeCount() { changesCount = 0; for (ResultSetRow row : curRows) { if (row.getState() != ResultSetRow.STATE_NORMAL) { changesCount++; } else if (row.changes != null) { changesCount += row.changes.size(); } } } public DBDAttributeBinding getDocumentAttribute() { return documentAttribute; } @NotNull public DBDAttributeBinding[] getAttributes() { return attributes; } @NotNull public DBDAttributeBinding getAttribute(int index) { return attributes[index]; } @NotNull public List<DBDAttributeBinding> getVisibleAttributes() { return visibleAttributes; } public int getVisibleAttributeCount() { return visibleAttributes.size(); } @Nullable public List<DBDAttributeBinding> getVisibleAttributes(DBDAttributeBinding parent) { final List<DBDAttributeBinding> nestedBindings = parent.getNestedBindings(); if (nestedBindings == null || nestedBindings.isEmpty()) { return null; } List<DBDAttributeBinding> result = new ArrayList<>(nestedBindings); for (Iterator<DBDAttributeBinding> iter = result.iterator(); iter.hasNext(); ) { final DBDAttributeConstraint constraint = dataFilter.getConstraint(iter.next()); if (constraint != null && !constraint.isVisible()) { iter.remove(); } } return result; } @NotNull public DBDAttributeBinding getVisibleAttribute(int index) { return visibleAttributes.get(index); } public void setAttributeVisibility(@NotNull DBDAttributeBinding attribute, boolean visible) { DBDAttributeConstraint constraint = dataFilter.getConstraint(attribute); if (constraint != null && constraint.isVisible() != visible) { constraint.setVisible(visible); if (attribute.getParentObject() == null) { if (visible) { visibleAttributes.add(attribute); } else { visibleAttributes.remove(attribute); } } } } @Nullable public DBDAttributeBinding getAttributeBinding(@Nullable DBSAttributeBase attribute) { return DBUtils.findBinding(attributes, attribute); } @Nullable DBDAttributeBinding getAttributeBinding(@Nullable DBSEntity entity, @NotNull String attrName) { for (DBDAttributeBinding attribute : visibleAttributes) { DBDRowIdentifier rowIdentifier = attribute.getRowIdentifier(); if ((entity == null || (rowIdentifier != null && rowIdentifier.getEntity() == entity)) && attribute.getName().equals(attrName)) { return attribute; } } return null; } public boolean isEmpty() { return getRowCount() <= 0 || visibleAttributes.size() <= 0; } public int getRowCount() { return curRows.size(); } @NotNull public List<ResultSetRow> getAllRows() { return curRows; } @NotNull public Object[] getRowData(int index) { return curRows.get(index).values; } @NotNull public ResultSetRow getRow(int index) { return curRows.get(index); } public Long getTotalRowCount() { return totalRowCount; } void setTotalRowCount(Long totalRowCount) { this.totalRowCount = totalRowCount; } @Nullable public Object getCellValue(@NotNull DBDAttributeBinding attribute, @NotNull ResultSetRow row) { int depth = attribute.getLevel(); if (depth == 0) { final int index = attribute.getOrdinalPosition(); if (index >= row.values.length) { log.debug("Bad attribute - index out of row values' bounds"); return null; } else { return row.values[index]; } } Object curValue = row.values[attribute.getTopParent().getOrdinalPosition()]; for (int i = 0; i < depth; i++) { if (curValue == null) { break; } DBDAttributeBinding attr = attribute.getParent(depth - i - 1); assert attr != null; try { curValue = attr.extractNestedValue(curValue); } catch (DBCException e) { log.debug("Error reading nested value of [" + attr.getName() + "]", e); curValue = null; break; } } return curValue; } /** * Updates cell value. Saves previous value. * * @param attr Attribute * @param row row index * @param value new value * @return true on success */ public boolean updateCellValue(@NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, @Nullable Object value) { return updateCellValue(attr, row, value, true); } public boolean updateCellValue(@NotNull DBDAttributeBinding attr, @NotNull ResultSetRow row, @Nullable Object value, boolean updateChanges) { int depth = attr.getLevel(); int rootIndex; if (depth == 0) { rootIndex = attr.getOrdinalPosition(); } else { rootIndex = attr.getTopParent().getOrdinalPosition(); } Object rootValue = row.values[rootIndex]; Object ownerValue = depth > 0 ? rootValue : null; { // Obtain owner value and create all intermediate values for (int i = 0; i < depth; i++) { if (ownerValue == null) { // Create new owner object log.warn("Null owner value"); return false; } if (i == depth - 1) { break; } DBDAttributeBinding ownerAttr = attr.getParent(depth - i - 1); assert ownerAttr != null; try { ownerValue = ownerAttr.extractNestedValue(ownerValue); } catch (DBCException e) { log.warn("Error getting field [" + ownerAttr.getName() + "] value", e); return false; } } } // Get old value Object oldValue = rootValue; if (ownerValue != null) { try { oldValue = attr.extractNestedValue(ownerValue); } catch (DBCException e) { log.error("Error getting [" + attr.getName() + "] value", e); } } if ((value instanceof DBDValue && value == oldValue && ((DBDValue) value).isModified()) || !CommonUtils.equalObjects(oldValue, value)) { // If DBDValue was updated (kind of CONTENT?) or actual value was changed if (ownerValue == null && DBUtils.isNullValue(oldValue) && DBUtils.isNullValue(value)) { // Both nulls - nothing to update return false; } // Check composite type if (ownerValue != null) { if (!(ownerValue instanceof DBDComposite)) { log.warn("Value [" + ownerValue + "] edit is not supported"); return false; } } // Do not add edited cell for new/deleted rows if (row.getState() == ResultSetRow.STATE_NORMAL) { boolean cellWasEdited = row.changes != null && row.changes.containsKey(attr); Object oldOldValue = !cellWasEdited ? null : row.changes.get(attr); if (cellWasEdited && !CommonUtils.equalObjects(oldValue, oldOldValue) && !CommonUtils.equalObjects(oldValue, value)) { // Value rewrite - release previous stored old value DBUtils.releaseValue(oldValue); } else if (updateChanges) { if (value instanceof DBDValue || !CommonUtils.equalObjects(value, oldValue)) { row.addChange(attr, oldValue); } else { updateChanges = false; } } if (updateChanges && row.getState() == ResultSetRow.STATE_NORMAL && !cellWasEdited) { changesCount++; } } if (ownerValue != null) { ((DBDComposite) ownerValue).setAttributeValue(attr.getAttribute(), value); } else { row.values[rootIndex] = value; } return true; } return false; } boolean isDynamicMetadata() { return metadataDynamic; } boolean isMetadataChanged() { return metadataChanged; } /** * Sets new metadata of result set * * @param resultSet resultset * @param newAttributes attributes metadata */ public void setMetaData(@NotNull DBCResultSet resultSet, @NotNull DBDAttributeBinding[] newAttributes) { boolean update = false; DBCStatement sourceStatement = resultSet.getSourceStatement(); if (sourceStatement != null) { this.executionSource = sourceStatement.getStatementSource(); } else { this.executionSource = null; } if (resultSet instanceof DBCResultSetTrace) { this.trace = ((DBCResultSetTrace) resultSet).getExecutionTrace(); } else { this.trace = null; } if (this.attributes == null || this.attributes.length == 0 || this.attributes.length != newAttributes.length || isDynamicMetadata()) { update = true; } else { for (int i = 0; i < this.attributes.length; i++) { if (!ResultSetUtils.equalAttributes(this.attributes[i].getMetaAttribute(), newAttributes[i].getMetaAttribute())) { update = true; break; } } } this.metadataChanged = update; if (update) { if (!ArrayUtils.isEmpty(this.attributes) && !ArrayUtils.isEmpty(newAttributes) && isDynamicMetadata() && this.attributes[0].getTopParent().getMetaAttribute().getSource() == newAttributes[0].getTopParent().getMetaAttribute().getSource()) { // the same source metadataChanged = false; } else { metadataChanged = true; } } this.clearData(); this.attributes = newAttributes; this.documentAttribute = null; metadataDynamic = this.attributes.length > 0 && this.attributes[0].getTopParent().getDataSource().getInfo().isDynamicMetadata(); { // Detect document attribute // It has to be only one attribute in list (excluding pseudo attributes). DBDAttributeBinding realAttr = null; if (attributes.length == 1) { realAttr = attributes[0]; } else { for (DBDAttributeBinding attr : attributes) { if (!attr.isPseudoAttribute()) { if (realAttr != null) { // more than one realAttr = null; break; } realAttr = attr; } } } if (realAttr != null) { if (realAttr.getDataKind() == DBPDataKind.DOCUMENT || realAttr.getDataKind() == DBPDataKind.CONTENT) { documentAttribute = realAttr; } } updateColorMapping(); } } public void setData(@NotNull List<Object[]> rows) { // Clear previous data this.clearData(); { // Extract nested attributes from single top-level attribute if (attributes.length == 1) { DBDAttributeBinding topAttr = attributes[0]; if (topAttr.getDataKind() == DBPDataKind.DOCUMENT || topAttr.getDataKind() == DBPDataKind.STRUCT) { List<DBDAttributeBinding> nested = topAttr.getNestedBindings(); if (nested != null && !nested.isEmpty()) { attributes = nested.toArray(new DBDAttributeBinding[nested.size()]); fillVisibleAttributes(); } } } } // Add new data appendData(rows); // Init data filter if (metadataChanged) { this.dataFilter = createDataFilter(); } else { DBDDataFilter prevFilter = dataFilter; this.dataFilter = createDataFilter(); updateDataFilter(prevFilter); } this.visibleAttributes.sort(POSITION_SORTER); { // Check single source flag DBSEntity sourceTable = null; for (DBDAttributeBinding attribute : visibleAttributes) { if (attribute.isPseudoAttribute()) { continue; } DBDRowIdentifier rowIdentifier = attribute.getRowIdentifier(); if (rowIdentifier != null) { if (sourceTable == null) { sourceTable = rowIdentifier.getEntity(); } else if (sourceTable != rowIdentifier.getEntity()) { sourceTable = null; break; } } else { // Do not mark it a multi-source. // It is just some column without identifier, probably a constant or an expression //singleSourceCells = false; //break; } } singleSourceEntity = sourceTable; updateColorMapping(); } hasData = true; } boolean hasColorMapping(DBDAttributeBinding binding) { return colorMapping.containsKey(binding); } boolean hasColorMapping(DBSEntity entity) { DBVEntity virtualEntity = DBVUtils.findVirtualEntity(entity, false); return virtualEntity != null && !CommonUtils.isEmpty(virtualEntity.getColorOverrides()); } void updateColorMapping() { colorMapping.clear(); DBSEntity entity = getSingleSource(); if (entity == null) { return; } DBVEntity virtualEntity = DBVUtils.findVirtualEntity(entity, false); if (virtualEntity != null) { List<DBVColorOverride> coList = virtualEntity.getColorOverrides(); if (!CommonUtils.isEmpty(coList)) { for (DBVColorOverride co : coList) { DBDAttributeBinding binding = getAttributeBinding(entity, co.getAttributeName()); if (binding != null) { List<AttributeColorSettings> cmList = colorMapping.computeIfAbsent(binding, k -> new ArrayList<>()); cmList.add(new AttributeColorSettings(co)); } } } } updateRowColors(curRows); } private void updateRowColors(List<ResultSetRow> rows) { if (colorMapping.isEmpty()) { for (ResultSetRow row : rows) { row.foreground = null; row.background = null; } } else { for (Map.Entry<DBDAttributeBinding, List<AttributeColorSettings>> entry : colorMapping.entrySet()) { for (ResultSetRow row : rows) { final DBDAttributeBinding binding = entry.getKey(); final Object cellValue = getCellValue(binding, row); //final String cellStringValue = binding.getValueHandler().getValueDisplayString(binding, cellValue, DBDDisplayFormat.NATIVE); for (AttributeColorSettings acs : entry.getValue()) { if (acs.evaluate(cellValue)) { row.foreground = acs.colorForeground; row.background = acs.colorBackground; break; } } } } } } public void appendData(@NotNull List<Object[]> rows) { int rowCount = rows.size(); int firstRowNum = curRows.size(); List<ResultSetRow> newRows = new ArrayList<>(rowCount); for (int i = 0; i < rowCount; i++) { newRows.add( new ResultSetRow(firstRowNum + i, rows.get(i))); } curRows.addAll(newRows); updateRowColors(newRows); } void clearData() { // Refresh all rows this.releaseAll(); hasData = false; } public boolean hasData() { return hasData; } public boolean isDirty() { return changesCount != 0; } public boolean isAttributeReadOnly(@NotNull DBDAttributeBinding attribute) { // if (!isSingleSource()) { // return true; // } if (attribute == null || attribute.getMetaAttribute().isReadOnly()) { return true; } DBDRowIdentifier rowIdentifier = attribute.getRowIdentifier(); if (rowIdentifier == null || !(rowIdentifier.getEntity() instanceof DBSDataManipulator)) { return true; } DBSDataManipulator dataContainer = (DBSDataManipulator) rowIdentifier.getEntity(); return (dataContainer.getSupportedFeatures() & DBSDataManipulator.DATA_UPDATE) == 0; } public boolean isUpdateInProgress() { return updateInProgress; } void setUpdateInProgress(boolean updateInProgress) { this.updateInProgress = updateInProgress; } @NotNull ResultSetRow addNewRow(int rowNum, @NotNull Object[] data) { ResultSetRow newRow = new ResultSetRow(curRows.size(), data); newRow.setVisualNumber(rowNum); newRow.setState(ResultSetRow.STATE_ADDED); shiftRows(newRow, 1); curRows.add(rowNum, newRow); changesCount++; return newRow; } /** * Removes row with specified index from data * * @param row row * @return true if row was physically removed (only in case if this row was previously added) * or false if it just marked as deleted */ boolean deleteRow(@NotNull ResultSetRow row) { if (row.getState() == ResultSetRow.STATE_ADDED) { cleanupRow(row); return true; } else { // Mark row as deleted row.setState(ResultSetRow.STATE_REMOVED); changesCount++; return false; } } void cleanupRow(@NotNull ResultSetRow row) { row.release(); this.curRows.remove(row.getVisualNumber()); this.shiftRows(row, -1); } boolean cleanupRows(Collection<ResultSetRow> rows) { if (rows != null && !rows.isEmpty()) { // Remove rows (in descending order to prevent concurrent modification errors) List<ResultSetRow> rowsToRemove = new ArrayList<>(rows); rowsToRemove.sort(Comparator.comparingInt(ResultSetRow::getVisualNumber)); for (ResultSetRow row : rowsToRemove) { cleanupRow(row); } return true; } else { return false; } } private void shiftRows(@NotNull ResultSetRow relative, int delta) { for (ResultSetRow row : curRows) { if (row.getVisualNumber() >= relative.getVisualNumber()) { row.setVisualNumber(row.getVisualNumber() + delta); } if (row.getRowNumber() >= relative.getRowNumber()) { row.setRowNumber(row.getRowNumber() + delta); } } } private void releaseAll() { final List<ResultSetRow> oldRows = curRows; this.curRows = new ArrayList<>(); this.totalRowCount = null; // Cleanup in separate job. // Sometimes model cleanup takes much time (e.g. freeing LOB values) // So let's do it in separate job to avoid UI locking new AbstractJob("Cleanup model") { { setSystem(true); } @Override protected IStatus run(DBRProgressMonitor monitor) { for (ResultSetRow row : oldRows) { row.release(); } return Status.OK_STATUS; } }.schedule(); } public DBDDataFilter getDataFilter() { return dataFilter; } /** * Sets new data filter * * @param dataFilter data filter * @return true if visible attributes were changed. Spreadsheet has to be refreshed */ boolean setDataFilter(DBDDataFilter dataFilter) { this.dataFilter = dataFilter; // Check if filter misses some attributes List<DBDAttributeConstraint> newConstraints = new ArrayList<>(); for (DBDAttributeBinding binding : attributes) { if (dataFilter.getConstraint(binding) == null) { addConstraints(newConstraints, binding); } } if (!newConstraints.isEmpty()) { dataFilter.addConstraints(newConstraints); } List<DBDAttributeBinding> newBindings = new ArrayList<>(); for (DBSAttributeBase attr : this.dataFilter.getOrderedVisibleAttributes()) { DBDAttributeBinding binding = getAttributeBinding(attr); if (binding != null) { newBindings.add(binding); } } if (!newBindings.equals(visibleAttributes)) { visibleAttributes = newBindings; return true; } return false; } void updateDataFilter(DBDDataFilter filter) { this.visibleAttributes.clear(); Collections.addAll(this.visibleAttributes, this.attributes); for (DBDAttributeConstraint constraint : filter.getConstraints()) { DBDAttributeConstraint filterConstraint = this.dataFilter.getConstraint(constraint.getAttribute(), true); if (filterConstraint == null) { //log.warn("Constraint for attribute [" + constraint.getAttribute().getName() + "] not found"); continue; } if (constraint.getOperator() != null) { filterConstraint.setOperator(constraint.getOperator()); filterConstraint.setReverseOperator(constraint.isReverseOperator()); filterConstraint.setValue(constraint.getValue()); } else { filterConstraint.setCriteria(constraint.getCriteria()); } filterConstraint.setOrderPosition(constraint.getOrderPosition()); filterConstraint.setOrderDescending(constraint.isOrderDescending()); filterConstraint.setVisible(constraint.isVisible()); filterConstraint.setVisualPosition(constraint.getVisualPosition()); if (filterConstraint.getAttribute() instanceof DBDAttributeBinding) { if (!constraint.isVisible()) { visibleAttributes.remove(filterConstraint.getAttribute()); } else { if (!visibleAttributes.contains(filterConstraint.getAttribute())) { DBDAttributeBinding attribute = (DBDAttributeBinding) filterConstraint.getAttribute(); if (attribute.getParentObject() == null) { // Add only root attributes visibleAttributes.add(attribute); } } } } } if (filter.getConstraints().size() != attributes.length) { // Update visibility for (Iterator<DBDAttributeBinding> iter = visibleAttributes.iterator(); iter.hasNext(); ) { final DBDAttributeBinding attr = iter.next(); if (filter.getConstraint(attr, true) == null) { // No constraint for this attribute: use default visibility if (!isVisibleByDefault(attr)) { iter.remove(); } } } } this.visibleAttributes.sort(POSITION_SORTER); this.dataFilter.setWhere(filter.getWhere()); this.dataFilter.setOrder(filter.getOrder()); this.dataFilter.setAnyConstraint(filter.isAnyConstraint()); } public void resetOrdering() { final boolean hasOrdering = dataFilter.hasOrdering(); // Sort locally final List<DBDAttributeConstraint> orderConstraints = dataFilter.getOrderConstraints(); curRows.sort((row1, row2) -> { if (!hasOrdering) { return row1.getRowNumber() - row2.getRowNumber(); } int result = 0; for (DBDAttributeConstraint co : orderConstraints) { final DBDAttributeBinding binding = getAttributeBinding(co.getAttribute()); if (binding == null) { continue; } Object cell1 = getCellValue(binding, row1); Object cell2 = getCellValue(binding, row2); if (cell1 == cell2) { result = 0; } else if (DBUtils.isNullValue(cell1)) { result = 1; } else if (DBUtils.isNullValue(cell2)) { result = -1; } else if (cell1 instanceof Comparable) { result = ((Comparable) cell1).compareTo(cell2); } else { String str1 = String.valueOf(cell1); String str2 = String.valueOf(cell2); result = str1.compareTo(str2); } if (co.isOrderDescending()) { result = -result; } if (result != 0) { break; } } return result; }); for (int i = 0; i < curRows.size(); i++) { curRows.get(i).setVisualNumber(i); } } private void fillVisibleAttributes() { this.visibleAttributes.clear(); boolean entityDataView = executionSource != null && executionSource.getDataContainer() instanceof DBSEntity; DBSObjectFilter columnFilter = null; if (entityDataView) { // Detect column filter DBSEntity entity = (DBSEntity) executionSource.getDataContainer(); DBPDataSourceContainer container = entity.getDataSource().getContainer(); if (container.getPreferenceStore().getBoolean(ResultSetPreferences.RESULT_SET_USE_NAVIGATOR_FILTERS) && attributes.length > 0) { DBSEntityAttribute entityAttribute = attributes[0].getEntityAttribute(); if (entityAttribute != null) { columnFilter = container.getObjectFilter(entityAttribute.getClass(), entity, false); } } } // Filter pseudo attributes if we query single entity for (DBDAttributeBinding binding : this.attributes) { if (!entityDataView || isVisibleByDefault(binding)) { // Make visible "real" attributes if (columnFilter != null && !columnFilter.matches(binding.getName())) { // Filtered out by column filter continue; } this.visibleAttributes.add(binding); } } } private static boolean isVisibleByDefault(DBDAttributeBinding binding) { return !binding.isPseudoAttribute(); } public DBCStatistics getStatistics() { return statistics; } public void setStatistics(DBCStatistics statistics) { this.statistics = statistics; } public DBCTrace getTrace() { return trace; } }
RSV: local results ordering fix Former-commit-id: 277d78019e6976e0e382719ee8720b471e94cf8c
plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetModel.java
RSV: local results ordering fix
<ide><path>lugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/ResultSetModel.java <ide> result = 1; <ide> } else if (DBUtils.isNullValue(cell2)) { <ide> result = -1; <add> } else if (cell1 instanceof Number && cell2 instanceof Number) { <add> // Actual data type for the same column may differ (e.g. partially read from server, partially added on client side) <add> double numDiff = ((Number) cell1).doubleValue() - ((Number) cell2).doubleValue(); <add> result = numDiff < 0 ? -1 : (numDiff > 0 ? 1 : 0); <ide> } else if (cell1 instanceof Comparable) { <ide> result = ((Comparable) cell1).compareTo(cell2); <ide> } else {
Java
lgpl-2.1
9ad83c6f77391d4315f2f3a9da70d6a7ac904e4b
0
melloc/roguelike,melloc/roguelike
package edu.brown.cs.roguelike.engine.proc; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.geom.Rectangle2D; import cs195n.Vec2i; import edu.brown.cs.roguelike.engine.level.Hallway; import edu.brown.cs.roguelike.engine.level.Level; import edu.brown.cs.roguelike.engine.level.Room; import edu.brown.cs.roguelike.engine.level.Tile; import edu.brown.cs.roguelike.engine.proc.cs195n.Application; /** * A tester for level generation * @author jte * */ public class LevelGenTester extends Application { private final int SIZEX = 80; private final int SIZEY = 60; RoomGenerator rg; Level level; int scalex; int scaley; private boolean drawn = false; public LevelGenTester(String title, boolean fullscreen) { super(title, fullscreen); rg = new RoomGenerator(); level = rg.generateLevel(new Vec2i(SIZEX,SIZEY)); scalex = DEFAULT_WINDOW_SIZE.x / SIZEX; scaley = DEFAULT_WINDOW_SIZE.y / SIZEY; } public static void main(String[] args) { LevelGenTester test = new LevelGenTester("DAT LEVELGEN!", false); test.startup(); } @Override protected void onDraw(Graphics2D g) { //if(!drawn) //{ for(int i = 0; i<level.tiles.length; i++) { for(int j = 0; j<level.tiles[0].length; j++) { Tile t = level.tiles[i][j]; Rectangle2D rect = new Rectangle2D.Float(i*scalex,j*scaley,(i+1)*scalex,(j+1)*scaley); if(t.isPassable()) { g.setColor(Color.gray); } else { g.setColor(Color.black); } g.fill(rect); g.setColor(Color.LIGHT_GRAY); g.draw(rect); } } for(Room r : level.getRooms()) { Rectangle2D rect = new Rectangle2D.Float(r.min.x*scalex,r.min.y*scaley,(r.max.x - r.min.x + 1)*scalex,(r.max.y - r.min.y + 1)*scaley); g.setColor(Color.green); g.draw(rect); } for(Hallway h : level.getHallways()) { int minX = Math.min(h.startTile.x, h.endTile.x); int minY = Math.min(h.startTile.y, h.endTile.y); int width = Math.abs(h.startTile.x- h.endTile.x) + 1; int height = Math.abs(h.startTile.y- h.endTile.y) + 1; Rectangle2D rect = new Rectangle2D.Float(minX*scalex,minY*scaley,width*scalex,height*scaley); g.setColor(Color.red); g.draw(rect); } drawn = true; //} } @Override protected void onKeyTyped(KeyEvent e) { } @Override protected void onKeyPressed(KeyEvent e) { level = rg.generateLevel(new Vec2i(SIZEX,SIZEY)); drawn = false; } @Override protected void onKeyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseDragged(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseMoved(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseWheelMoved(MouseWheelEvent e) { // TODO Auto-generated method stub } @Override protected void onResize(Vec2i newSize) { // TODO Auto-generated method stub } }
engine/src/main/java/edu/brown/cs/roguelike/engine/proc/LevelGenTester.java
package edu.brown.cs.roguelike.engine.proc; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.geom.Rectangle2D; import cs195n.Vec2i; import edu.brown.cs.roguelike.engine.level.Level; import edu.brown.cs.roguelike.engine.level.Tile; import edu.brown.cs.roguelike.engine.proc.cs195n.Application; /** * A tester for level generation * @author jte * */ public class LevelGenTester extends Application { private final int SIZEX = 80; private final int SIZEY = 60; RoomGenerator rg; Level level; int scalex; int scaley; private boolean drawn = false; public LevelGenTester(String title, boolean fullscreen) { super(title, fullscreen); rg = new RoomGenerator(); level = rg.generateLevel(new Vec2i(SIZEX,SIZEY)); scalex = DEFAULT_WINDOW_SIZE.x / SIZEX; scaley = DEFAULT_WINDOW_SIZE.y / SIZEY; } public static void main(String[] args) { LevelGenTester test = new LevelGenTester("DAT LEVELGEN!", false); test.startup(); } @Override protected void onDraw(Graphics2D g) { //if(!drawn) //{ for(int i = 0; i<level.tiles.length; i++) { for(int j = 0; j<level.tiles[0].length; j++) { Tile t = level.tiles[i][j]; Rectangle2D rect = new Rectangle2D.Float(i*scalex,j*scaley,(i+1)*scalex,(j+1)*scaley); if(t.isPassable()) { g.setColor(Color.gray); } else { g.setColor(Color.black); } g.fill(rect); g.setColor(Color.LIGHT_GRAY); g.draw(rect); } } drawn = true; //} } @Override protected void onKeyTyped(KeyEvent e) { } @Override protected void onKeyPressed(KeyEvent e) { level = rg.generateLevel(new Vec2i(SIZEX,SIZEY)); drawn = false; } @Override protected void onKeyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseDragged(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseMoved(MouseEvent e) { // TODO Auto-generated method stub } @Override protected void onMouseWheelMoved(MouseWheelEvent e) { // TODO Auto-generated method stub } @Override protected void onResize(Vec2i newSize) { // TODO Auto-generated method stub } }
Updated Levelgen Viewer with colour display Rooms higlighted in green and hallways highlighted in red
engine/src/main/java/edu/brown/cs/roguelike/engine/proc/LevelGenTester.java
Updated Levelgen Viewer with colour display
<ide><path>ngine/src/main/java/edu/brown/cs/roguelike/engine/proc/LevelGenTester.java <ide> import java.awt.geom.Rectangle2D; <ide> <ide> import cs195n.Vec2i; <add>import edu.brown.cs.roguelike.engine.level.Hallway; <ide> import edu.brown.cs.roguelike.engine.level.Level; <add>import edu.brown.cs.roguelike.engine.level.Room; <ide> import edu.brown.cs.roguelike.engine.level.Tile; <ide> import edu.brown.cs.roguelike.engine.proc.cs195n.Application; <ide> <ide> g.draw(rect); <ide> } <ide> } <add> for(Room r : level.getRooms()) { <add> Rectangle2D rect = new Rectangle2D.Float(r.min.x*scalex,r.min.y*scaley,(r.max.x - r.min.x + 1)*scalex,(r.max.y - r.min.y + 1)*scaley); <add> g.setColor(Color.green); <add> g.draw(rect); <add> } <add> for(Hallway h : level.getHallways()) { <add> int minX = Math.min(h.startTile.x, h.endTile.x); <add> int minY = Math.min(h.startTile.y, h.endTile.y); <add> int width = Math.abs(h.startTile.x- h.endTile.x) + 1; <add> int height = Math.abs(h.startTile.y- h.endTile.y) + 1; <add> Rectangle2D rect = new Rectangle2D.Float(minX*scalex,minY*scaley,width*scalex,height*scaley); <add> <add> g.setColor(Color.red); <add> g.draw(rect); <add> } <add> <ide> drawn = true; <add> <add> <ide> //} <ide> } <ide>
Java
apache-2.0
a08ca79ef7bacb2727db1b8feb53afe55634aa0f
0
google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt,google/conscrypt
/* * Copyright (C) 2012 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 org.conscrypt; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidParameterException; import java.security.spec.ECField; import java.security.spec.ECFieldFp; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.EllipticCurve; /** * Represents a BoringSSL EC_GROUP object. */ final class OpenSSLECGroupContext { private final NativeRef.EC_GROUP groupCtx; OpenSSLECGroupContext(NativeRef.EC_GROUP groupCtx) { this.groupCtx = groupCtx; } static OpenSSLECGroupContext getCurveByName(String curveName) { // Workaround for OpenSSL not supporting SECG names for NIST P-256 (aka // ANSI X9.62 prime256v1). if ("secp256r1".equals(curveName)) { curveName = "prime256v1"; } final long ctx = NativeCrypto.EC_GROUP_new_by_curve_name(curveName); if (ctx == 0) { return null; } NativeRef.EC_GROUP groupRef = new NativeRef.EC_GROUP(ctx); return new OpenSSLECGroupContext(groupRef); } @Override public boolean equals(Object o) { throw new IllegalArgumentException("OpenSSLECGroupContext.equals is not defined"); } @Override public int hashCode() { // TODO Auto-generated method stub return super.hashCode(); } NativeRef.EC_GROUP getNativeRef() { return groupCtx; } static OpenSSLECGroupContext getInstance(ECParameterSpec params) throws InvalidAlgorithmParameterException { String curveName = Platform.getCurveName(params); if (curveName != null) { return OpenSSLECGroupContext.getCurveByName(curveName); } // Try to find recognise the underlying curve from the parameters. final EllipticCurve curve = params.getCurve(); final ECField field = curve.getField(); final BigInteger p; if (field instanceof ECFieldFp) { p = ((ECFieldFp) field).getP(); } else { throw new InvalidParameterException("unhandled field class " + field.getClass().getName()); } final ECPoint generator = params.getGenerator(); final BigInteger b = curve.getB(); final BigInteger x = generator.getAffineX(); final BigInteger y = generator.getAffineY(); // The 'a' value isn't checked in the following because it's unclear // whether users would set it to -3 or p-3. switch (p.bitLength()) { case 224: if (p.toString(16).equals("ffffffffffffffffffffffffffffffff000000000000000000000001") && b.toString(16).equals("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4") && x.toString(16).equals("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21") && y.toString(16).equals("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34")) { curveName = "secp224r1"; } break; case 256: if (p.toString(16).equals("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff") && b.toString(16).equals("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b") && x.toString(16).equals("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296") && y.toString(16).equals("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")) { curveName = "prime256v1"; } break; case 384: if (p.toString(16).equals("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff") && b.toString(16).equals("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef") && x.toString(16).equals("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7") && y.toString(16).equals("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")) { curveName = "secp384r1"; } break; case 521: if (p.toString(16).equals("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") && b.toString(16).equals("51953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00") && x.toString(16).equals("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66") && y.toString(16).equals("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")) { curveName = "secp521r1"; } break; } if (curveName != null) { return OpenSSLECGroupContext.getCurveByName(curveName); } final BigInteger a = curve.getA(); final BigInteger order = params.getOrder(); final int cofactor = params.getCofactor(); long group; try { group = NativeCrypto.EC_GROUP_new_arbitrary( p.toByteArray(), a.toByteArray(), b.toByteArray(), x.toByteArray(), y.toByteArray(), order.toByteArray(), cofactor); } catch (Throwable exception) { throw new InvalidAlgorithmParameterException("EC_GROUP_new_arbitrary failed", exception); } if (group == 0) { throw new InvalidAlgorithmParameterException("EC_GROUP_new_arbitrary returned NULL"); } NativeRef.EC_GROUP groupRef = new NativeRef.EC_GROUP(group); return new OpenSSLECGroupContext(groupRef); } ECParameterSpec getECParameterSpec() { final String curveName = NativeCrypto.EC_GROUP_get_curve_name(groupCtx); final byte[][] curveParams = NativeCrypto.EC_GROUP_get_curve(groupCtx); final BigInteger p = new BigInteger(curveParams[0]); final BigInteger a = new BigInteger(curveParams[1]); final BigInteger b = new BigInteger(curveParams[2]); final ECField field = new ECFieldFp(p); final EllipticCurve curve = new EllipticCurve(field, a, b); final OpenSSLECPointContext generatorCtx = new OpenSSLECPointContext(this, new NativeRef.EC_POINT(NativeCrypto.EC_GROUP_get_generator(groupCtx))); final ECPoint generator = generatorCtx.getECPoint(); final BigInteger order = new BigInteger(NativeCrypto.EC_GROUP_get_order(groupCtx)); final BigInteger cofactor = new BigInteger(NativeCrypto.EC_GROUP_get_cofactor(groupCtx)); ECParameterSpec spec = new ECParameterSpec(curve, generator, order, cofactor.intValue()); Platform.setCurveName(spec, curveName); return spec; } }
common/src/main/java/org/conscrypt/OpenSSLECGroupContext.java
/* * Copyright (C) 2012 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 org.conscrypt; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidParameterException; import java.security.spec.ECField; import java.security.spec.ECFieldFp; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.EllipticCurve; /** * Represents a BoringSSL EC_GROUP object. */ final class OpenSSLECGroupContext { private final NativeRef.EC_GROUP groupCtx; OpenSSLECGroupContext(NativeRef.EC_GROUP groupCtx) { this.groupCtx = groupCtx; } static OpenSSLECGroupContext getCurveByName(String curveName) { // Workaround for OpenSSL not supporting SECG names for NIST P-256 (aka // ANSI X9.62 prime256v1). if ("secp256r1".equals(curveName)) { curveName = "prime256v1"; } final long ctx = NativeCrypto.EC_GROUP_new_by_curve_name(curveName); if (ctx == 0) { return null; } NativeRef.EC_GROUP groupRef = new NativeRef.EC_GROUP(ctx); return new OpenSSLECGroupContext(groupRef); } @Override public boolean equals(Object o) { throw new IllegalArgumentException("OpenSSLECGroupContext.equals is not defined"); } @Override public int hashCode() { // TODO Auto-generated method stub return super.hashCode(); } NativeRef.EC_GROUP getNativeRef() { return groupCtx; } static OpenSSLECGroupContext getInstance(ECParameterSpec params) throws InvalidAlgorithmParameterException { String curveName = Platform.getCurveName(params); if (curveName != null) { return OpenSSLECGroupContext.getCurveByName(curveName); } // Try to find recognise the underlying curve from the parameters. final EllipticCurve curve = params.getCurve(); final ECField field = curve.getField(); final BigInteger p; if (field instanceof ECFieldFp) { p = ((ECFieldFp) field).getP(); } else { throw new InvalidParameterException("unhandled field class " + field.getClass().getName()); } final ECPoint generator = params.getGenerator(); final BigInteger b = curve.getB(); final BigInteger x = generator.getAffineX(); final BigInteger y = generator.getAffineY(); // The 'a' value isn't checked in the following because it's unclear // whether users would set it to -3 or p-3. switch (p.bitLength()) { case 224: if (p.toString(16).equals("ffffffffffffffffffffffffffffffff000000000000000000000001") && b.toString(16).equals("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4") && x.toString(16).equals("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21") && y.toString(16).equals("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34")) { curveName = "secp224r1"; } break; case 256: if (p.toString(16).equals("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff") && b.toString(16).equals("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b") && x.toString(16).equals("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296") && y.toString(16).equals("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")) { curveName = "prime256v1"; } break; case 384: if (p.toString(16).equals("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff") && b.toString(16).equals("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef") && x.toString(16).equals("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7") && y.toString(16).equals("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")) { curveName = "secp384r1"; } break; case 521: if (p.toString(16).equals("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") && b.toString(16).equals("051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00") && x.toString(16).equals("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66") && y.toString(16).equals("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")) { curveName = "secp521r1"; } break; } if (curveName != null) { return OpenSSLECGroupContext.getCurveByName(curveName); } final BigInteger a = curve.getA(); final BigInteger order = params.getOrder(); final int cofactor = params.getCofactor(); long group; try { group = NativeCrypto.EC_GROUP_new_arbitrary( p.toByteArray(), a.toByteArray(), b.toByteArray(), x.toByteArray(), y.toByteArray(), order.toByteArray(), cofactor); } catch (Throwable exception) { throw new InvalidAlgorithmParameterException("EC_GROUP_new_arbitrary failed", exception); } if (group == 0) { throw new InvalidAlgorithmParameterException("EC_GROUP_new_arbitrary returned NULL"); } NativeRef.EC_GROUP groupRef = new NativeRef.EC_GROUP(group); return new OpenSSLECGroupContext(groupRef); } ECParameterSpec getECParameterSpec() { final String curveName = NativeCrypto.EC_GROUP_get_curve_name(groupCtx); final byte[][] curveParams = NativeCrypto.EC_GROUP_get_curve(groupCtx); final BigInteger p = new BigInteger(curveParams[0]); final BigInteger a = new BigInteger(curveParams[1]); final BigInteger b = new BigInteger(curveParams[2]); final ECField field = new ECFieldFp(p); final EllipticCurve curve = new EllipticCurve(field, a, b); final OpenSSLECPointContext generatorCtx = new OpenSSLECPointContext(this, new NativeRef.EC_POINT(NativeCrypto.EC_GROUP_get_generator(groupCtx))); final ECPoint generator = generatorCtx.getECPoint(); final BigInteger order = new BigInteger(NativeCrypto.EC_GROUP_get_order(groupCtx)); final BigInteger cofactor = new BigInteger(NativeCrypto.EC_GROUP_get_cofactor(groupCtx)); ECParameterSpec spec = new ECParameterSpec(curve, generator, order, cofactor.intValue()); Platform.setCurveName(spec, curveName); return spec; } }
Remove the leading zero in secp521r1 detection value. (#371) BigInteger.toString() doesn't produce leading zeroes, so this was preventing us from detecting secp521r1 when specified as parameters instead of by name.
common/src/main/java/org/conscrypt/OpenSSLECGroupContext.java
Remove the leading zero in secp521r1 detection value. (#371)
<ide><path>ommon/src/main/java/org/conscrypt/OpenSSLECGroupContext.java <ide> break; <ide> case 521: <ide> if (p.toString(16).equals("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") && <del> b.toString(16).equals("051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00") && <add> b.toString(16).equals("51953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00") && <ide> x.toString(16).equals("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66") && <ide> y.toString(16).equals("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")) { <ide> curveName = "secp521r1";
Java
mit
c40a1dcb2f72f3c5f7a609f3010944e74f96c565
0
WojciechKo/Walletudo,WojciechKo/Walletudo
package com.walletudo.ui.statistics; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.CardView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.github.clans.fab.FloatingActionMenu; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.walletudo.R; import com.walletudo.Walletudo; import com.walletudo.model.Tag; import com.walletudo.service.StatisticService; import com.walletudo.ui.view.AmountView; import com.walletudo.ui.view.PeriodView; import com.walletudo.ui.view.TagView; import org.joda.time.LocalDate; import java.util.List; import java.util.Map; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; public class StatisticFragment extends Fragment { private static final int FAB_MENU_COUNT = 3; @InjectView(R.id.summaryView) CardView summaryView; @InjectView(R.id.balance) AmountView balance; @InjectView(R.id.period) PeriodView period; @InjectView(R.id.viewPager) ViewPager viewPager; @InjectView(R.id.emptyProfitList) TextView emptyProfitList; @InjectView(R.id.profitList) ListView profitList; @InjectView(R.id.emptyLostList) TextView emptyLostList; @InjectView(R.id.lostList) ListView lostList; @InjectView(R.id.fab) FloatingActionMenu fab; @Inject StatisticService statisticService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((Walletudo) getActivity().getApplication()).component().inject(this); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = View.inflate(getActivity(), R.layout.fragment_statistics, null); ButterKnife.inject(this, view); setupViews(); onFabWeekPeriodClick(); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.toolbar_tabs); tabLayout.setVisibility(View.VISIBLE); tabLayout.setupWithViewPager(viewPager); } private void setupViews() { profitList.setEmptyView(emptyProfitList); lostList.setEmptyView(emptyLostList); viewPager.setAdapter(new PagerAdapter() { @Override public Object instantiateItem(ViewGroup container, int position) { switch (position) { case 0: return getActivity().findViewById(R.id.profitView); case 1: return getActivity().findViewById(R.id.lostView); } return null; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.statisticsProfitLabel); case 1: return getString(R.string.statisticsLostLabel); } return ""; } @Override public int getCount() { return 2; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((View) object); } }); } @OnClick(R.id.fab_week) public void onFabWeekPeriodClick() { LocalDate now = LocalDate.now(); setupStatisticFromPeriod(now.dayOfWeek().withMinimumValue(), now.dayOfWeek().withMaximumValue()); fab.close(true); } @OnClick(R.id.fab_month) public void onFabMonthPeriodClick() { LocalDate now = LocalDate.now(); setupStatisticFromPeriod(now.dayOfMonth().withMinimumValue(), now.dayOfMonth().withMaximumValue()); fab.close(true); } @OnClick(R.id.fab_custom) public void onFabCustomPeriodClick() { Toast.makeText(getActivity(), getActivity().getString(R.string.statisticCustomPeriodNotAvailable), Toast.LENGTH_SHORT).show(); } private void setupStatisticFromPeriod(LocalDate from, LocalDate to) { StatisticService.Statistics statistics = statisticService.getStatistics(from.toDate(), to.toDate()); balance.setAmount(statistics.getBalance()); period.setPeriod(from.toDate(), to.plusDays(1).toDate()); profitList.setAdapter(new StatisticEntryAdapter(getActivity(), statistics.getProfit())); handlePaddingOnProfitAndLostList(); List<Map.Entry<Tag, Double>> lost = Lists.transform(statistics.getLost(), new Function<Map.Entry<Tag, Double>, Map.Entry<Tag, Double>>() { @Override public Map.Entry<Tag, Double> apply(@Nullable Map.Entry<Tag, Double> input) { return Maps.immutableEntry(input.getKey(), -input.getValue()); } }); lostList.setAdapter(new StatisticEntryAdapter(getActivity(), lost)); } private void handlePaddingOnProfitAndLostList() { summaryView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int listTopPadding = summaryView.getHeight() + ((ViewGroup.MarginLayoutParams) summaryView.getLayoutParams()).topMargin; profitList.setPadding(0, listTopPadding, 0, profitList.getPaddingBottom()); lostList.setPadding(0, listTopPadding, 0, lostList.getPaddingBottom()); summaryView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); fab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int listBottomPadding = (fab.getHeight() / (FAB_MENU_COUNT + 1)) + ((ViewGroup.MarginLayoutParams) fab.getLayoutParams()).bottomMargin; profitList.setPadding(0, profitList.getPaddingTop(), 0, listBottomPadding); lostList.setPadding(0, profitList.getPaddingTop(), 0, listBottomPadding); summaryView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } public static class StatisticEntryAdapter extends BaseAdapter { private List<Map.Entry<Tag, Double>> profit; private Context context; public StatisticEntryAdapter(Context context, List<Map.Entry<Tag, Double>> profit) { this.context = context; this.profit = profit; } @Override public int getCount() { return profit.size(); } @Override public Map.Entry<Tag, Double> getItem(int position) { return profit.get(position); } @Override public long getItemId(int position) { return getItem(position).getKey().getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_statistics_list, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Map.Entry<Tag, Double> item = getItem(position); holder.tag.setText(item.getKey().getName()); holder.tag.setTagColor(item.getKey().getColor()); holder.amount.setAmount(item.getValue()); return convertView; } static class ViewHolder { @InjectView(R.id.tag) TagView tag; @InjectView(R.id.amount) AmountView amount; ViewHolder(View view) { ButterKnife.inject(this, view); } } } }
app/src/main/java/com/walletudo/ui/statistics/StatisticFragment.java
package com.walletudo.ui.statistics; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.widget.CardView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.github.clans.fab.FloatingActionMenu; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.walletudo.R; import com.walletudo.Walletudo; import com.walletudo.model.Tag; import com.walletudo.service.StatisticService; import com.walletudo.ui.view.AmountView; import com.walletudo.ui.view.PeriodView; import com.walletudo.ui.view.TagView; import org.joda.time.LocalDate; import java.util.List; import java.util.Map; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; public class StatisticFragment extends Fragment { private static final int FAB_MENU_COUNT = 3; @InjectView(R.id.summaryView) CardView summaryView; @InjectView(R.id.balance) AmountView balance; @InjectView(R.id.period) PeriodView period; @InjectView(R.id.viewPager) ViewPager viewPager; @InjectView(R.id.emptyProfitList) TextView emptyProfitList; @InjectView(R.id.profitList) ListView profitList; @InjectView(R.id.emptyLostList) TextView emptyLostList; @InjectView(R.id.lostList) ListView lostList; @InjectView(R.id.fab) FloatingActionMenu fab; @Inject StatisticService statisticService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((Walletudo) getActivity().getApplication()).component().inject(this); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = View.inflate(getActivity(), R.layout.fragment_statistics, null); ButterKnife.inject(this, view); setupViews(); onFabWeekPeriodClick(); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.toolbar_tabs); tabLayout.setVisibility(View.VISIBLE); tabLayout.setupWithViewPager(viewPager); } private void setupViews() { profitList.setEmptyView(emptyProfitList); lostList.setEmptyView(emptyLostList); viewPager.setAdapter(new PagerAdapter() { @Override public Object instantiateItem(ViewGroup container, int position) { switch (position) { case 0: return getActivity().findViewById(R.id.profitView); case 1: return getActivity().findViewById(R.id.lostView); } return null; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.statisticsProfitLabel); case 1: return getString(R.string.statisticsLostLabel); } return ""; } @Override public int getCount() { return 2; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((View) object); } }); } @OnClick(R.id.fab_week) public void onFabWeekPeriodClick() { LocalDate now = LocalDate.now(); setupStatisticFromPeriod(now.dayOfWeek().withMinimumValue(), now.dayOfWeek().withMaximumValue()); fab.close(true); } @OnClick(R.id.fab_month) public void onFabMonthPeriodClick() { LocalDate now = LocalDate.now(); setupStatisticFromPeriod(now.dayOfMonth().withMinimumValue(), now.dayOfMonth().withMaximumValue()); fab.close(true); } @OnClick(R.id.fab_custom) public void onFabCustomPeriodClick() { Toast.makeText(getActivity(), getActivity().getString(R.string.statisticCustomPeriodNotAvailable), Toast.LENGTH_SHORT).show(); } private void setupStatisticFromPeriod(LocalDate from, LocalDate to) { StatisticService.Statistics statistics = statisticService.getStatistics(from.toDate(), to.toDate()); balance.setAmount(statistics.getBalance()); period.setPeriod(from.toDate(), to.plusDays(1).toDate()); profitList.setAdapter(new StatisticEntryAdapter(getActivity(), statistics.getProfit())); int listTopPadding = summaryView.getHeight() + ((ViewGroup.MarginLayoutParams) summaryView.getLayoutParams()).topMargin; int listBottomPaddin = (fab.getHeight() / (FAB_MENU_COUNT + 1)) + ((ViewGroup.MarginLayoutParams) fab.getLayoutParams()).bottomMargin; profitList.setPadding(0, listTopPadding, 0, listBottomPaddin); lostList.setPadding(0, listTopPadding, 0, listBottomPaddin); List<Map.Entry<Tag, Double>> lost = Lists.transform(statistics.getLost(), new Function<Map.Entry<Tag, Double>, Map.Entry<Tag, Double>>() { @Override public Map.Entry<Tag, Double> apply(@Nullable Map.Entry<Tag, Double> input) { return Maps.immutableEntry(input.getKey(), -input.getValue()); } }); lostList.setAdapter(new StatisticEntryAdapter(getActivity(), lost)); } public static class StatisticEntryAdapter extends BaseAdapter { private List<Map.Entry<Tag, Double>> profit; private Context context; public StatisticEntryAdapter(Context context, List<Map.Entry<Tag, Double>> profit) { this.context = context; this.profit = profit; } @Override public int getCount() { return profit.size(); } @Override public Map.Entry<Tag, Double> getItem(int position) { return profit.get(position); } @Override public long getItemId(int position) { return getItem(position).getKey().getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_statistics_list, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Map.Entry<Tag, Double> item = getItem(position); holder.tag.setText(item.getKey().getName()); holder.tag.setTagColor(item.getKey().getColor()); holder.amount.setAmount(item.getValue()); return convertView; } static class ViewHolder { @InjectView(R.id.tag) TagView tag; @InjectView(R.id.amount) AmountView amount; ViewHolder(View view) { ButterKnife.inject(this, view); } } } }
Fix list padding
app/src/main/java/com/walletudo/ui/statistics/StatisticFragment.java
Fix list padding
<ide><path>pp/src/main/java/com/walletudo/ui/statistics/StatisticFragment.java <ide> import android.view.LayoutInflater; <ide> import android.view.View; <ide> import android.view.ViewGroup; <add>import android.view.ViewTreeObserver; <ide> import android.widget.BaseAdapter; <ide> import android.widget.ListView; <ide> import android.widget.TextView; <ide> period.setPeriod(from.toDate(), to.plusDays(1).toDate()); <ide> <ide> profitList.setAdapter(new StatisticEntryAdapter(getActivity(), statistics.getProfit())); <del> int listTopPadding = summaryView.getHeight() + ((ViewGroup.MarginLayoutParams) summaryView.getLayoutParams()).topMargin; <del> int listBottomPaddin = (fab.getHeight() / (FAB_MENU_COUNT + 1)) + ((ViewGroup.MarginLayoutParams) fab.getLayoutParams()).bottomMargin; <del> profitList.setPadding(0, listTopPadding, 0, listBottomPaddin); <del> lostList.setPadding(0, listTopPadding, 0, listBottomPaddin); <add> handlePaddingOnProfitAndLostList(); <ide> <ide> List<Map.Entry<Tag, Double>> lost = Lists.transform(statistics.getLost(), new Function<Map.Entry<Tag, Double>, Map.Entry<Tag, Double>>() { <ide> @Override <ide> } <ide> }); <ide> lostList.setAdapter(new StatisticEntryAdapter(getActivity(), lost)); <add> } <add> <add> private void handlePaddingOnProfitAndLostList() { <add> summaryView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { <add> @Override <add> public void onGlobalLayout() { <add> int listTopPadding = summaryView.getHeight() + ((ViewGroup.MarginLayoutParams) summaryView.getLayoutParams()).topMargin; <add> profitList.setPadding(0, listTopPadding, 0, profitList.getPaddingBottom()); <add> lostList.setPadding(0, listTopPadding, 0, lostList.getPaddingBottom()); <add> summaryView.getViewTreeObserver().removeOnGlobalLayoutListener(this); <add> } <add> }); <add> fab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { <add> @Override <add> public void onGlobalLayout() { <add> int listBottomPadding = (fab.getHeight() / (FAB_MENU_COUNT + 1)) + ((ViewGroup.MarginLayoutParams) fab.getLayoutParams()).bottomMargin; <add> profitList.setPadding(0, profitList.getPaddingTop(), 0, listBottomPadding); <add> lostList.setPadding(0, profitList.getPaddingTop(), 0, listBottomPadding); <add> summaryView.getViewTreeObserver().removeOnGlobalLayoutListener(this); <add> } <add> }); <ide> } <ide> <ide> public static class StatisticEntryAdapter extends BaseAdapter {
Java
mit
43ffbcac41a13bc1c2ebc483179d86cdf23f85e8
0
gurkenlabs/litiengine,gurkenlabs/litiengine
package de.gurkenlabs.utiliti.components; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Stroke; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.gurkenlabs.core.Align; import de.gurkenlabs.core.Valign; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.Resources; import de.gurkenlabs.litiengine.SpriteSheetInfo; import de.gurkenlabs.litiengine.entities.CollisionEntity; import de.gurkenlabs.litiengine.entities.DecorMob.MovementBehavior; import de.gurkenlabs.litiengine.environment.Environment; import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.IMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.ITileset; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperty; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectType; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.environment.tilemap.TmxMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint; import de.gurkenlabs.litiengine.environment.tilemap.xml.Map; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset; import de.gurkenlabs.litiengine.graphics.ImageCache; import de.gurkenlabs.litiengine.graphics.ImageFormat; import de.gurkenlabs.litiengine.graphics.LightSource; import de.gurkenlabs.litiengine.graphics.RenderEngine; import de.gurkenlabs.litiengine.graphics.Spritesheet; import de.gurkenlabs.litiengine.gui.GuiComponent; import de.gurkenlabs.litiengine.input.Input; import de.gurkenlabs.util.MathUtilities; import de.gurkenlabs.util.geom.GeometricUtilities; import de.gurkenlabs.util.io.FileUtilities; import de.gurkenlabs.util.io.ImageSerializer; import de.gurkenlabs.util.io.XmlUtilities; import de.gurkenlabs.utiliti.EditorScreen; import de.gurkenlabs.utiliti.Program; import de.gurkenlabs.utiliti.UndoManager; public class MapComponent extends EditorComponent { public enum TransformType { UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT, NONE } public static final int EDITMODE_CREATE = 0; public static final int EDITMODE_EDIT = 1; public static final int EDITMODE_MOVE = 2; private static final Logger log = Logger.getLogger(MapComponent.class.getName()); private static final float[] zooms = new float[] { 0.1f, 0.25f, 0.5f, 1, 1.5f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 16f, 32f, 50f, 80f, 100f }; private static final String DEFAULT_MAPOBJECTLAYER_NAME = "default"; private static final int TRANSFORM_RECT_SIZE = 6; private static final int BASE_SCROLL_SPEED = 50; private static final Color DEFAULT_COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); private static final Color COLOR_NAME_FILL = new Color(0, 0, 0, 60); private static final Color COLOR_FOCUS_BORDER = Color.BLACK; private static final Color COLOR_SELECTION_BORDER = new Color(0, 0, 0, 200); private static final Color COLOR_COLLISION_FILL = new Color(255, 0, 0, 15); private static final Color COLOR_NOCOLLISION_FILL = new Color(255, 100, 0, 15); private static final Color COLOR_COLLISION_BORDER = Color.RED; private static final Color COLOR_NOCOLLISION_BORDER = Color.ORANGE; private static final Color COLOR_SPAWNPOINT = Color.GREEN; private static final Color COLOR_LANE = Color.YELLOW; private static final Color COLOR_NEWOBJECT_FILL = new Color(0, 255, 0, 50); private static final Color COLOR_NEWOBJECT_BORDER = Color.GREEN.darker(); private static final Color COLOR_TRANSFORM_RECT_FILL = new Color(255, 255, 255, 100); private static final Color COLOR_SHADOW_FILL = new Color(85, 130, 200, 15); private static final Color COLOR_SHADOW_BORDER = new Color(30, 85, 170); private static final Color COLOR_MOUSE_SELECTION_AREA_FILL = new Color(0, 130, 152, 80); private static final Color COLOR_MOUSE_SELECTION_AREA_BORDER = new Color(0, 130, 152, 150); private double currentTransformRectSize = TRANSFORM_RECT_SIZE; private final java.util.Map<TransformType, Rectangle2D> transformRects; private final List<Consumer<Integer>> editModeChangedConsumer; private final List<Consumer<IMapObject>> focusChangedConsumer; private final List<Consumer<Map>> mapLoadedConsumer; private final java.util.Map<String, Point2D> cameraFocus; private final java.util.Map<String, IMapObject> focusedObjects; private final java.util.Map<String, List<MapObject>> selectedObjects; private int currentEditMode = EDITMODE_EDIT; private TransformType currentTransform; private int currentZoomIndex = 7; private final List<Map> maps; private float scrollSpeed = BASE_SCROLL_SPEED; private Point2D startPoint; private Point2D dragPoint; private Point2D dragLocationMapObject; private boolean isMoving; private boolean isTransforming; private boolean isFocussing; private Dimension dragSizeMapObject; private Rectangle2D newObjectArea; private IMapObject copiedMapObject; private int gridSize; private boolean snapToGrid = true; private boolean renderGrid = false; private boolean renderCollisionBoxes = true; private final EditorScreen screen; private boolean loading; private boolean initialized; public MapComponent(final EditorScreen screen) { super(ComponentType.MAP); this.editModeChangedConsumer = new CopyOnWriteArrayList<>(); this.focusChangedConsumer = new CopyOnWriteArrayList<>(); this.mapLoadedConsumer = new CopyOnWriteArrayList<>(); this.focusedObjects = new ConcurrentHashMap<>(); this.selectedObjects = new ConcurrentHashMap<>(); this.maps = new ArrayList<>(); this.cameraFocus = new ConcurrentHashMap<>(); this.transformRects = new ConcurrentHashMap<>(); this.screen = screen; Game.getCamera().onZoomChanged(zoom -> { this.currentTransformRectSize = TRANSFORM_RECT_SIZE / zoom; this.updateTransformControls(); }); this.gridSize = Program.getUserPreferences().getGridSize(); } public void onEditModeChanged(Consumer<Integer> cons) { this.editModeChangedConsumer.add(cons); } public void onFocusChanged(Consumer<IMapObject> cons) { this.focusChangedConsumer.add(cons); } public void onMapLoaded(Consumer<Map> cons) { this.mapLoadedConsumer.add(cons); } @Override public void render(Graphics2D g) { if (Game.getEnvironment() == null) { return; } final BasicStroke shapeStroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); if (this.renderCollisionBoxes) { this.renderCollisionBoxes(g, shapeStroke); } this.renderGrid(g); switch (this.currentEditMode) { case EDITMODE_CREATE: this.renderNewObjectArea(g, shapeStroke); break; case EDITMODE_EDIT: this.renderMouseSelectionArea(g, shapeStroke); break; default: break; } this.renderSelection(g); this.renderFocus(g); super.render(g); } public void loadMaps(String projectPath) { final List<String> files = FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "tmx"); log.log(Level.INFO, "{0} maps found in folder {1}", new Object[] { files.size(), projectPath }); final List<Map> loadedMaps = new ArrayList<>(); for (final String mapFile : files) { final IMapLoader tmxLoader = new TmxMapLoader(); Map map = (Map) tmxLoader.loadMap(mapFile); loadedMaps.add(map); log.log(Level.INFO, "map found: {0}", new Object[] { map.getFileName() }); } this.loadMaps(loadedMaps); } public void loadMaps(List<Map> maps) { EditorScreen.instance().getMapObjectPanel().bind(null); this.setFocus(null, true); this.getMaps().clear(); Collections.sort(maps); this.getMaps().addAll(maps); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); } public List<Map> getMaps() { return this.maps; } public int getGridSize() { return this.gridSize; } public IMapObject getFocusedMapObject() { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { return this.focusedObjects.get(Game.getEnvironment().getMap().getFileName()); } return null; } public IMapObject getCopiedMapObject() { return this.copiedMapObject; } public boolean isLoading() { return this.loading; } @Override public void prepare() { Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0); Game.getScreenManager().getRenderComponent().addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { startPoint = null; } }); this.setupControls(); super.prepare(); this.setupMouseControls(); } public void loadEnvironment(Map map) { this.loading = true; try { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { double x = Game.getCamera().getFocus().getX(); double y = Game.getCamera().getFocus().getY(); Point2D newPoint = new Point2D.Double(x, y); this.cameraFocus.put(Game.getEnvironment().getMap().getFileName(), newPoint); } Point2D newFocus = null; if (this.cameraFocus.containsKey(map.getFileName())) { newFocus = this.cameraFocus.get(map.getFileName()); } else { newFocus = new Point2D.Double(map.getSizeInPixels().getWidth() / 2, map.getSizeInPixels().getHeight() / 2); this.cameraFocus.put(map.getFileName(), newFocus); } Game.getCamera().setFocus(new Point2D.Double(newFocus.getX(), newFocus.getY())); this.ensureUniqueIds(map); Environment env = new Environment(map); env.init(); Game.loadEnvironment(env); Program.updateScrollBars(); EditorScreen.instance().getMapSelectionPanel().setSelection(map.getFileName()); EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); for (Consumer<Map> cons : this.mapLoadedConsumer) { cons.accept(map); } } finally { this.loading = false; } } public void reloadEnvironment() { if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) { return; } this.loadEnvironment((Map) Game.getEnvironment().getMap()); } public void add(IMapObject mapObject) { this.add(mapObject, getCurrentLayer()); } public void add(IMapObject mapObject, IMapObjectLayer layer) { layer.addMapObject(mapObject); Game.getEnvironment().loadFromMap(mapObject.getId()); if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } Game.getScreenManager().getRenderComponent().requestFocus(); this.setFocus(mapObject, true); this.setEditMode(EDITMODE_EDIT); UndoManager.instance().mapObjectAdded(mapObject); } public void copy() { this.copiedMapObject = this.getFocusedMapObject(); } public void paste() { if (this.copiedMapObject != null) { int x = (int) Input.mouse().getMapLocation().getX(); int y = (int) Input.mouse().getMapLocation().getY(); this.paste(x, y); } } public void paste(int x, int y) { if (this.copiedMapObject != null) { this.newObjectArea = new Rectangle(x, y, (int) this.copiedMapObject.getDimension().getWidth(), (int) this.copiedMapObject.getDimension().getHeight()); this.copyMapObject(this.copiedMapObject); } } public void cut() { this.copiedMapObject = this.getFocusedMapObject(); UndoManager.instance().mapObjectDeleting(this.copiedMapObject); this.delete(this.copiedMapObject); } public void delete() { final IMapObject deleteObject = this.getFocusedMapObject(); if (deleteObject == null) { return; } int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), "Do you really want to delete the entity [" + deleteObject.getId() + "]", "Delete Entity?", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.OK_OPTION) { UndoManager.instance().mapObjectDeleting(deleteObject); this.delete(deleteObject); } } public void delete(final IMapObject mapObject) { if (mapObject == null) { return; } MapObjectType type = MapObjectType.get(mapObject.getType()); Game.getEnvironment().getMap().removeMapObject(mapObject.getId()); Game.getEnvironment().remove(mapObject.getId()); if (type == MapObjectType.STATICSHADOW || type == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } this.setFocus(null, true); } public void defineBlueprint() { final String map = Game.getEnvironment().getMap().getFileName(); if (this.getFocusedMapObject() == null) { return; } Object name = JOptionPane.showInputDialog(Game.getScreenManager().getRenderComponent(), "Name:", "Enter blueprint name", JOptionPane.PLAIN_MESSAGE, null, null, this.getFocusedMapObject().getName()); if (name == null) { return; } Blueprint blueprint = new Blueprint(name.toString(), this.selectedObjects.get(map).toArray(new MapObject[this.selectedObjects.get(map).size()])); EditorScreen.instance().getGameFile().getBluePrints().add(blueprint); Program.getAssetTree().forceUpdate(); } public void centerCameraOnFocus() { if (this.getFocusedMapObject() != null) { final Rectangle2D focus = this.getFocus(); if (focus == null) { return; } Game.getCamera().setFocus(new Point2D.Double(focus.getCenterX(), focus.getCenterY())); } } public void setEditMode(int editMode) { if (editMode == this.currentEditMode) { return; } switch (editMode) { case EDITMODE_CREATE: this.setFocus(null, true); EditorScreen.instance().getMapObjectPanel().bind(null); break; case EDITMODE_EDIT: Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); break; case EDITMODE_MOVE: Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_MOVE, 0, 0); break; default: break; } this.currentEditMode = editMode; for (Consumer<Integer> cons : this.editModeChangedConsumer) { cons.accept(this.currentEditMode); } } public void setFocus(IMapObject mapObject, boolean clearSelection) { if (this.isFocussing) { return; } this.isFocussing = true; try { final IMapObject currentFocus = this.getFocusedMapObject(); if (mapObject != null && currentFocus != null && mapObject.equals(currentFocus) || mapObject == null && currentFocus == null) { return; } if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) { return; } if (this.isMoving || this.isTransforming) { return; } EditorScreen.instance().getMapObjectPanel().bind(mapObject); EditorScreen.instance().getMapSelectionPanel().focus(mapObject); if (mapObject == null) { this.focusedObjects.remove(Game.getEnvironment().getMap().getFileName()); } else { this.focusedObjects.put(Game.getEnvironment().getMap().getFileName(), mapObject); } for (Consumer<IMapObject> cons : this.focusChangedConsumer) { cons.accept(mapObject); } this.updateTransformControls(); this.setselection(mapObject, clearSelection, Input.keyboard().isPressed(KeyEvent.VK_SHIFT)); } finally { this.isFocussing = false; } } private void setselection(IMapObject mapObject, boolean clearSelection, boolean shiftPressed) { final String map = Game.getEnvironment().getMap().getFileName(); if (mapObject == null) { this.selectedObjects.get(map).clear(); return; } if (!this.selectedObjects.containsKey(map)) { this.selectedObjects.put(map, new CopyOnWriteArrayList<>()); } if (!clearSelection && shiftPressed) { if (!this.selectedObjects.get(map).contains(mapObject)) { this.selectedObjects.get(map).add((MapObject) mapObject); } return; } this.selectedObjects.get(map).clear(); this.selectedObjects.get(map).add((MapObject) mapObject); } public void setGridSize(int gridSize) { Program.getUserPreferences().setGridSize(gridSize); this.gridSize = gridSize; } public boolean isSnapToGrid() { return this.snapToGrid; } public void setSnapToGrid(boolean snapToGrid) { this.snapToGrid = snapToGrid; } public boolean isRenderGrid() { return this.renderGrid; } public void setRenderGrid(boolean renderGrid) { this.renderGrid = renderGrid; } public boolean isRenderCollisionBoxes() { return this.renderCollisionBoxes; } public void setRenderCollisionBoxes(boolean renderCollisionBoxes) { this.renderCollisionBoxes = renderCollisionBoxes; } public void updateTransformControls() { final Rectangle2D focus = this.getFocus(); if (focus == null) { this.transformRects.clear(); return; } for (TransformType trans : TransformType.values()) { if (trans == TransformType.NONE) { continue; } Rectangle2D transRect = new Rectangle2D.Double(this.getTransX(trans, focus), this.getTransY(trans, focus), this.currentTransformRectSize, this.currentTransformRectSize); this.transformRects.put(trans, transRect); } } public void deleteMap() { if (this.getMaps() == null || this.getMaps().isEmpty()) { return; } if (Game.getEnvironment() == null && Game.getEnvironment().getMap() == null) { return; } int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("hud_deleteMapMessage") + "\n" + Game.getEnvironment().getMap().getName(), Resources.get("hud_deleteMap"), JOptionPane.YES_NO_OPTION); if (n != JOptionPane.YES_OPTION) { return; } this.getMaps().removeIf(x -> x.getFileName().equals(Game.getEnvironment().getMap().getFileName())); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); if (!this.maps.isEmpty()) { this.loadEnvironment(this.maps.get(0)); } else { this.loadEnvironment(null); } } public void importMap() { if (this.getMaps() == null) { return; } JFileChooser chooser; try { String defaultPath = EditorScreen.instance().getProjectPath() != null ? EditorScreen.instance().getProjectPath() : new File(".").getCanonicalPath(); chooser = new JFileChooser(defaultPath); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setDialogTitle("Import Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); int result = chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()); if (result == JFileChooser.APPROVE_OPTION) { final IMapLoader tmxLoader = new TmxMapLoader(); String mapPath = chooser.getSelectedFile().toString(); Map map = (Map) tmxLoader.loadMap(mapPath); if (map == null) { log.log(Level.WARNING, "could not load map from file {0}", new Object[] { mapPath }); return; } if (map.getMapObjectLayers().isEmpty()) { // make sure there's a map object layer on the map because we need one to add // any kind of entities MapObjectLayer layer = new MapObjectLayer(); layer.setName(DEFAULT_MAPOBJECTLAYER_NAME); map.addMapObjectLayer(layer); } Optional<Map> current = this.maps.stream().filter(x -> x.getFileName().equals(map.getFileName())).findFirst(); if (current.isPresent()) { int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), "Do you really want to replace the existing map '" + map.getFileName() + "' ?", "Replace Map", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { this.getMaps().remove(current.get()); ImageCache.MAPS.clear(); } else { return; } } this.getMaps().add(map); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); // remove old spritesheets for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.find(tileSet.getImage().getSource()); if (sprite != null) { Spritesheet.remove(sprite.getName()); this.screen.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(sprite.getName())); } } for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.load(tileSet); this.screen.getGameFile().getSpriteSheets().add(new SpriteSheetInfo(sprite)); } for (IImageLayer imageLayer : map.getImageLayers()) { BufferedImage img = Resources.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true); Spritesheet sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight()); this.screen.getGameFile().getSpriteSheets().add(new SpriteSheetInfo(sprite)); } // remove old tilesets for (ITileset tileset : map.getExternalTilesets()) { this.screen.getGameFile().getTilesets().removeIf(x -> x.getName().equals(tileset.getName())); } this.screen.getGameFile().getTilesets().addAll(map.getExternalTilesets()); this.loadEnvironment(map); log.log(Level.INFO, "imported map {0}", new Object[] { map.getFileName() }); } } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } } public void exportMap() { if (this.getMaps() == null || this.getMaps().isEmpty()) { return; } Map map = (Map) Game.getEnvironment().getMap(); if (map == null) { return; } this.exportMap(map); } public void exportMap(Map map) { JFileChooser chooser; try { String source = EditorScreen.instance().getProjectPath(); chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setDialogTitle("Export Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); chooser.setSelectedFile(new File(map.getFileName() + "." + Map.FILE_EXTENSION)); int result = chooser.showSaveDialog(Game.getScreenManager().getRenderComponent()); if (result == JFileChooser.APPROVE_OPTION) { String newFile = XmlUtilities.save(map, chooser.getSelectedFile().toString(), Map.FILE_EXTENSION); // save all tilesets manually because a map has a relative reference to // the tilesets String dir = FileUtilities.getParentDirPath(newFile); for (ITileset tileSet : map.getTilesets()) { ImageFormat format = ImageFormat.get(FileUtilities.getExtension(tileSet.getImage().getSource())); ImageSerializer.saveImage(Paths.get(dir, tileSet.getImage().getSource()).toString(), Spritesheet.find(tileSet.getImage().getSource()).getImage(), format); Tileset tile = (Tileset) tileSet; if (tile.isExternal()) { tile.saveSource(dir); } } log.log(Level.INFO, "exported {0} to {1}", new Object[] { map.getFileName(), newFile }); } } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } } public void zoomIn() { if (this.currentZoomIndex < zooms.length - 1) { this.currentZoomIndex++; } this.setCurrentZoom(); this.updateScrollSpeed(); } public void zoomOut() { if (this.currentZoomIndex > 0) { this.currentZoomIndex--; } this.setCurrentZoom(); this.updateScrollSpeed(); } private void updateScrollSpeed() { this.scrollSpeed = BASE_SCROLL_SPEED / zooms[this.currentZoomIndex]; } private IMapObject copyMapObject(IMapObject obj) { IMapObject mo = new MapObject(); mo.setType(obj.getType()); mo.setX(this.snapX(this.newObjectArea.getX())); mo.setY(this.snapY(this.newObjectArea.getY())); mo.setWidth((int) obj.getDimension().getWidth()); mo.setHeight((int) obj.getDimension().getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(obj.getName()); mo.setCustomProperties(obj.getAllCustomProperties()); this.add(mo); return mo; } private void ensureUniqueIds(IMap map) { int maxMapId = MapUtilities.getMaxMapId(map); List<Integer> usedIds = new ArrayList<>(); for (IMapObject obj : map.getMapObjects()) { if (usedIds.contains(obj.getId())) { obj.setId(++maxMapId); } usedIds.add(obj.getId()); } } private static IMapObjectLayer getCurrentLayer() { int layerIndex = EditorScreen.instance().getMapSelectionPanel().getSelectedLayerIndex(); if (layerIndex < 0 || layerIndex >= Game.getEnvironment().getMap().getMapObjectLayers().size()) { layerIndex = 0; } return Game.getEnvironment().getMap().getMapObjectLayers().get(layerIndex); } private IMapObject createNewMapObject(MapObjectType type) { IMapObject mo = new MapObject(); mo.setType(type.toString()); mo.setX((int) this.newObjectArea.getX()); mo.setY((int) this.newObjectArea.getY()); mo.setWidth((int) this.newObjectArea.getWidth()); mo.setHeight((int) this.newObjectArea.getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(""); switch (type) { case PROP: mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObjectArea.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObjectArea.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISION, "true"); mo.setCustomProperty(MapObjectProperty.PROP_INDESTRUCTIBLE, "false"); mo.setCustomProperty(MapObjectProperty.PROP_ADDSHADOW, "true"); break; case DECORMOB: mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObjectArea.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObjectArea.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISION, "false"); mo.setCustomProperty(MapObjectProperty.DECORMOB_VELOCITY, "2"); mo.setCustomProperty(MapObjectProperty.DECORMOB_BEHAVIOUR, MovementBehavior.IDLE.toString()); break; case LIGHTSOURCE: mo.setCustomProperty(MapObjectProperty.LIGHT_ALPHA, "180"); mo.setCustomProperty(MapObjectProperty.LIGHT_COLOR, "#ffffff"); mo.setCustomProperty(MapObjectProperty.LIGHT_SHAPE, LightSource.ELLIPSE); mo.setCustomProperty(MapObjectProperty.LIGHT_ACTIVE, "true"); break; case SPAWNPOINT: default: break; } this.add(mo); return mo; } private Rectangle2D getCurrentMouseSelectionArea(boolean snap) { final Point2D start = this.startPoint; if (start == null) { return null; } final Point2D endPoint = Input.mouse().getMapLocation(); double minX = Math.min(start.getX(), endPoint.getX()); double maxX = Math.max(start.getX(), endPoint.getX()); double minY = Math.min(start.getY(), endPoint.getY()); double maxY = Math.max(start.getY(), endPoint.getY()); if (snap) { minX = this.snapX(minX); maxX = this.snapX(maxX); minY = this.snapY(minY); maxY = this.snapY(maxY); } double width = Math.abs(minX - maxX); double height = Math.abs(minY - maxY); return new Rectangle2D.Double(minX, minY, width, height); } private Rectangle2D getFocus() { final IMapObject focusedObject = this.getFocusedMapObject(); if (focusedObject == null) { return null; } return focusedObject.getBoundingBox(); } private double getTransX(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case UP: return focus.getCenterX() - this.currentTransformRectSize / 2; case LEFT: case DOWNLEFT: case UPLEFT: return focus.getX() - this.currentTransformRectSize; case RIGHT: case DOWNRIGHT: case UPRIGHT: return focus.getMaxX(); default: return 0; } } private double getTransY(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case DOWNLEFT: case DOWNRIGHT: return focus.getMaxY(); case UP: case UPLEFT: case UPRIGHT: return focus.getY() - this.currentTransformRectSize; case LEFT: case RIGHT: return focus.getCenterY() - this.currentTransformRectSize / 2; default: return 0; } } private void handleTransform() { final IMapObject transformObject = this.getFocusedMapObject(); if (transformObject == null || this.currentEditMode != EDITMODE_EDIT || currentTransform == TransformType.NONE) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(transformObject.getX(), transformObject.getY()); this.dragSizeMapObject = new Dimension(transformObject.getDimension()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newWidth = this.dragSizeMapObject.getWidth(); double newHeight = this.dragSizeMapObject.getHeight(); double newX = this.snapX(this.dragLocationMapObject.getX()); double newY = this.snapY(this.dragLocationMapObject.getY()); switch (this.currentTransform) { case DOWN: newHeight += deltaY; break; case DOWNRIGHT: newHeight += deltaY; newWidth += deltaX; break; case DOWNLEFT: newHeight += deltaY; newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case LEFT: newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case RIGHT: newWidth += deltaX; break; case UP: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); break; case UPLEFT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case UPRIGHT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth += deltaX; break; default: return; } transformObject.setWidth(this.snapX(newWidth)); transformObject.setHeight(this.snapY(newHeight)); transformObject.setX(this.snapX(newX)); transformObject.setY(this.snapY(newY)); Game.getEnvironment().reloadFromMap(transformObject.getId()); if (MapObjectType.get(transformObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(transformObject); this.updateTransformControls(); } private void handleEntityDrag(IMapObject mapObject) { final IMapObject dragObject = mapObject; if (dragObject == null || (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.currentEditMode != EDITMODE_MOVE)) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(dragObject.getX(), dragObject.getY()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newX = this.snapX(this.dragLocationMapObject.getX() + deltaX); double newY = this.snapY(this.dragLocationMapObject.getY() + deltaY); dragObject.setX((int) newX); dragObject.setY((int) newY); Game.getEnvironment().reloadFromMap(dragObject.getId()); if (MapObjectType.get(dragObject.getType()) == MapObjectType.STATICSHADOW || MapObjectType.get(dragObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(dragObject); this.updateTransformControls(); } private void setCurrentZoom() { Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0); } private void setupControls() { if (this.initialized) { return; } Input.keyboard().onKeyReleased(KeyEvent.VK_ADD, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomIn(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_SUBTRACT, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomOut(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_SPACE, e -> { this.centerCameraOnFocus(); }); Input.keyboard().onKeyPressed(KeyEvent.VK_CONTROL, e -> { if (this.currentEditMode == EDITMODE_EDIT) { this.setEditMode(EDITMODE_MOVE); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_CONTROL, e -> { this.setEditMode(EDITMODE_EDIT); }); Input.keyboard().onKeyReleased(KeyEvent.VK_Z, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().undo(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_Y, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().redo(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_DELETE, e -> { if (this.isSuspended() || !this.isVisible() || this.getFocusedMapObject() == null) { return; } if (Game.getScreenManager().getRenderComponent().hasFocus() && this.currentEditMode == EDITMODE_EDIT) { this.delete(); } }); Input.mouse().onWheelMoved(e -> { if (!this.hasFocus()) { return; } final Point2D currentFocus = Game.getCamera().getFocus(); // horizontal scrolling if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.dragPoint == null) { if (e.getWheelRotation() < 0) { Point2D newFocus = new Point2D.Double(currentFocus.getX() - this.scrollSpeed, currentFocus.getY()); Game.getCamera().setFocus(newFocus); } else { Point2D newFocus = new Point2D.Double(currentFocus.getX() + this.scrollSpeed, currentFocus.getY()); Game.getCamera().setFocus(newFocus); } Program.getHorizontalScrollBar().setValue((int) Game.getCamera().getViewPort().getCenterX()); return; } if (Input.keyboard().isPressed(KeyEvent.VK_ALT)) { if (e.getWheelRotation() < 0) { this.zoomIn(); } else { this.zoomOut(); } return; } if (e.getWheelRotation() < 0) { Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() - this.scrollSpeed); Game.getCamera().setFocus(newFocus); } else { Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() + this.scrollSpeed); Game.getCamera().setFocus(newFocus); } Program.getVerticalcrollBar().setValue((int) Game.getCamera().getViewPort().getCenterY()); }); } private void setupMouseControls() { if (this.initialized) { return; } this.onMouseMoved(e -> { if (this.getFocus() == null) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; return; } boolean hovered = false; if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { return; } for (Entry<TransformType, Rectangle2D> entry : this.transformRects.entrySet()) { Rectangle2D rect = entry.getValue(); Rectangle2D hoverrect = new Rectangle2D.Double(rect.getX() - rect.getWidth() * 2, rect.getY() - rect.getHeight() * 2, rect.getWidth() * 4, rect.getHeight() * 4); if (hoverrect.contains(Input.mouse().getMapLocation())) { hovered = true; if (entry.getKey() == TransformType.DOWN || entry.getKey() == TransformType.UP) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_VERTICAL, 0, 0); } else if (entry.getKey() == TransformType.UPLEFT || entry.getKey() == TransformType.DOWNRIGHT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_LEFT, 0, 0); } else if (entry.getKey() == TransformType.UPRIGHT || entry.getKey() == TransformType.DOWNLEFT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_RIGHT, 0, 0); } else { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_HORIZONTAL, 0, 0); } currentTransform = entry.getKey(); break; } } if (!hovered) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; } }); this.onMousePressed(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: this.startPoint = Input.mouse().getMapLocation(); break; case EDITMODE_MOVE: break; case EDITMODE_EDIT: if (this.isMoving || this.currentTransform != TransformType.NONE || SwingUtilities.isRightMouseButton(e.getEvent())) { return; } final Point2D mouse = Input.mouse().getMapLocation(); this.startPoint = mouse; boolean somethingIsFocused = false; boolean currentObjectFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (somethingIsFocused) { break; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.PATH) { continue; } if (mapObject.getBoundingBox().contains(mouse)) { if (this.getFocusedMapObject() != null && mapObject.getId() == this.getFocusedMapObject().getId()) { currentObjectFocused = true; continue; } this.setFocus(mapObject, false); EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; break; } } } if (!somethingIsFocused && !currentObjectFocused) { this.setFocus(null, true); EditorScreen.instance().getMapObjectPanel().bind(null); } break; } }); this.onMouseDragged(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: if (startPoint == null) { return; } newObjectArea = this.getCurrentMouseSelectionArea(true); break; case EDITMODE_EDIT: if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(this.getFocusedMapObject()); return; } else if (this.currentTransform != TransformType.NONE) { if (!this.isTransforming) { this.isTransforming = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleTransform(); return; } break; case EDITMODE_MOVE: if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(this.getFocusedMapObject()); break; default: break; } }); this.onMouseReleased(e -> { if (!this.hasFocus()) { return; } this.dragPoint = null; this.dragLocationMapObject = null; this.dragSizeMapObject = null; switch (this.currentEditMode) { case EDITMODE_CREATE: if (this.newObjectArea == null) { break; } IMapObject mo = this.createNewMapObject(EditorScreen.instance().getMapObjectPanel().getObjectType()); this.newObjectArea = null; this.setFocus(mo, true); EditorScreen.instance().getMapObjectPanel().bind(mo); this.setEditMode(EDITMODE_EDIT); break; case EDITMODE_MOVE: if (this.isMoving) { this.isMoving = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } break; case EDITMODE_EDIT: if (this.isMoving || this.isTransforming) { this.isMoving = false; this.isTransforming = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } if (this.startPoint == null) { return; } Rectangle2D rect = this.getCurrentMouseSelectionArea(false); if (rect.getHeight() == 0 || rect.getWidth() == 0) { break; } boolean somethingIsFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null || !EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.PATH) { continue; } if (!GeometricUtilities.intersects(rect, mapObject.getBoundingBox())) { continue; } if (mapObject.equals(this.getFocusedMapObject())) { somethingIsFocused = true; continue; } this.setselection(mapObject, false, true); if (somethingIsFocused) { continue; } this.setFocus(mapObject, false); EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; } } if (!somethingIsFocused) { this.setFocus(null, true); EditorScreen.instance().getMapObjectPanel().bind(null); } break; default: break; } this.startPoint = null; }); this.initialized = true; } private int snapX(double x) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(x), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getWidth()); } double snapped = ((int) (x / this.gridSize) * this.gridSize); return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getWidth())); } private int snapY(double y) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(y), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getHeight()); } int snapped = (int) (y / this.gridSize) * this.gridSize; return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getHeight())); } private boolean hasFocus() { if (this.isSuspended() || !this.isVisible()) { return false; } for (GuiComponent comp : this.getComponents()) { if (comp.isHovered() && !comp.isSuspended()) { return false; } } return true; } private void renderCollisionBoxes(Graphics2D g, BasicStroke shapeStroke) { // render all entities for (final IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } Color colorBoundingBoxFill; if (layer.getColor() != null) { colorBoundingBoxFill = new Color(layer.getColor().getRed(), layer.getColor().getGreen(), layer.getColor().getBlue(), 15); } else { colorBoundingBoxFill = DEFAULT_COLOR_BOUNDING_BOX_FILL; } for (final IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } String objectName = mapObject.getName(); if (objectName != null && !objectName.isEmpty()) { Rectangle2D nameBackground = new Rectangle2D.Double(mapObject.getX(), mapObject.getBoundingBox().getMaxY() - 3, mapObject.getDimension().getWidth(), 3); g.setColor(COLOR_NAME_FILL); RenderEngine.fillShape(g, nameBackground); } MapObjectType type = MapObjectType.get(mapObject.getType()); // render spawn points if (type == MapObjectType.SPAWNPOINT) { g.setColor(COLOR_SPAWNPOINT); RenderEngine.fillShape(g, new Rectangle2D.Double(mapObject.getBoundingBox().getCenterX() - 1, mapObject.getBoundingBox().getCenterY() - 1, 2, 2)); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.COLLISIONBOX) { g.setColor(COLOR_COLLISION_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_COLLISION_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.STATICSHADOW) { g.setColor(COLOR_SHADOW_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_SHADOW_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.PATH) { // render lane if (mapObject.getPolyline() == null || mapObject.getPolyline().getPoints().isEmpty()) { continue; } // found the path for the rat final Path2D path = MapUtilities.convertPolylineToPath(mapObject); if (path == null) { continue; } g.setColor(COLOR_LANE); RenderEngine.drawShape(g, path, shapeStroke); Point2D start = new Point2D.Double(mapObject.getLocation().getX(), mapObject.getLocation().getY()); RenderEngine.fillShape(g, new Ellipse2D.Double(start.getX() - 1, start.getY() - 1, 3, 3)); RenderEngine.drawMapText(g, "#" + mapObject.getId() + "(" + mapObject.getName() + ")", start.getX(), start.getY() - 5); } // render bounding boxes g.setColor(colorBoundingBoxFill); // don't fill rect for lightsource because it is important to judge // the color if (type != MapObjectType.LIGHTSOURCE) { if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_FILL); } RenderEngine.fillShape(g, mapObject.getBoundingBox()); } if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); } RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); // render collision boxes String coll = mapObject.getCustomProperty(MapObjectProperty.COLLISION); final String collisionBoxWidthFactor = mapObject.getCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH); final String collisionBoxHeightFactor = mapObject.getCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT); final Align align = Align.get(mapObject.getCustomProperty(MapObjectProperty.COLLISION_ALGIN)); final Valign valign = Valign.get(mapObject.getCustomProperty(MapObjectProperty.COLLISION_VALGIN)); if (coll != null && collisionBoxWidthFactor != null && collisionBoxHeightFactor != null) { boolean collision = Boolean.parseBoolean(coll); final Color collisionColor = collision ? COLOR_COLLISION_FILL : COLOR_NOCOLLISION_FILL; final Color collisionShapeColor = collision ? COLOR_COLLISION_BORDER : COLOR_NOCOLLISION_BORDER; float collisionBoxWidth = 0; float collisionBoxHeight = 0; try { collisionBoxWidth = Float.parseFloat(collisionBoxWidthFactor); collisionBoxHeight = Float.parseFloat(collisionBoxHeightFactor); } catch (NumberFormatException | NullPointerException e) { log.log(Level.SEVERE, e.getMessage(), e); } g.setColor(collisionColor); Rectangle2D collisionBox = CollisionEntity.getCollisionBox(mapObject.getLocation(), mapObject.getDimension().getWidth(), mapObject.getDimension().getHeight(), collisionBoxWidth, collisionBoxHeight, align, valign); RenderEngine.fillShape(g, collisionBox); g.setColor(collisionShapeColor); RenderEngine.drawShape(g, collisionBox, shapeStroke); } g.setColor(Color.WHITE); float textSize = 3 * zooms[this.currentZoomIndex]; g.setFont(Program.TEXT_FONT.deriveFont(textSize)); RenderEngine.drawMapText(g, objectName, mapObject.getX() + 1, mapObject.getBoundingBox().getMaxY()); } } } private void renderGrid(Graphics2D g) { // render the grid if (this.renderGrid && Game.getCamera().getRenderScale() >= 1) { g.setColor(new Color(255, 255, 255, 100)); final Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); final double viewPortX = Math.max(0, Game.getCamera().getViewPort().getX()); final double viewPortMaxX = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getWidth(), Game.getCamera().getViewPort().getMaxX()); final double viewPortY = Math.max(0, Game.getCamera().getViewPort().getY()); final double viewPortMaxY = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getHeight(), Game.getCamera().getViewPort().getMaxY()); final int startX = Math.max(0, (int) (viewPortX / gridSize) * gridSize); final int startY = Math.max(0, (int) (viewPortY / gridSize) * gridSize); for (int x = startX; x <= viewPortMaxX; x += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(x, viewPortY, x, viewPortMaxY), stroke); } for (int y = startY; y <= viewPortMaxY; y += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(viewPortX, y, viewPortMaxX, y), stroke); } } } private void renderNewObjectArea(Graphics2D g, Stroke shapeStroke) { if (this.newObjectArea == null) { return; } g.setColor(COLOR_NEWOBJECT_FILL); RenderEngine.fillShape(g, newObjectArea); g.setColor(COLOR_NEWOBJECT_BORDER); RenderEngine.drawShape(g, newObjectArea, shapeStroke); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, newObjectArea.getWidth() + "", newObjectArea.getX() + newObjectArea.getWidth() / 2 - 3, newObjectArea.getY() - 5); RenderEngine.drawMapText(g, newObjectArea.getHeight() + "", newObjectArea.getX() - 10, newObjectArea.getY() + newObjectArea.getHeight() / 2); } private void renderMouseSelectionArea(Graphics2D g, Stroke shapeStroke) { // draw mouse selection area final Point2D start = this.startPoint; if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { final Rectangle2D rect = this.getCurrentMouseSelectionArea(false); if (rect == null) { return; } g.setColor(COLOR_MOUSE_SELECTION_AREA_FILL); RenderEngine.fillShape(g, rect); g.setColor(COLOR_MOUSE_SELECTION_AREA_BORDER); RenderEngine.drawShape(g, rect, shapeStroke); } } private void renderFocus(Graphics2D g) { // render the focus and the transform rects final Rectangle2D focus = this.getFocus(); final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focus != null && focusedMapObject != null) { Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 4, new float[] { 1f, 1f }, Game.getLoop().getTicks() / 15); g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, focus, stroke); Stroke whiteStroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 4, new float[] { 1f, 1f }, Game.getLoop().getTicks() / 15 - 1f); g.setColor(Color.WHITE); RenderEngine.drawShape(g, focus, whiteStroke); // render transform rects if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { Stroke transStroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); for (Rectangle2D trans : this.transformRects.values()) { g.setColor(COLOR_TRANSFORM_RECT_FILL); RenderEngine.fillShape(g, trans); g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, trans, transStroke); } } } if (focusedMapObject != null) { Point2D loc = Game.getCamera().getViewPortLocation(new Point2D.Double(focusedMapObject.getX() + focusedMapObject.getDimension().getWidth() / 2, focusedMapObject.getY())); g.setFont(Program.TEXT_FONT.deriveFont(Font.BOLD, 15f)); g.setColor(COLOR_FOCUS_BORDER); String id = "#" + focusedMapObject.getId(); RenderEngine.drawText(g, id, loc.getX() * Game.getCamera().getRenderScale() - g.getFontMetrics().stringWidth(id) / 2.0, loc.getY() * Game.getCamera().getRenderScale() - (5 * this.currentTransformRectSize)); if (MapObjectType.get(focusedMapObject.getType()) == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); g.setFont(Program.TEXT_FONT.deriveFont(11f)); RenderEngine.drawMapText(g, focusedMapObject.getName(), focusedMapObject.getX() + 2.0, focusedMapObject.getY() + 5.0); } } } private void renderSelection(Graphics2D g) { final String map = Game.getEnvironment().getMap().getFileName(); if (!this.selectedObjects.containsKey(map)) { return; } for (IMapObject mapObject : this.selectedObjects.get(map)) { if (mapObject.equals(this.getFocusedMapObject())) { continue; } Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 0, new float[] { 0.5f }, 0); g.setColor(COLOR_SELECTION_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), stroke); } } }
utiliti/src/de/gurkenlabs/utiliti/components/MapComponent.java
package de.gurkenlabs.utiliti.components; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Stroke; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.gurkenlabs.core.Align; import de.gurkenlabs.core.Valign; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.Resources; import de.gurkenlabs.litiengine.SpriteSheetInfo; import de.gurkenlabs.litiengine.entities.CollisionEntity; import de.gurkenlabs.litiengine.entities.DecorMob.MovementBehavior; import de.gurkenlabs.litiengine.environment.Environment; import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.IMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.ITileset; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperty; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectType; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.environment.tilemap.TmxMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint; import de.gurkenlabs.litiengine.environment.tilemap.xml.Map; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset; import de.gurkenlabs.litiengine.graphics.ImageCache; import de.gurkenlabs.litiengine.graphics.ImageFormat; import de.gurkenlabs.litiengine.graphics.LightSource; import de.gurkenlabs.litiengine.graphics.RenderEngine; import de.gurkenlabs.litiengine.graphics.Spritesheet; import de.gurkenlabs.litiengine.gui.GuiComponent; import de.gurkenlabs.litiengine.input.Input; import de.gurkenlabs.util.MathUtilities; import de.gurkenlabs.util.geom.GeometricUtilities; import de.gurkenlabs.util.io.FileUtilities; import de.gurkenlabs.util.io.ImageSerializer; import de.gurkenlabs.util.io.XmlUtilities; import de.gurkenlabs.utiliti.EditorScreen; import de.gurkenlabs.utiliti.Program; import de.gurkenlabs.utiliti.UndoManager; public class MapComponent extends EditorComponent { public enum TransformType { UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT, NONE } public static final int EDITMODE_CREATE = 0; public static final int EDITMODE_EDIT = 1; public static final int EDITMODE_MOVE = 2; private static final Logger log = Logger.getLogger(MapComponent.class.getName()); private static final float[] zooms = new float[] { 0.1f, 0.25f, 0.5f, 1, 1.5f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 16f, 32f, 50f, 80f, 100f }; private static final String DEFAULT_MAPOBJECTLAYER_NAME = "default"; private static final int TRANSFORM_RECT_SIZE = 6; private static final int BASE_SCROLL_SPEED = 50; private static final Color DEFAULT_COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); private static final Color COLOR_NAME_FILL = new Color(0, 0, 0, 60); private static final Color COLOR_FOCUS_FILL = new Color(0, 0, 0, 50); private static final Color COLOR_FOCUS_BORDER = Color.BLACK; private static final Color COLOR_SELECTION_BORDER = new Color(0, 0, 0, 150); private static final Color COLOR_COLLISION_FILL = new Color(255, 0, 0, 15); private static final Color COLOR_NOCOLLISION_FILL = new Color(255, 100, 0, 15); private static final Color COLOR_COLLISION_BORDER = Color.RED; private static final Color COLOR_NOCOLLISION_BORDER = Color.ORANGE; private static final Color COLOR_SPAWNPOINT = Color.GREEN; private static final Color COLOR_LANE = Color.YELLOW; private static final Color COLOR_NEWOBJECT_FILL = new Color(0, 255, 0, 50); private static final Color COLOR_NEWOBJECT_BORDER = Color.GREEN.darker(); private static final Color COLOR_TRANSFORM_RECT_FILL = new Color(255, 255, 255, 100); private static final Color COLOR_SHADOW_FILL = new Color(85, 130, 200, 15); private static final Color COLOR_SHADOW_BORDER = new Color(30, 85, 170); private double currentTransformRectSize = TRANSFORM_RECT_SIZE; private final java.util.Map<TransformType, Rectangle2D> transformRects; private final List<Consumer<Integer>> editModeChangedConsumer; private final List<Consumer<IMapObject>> focusChangedConsumer; private final List<Consumer<Map>> mapLoadedConsumer; private final java.util.Map<String, Point2D> cameraFocus; private final java.util.Map<String, IMapObject> focusedObjects; private final java.util.Map<String, List<MapObject>> selectedObjects; private int currentEditMode = EDITMODE_EDIT; private TransformType currentTransform; private int currentZoomIndex = 7; private final List<Map> maps; private float scrollSpeed = BASE_SCROLL_SPEED; private Point2D startPoint; private Point2D dragPoint; private Point2D dragLocationMapObject; private boolean isMoving; private boolean isTransforming; private boolean isFocussing; private Dimension dragSizeMapObject; private Rectangle2D newObject; private IMapObject copiedMapObject; private int gridSize; private boolean snapToGrid = true; private boolean renderGrid = false; private boolean renderCollisionBoxes = true; private final EditorScreen screen; private boolean loading; private boolean initialized; public MapComponent(final EditorScreen screen) { super(ComponentType.MAP); this.editModeChangedConsumer = new CopyOnWriteArrayList<>(); this.focusChangedConsumer = new CopyOnWriteArrayList<>(); this.mapLoadedConsumer = new CopyOnWriteArrayList<>(); this.focusedObjects = new ConcurrentHashMap<>(); this.selectedObjects = new ConcurrentHashMap<>(); this.maps = new ArrayList<>(); this.cameraFocus = new ConcurrentHashMap<>(); this.transformRects = new ConcurrentHashMap<>(); this.screen = screen; Game.getCamera().onZoomChanged(zoom -> { this.currentTransformRectSize = TRANSFORM_RECT_SIZE / zoom; this.updateTransformControls(); }); this.gridSize = Program.getUserPreferences().getGridSize(); } public void onEditModeChanged(Consumer<Integer> cons) { this.editModeChangedConsumer.add(cons); } public void onFocusChanged(Consumer<IMapObject> cons) { this.focusChangedConsumer.add(cons); } public void onMapLoaded(Consumer<Map> cons) { this.mapLoadedConsumer.add(cons); } @Override public void render(Graphics2D g) { if (Game.getEnvironment() == null) { return; } final BasicStroke shapeStroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); if (this.renderCollisionBoxes) { this.renderCollisionBoxes(g, shapeStroke); } switch (this.currentEditMode) { case EDITMODE_CREATE: if (newObject != null) { g.setColor(COLOR_NEWOBJECT_FILL); RenderEngine.fillShape(g, newObject); g.setColor(COLOR_NEWOBJECT_BORDER); RenderEngine.drawShape(g, newObject, shapeStroke); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, newObject.getWidth() + "", newObject.getX() + newObject.getWidth() / 2 - 3, newObject.getY() - 5); RenderEngine.drawMapText(g, newObject.getHeight() + "", newObject.getX() - 10, newObject.getY() + newObject.getHeight() / 2); } break; case EDITMODE_EDIT: // draw mouse selection area final Point2D start = this.startPoint; if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { final Rectangle2D rect = this.getCurrentMouseSelectionArea(); if (rect == null) { break; } g.setColor(new Color(0, 130, 152, 30)); RenderEngine.fillShape(g, rect); if (rect.getWidth() > 0 || rect.getHeight() > 0) { g.setColor(new Color(0, 130, 152, 255)); g.setFont(g.getFont().deriveFont(Font.BOLD)); RenderEngine.drawMapText(g, rect.getWidth() + "", rect.getX() + rect.getWidth() / 2 - 3, rect.getY() - 5); RenderEngine.drawMapText(g, rect.getHeight() + "", rect.getX() - 10, rect.getY() + rect.getHeight() / 2); } g.setColor(new Color(0, 130, 152, 150)); RenderEngine.drawShape(g, rect, new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1 }, 0)); } break; default: break; } this.renderGrid(g); this.renderSelection(g); this.renderFocus(g); super.render(g); } public void loadMaps(String projectPath) { final List<String> files = FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "tmx"); log.log(Level.INFO, "{0} maps found in folder {1}", new Object[] { files.size(), projectPath }); final List<Map> loadedMaps = new ArrayList<>(); for (final String mapFile : files) { final IMapLoader tmxLoader = new TmxMapLoader(); Map map = (Map) tmxLoader.loadMap(mapFile); loadedMaps.add(map); log.log(Level.INFO, "map found: {0}", new Object[] { map.getFileName() }); } this.loadMaps(loadedMaps); } public void loadMaps(List<Map> maps) { EditorScreen.instance().getMapObjectPanel().bind(null); this.setFocus(null, true); this.getMaps().clear(); Collections.sort(maps); this.getMaps().addAll(maps); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); } public List<Map> getMaps() { return this.maps; } public int getGridSize() { return this.gridSize; } public IMapObject getFocusedMapObject() { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { return this.focusedObjects.get(Game.getEnvironment().getMap().getFileName()); } return null; } public IMapObject getCopiedMapObject() { return this.copiedMapObject; } public boolean isLoading() { return this.loading; } @Override public void prepare() { Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0); Game.getScreenManager().getRenderComponent().addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { startPoint = null; } }); this.setupControls(); super.prepare(); this.setupMouseControls(); } public void loadEnvironment(Map map) { this.loading = true; try { if (Game.getEnvironment() != null && Game.getEnvironment().getMap() != null) { double x = Game.getCamera().getFocus().getX(); double y = Game.getCamera().getFocus().getY(); Point2D newPoint = new Point2D.Double(x, y); this.cameraFocus.put(Game.getEnvironment().getMap().getFileName(), newPoint); } Point2D newFocus = null; if (this.cameraFocus.containsKey(map.getFileName())) { newFocus = this.cameraFocus.get(map.getFileName()); } else { newFocus = new Point2D.Double(map.getSizeInPixels().getWidth() / 2, map.getSizeInPixels().getHeight() / 2); this.cameraFocus.put(map.getFileName(), newFocus); } Game.getCamera().setFocus(new Point2D.Double(newFocus.getX(), newFocus.getY())); this.ensureUniqueIds(map); Environment env = new Environment(map); env.init(); Game.loadEnvironment(env); Program.updateScrollBars(); EditorScreen.instance().getMapSelectionPanel().setSelection(map.getFileName()); EditorScreen.instance().getMapObjectPanel().bind(this.getFocusedMapObject()); for (Consumer<Map> cons : this.mapLoadedConsumer) { cons.accept(map); } } finally { this.loading = false; } } public void reloadEnvironment() { if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) { return; } this.loadEnvironment((Map) Game.getEnvironment().getMap()); } public void add(IMapObject mapObject) { this.add(mapObject, getCurrentLayer()); } public void add(IMapObject mapObject, IMapObjectLayer layer) { layer.addMapObject(mapObject); Game.getEnvironment().loadFromMap(mapObject.getId()); if (MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } Game.getScreenManager().getRenderComponent().requestFocus(); this.setFocus(mapObject, true); this.setEditMode(EDITMODE_EDIT); UndoManager.instance().mapObjectAdded(mapObject); } public void copy() { this.copiedMapObject = this.getFocusedMapObject(); } public void paste() { if (this.copiedMapObject != null) { int x = (int) Input.mouse().getMapLocation().getX(); int y = (int) Input.mouse().getMapLocation().getY(); this.paste(x, y); } } public void paste(int x, int y) { if (this.copiedMapObject != null) { this.newObject = new Rectangle(x, y, (int) this.copiedMapObject.getDimension().getWidth(), (int) this.copiedMapObject.getDimension().getHeight()); this.copyMapObject(this.copiedMapObject); } } public void cut() { this.copiedMapObject = this.getFocusedMapObject(); UndoManager.instance().mapObjectDeleting(this.copiedMapObject); this.delete(this.copiedMapObject); } public void delete() { final IMapObject deleteObject = this.getFocusedMapObject(); if (deleteObject == null) { return; } int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), "Do you really want to delete the entity [" + deleteObject.getId() + "]", "Delete Entity?", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.OK_OPTION) { UndoManager.instance().mapObjectDeleting(deleteObject); this.delete(deleteObject); } } public void delete(final IMapObject mapObject) { if (mapObject == null) { return; } MapObjectType type = MapObjectType.get(mapObject.getType()); Game.getEnvironment().getMap().removeMapObject(mapObject.getId()); Game.getEnvironment().remove(mapObject.getId()); if (type == MapObjectType.STATICSHADOW || type == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } this.setFocus(null, true); } public void defineBlueprint() { final String map = Game.getEnvironment().getMap().getFileName(); if (this.getFocusedMapObject() == null) { return; } Object name = JOptionPane.showInputDialog(Game.getScreenManager().getRenderComponent(), "Name:", "Enter blueprint name", JOptionPane.PLAIN_MESSAGE, null, null, this.getFocusedMapObject().getName()); if (name == null) { return; } Blueprint blueprint = new Blueprint(name.toString(), this.selectedObjects.get(map).toArray(new MapObject[this.selectedObjects.get(map).size()])); EditorScreen.instance().getGameFile().getBluePrints().add(blueprint); Program.getAssetTree().forceUpdate(); } public void centerCameraOnFocus() { if (this.getFocusedMapObject() != null) { final Rectangle2D focus = this.getFocus(); if (focus == null) { return; } Game.getCamera().setFocus(new Point2D.Double(focus.getCenterX(), focus.getCenterY())); } } public void setEditMode(int editMode) { if (editMode == this.currentEditMode) { return; } switch (editMode) { case EDITMODE_CREATE: this.setFocus(null, true); EditorScreen.instance().getMapObjectPanel().bind(null); break; case EDITMODE_EDIT: Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); break; case EDITMODE_MOVE: Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_MOVE, 0, 0); break; default: break; } this.currentEditMode = editMode; for (Consumer<Integer> cons : this.editModeChangedConsumer) { cons.accept(this.currentEditMode); } } public void setFocus(IMapObject mapObject, boolean clearSelection) { if (this.isFocussing) { return; } this.isFocussing = true; try { final IMapObject currentFocus = this.getFocusedMapObject(); if (mapObject != null && currentFocus != null && mapObject.equals(currentFocus) || mapObject == null && currentFocus == null) { return; } if (Game.getEnvironment() == null || Game.getEnvironment().getMap() == null) { return; } if (this.isMoving || this.isTransforming) { return; } EditorScreen.instance().getMapObjectPanel().bind(mapObject); EditorScreen.instance().getMapSelectionPanel().focus(mapObject); if (mapObject == null) { this.focusedObjects.remove(Game.getEnvironment().getMap().getFileName()); } else { this.focusedObjects.put(Game.getEnvironment().getMap().getFileName(), mapObject); } for (Consumer<IMapObject> cons : this.focusChangedConsumer) { cons.accept(mapObject); } this.updateTransformControls(); this.setselection(mapObject, clearSelection, Input.keyboard().isPressed(KeyEvent.VK_SHIFT)); } finally { this.isFocussing = false; } } private void setselection(IMapObject mapObject, boolean clearSelection, boolean shiftPressed) { final String map = Game.getEnvironment().getMap().getFileName(); if (mapObject == null) { this.selectedObjects.get(map).clear(); return; } if (!this.selectedObjects.containsKey(map)) { this.selectedObjects.put(map, new CopyOnWriteArrayList<>()); } if (!clearSelection && shiftPressed) { if (!this.selectedObjects.get(map).contains(mapObject)) { this.selectedObjects.get(map).add((MapObject) mapObject); } return; } this.selectedObjects.get(map).clear(); this.selectedObjects.get(map).add((MapObject) mapObject); } public void setGridSize(int gridSize) { Program.getUserPreferences().setGridSize(gridSize); this.gridSize = gridSize; } public boolean isSnapToGrid() { return this.snapToGrid; } public void setSnapToGrid(boolean snapToGrid) { this.snapToGrid = snapToGrid; } public boolean isRenderGrid() { return this.renderGrid; } public void setRenderGrid(boolean renderGrid) { this.renderGrid = renderGrid; } public boolean isRenderCollisionBoxes() { return this.renderCollisionBoxes; } public void setRenderCollisionBoxes(boolean renderCollisionBoxes) { this.renderCollisionBoxes = renderCollisionBoxes; } public void updateTransformControls() { final Rectangle2D focus = this.getFocus(); if (focus == null) { this.transformRects.clear(); return; } for (TransformType trans : TransformType.values()) { if (trans == TransformType.NONE) { continue; } Rectangle2D transRect = new Rectangle2D.Double(this.getTransX(trans, focus), this.getTransY(trans, focus), this.currentTransformRectSize, this.currentTransformRectSize); this.transformRects.put(trans, transRect); } } public void deleteMap() { if (this.getMaps() == null || this.getMaps().isEmpty()) { return; } if (Game.getEnvironment() == null && Game.getEnvironment().getMap() == null) { return; } int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("hud_deleteMapMessage") + "\n" + Game.getEnvironment().getMap().getName(), Resources.get("hud_deleteMap"), JOptionPane.YES_NO_OPTION); if (n != JOptionPane.YES_OPTION) { return; } this.getMaps().removeIf(x -> x.getFileName().equals(Game.getEnvironment().getMap().getFileName())); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); if (!this.maps.isEmpty()) { this.loadEnvironment(this.maps.get(0)); } else { this.loadEnvironment(null); } } public void importMap() { if (this.getMaps() == null) { return; } JFileChooser chooser; try { String defaultPath = EditorScreen.instance().getProjectPath() != null ? EditorScreen.instance().getProjectPath() : new File(".").getCanonicalPath(); chooser = new JFileChooser(defaultPath); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setDialogTitle("Import Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); int result = chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()); if (result == JFileChooser.APPROVE_OPTION) { final IMapLoader tmxLoader = new TmxMapLoader(); String mapPath = chooser.getSelectedFile().toString(); Map map = (Map) tmxLoader.loadMap(mapPath); if (map == null) { log.log(Level.WARNING, "could not load map from file {0}", new Object[] { mapPath }); return; } if (map.getMapObjectLayers().isEmpty()) { // make sure there's a map object layer on the map because we need one to add // any kind of entities MapObjectLayer layer = new MapObjectLayer(); layer.setName(DEFAULT_MAPOBJECTLAYER_NAME); map.addMapObjectLayer(layer); } Optional<Map> current = this.maps.stream().filter(x -> x.getFileName().equals(map.getFileName())).findFirst(); if (current.isPresent()) { int n = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), "Do you really want to replace the existing map '" + map.getFileName() + "' ?", "Replace Map", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { this.getMaps().remove(current.get()); ImageCache.MAPS.clear(); } else { return; } } this.getMaps().add(map); EditorScreen.instance().getMapSelectionPanel().bind(this.getMaps()); // remove old spritesheets for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.find(tileSet.getImage().getSource()); if (sprite != null) { Spritesheet.remove(sprite.getName()); this.screen.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(sprite.getName())); } } for (ITileset tileSet : map.getTilesets()) { Spritesheet sprite = Spritesheet.load(tileSet); this.screen.getGameFile().getSpriteSheets().add(new SpriteSheetInfo(sprite)); } for (IImageLayer imageLayer : map.getImageLayers()) { BufferedImage img = Resources.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true); Spritesheet sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight()); this.screen.getGameFile().getSpriteSheets().add(new SpriteSheetInfo(sprite)); } // remove old tilesets for (ITileset tileset : map.getExternalTilesets()) { this.screen.getGameFile().getTilesets().removeIf(x -> x.getName().equals(tileset.getName())); } this.screen.getGameFile().getTilesets().addAll(map.getExternalTilesets()); this.loadEnvironment(map); log.log(Level.INFO, "imported map {0}", new Object[] { map.getFileName() }); } } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } } public void exportMap() { if (this.getMaps() == null || this.getMaps().isEmpty()) { return; } Map map = (Map) Game.getEnvironment().getMap(); if (map == null) { return; } this.exportMap(map); } public void exportMap(Map map) { JFileChooser chooser; try { String source = EditorScreen.instance().getProjectPath(); chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setDialogTitle("Export Map"); FileFilter filter = new FileNameExtensionFilter("tmx - Tilemap XML", Map.FILE_EXTENSION); chooser.setFileFilter(filter); chooser.addChoosableFileFilter(filter); chooser.setSelectedFile(new File(map.getFileName() + "." + Map.FILE_EXTENSION)); int result = chooser.showSaveDialog(Game.getScreenManager().getRenderComponent()); if (result == JFileChooser.APPROVE_OPTION) { String newFile = XmlUtilities.save(map, chooser.getSelectedFile().toString(), Map.FILE_EXTENSION); // save all tilesets manually because a map has a relative reference to // the tilesets String dir = FileUtilities.getParentDirPath(newFile); for (ITileset tileSet : map.getTilesets()) { ImageFormat format = ImageFormat.get(FileUtilities.getExtension(tileSet.getImage().getSource())); ImageSerializer.saveImage(Paths.get(dir, tileSet.getImage().getSource()).toString(), Spritesheet.find(tileSet.getImage().getSource()).getImage(), format); Tileset tile = (Tileset) tileSet; if (tile.isExternal()) { tile.saveSource(dir); } } log.log(Level.INFO, "exported {0} to {1}", new Object[] { map.getFileName(), newFile }); } } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } } public void zoomIn() { if (this.currentZoomIndex < zooms.length - 1) { this.currentZoomIndex++; } this.setCurrentZoom(); this.updateScrollSpeed(); } public void zoomOut() { if (this.currentZoomIndex > 0) { this.currentZoomIndex--; } this.setCurrentZoom(); this.updateScrollSpeed(); } private void updateScrollSpeed() { this.scrollSpeed = BASE_SCROLL_SPEED / zooms[this.currentZoomIndex]; } private IMapObject copyMapObject(IMapObject obj) { IMapObject mo = new MapObject(); mo.setType(obj.getType()); mo.setX(this.snapX(this.newObject.getX())); mo.setY(this.snapY(this.newObject.getY())); mo.setWidth((int) obj.getDimension().getWidth()); mo.setHeight((int) obj.getDimension().getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(obj.getName()); mo.setCustomProperties(obj.getAllCustomProperties()); this.add(mo); return mo; } private void ensureUniqueIds(IMap map) { int maxMapId = MapUtilities.getMaxMapId(map); List<Integer> usedIds = new ArrayList<>(); for (IMapObject obj : map.getMapObjects()) { if (usedIds.contains(obj.getId())) { obj.setId(++maxMapId); } usedIds.add(obj.getId()); } } private static IMapObjectLayer getCurrentLayer() { int layerIndex = EditorScreen.instance().getMapSelectionPanel().getSelectedLayerIndex(); if (layerIndex < 0 || layerIndex >= Game.getEnvironment().getMap().getMapObjectLayers().size()) { layerIndex = 0; } return Game.getEnvironment().getMap().getMapObjectLayers().get(layerIndex); } private IMapObject createNewMapObject(MapObjectType type) { IMapObject mo = new MapObject(); mo.setType(type.toString()); mo.setX((int) this.newObject.getX()); mo.setY((int) this.newObject.getY()); mo.setWidth((int) this.newObject.getWidth()); mo.setHeight((int) this.newObject.getHeight()); mo.setId(Game.getEnvironment().getNextMapId()); mo.setName(""); switch (type) { case PROP: mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObject.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObject.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISION, "true"); mo.setCustomProperty(MapObjectProperty.PROP_INDESTRUCTIBLE, "false"); mo.setCustomProperty(MapObjectProperty.PROP_ADDSHADOW, "true"); break; case DECORMOB: mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObject.getWidth() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObject.getHeight() * 0.4) + ""); mo.setCustomProperty(MapObjectProperty.COLLISION, "false"); mo.setCustomProperty(MapObjectProperty.DECORMOB_VELOCITY, "2"); mo.setCustomProperty(MapObjectProperty.DECORMOB_BEHAVIOUR, MovementBehavior.IDLE.toString()); break; case LIGHTSOURCE: mo.setCustomProperty(MapObjectProperty.LIGHT_ALPHA, "180"); mo.setCustomProperty(MapObjectProperty.LIGHT_COLOR, "#ffffff"); mo.setCustomProperty(MapObjectProperty.LIGHT_SHAPE, LightSource.ELLIPSE); mo.setCustomProperty(MapObjectProperty.LIGHT_ACTIVE, "true"); break; case SPAWNPOINT: default: break; } this.add(mo); return mo; } private Rectangle2D getCurrentMouseSelectionArea() { final Point2D start = this.startPoint; if (start == null) { return null; } final Point2D endPoint = Input.mouse().getMapLocation(); double minX = this.snapX(Math.min(start.getX(), endPoint.getX())); double maxX = this.snapX(Math.max(start.getX(), endPoint.getX())); double minY = this.snapY(Math.min(start.getY(), endPoint.getY())); double maxY = this.snapY(Math.max(start.getY(), endPoint.getY())); double width = Math.abs(minX - maxX); double height = Math.abs(minY - maxY); return new Rectangle2D.Double(minX, minY, width, height); } private Rectangle2D getFocus() { final IMapObject focusedObject = this.getFocusedMapObject(); if (focusedObject == null) { return null; } return focusedObject.getBoundingBox(); } private double getTransX(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case UP: return focus.getCenterX() - this.currentTransformRectSize / 2; case LEFT: case DOWNLEFT: case UPLEFT: return focus.getX() - this.currentTransformRectSize; case RIGHT: case DOWNRIGHT: case UPRIGHT: return focus.getMaxX(); default: return 0; } } private double getTransY(TransformType type, Rectangle2D focus) { switch (type) { case DOWN: case DOWNLEFT: case DOWNRIGHT: return focus.getMaxY(); case UP: case UPLEFT: case UPRIGHT: return focus.getY() - this.currentTransformRectSize; case LEFT: case RIGHT: return focus.getCenterY() - this.currentTransformRectSize / 2; default: return 0; } } private void handleTransform() { final IMapObject transformObject = this.getFocusedMapObject(); if (transformObject == null || this.currentEditMode != EDITMODE_EDIT || currentTransform == TransformType.NONE) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(transformObject.getX(), transformObject.getY()); this.dragSizeMapObject = new Dimension(transformObject.getDimension()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newWidth = this.dragSizeMapObject.getWidth(); double newHeight = this.dragSizeMapObject.getHeight(); double newX = this.snapX(this.dragLocationMapObject.getX()); double newY = this.snapY(this.dragLocationMapObject.getY()); switch (this.currentTransform) { case DOWN: newHeight += deltaY; break; case DOWNRIGHT: newHeight += deltaY; newWidth += deltaX; break; case DOWNLEFT: newHeight += deltaY; newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case LEFT: newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case RIGHT: newWidth += deltaX; break; case UP: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); break; case UPLEFT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth -= deltaX; newX += deltaX; newX = MathUtilities.clamp(newX, 0, this.dragLocationMapObject.getX() + this.dragSizeMapObject.getWidth()); break; case UPRIGHT: newHeight -= deltaY; newY += deltaY; newY = MathUtilities.clamp(newY, 0, this.dragLocationMapObject.getY() + this.dragSizeMapObject.getHeight()); newWidth += deltaX; break; default: return; } transformObject.setWidth(this.snapX(newWidth)); transformObject.setHeight(this.snapY(newHeight)); transformObject.setX(this.snapX(newX)); transformObject.setY(this.snapY(newY)); Game.getEnvironment().reloadFromMap(transformObject.getId()); if (MapObjectType.get(transformObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(transformObject); this.updateTransformControls(); } private void handleEntityDrag(IMapObject mapObject) { final IMapObject dragObject = mapObject; if (dragObject == null || (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.currentEditMode != EDITMODE_MOVE)) { return; } if (this.dragPoint == null) { this.dragPoint = Input.mouse().getMapLocation(); this.dragLocationMapObject = new Point2D.Double(dragObject.getX(), dragObject.getY()); return; } double deltaX = Input.mouse().getMapLocation().getX() - this.dragPoint.getX(); double deltaY = Input.mouse().getMapLocation().getY() - this.dragPoint.getY(); double newX = this.snapX(this.dragLocationMapObject.getX() + deltaX); double newY = this.snapY(this.dragLocationMapObject.getY() + deltaY); dragObject.setX((int) newX); dragObject.setY((int) newY); Game.getEnvironment().reloadFromMap(dragObject.getId()); if (MapObjectType.get(dragObject.getType()) == MapObjectType.STATICSHADOW || MapObjectType.get(dragObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.getEnvironment().getAmbientLight().createImage(); } EditorScreen.instance().getMapObjectPanel().bind(dragObject); this.updateTransformControls(); } private void setCurrentZoom() { Game.getCamera().setZoom(zooms[this.currentZoomIndex], 0); } private void setupControls() { if (this.initialized) { return; } Input.keyboard().onKeyReleased(KeyEvent.VK_ADD, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomIn(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_SUBTRACT, e -> { if (this.isSuspended() || !this.isVisible()) { return; } if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { this.zoomOut(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_SPACE, e -> { this.centerCameraOnFocus(); }); Input.keyboard().onKeyPressed(KeyEvent.VK_CONTROL, e -> { if (this.currentEditMode == EDITMODE_EDIT) { this.setEditMode(EDITMODE_MOVE); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_CONTROL, e -> { this.setEditMode(EDITMODE_EDIT); }); Input.keyboard().onKeyReleased(KeyEvent.VK_Z, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().undo(); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_Y, e -> { if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { UndoManager.instance().redo(); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_DELETE, e -> { if (this.isSuspended() || !this.isVisible() || this.getFocusedMapObject() == null) { return; } if (Game.getScreenManager().getRenderComponent().hasFocus() && this.currentEditMode == EDITMODE_EDIT) { this.delete(); } }); Input.mouse().onWheelMoved(e -> { if (!this.hasFocus()) { return; } final Point2D currentFocus = Game.getCamera().getFocus(); // horizontal scrolling if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL) && this.dragPoint == null) { if (e.getWheelRotation() < 0) { Point2D newFocus = new Point2D.Double(currentFocus.getX() - this.scrollSpeed, currentFocus.getY()); Game.getCamera().setFocus(newFocus); } else { Point2D newFocus = new Point2D.Double(currentFocus.getX() + this.scrollSpeed, currentFocus.getY()); Game.getCamera().setFocus(newFocus); } Program.getHorizontalScrollBar().setValue((int) Game.getCamera().getViewPort().getCenterX()); return; } if (Input.keyboard().isPressed(KeyEvent.VK_ALT)) { if (e.getWheelRotation() < 0) { this.zoomIn(); } else { this.zoomOut(); } return; } if (e.getWheelRotation() < 0) { Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() - this.scrollSpeed); Game.getCamera().setFocus(newFocus); } else { Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() + this.scrollSpeed); Game.getCamera().setFocus(newFocus); } Program.getVerticalcrollBar().setValue((int) Game.getCamera().getViewPort().getCenterY()); }); } private void setupMouseControls() { if (this.initialized) { return; } this.onMouseMoved(e -> { if (this.getFocus() == null) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; return; } boolean hovered = false; if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { return; } for (TransformType type : this.transformRects.keySet()) { Rectangle2D rect = this.transformRects.get(type); Rectangle2D hoverrect = new Rectangle2D.Double(rect.getX() - rect.getWidth() * 2, rect.getY() - rect.getHeight() * 2, rect.getWidth() * 4, rect.getHeight() * 4); if (hoverrect.contains(Input.mouse().getMapLocation())) { hovered = true; if (type == TransformType.DOWN || type == TransformType.UP) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_VERTICAL, 0, 0); } else if (type == TransformType.UPLEFT || type == TransformType.DOWNRIGHT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_LEFT, 0, 0); } else if (type == TransformType.UPRIGHT || type == TransformType.DOWNLEFT) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_RIGHT, 0, 0); } else { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_HORIZONTAL, 0, 0); } currentTransform = type; break; } } if (!hovered) { Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0); currentTransform = TransformType.NONE; } }); this.onMousePressed(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: this.startPoint = Input.mouse().getMapLocation(); break; case EDITMODE_MOVE: break; case EDITMODE_EDIT: if (this.isMoving || this.currentTransform != TransformType.NONE || SwingUtilities.isRightMouseButton(e.getEvent())) { return; } final Point2D mouse = Input.mouse().getMapLocation(); this.startPoint = mouse; boolean somethingIsFocused = false; boolean currentObjectFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (somethingIsFocused) { break; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.PATH) { continue; } if (mapObject.getBoundingBox().contains(mouse)) { if (this.getFocusedMapObject() != null && mapObject.getId() == this.getFocusedMapObject().getId()) { currentObjectFocused = true; continue; } this.setFocus(mapObject, false); EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; break; } } } if (!somethingIsFocused && !currentObjectFocused) { this.setFocus(null, true); EditorScreen.instance().getMapObjectPanel().bind(null); } break; } }); this.onMouseDragged(e -> { if (!this.hasFocus()) { return; } switch (this.currentEditMode) { case EDITMODE_CREATE: if (startPoint == null) { return; } newObject = this.getCurrentMouseSelectionArea(); break; case EDITMODE_EDIT: if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(this.getFocusedMapObject()); return; } else if (this.currentTransform != TransformType.NONE) { if (!this.isTransforming) { this.isTransforming = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleTransform(); return; } break; case EDITMODE_MOVE: if (!this.isMoving) { this.isMoving = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } this.handleEntityDrag(this.getFocusedMapObject()); break; default: break; } }); this.onMouseReleased(e -> { if (!this.hasFocus()) { return; } this.dragPoint = null; this.dragLocationMapObject = null; this.dragSizeMapObject = null; switch (this.currentEditMode) { case EDITMODE_CREATE: if (this.newObject == null) { break; } IMapObject mo = this.createNewMapObject(EditorScreen.instance().getMapObjectPanel().getObjectType()); this.newObject = null; this.setFocus(mo, true); EditorScreen.instance().getMapObjectPanel().bind(mo); this.setEditMode(EDITMODE_EDIT); break; case EDITMODE_MOVE: if (this.isMoving) { this.isMoving = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } break; case EDITMODE_EDIT: if (this.isMoving || this.isTransforming) { this.isMoving = false; this.isTransforming = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } if (this.startPoint == null) { return; } Rectangle2D rect = this.getCurrentMouseSelectionArea(); if (rect.getHeight() == 0 || rect.getWidth() == 0) { break; } boolean somethingIsFocused = false; for (IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null || !EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == MapObjectType.PATH) { continue; } if (!GeometricUtilities.intersects(rect, mapObject.getBoundingBox())) { continue; } if (mapObject.equals(this.getFocusedMapObject())) { somethingIsFocused = true; continue; } this.setselection(mapObject, false, true); if (somethingIsFocused) { continue; } this.setFocus(mapObject, false); EditorScreen.instance().getMapObjectPanel().bind(mapObject); somethingIsFocused = true; } } if (!somethingIsFocused) { this.setFocus(null, true); EditorScreen.instance().getMapObjectPanel().bind(null); } break; default: break; } this.startPoint = null; }); this.initialized = true; } private int snapX(double x) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(x), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getWidth()); } double snapped = ((int) (x / this.gridSize) * this.gridSize); return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getWidth())); } private int snapY(double y) { if (!this.snapToGrid) { return MathUtilities.clamp((int) Math.round(y), 0, (int) Game.getEnvironment().getMap().getSizeInPixels().getHeight()); } int snapped = (int) (y / this.gridSize) * this.gridSize; return (int) Math.round(Math.min(Math.max(snapped, 0), Game.getEnvironment().getMap().getSizeInPixels().getHeight())); } private boolean hasFocus() { if (this.isSuspended() || !this.isVisible()) { return false; } for (GuiComponent comp : this.getComponents()) { if (comp.isHovered() && !comp.isSuspended()) { return false; } } return true; } private void renderCollisionBoxes(Graphics2D g, BasicStroke shapeStroke) { // render all entities for (final IMapObjectLayer layer : Game.getEnvironment().getMap().getMapObjectLayers()) { if (layer == null) { continue; } if (!EditorScreen.instance().getMapSelectionPanel().isSelectedMapObjectLayer(layer.getName())) { continue; } Color colorBoundingBoxFill; if (layer.getColor() != null) { colorBoundingBoxFill = new Color(layer.getColor().getRed(), layer.getColor().getGreen(), layer.getColor().getBlue(), 15); } else { colorBoundingBoxFill = DEFAULT_COLOR_BOUNDING_BOX_FILL; } for (final IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } String objectName = mapObject.getName(); if (objectName != null && !objectName.isEmpty()) { Rectangle2D nameBackground = new Rectangle2D.Double(mapObject.getX(), mapObject.getBoundingBox().getMaxY() - 3, mapObject.getDimension().getWidth(), 3); g.setColor(COLOR_NAME_FILL); RenderEngine.fillShape(g, nameBackground); } MapObjectType type = MapObjectType.get(mapObject.getType()); // render spawn points if (type == MapObjectType.SPAWNPOINT) { g.setColor(COLOR_SPAWNPOINT); RenderEngine.fillShape(g, new Rectangle2D.Double(mapObject.getBoundingBox().getCenterX() - 1, mapObject.getBoundingBox().getCenterY() - 1, 2, 2)); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.COLLISIONBOX) { g.setColor(COLOR_COLLISION_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_COLLISION_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.STATICSHADOW) { g.setColor(COLOR_SHADOW_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); g.setColor(COLOR_SHADOW_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } else if (type == MapObjectType.PATH) { // render lane if (mapObject.getPolyline() == null || mapObject.getPolyline().getPoints().isEmpty()) { continue; } // found the path for the rat final Path2D path = MapUtilities.convertPolylineToPath(mapObject); if (path == null) { continue; } g.setColor(COLOR_LANE); RenderEngine.drawShape(g, path, shapeStroke); Point2D start = new Point2D.Double(mapObject.getLocation().getX(), mapObject.getLocation().getY()); RenderEngine.fillShape(g, new Ellipse2D.Double(start.getX() - 1, start.getY() - 1, 3, 3)); RenderEngine.drawMapText(g, "#" + mapObject.getId() + "(" + mapObject.getName() + ")", start.getX(), start.getY() - 5); } // render bounding boxes final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focusedMapObject == null || mapObject.getId() != focusedMapObject.getId()) { g.setColor(colorBoundingBoxFill); // don't fill rect for lightsource because it is important to judge // the color if (type != MapObjectType.LIGHTSOURCE) { if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_FILL); } RenderEngine.fillShape(g, mapObject.getBoundingBox()); } if (type == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); } RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); } // render collision boxes String coll = mapObject.getCustomProperty(MapObjectProperty.COLLISION); final String collisionBoxWidthFactor = mapObject.getCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH); final String collisionBoxHeightFactor = mapObject.getCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT); final Align align = Align.get(mapObject.getCustomProperty(MapObjectProperty.COLLISION_ALGIN)); final Valign valign = Valign.get(mapObject.getCustomProperty(MapObjectProperty.COLLISION_VALGIN)); if (coll != null && collisionBoxWidthFactor != null && collisionBoxHeightFactor != null) { boolean collision = Boolean.parseBoolean(coll); final Color collisionColor = collision ? COLOR_COLLISION_FILL : COLOR_NOCOLLISION_FILL; final Color collisionShapeColor = collision ? COLOR_COLLISION_BORDER : COLOR_NOCOLLISION_BORDER; float collisionBoxWidth = 0; float collisionBoxHeight = 0; try { collisionBoxWidth = Float.parseFloat(collisionBoxWidthFactor); collisionBoxHeight = Float.parseFloat(collisionBoxHeightFactor); } catch (NumberFormatException | NullPointerException e) { log.log(Level.SEVERE, e.getMessage(), e); } g.setColor(collisionColor); Rectangle2D collisionBox = CollisionEntity.getCollisionBox(mapObject.getLocation(), mapObject.getDimension().getWidth(), mapObject.getDimension().getHeight(), collisionBoxWidth, collisionBoxHeight, align, valign); RenderEngine.fillShape(g, collisionBox); g.setColor(collisionShapeColor); RenderEngine.drawShape(g, collisionBox, shapeStroke); } g.setColor(Color.WHITE); float textSize = 3 * zooms[this.currentZoomIndex]; g.setFont(Program.TEXT_FONT.deriveFont(textSize)); RenderEngine.drawMapText(g, objectName, mapObject.getX() + 1, mapObject.getBoundingBox().getMaxY()); } } } private void renderGrid(Graphics2D g) { // render the grid if (this.renderGrid && Game.getCamera().getRenderScale() >= 1) { g.setColor(new Color(255, 255, 255, 100)); final Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); final double viewPortX = Math.max(0, Game.getCamera().getViewPort().getX()); final double viewPortMaxX = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getWidth(), Game.getCamera().getViewPort().getMaxX()); final double viewPortY = Math.max(0, Game.getCamera().getViewPort().getY()); final double viewPortMaxY = Math.min(Game.getEnvironment().getMap().getSizeInPixels().getHeight(), Game.getCamera().getViewPort().getMaxY()); final int startX = Math.max(0, (int) (viewPortX / gridSize) * gridSize); final int startY = Math.max(0, (int) (viewPortY / gridSize) * gridSize); for (int x = startX; x <= viewPortMaxX; x += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(x, viewPortY, x, viewPortMaxY), stroke); } for (int y = startY; y <= viewPortMaxY; y += gridSize) { RenderEngine.drawShape(g, new Line2D.Double(viewPortX, y, viewPortMaxX, y), stroke); } } } private void renderFocus(Graphics2D g) { // render the focus and the transform rects final Rectangle2D focus = this.getFocus(); final IMapObject focusedMapObject = this.getFocusedMapObject(); if (focus != null && focusedMapObject != null) { Stroke stroke = new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1f }, 0); if (MapObjectType.get(focusedMapObject.getType()) != MapObjectType.LIGHTSOURCE) { g.setColor(COLOR_FOCUS_FILL); RenderEngine.fillShape(g, focus); } g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, focus, stroke); // render transform rects if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { Stroke transStroke = new BasicStroke(1 / Game.getCamera().getRenderScale()); for (Rectangle2D trans : this.transformRects.values()) { g.setColor(COLOR_TRANSFORM_RECT_FILL); RenderEngine.fillShape(g, trans); g.setColor(COLOR_FOCUS_BORDER); RenderEngine.drawShape(g, trans, transStroke); } } } if (focusedMapObject != null) { Point2D loc = Game.getCamera().getViewPortLocation(new Point2D.Double(focusedMapObject.getX() + focusedMapObject.getDimension().getWidth() / 2, focusedMapObject.getY())); g.setFont(Program.TEXT_FONT.deriveFont(Font.BOLD, 15f)); g.setColor(COLOR_FOCUS_BORDER); String id = "#" + focusedMapObject.getId(); RenderEngine.drawText(g, id, loc.getX() * Game.getCamera().getRenderScale() - g.getFontMetrics().stringWidth(id) / 2.0, loc.getY() * Game.getCamera().getRenderScale() - (5 * this.currentTransformRectSize)); if (MapObjectType.get(focusedMapObject.getType()) == MapObjectType.TRIGGER) { g.setColor(COLOR_NOCOLLISION_BORDER); g.setFont(Program.TEXT_FONT.deriveFont(11f)); RenderEngine.drawMapText(g, focusedMapObject.getName(), focusedMapObject.getX() + 2.0, focusedMapObject.getY() + 5.0); } } } private void renderSelection(Graphics2D g) { final String map = Game.getEnvironment().getMap().getFileName(); if (!this.selectedObjects.containsKey(map)) { return; } for (IMapObject mapObject : this.selectedObjects.get(map)) { if (mapObject.equals(this.getFocusedMapObject())) { continue; } Stroke stroke = new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 0.5f }, 0); if (MapObjectType.get(mapObject.getType()) != MapObjectType.LIGHTSOURCE) { g.setColor(COLOR_FOCUS_FILL); RenderEngine.fillShape(g, mapObject.getBoundingBox()); } g.setColor(COLOR_SELECTION_BORDER); RenderEngine.drawShape(g, mapObject.getBoundingBox(), stroke); } } }
The ants are now marching!
utiliti/src/de/gurkenlabs/utiliti/components/MapComponent.java
The ants are now marching!
<ide><path>tiliti/src/de/gurkenlabs/utiliti/components/MapComponent.java <ide> import java.util.ArrayList; <ide> import java.util.Collections; <ide> import java.util.List; <add>import java.util.Map.Entry; <ide> import java.util.Optional; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.CopyOnWriteArrayList; <ide> <ide> private static final Color DEFAULT_COLOR_BOUNDING_BOX_FILL = new Color(0, 0, 0, 35); <ide> private static final Color COLOR_NAME_FILL = new Color(0, 0, 0, 60); <del> private static final Color COLOR_FOCUS_FILL = new Color(0, 0, 0, 50); <ide> private static final Color COLOR_FOCUS_BORDER = Color.BLACK; <del> private static final Color COLOR_SELECTION_BORDER = new Color(0, 0, 0, 150); <add> private static final Color COLOR_SELECTION_BORDER = new Color(0, 0, 0, 200); <ide> private static final Color COLOR_COLLISION_FILL = new Color(255, 0, 0, 15); <ide> private static final Color COLOR_NOCOLLISION_FILL = new Color(255, 100, 0, 15); <ide> private static final Color COLOR_COLLISION_BORDER = Color.RED; <ide> private static final Color COLOR_TRANSFORM_RECT_FILL = new Color(255, 255, 255, 100); <ide> private static final Color COLOR_SHADOW_FILL = new Color(85, 130, 200, 15); <ide> private static final Color COLOR_SHADOW_BORDER = new Color(30, 85, 170); <add> private static final Color COLOR_MOUSE_SELECTION_AREA_FILL = new Color(0, 130, 152, 80); <add> private static final Color COLOR_MOUSE_SELECTION_AREA_BORDER = new Color(0, 130, 152, 150); <ide> <ide> private double currentTransformRectSize = TRANSFORM_RECT_SIZE; <ide> private final java.util.Map<TransformType, Rectangle2D> transformRects; <ide> private boolean isTransforming; <ide> private boolean isFocussing; <ide> private Dimension dragSizeMapObject; <del> private Rectangle2D newObject; <add> private Rectangle2D newObjectArea; <ide> private IMapObject copiedMapObject; <ide> private int gridSize; <ide> <ide> this.renderCollisionBoxes(g, shapeStroke); <ide> } <ide> <add> this.renderGrid(g); <add> <ide> switch (this.currentEditMode) { <ide> case EDITMODE_CREATE: <del> if (newObject != null) { <del> g.setColor(COLOR_NEWOBJECT_FILL); <del> RenderEngine.fillShape(g, newObject); <del> g.setColor(COLOR_NEWOBJECT_BORDER); <del> RenderEngine.drawShape(g, newObject, shapeStroke); <del> g.setFont(g.getFont().deriveFont(Font.BOLD)); <del> RenderEngine.drawMapText(g, newObject.getWidth() + "", newObject.getX() + newObject.getWidth() / 2 - 3, newObject.getY() - 5); <del> RenderEngine.drawMapText(g, newObject.getHeight() + "", newObject.getX() - 10, newObject.getY() + newObject.getHeight() / 2); <del> } <add> this.renderNewObjectArea(g, shapeStroke); <ide> break; <ide> case EDITMODE_EDIT: <del> // draw mouse selection area <del> final Point2D start = this.startPoint; <del> if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { <del> final Rectangle2D rect = this.getCurrentMouseSelectionArea(); <del> if (rect == null) { <del> break; <del> } <del> <del> g.setColor(new Color(0, 130, 152, 30)); <del> RenderEngine.fillShape(g, rect); <del> if (rect.getWidth() > 0 || rect.getHeight() > 0) { <del> g.setColor(new Color(0, 130, 152, 255)); <del> g.setFont(g.getFont().deriveFont(Font.BOLD)); <del> RenderEngine.drawMapText(g, rect.getWidth() + "", rect.getX() + rect.getWidth() / 2 - 3, rect.getY() - 5); <del> RenderEngine.drawMapText(g, rect.getHeight() + "", rect.getX() - 10, rect.getY() + rect.getHeight() / 2); <del> } <del> g.setColor(new Color(0, 130, 152, 150)); <del> RenderEngine.drawShape(g, rect, new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1 }, 0)); <del> } <add> this.renderMouseSelectionArea(g, shapeStroke); <ide> break; <ide> default: <ide> break; <ide> } <ide> <del> this.renderGrid(g); <ide> this.renderSelection(g); <ide> this.renderFocus(g); <ide> <ide> <ide> public void paste(int x, int y) { <ide> if (this.copiedMapObject != null) { <del> this.newObject = new Rectangle(x, y, (int) this.copiedMapObject.getDimension().getWidth(), (int) this.copiedMapObject.getDimension().getHeight()); <add> this.newObjectArea = new Rectangle(x, y, (int) this.copiedMapObject.getDimension().getWidth(), (int) this.copiedMapObject.getDimension().getHeight()); <ide> this.copyMapObject(this.copiedMapObject); <ide> } <ide> } <ide> <ide> IMapObject mo = new MapObject(); <ide> mo.setType(obj.getType()); <del> mo.setX(this.snapX(this.newObject.getX())); <del> mo.setY(this.snapY(this.newObject.getY())); <add> mo.setX(this.snapX(this.newObjectArea.getX())); <add> mo.setY(this.snapY(this.newObjectArea.getY())); <ide> mo.setWidth((int) obj.getDimension().getWidth()); <ide> mo.setHeight((int) obj.getDimension().getHeight()); <ide> mo.setId(Game.getEnvironment().getNextMapId()); <ide> private IMapObject createNewMapObject(MapObjectType type) { <ide> IMapObject mo = new MapObject(); <ide> mo.setType(type.toString()); <del> mo.setX((int) this.newObject.getX()); <del> mo.setY((int) this.newObject.getY()); <del> mo.setWidth((int) this.newObject.getWidth()); <del> mo.setHeight((int) this.newObject.getHeight()); <add> mo.setX((int) this.newObjectArea.getX()); <add> mo.setY((int) this.newObjectArea.getY()); <add> mo.setWidth((int) this.newObjectArea.getWidth()); <add> mo.setHeight((int) this.newObjectArea.getHeight()); <ide> mo.setId(Game.getEnvironment().getNextMapId()); <ide> mo.setName(""); <ide> <ide> switch (type) { <ide> case PROP: <del> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObject.getWidth() * 0.4) + ""); <del> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObject.getHeight() * 0.4) + ""); <add> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObjectArea.getWidth() * 0.4) + ""); <add> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObjectArea.getHeight() * 0.4) + ""); <ide> mo.setCustomProperty(MapObjectProperty.COLLISION, "true"); <ide> mo.setCustomProperty(MapObjectProperty.PROP_INDESTRUCTIBLE, "false"); <ide> mo.setCustomProperty(MapObjectProperty.PROP_ADDSHADOW, "true"); <ide> break; <ide> case DECORMOB: <del> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObject.getWidth() * 0.4) + ""); <del> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObject.getHeight() * 0.4) + ""); <add> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_WIDTH, (this.newObjectArea.getWidth() * 0.4) + ""); <add> mo.setCustomProperty(MapObjectProperty.COLLISIONBOX_HEIGHT, (this.newObjectArea.getHeight() * 0.4) + ""); <ide> mo.setCustomProperty(MapObjectProperty.COLLISION, "false"); <ide> mo.setCustomProperty(MapObjectProperty.DECORMOB_VELOCITY, "2"); <ide> mo.setCustomProperty(MapObjectProperty.DECORMOB_BEHAVIOUR, MovementBehavior.IDLE.toString()); <ide> return mo; <ide> } <ide> <del> private Rectangle2D getCurrentMouseSelectionArea() { <add> private Rectangle2D getCurrentMouseSelectionArea(boolean snap) { <ide> final Point2D start = this.startPoint; <ide> if (start == null) { <ide> return null; <ide> } <ide> <ide> final Point2D endPoint = Input.mouse().getMapLocation(); <del> double minX = this.snapX(Math.min(start.getX(), endPoint.getX())); <del> double maxX = this.snapX(Math.max(start.getX(), endPoint.getX())); <del> double minY = this.snapY(Math.min(start.getY(), endPoint.getY())); <del> double maxY = this.snapY(Math.max(start.getY(), endPoint.getY())); <add> double minX = Math.min(start.getX(), endPoint.getX()); <add> double maxX = Math.max(start.getX(), endPoint.getX()); <add> double minY = Math.min(start.getY(), endPoint.getY()); <add> double maxY = Math.max(start.getY(), endPoint.getY()); <add> <add> if (snap) { <add> minX = this.snapX(minX); <add> maxX = this.snapX(maxX); <add> minY = this.snapY(minY); <add> maxY = this.snapY(maxY); <add> } <ide> <ide> double width = Math.abs(minX - maxX); <ide> double height = Math.abs(minY - maxY); <ide> if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { <ide> return; <ide> } <del> for (TransformType type : this.transformRects.keySet()) { <del> Rectangle2D rect = this.transformRects.get(type); <add> for (Entry<TransformType, Rectangle2D> entry : this.transformRects.entrySet()) { <add> Rectangle2D rect = entry.getValue(); <ide> Rectangle2D hoverrect = new Rectangle2D.Double(rect.getX() - rect.getWidth() * 2, rect.getY() - rect.getHeight() * 2, rect.getWidth() * 4, rect.getHeight() * 4); <ide> if (hoverrect.contains(Input.mouse().getMapLocation())) { <ide> hovered = true; <del> if (type == TransformType.DOWN || type == TransformType.UP) { <add> if (entry.getKey() == TransformType.DOWN || entry.getKey() == TransformType.UP) { <ide> Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_VERTICAL, 0, 0); <del> } else if (type == TransformType.UPLEFT || type == TransformType.DOWNRIGHT) { <add> } else if (entry.getKey() == TransformType.UPLEFT || entry.getKey() == TransformType.DOWNRIGHT) { <ide> Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_LEFT, 0, 0); <del> } else if (type == TransformType.UPRIGHT || type == TransformType.DOWNLEFT) { <add> } else if (entry.getKey() == TransformType.UPRIGHT || entry.getKey() == TransformType.DOWNLEFT) { <ide> Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_DIAGONAL_RIGHT, 0, 0); <ide> } else { <ide> Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_TRANS_HORIZONTAL, 0, 0); <ide> } <ide> <del> currentTransform = type; <add> currentTransform = entry.getKey(); <ide> break; <ide> } <ide> } <ide> return; <ide> } <ide> <del> newObject = this.getCurrentMouseSelectionArea(); <add> newObjectArea = this.getCurrentMouseSelectionArea(true); <ide> break; <ide> case EDITMODE_EDIT: <ide> if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { <ide> <ide> switch (this.currentEditMode) { <ide> case EDITMODE_CREATE: <del> if (this.newObject == null) { <add> if (this.newObjectArea == null) { <ide> break; <ide> } <ide> IMapObject mo = this.createNewMapObject(EditorScreen.instance().getMapObjectPanel().getObjectType()); <del> this.newObject = null; <add> this.newObjectArea = null; <ide> this.setFocus(mo, true); <ide> EditorScreen.instance().getMapObjectPanel().bind(mo); <ide> this.setEditMode(EDITMODE_EDIT); <ide> return; <ide> } <ide> <del> Rectangle2D rect = this.getCurrentMouseSelectionArea(); <add> Rectangle2D rect = this.getCurrentMouseSelectionArea(false); <ide> if (rect.getHeight() == 0 || rect.getWidth() == 0) { <ide> break; <ide> } <ide> } <ide> <ide> // render bounding boxes <del> final IMapObject focusedMapObject = this.getFocusedMapObject(); <del> if (focusedMapObject == null || mapObject.getId() != focusedMapObject.getId()) { <del> g.setColor(colorBoundingBoxFill); <del> <del> // don't fill rect for lightsource because it is important to judge <del> // the color <del> if (type != MapObjectType.LIGHTSOURCE) { <del> if (type == MapObjectType.TRIGGER) { <del> g.setColor(COLOR_NOCOLLISION_FILL); <del> } <del> RenderEngine.fillShape(g, mapObject.getBoundingBox()); <add> g.setColor(colorBoundingBoxFill); <add> <add> // don't fill rect for lightsource because it is important to judge <add> // the color <add> if (type != MapObjectType.LIGHTSOURCE) { <add> if (type == MapObjectType.TRIGGER) { <add> g.setColor(COLOR_NOCOLLISION_FILL); <ide> } <del> <del> if (type == MapObjectType.TRIGGER) { <del> g.setColor(COLOR_NOCOLLISION_BORDER); <del> } <del> <del> RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); <del> } <add> RenderEngine.fillShape(g, mapObject.getBoundingBox()); <add> } <add> <add> if (type == MapObjectType.TRIGGER) { <add> g.setColor(COLOR_NOCOLLISION_BORDER); <add> } <add> <add> RenderEngine.drawShape(g, mapObject.getBoundingBox(), shapeStroke); <ide> <ide> // render collision boxes <ide> String coll = mapObject.getCustomProperty(MapObjectProperty.COLLISION); <ide> } <ide> } <ide> <add> private void renderNewObjectArea(Graphics2D g, Stroke shapeStroke) { <add> if (this.newObjectArea == null) { <add> return; <add> } <add> <add> g.setColor(COLOR_NEWOBJECT_FILL); <add> RenderEngine.fillShape(g, newObjectArea); <add> g.setColor(COLOR_NEWOBJECT_BORDER); <add> RenderEngine.drawShape(g, newObjectArea, shapeStroke); <add> g.setFont(g.getFont().deriveFont(Font.BOLD)); <add> RenderEngine.drawMapText(g, newObjectArea.getWidth() + "", newObjectArea.getX() + newObjectArea.getWidth() / 2 - 3, newObjectArea.getY() - 5); <add> RenderEngine.drawMapText(g, newObjectArea.getHeight() + "", newObjectArea.getX() - 10, newObjectArea.getY() + newObjectArea.getHeight() / 2); <add> } <add> <add> private void renderMouseSelectionArea(Graphics2D g, Stroke shapeStroke) { <add> // draw mouse selection area <add> final Point2D start = this.startPoint; <add> if (start != null && !Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { <add> final Rectangle2D rect = this.getCurrentMouseSelectionArea(false); <add> if (rect == null) { <add> return; <add> } <add> <add> g.setColor(COLOR_MOUSE_SELECTION_AREA_FILL); <add> RenderEngine.fillShape(g, rect); <add> g.setColor(COLOR_MOUSE_SELECTION_AREA_BORDER); <add> RenderEngine.drawShape(g, rect, shapeStroke); <add> } <add> } <add> <ide> private void renderFocus(Graphics2D g) { <ide> // render the focus and the transform rects <ide> final Rectangle2D focus = this.getFocus(); <ide> final IMapObject focusedMapObject = this.getFocusedMapObject(); <ide> if (focus != null && focusedMapObject != null) { <del> Stroke stroke = new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 1f }, 0); <del> if (MapObjectType.get(focusedMapObject.getType()) != MapObjectType.LIGHTSOURCE) { <del> g.setColor(COLOR_FOCUS_FILL); <del> RenderEngine.fillShape(g, focus); <del> } <del> <add> Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 4, new float[] { 1f, 1f }, Game.getLoop().getTicks() / 15); <ide> g.setColor(COLOR_FOCUS_BORDER); <ide> RenderEngine.drawShape(g, focus, stroke); <add> <add> Stroke whiteStroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 4, new float[] { 1f, 1f }, Game.getLoop().getTicks() / 15 - 1f); <add> g.setColor(Color.WHITE); <add> RenderEngine.drawShape(g, focus, whiteStroke); <ide> <ide> // render transform rects <ide> if (!Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { <ide> continue; <ide> } <ide> <del> Stroke stroke = new BasicStroke(2 / Game.getCamera().getRenderScale(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 0.5f }, 0); <del> if (MapObjectType.get(mapObject.getType()) != MapObjectType.LIGHTSOURCE) { <del> g.setColor(COLOR_FOCUS_FILL); <del> RenderEngine.fillShape(g, mapObject.getBoundingBox()); <del> } <add> Stroke stroke = new BasicStroke(1 / Game.getCamera().getRenderScale(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, 0, new float[] { 0.5f }, 0); <ide> <ide> g.setColor(COLOR_SELECTION_BORDER); <ide> RenderEngine.drawShape(g, mapObject.getBoundingBox(), stroke);
Java
bsd-3-clause
d7471e549463b7fa5c84c0faa34bd023e26807b2
0
joansmith/basex,BaseXdb/basex,ksclarke/basex,joansmith/basex,deshmnnit04/basex,drmacro/basex,BaseXdb/basex,deshmnnit04/basex,JensErat/basex,drmacro/basex,BaseXdb/basex,dimitarp/basex,JensErat/basex,vincentml/basex,deshmnnit04/basex,drmacro/basex,dimitarp/basex,deshmnnit04/basex,dimitarp/basex,vincentml/basex,drmacro/basex,dimitarp/basex,dimitarp/basex,joansmith/basex,vincentml/basex,joansmith/basex,BaseXdb/basex,deshmnnit04/basex,ksclarke/basex,vincentml/basex,deshmnnit04/basex,JensErat/basex,dimitarp/basex,joansmith/basex,vincentml/basex,deshmnnit04/basex,BaseXdb/basex,joansmith/basex,joansmith/basex,drmacro/basex,joansmith/basex,dimitarp/basex,JensErat/basex,ksclarke/basex,BaseXdb/basex,BaseXdb/basex,dimitarp/basex,ksclarke/basex,joansmith/basex,ksclarke/basex,deshmnnit04/basex,deshmnnit04/basex,JensErat/basex,ksclarke/basex,vincentml/basex,vincentml/basex,drmacro/basex,ksclarke/basex,deshmnnit04/basex,BaseXdb/basex,drmacro/basex,dimitarp/basex,dimitarp/basex,drmacro/basex,ksclarke/basex,joansmith/basex,ksclarke/basex,dimitarp/basex,JensErat/basex,ksclarke/basex,BaseXdb/basex,JensErat/basex,drmacro/basex,vincentml/basex,joansmith/basex,drmacro/basex,joansmith/basex,JensErat/basex,ksclarke/basex,vincentml/basex,vincentml/basex,BaseXdb/basex,drmacro/basex,ksclarke/basex,deshmnnit04/basex,drmacro/basex,vincentml/basex,dimitarp/basex,vincentml/basex,deshmnnit04/basex,JensErat/basex,JensErat/basex,JensErat/basex,JensErat/basex,BaseXdb/basex,BaseXdb/basex
package org.basex.gui.text; import static org.basex.gui.layout.BaseXKeys.*; import static org.basex.util.Token.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.*; import org.basex.core.*; import org.basex.gui.*; import org.basex.gui.GUIConstants.Fill; import org.basex.gui.dialog.*; import org.basex.gui.layout.*; import org.basex.io.*; import org.basex.util.*; /** * Renders and provides edit capabilities for text. * * @author BaseX Team 2005-14, BSD License * @author Christian Gruen */ public class TextPanel extends BaseXPanel { /** Delay for highlighting an error. */ private static final int ERROR_DELAY = 500; /** Search direction. */ public enum SearchDir { /** Current hit. */ CURRENT, /** Next hit. */ FORWARD, /** Previous hit. */ BACKWARD, } /** Editor action. */ public enum Action { /** Check for changes; do nothing if input has not changed. */ CHECK, /** Enforce parsing of input. */ PARSE, /** Enforce execution of input. */ EXECUTE } /** Text editor. */ protected final TextEditor editor; /** Undo history. */ public final History hist; /** Search bar. */ protected SearchBar search; /** Renderer reference. */ private final TextRenderer rend; /** Scrollbar reference. */ private final BaseXScrollBar scroll; /** Editable flag. */ private final boolean editable; /** Link listener. */ private LinkListener linkListener; /** * Default constructor. * @param edit editable flag * @param win parent window */ public TextPanel(final boolean edit, final Window win) { this(EMPTY, edit, win); } /** * Default constructor. * @param txt initial text * @param edit editable flag * @param win parent window */ public TextPanel(final byte[] txt, final boolean edit, final Window win) { super(win); editable = edit; editor = new TextEditor(gui); setFocusable(true); setFocusTraversalKeysEnabled(!edit); addMouseMotionListener(this); addMouseWheelListener(this); addComponentListener(this); addMouseListener(this); addKeyListener(this); addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if(isEnabled()) caret(true); } @Override public void focusLost(final FocusEvent e) { caret(false); rend.caret(false); } }); setFont(GUIConstants.dmfont); layout(new BorderLayout()); scroll = new BaseXScrollBar(this); rend = new TextRenderer(editor, scroll, editable, gui); add(rend, BorderLayout.CENTER); add(scroll, BorderLayout.EAST); setText(txt); hist = new History(edit ? editor.text() : null); if(edit) { setBackground(Color.white); setBorder(new MatteBorder(1, 1, 0, 0, GUIConstants.color(6))); } else { mode(Fill.NONE); } new BaseXPopup(this, edit ? new GUICommand[] { new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null, new UndoCmd(), new RedoCmd(), null, new AllCmd(), new CutCmd(), new CopyCmd(), new PasteCmd(), new DelCmd() } : new GUICommand[] { new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null, new AllCmd(), new CopyCmd() } ); } /** * Sets the output text. * @param t output text */ public void setText(final String t) { setText(token(t)); } /** * Sets the output text. * @param t output text */ public void setText(final byte[] t) { setText(t, t.length); resetError(); } /** * Returns a currently marked string if it does not extend over more than one line. * @return search string, or {@code null} */ public String searchString() { final String string = editor.copy(); return string.isEmpty() || string.contains("\n") ? null : string; } /** * Returns the line and column of the current caret position. * @return line/column */ public final int[] pos() { return rend.pos(); } /** * Sets the output text. * @param t output text * @param s text size */ public final void setText(final byte[] t, final int s) { byte[] txt = t; if(Token.contains(t, '\r')) { // remove carriage returns int ns = 0; for(int r = 0; r < s; ++r) { final byte b = t[r]; if(b != '\r') t[ns++] = b; } // new text is different... txt = Arrays.copyOf(t, ns); } if(editor.text(txt)) { if(hist != null) hist.store(txt, editor.pos(), 0); } componentResized(null); } /** * Sets a syntax highlighter, based on the file format. * @param file file reference * @param opened indicates if file was opened from disk */ protected final void setSyntax(final IO file, final boolean opened) { setSyntax(!opened || file.hasSuffix(IO.XQSUFFIXES) ? new SyntaxXQuery() : file.hasSuffix(IO.JSONSUFFIX) ? new SyntaxJSON() : file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.HTMLSUFFIXES) || file.hasSuffix(IO.XSLSUFFIXES) || file.hasSuffix(IO.BXSSUFFIX) ? new SyntaxXML() : Syntax.SIMPLE); } /** * Returns the editable flag. * @return boolean result */ public final boolean isEditable() { return editable; } /** * Sets a syntax highlighter. * @param syntax syntax reference */ public final void setSyntax(final Syntax syntax) { rend.setSyntax(syntax); } /** * Sets the caret to the specified position. A text selection will be removed. * @param pos caret position */ public final void setCaret(final int pos) { editor.pos(pos); cursorCode.invokeLater(1); caret(true); } /** * Returns the current text cursor. * @return cursor position */ private int getCaret() { return editor.pos(); } /** * Jumps to the end of the text. */ public final void scrollToEnd() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { editor.pos(editor.size()); cursorCode.execute(2); } }); } /** * Returns the output text. * @return output text */ public final byte[] getText() { return editor.text(); } /** * Tests if text has been selected. * @return result of check */ public final boolean selected() { return editor.selected(); } @Override public final void setFont(final Font f) { super.setFont(f); if(rend != null) { rend.setFont(f); scrollCode.invokeLater(true); } } /** Thread counter. */ private int errorID; /** * Removes the error marker. */ public final void resetError() { ++errorID; editor.error(-1); rend.repaint(); } /** * Sets the error marker. * @param pos start of optional error mark */ public final void error(final int pos) { final int eid = ++errorID; editor.error(pos); new Thread() { @Override public void run() { Performance.sleep(ERROR_DELAY); if(eid == errorID) rend.repaint(); } }.start(); } /** * Adds or removes a comment. */ public void comment() { final int caret = editor.pos(); if(editor.comment(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos()); scrollCode.invokeLater(true); } /** * Sorts text. */ public void sort() { final DialogSort ds = new DialogSort(gui); if(!ds.ok()) return; final int caret = editor.pos(); if(editor.sort()) hist.store(editor.text(), caret, editor.pos()); scrollCode.invokeLater(true); } /** * Formats the selected text. */ public void format() { final int caret = editor.pos(); if(editor.format(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos()); scrollCode.invokeLater(true); } @Override public final void setEnabled(final boolean enabled) { super.setEnabled(enabled); rend.setEnabled(enabled); scroll.setEnabled(enabled); caret(enabled); } /** * Selects the whole text. */ private void selectAll() { editor.select(0, editor.size()); rend.repaint(); } // SEARCH OPERATIONS ================================================================== /** * Installs a link listener. * @param ll link listener */ public final void setLinkListener(final LinkListener ll) { linkListener = ll; } /** * Installs a search bar. * @param s search bar */ final void setSearch(final SearchBar s) { search = s; } /** * Returns the search bar. * @return search bar */ public final SearchBar getSearch() { return search; } /** * Performs a search. * @param sc search context * @param jump jump to next hit */ final void search(final SearchContext sc, final boolean jump) { try { rend.search(sc); gui.status.setText(sc.search.isEmpty() ? Text.OK : Util.info(Text.STRINGS_FOUND_X, sc.nr())); if(jump) jump(SearchDir.CURRENT, false); } catch(final Exception ex) { final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", ""); gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg); } } /** * Replaces the text. * @param rc replace context */ final void replace(final ReplaceContext rc) { try { final int[] select = rend.replace(rc); if(rc.text != null) { final boolean sel = editor.selected(); setText(rc.text); editor.select(select[0], select[sel ? 1 : 0]); release(Action.CHECK); } gui.status.setText(Util.info(Text.STRINGS_REPLACED)); } catch(final Exception ex) { final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", ""); gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg); } } /** * Jumps to the current, next or previous search string. * @param dir search direction * @param select select hit */ protected final void jump(final SearchDir dir, final boolean select) { // updates the visible area final int y = rend.jump(dir, select); final int h = getHeight(); final int p = scroll.pos(); final int m = y + rend.fontHeight() * 3 - h; if(y != -1 && (p < m || p > y)) scroll.pos(y - h / 2); rend.repaint(); } // MOUSE INTERACTIONS ================================================================= @Override public final void mouseEntered(final MouseEvent e) { gui.cursor(GUIConstants.CURSORTEXT); } @Override public final void mouseExited(final MouseEvent e) { gui.cursor(GUIConstants.CURSORARROW); } @Override public final void mouseMoved(final MouseEvent e) { if(linkListener == null) return; final TextIterator iter = rend.jump(e.getPoint()); gui.cursor(iter.link() != null ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW); } @Override public void mouseReleased(final MouseEvent e) { if(linkListener == null) return; if(SwingUtilities.isLeftMouseButton(e)) { editor.endSelection(); // evaluate link if(!editor.selected()) { final TextIterator iter = rend.jump(e.getPoint()); final String link = iter.link(); if(link != null) linkListener.linkClicked(link); } } } @Override public void mouseClicked(final MouseEvent e) { if(!SwingUtilities.isMiddleMouseButton(e)) return; new PasteCmd().execute(gui); } @Override public final void mouseDragged(final MouseEvent e) { if(!SwingUtilities.isLeftMouseButton(e)) return; // selection mode select(e.getPoint(), false); final int y = Math.max(20, Math.min(e.getY(), getHeight() - 20)); if(y != e.getY()) scroll.pos(scroll.pos() + e.getY() - y); } @Override public final void mousePressed(final MouseEvent e) { if(!isEnabled() || !isFocusable()) return; requestFocusInWindow(); caret(true); if(SwingUtilities.isMiddleMouseButton(e)) copy(); final boolean shift = e.isShiftDown(); final boolean selected = editor.selected(); if(SwingUtilities.isLeftMouseButton(e)) { final int c = e.getClickCount(); if(c == 1) { // selection mode if(shift) editor.startSelection(true); select(e.getPoint(), !shift); } else if(c == 2) { editor.selectWord(); } else { editor.selectLine(); } } else if(!selected) { select(e.getPoint(), true); } } /** * Selects the text at the specified position. * @param point mouse position * @param start states if selection has just been started */ private void select(final Point point, final boolean start) { editor.select(rend.jump(point).pos(), start); rend.repaint(); } // KEY INTERACTIONS ======================================================= /** * Invokes special keys. * @param e key event * @return {@code true} if special key was processed */ private boolean specialKey(final KeyEvent e) { if(PREVTAB.is(e)) { gui.editor.tab(false); } else if(NEXTTAB.is(e)) { gui.editor.tab(true); } else if(CLOSETAB.is(e)) { gui.editor.close(null); } else if(search != null && ESCAPE.is(e)) { search.deactivate(true); } else { return false; } e.consume(); return true; } @Override public void keyPressed(final KeyEvent e) { // ignore modifier keys if(specialKey(e) || modifier(e)) return; // re-animate cursor caret(true); // operations without cursor movement... final int fh = rend.fontHeight(); if(SCROLLDOWN.is(e)) { scroll.pos(scroll.pos() + fh); return; } if(SCROLLUP.is(e)) { scroll.pos(scroll.pos() - fh); return; } // set cursor position final boolean selected = editor.selected(); final int pos = editor.pos(); final boolean shift = e.isShiftDown(); boolean down = true, consumed = true; // move caret int lc = Integer.MIN_VALUE; final byte[] txt = editor.text(); if(NEXTWORD.is(e)) { editor.nextWord(shift); } else if(PREVWORD.is(e)) { editor.prevWord(shift); down = false; } else if(TEXTSTART.is(e)) { editor.textStart(shift); down = false; } else if(TEXTEND.is(e)) { editor.textEnd(shift); } else if(LINESTART.is(e)) { editor.lineStart(shift); down = false; } else if(LINEEND.is(e)) { editor.lineEnd(shift); } else if(PREVPAGE_RO.is(e) && !hist.active()) { lc = editor.linesUp(getHeight() / fh, false, lastCol); down = false; } else if(NEXTPAGE_RO.is(e) && !hist.active()) { lc = editor.linesDown(getHeight() / fh, false, lastCol); } else if(PREVPAGE.is(e) && !BaseXKeys.sc(e)) { lc = editor.linesUp(getHeight() / fh, shift, lastCol); down = false; } else if(NEXTPAGE.is(e) && !BaseXKeys.sc(e)) { lc = editor.linesDown(getHeight() / fh, shift, lastCol); } else if(NEXTLINE.is(e) && !MOVEDOWN.is(e)) { lc = editor.linesDown(1, shift, lastCol); } else if(PREVLINE.is(e) && !MOVEUP.is(e)) { lc = editor.linesUp(1, shift, lastCol); down = false; } else if(NEXTCHAR.is(e)) { editor.next(shift); } else if(PREVCHAR.is(e)) { editor.previous(shift); down = false; } else { consumed = false; } lastCol = lc == Integer.MIN_VALUE ? -1 : lc; // edit text if(hist.active()) { if(MOVEDOWN.is(e)) { editor.move(true); } else if(MOVEUP.is(e)) { editor.move(false); } else if(COMPLETE.is(e)) { editor.complete(); } else if(DELLINE.is(e)) { editor.deleteLine(); } else if(DELNEXTWORD.is(e)) { editor.deleteNext(true); } else if(DELLINEEND.is(e)) { editor.deleteNext(false); } else if(DELNEXT.is(e)) { editor.delete(); } else if(DELPREVWORD.is(e)) { editor.deletePrev(true); down = false; } else if(DELLINESTART.is(e)) { editor.deletePrev(false); down = false; } else if(DELPREV.is(e)) { editor.deletePrev(); down = false; } else { consumed = false; } } if(consumed) e.consume(); final byte[] tmp = editor.text(); if(txt != tmp) { // text has changed: add old text to history hist.store(tmp, pos, editor.pos()); scrollCode.invokeLater(down); } else if(pos != editor.pos() || selected != editor.selected()) { // cursor position or selection state has changed cursorCode.invokeLater(down ? 2 : 0); } } /** Updates the scroll bar. */ private final GUICode scrollCode = new GUICode() { @Override public void execute(final Object down) { rend.updateScrollbar(); cursorCode.execute((Boolean) down ? 2 : 0); } }; /** Updates the cursor position. */ private final GUICode cursorCode = new GUICode() { @Override public void execute(final Object algn) { // updates the visible area final int p = scroll.pos(); final int y = rend.cursorY(); final int m = y + rend.fontHeight() * 3 - getHeight(); if(p < m || p > y) { final int align = (Integer) algn; scroll.pos(align == 0 ? y : align == 1 ? y - getHeight() / 2 : m); rend.repaint(); } } }; /** Last horizontal position. */ private int lastCol = -1; @Override public void keyTyped(final KeyEvent e) { if(!hist.active() || control(e) || DELNEXT.is(e) || DELPREV.is(e) || ESCAPE.is(e)) return; final int caret = editor.pos(); // remember if marked text is to be deleted final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar()); final boolean indent = TAB.is(e) && editor.indent(sb, e.isShiftDown()); // delete marked text final boolean selected = editor.selected() && !indent; if(selected) editor.delete(); final int move = ENTER.is(e) ? editor.enter(sb) : editor.add(sb, selected); // refresh history and adjust cursor position hist.store(editor.text(), caret, editor.pos()); if(move != 0) editor.pos(Math.min(editor.size(), caret + move)); // adjust text height scrollCode.invokeLater(true); e.consume(); } /** * Releases a key or mouse. Can be overwritten to react on events. * @param action action */ @SuppressWarnings("unused") protected void release(final Action action) { } // EDITOR COMMANDS ========================================================== /** * Copies the selected text to the clipboard. * @return true if text was copied */ private boolean copy() { final String txt = editor.copy(); if(txt.isEmpty()) return false; // copy selection to clipboard BaseXLayout.copy(txt); return true; } /** * Returns the clipboard text. * @return text */ private static String clip() { // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable tr = clip.getContents(null); if(tr != null) for(final Object o : BaseXLayout.contents(tr)) return o.toString(); return null; } /** * Finishes a command. * @param old old cursor position; store entry to history if position != -1 */ private void finish(final int old) { if(old != -1) hist.store(editor.text(), old, editor.pos()); scrollCode.invokeLater(true); release(Action.CHECK); } /** Text caret. */ private final Timer caretTimer = new Timer(500, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { rend.caret(!rend.caret()); } }); /** * Stops an old text cursor thread and, if requested, starts a new one. * @param start start/stop flag */ private void caret(final boolean start) { caretTimer.stop(); if(start) caretTimer.start(); rend.caret(start); } @Override public final void mouseWheelMoved(final MouseWheelEvent e) { scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20); rend.repaint(); } /** Calculation counter. */ private final GUICode resizeCode = new GUICode() { @Override public void execute(final Object arg) { rend.updateScrollbar(); // update scrollbar to display value within valid range scroll.pos(scroll.pos()); rend.repaint(); } }; @Override public final void componentResized(final ComponentEvent e) { resizeCode.invokeLater(); } /** Undo command. */ class UndoCmd extends GUIPopupCmd { /** Constructor. */ UndoCmd() { super(Text.UNDO, UNDOSTEP); } @Override public void execute() { if(!hist.active()) return; final byte[] t = hist.prev(); if(t == null) return; editor.text(t); editor.pos(hist.caret()); finish(-1); } @Override public boolean enabled(final GUI main) { return !hist.first(); } } /** Redo command. */ class RedoCmd extends GUIPopupCmd { /** Constructor. */ RedoCmd() { super(Text.REDO, REDOSTEP); } @Override public void execute() { if(!hist.active()) return; final byte[] t = hist.next(); if(t == null) return; editor.text(t); editor.pos(hist.caret()); finish(-1); } @Override public boolean enabled(final GUI main) { return !hist.last(); } } /** Cut command. */ class CutCmd extends GUIPopupCmd { /** Constructor. */ CutCmd() { super(Text.CUT, CUT1, CUT2); } @Override public void execute() { final int pos = editor.pos(); if(!copy()) return; editor.delete(); finish(pos); } @Override public boolean enabled(final GUI main) { return hist.active() && editor.selected(); } } /** Copy command. */ class CopyCmd extends GUIPopupCmd { /** Constructor. */ CopyCmd() { super(Text.COPY, COPY1, COPY2); } @Override public void execute() { copy(); } @Override public boolean enabled(final GUI main) { return editor.selected(); } } /** Paste command. */ class PasteCmd extends GUIPopupCmd { /** Constructor. */ PasteCmd() { super(Text.PASTE, PASTE1, PASTE2); } @Override public void execute() { final int pos = editor.pos(); final String clip = clip(); if(clip == null) return; if(editor.selected()) editor.delete(); editor.add(clip); finish(pos); } @Override public boolean enabled(final GUI main) { return hist.active() && clip() != null; } } /** Delete command. */ class DelCmd extends GUIPopupCmd { /** Constructor. */ DelCmd() { super(Text.DELETE, DELNEXT); } @Override public void execute() { final int pos = editor.pos(); editor.delete(); finish(pos); } @Override public boolean enabled(final GUI main) { return hist.active() && editor.selected(); } } /** Select all command. */ class AllCmd extends GUIPopupCmd { /** Constructor. */ AllCmd() { super(Text.SELECT_ALL, SELECTALL); } @Override public void execute() { selectAll(); } } /** Find next hit. */ class FindCmd extends GUIPopupCmd { /** Constructor. */ FindCmd() { super(Text.FIND + Text.DOTS, FIND); } @Override public void execute() { search.activate(searchString(), true); } @Override public boolean enabled(final GUI main) { return search != null; } } /** Find next hit. */ class FindNextCmd extends GUIPopupCmd { /** Constructor. */ FindNextCmd() { super(Text.FIND_NEXT, FINDNEXT1, FINDNEXT2); } @Override public void execute() { find(true); } @Override public boolean enabled(final GUI main) { return search != null; } } /** Find previous hit. */ class FindPrevCmd extends GUIPopupCmd { /** Constructor. */ FindPrevCmd() { super(Text.FIND_PREVIOUS, FINDPREV1, FINDPREV2); } @Override public void execute() { find(false); } @Override public boolean enabled(final GUI main) { return search != null; } } /** * Highlights the next/previous hit. * @param next next/previous hit */ private void find(final boolean next) { final boolean vis = search.isVisible(); search.activate(searchString(), false); jump(vis ? next ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true); } /** Go to line. */ class GotoCmd extends GUIPopupCmd { /** Constructor. */ GotoCmd() { super(Text.GO_TO_LINE + Text.DOTS, GOTOLINE); } @Override public void execute() { gotoLine(); } @Override public boolean enabled(final GUI main) { return search != null; } } /** * Jumps to a specific line. */ private void gotoLine() { final byte[] last = editor.text(); final int ll = last.length; final int cr = getCaret(); int l = 1; for(int e = 0; e < ll && e < cr; e += cl(last, e)) { if(last[e] == '\n') ++l; } final DialogLine dl = new DialogLine(gui, l); if(!dl.ok()) return; final int el = dl.line(); l = 1; int p = 0; for(int e = 0; e < ll && l < el; e += cl(last, e)) { if(last[e] != '\n') continue; p = e + 1; ++l; } setCaret(p); gui.editor.posCode.invokeLater(); } }
basex-core/src/main/java/org/basex/gui/text/TextPanel.java
package org.basex.gui.text; import static org.basex.gui.layout.BaseXKeys.*; import static org.basex.util.Token.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.*; import org.basex.core.*; import org.basex.gui.*; import org.basex.gui.GUIConstants.Fill; import org.basex.gui.dialog.*; import org.basex.gui.layout.*; import org.basex.io.*; import org.basex.util.*; /** * Renders and provides edit capabilities for text. * * @author BaseX Team 2005-14, BSD License * @author Christian Gruen */ public class TextPanel extends BaseXPanel { /** Delay for highlighting an error. */ private static final int ERROR_DELAY = 500; /** Search direction. */ public enum SearchDir { /** Current hit. */ CURRENT, /** Next hit. */ FORWARD, /** Previous hit. */ BACKWARD, } /** Editor action. */ public enum Action { /** Check for changes; do nothing if input has not changed. */ CHECK, /** Enforce parsing of input. */ PARSE, /** Enforce execution of input. */ EXECUTE } /** Text editor. */ protected final TextEditor editor; /** Undo history. */ public final History hist; /** Search bar. */ protected SearchBar search; /** Renderer reference. */ private final TextRenderer rend; /** Scrollbar reference. */ private final BaseXScrollBar scroll; /** Editable flag. */ private final boolean editable; /** Link listener. */ private LinkListener linkListener; /** * Default constructor. * @param edit editable flag * @param win parent window */ public TextPanel(final boolean edit, final Window win) { this(EMPTY, edit, win); } /** * Default constructor. * @param txt initial text * @param edit editable flag * @param win parent window */ public TextPanel(final byte[] txt, final boolean edit, final Window win) { super(win); editable = edit; editor = new TextEditor(gui); setFocusable(true); setFocusTraversalKeysEnabled(!edit); addMouseMotionListener(this); addMouseWheelListener(this); addComponentListener(this); addMouseListener(this); addKeyListener(this); addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if(isEnabled()) caret(true); } @Override public void focusLost(final FocusEvent e) { caret(false); rend.caret(false); } }); setFont(GUIConstants.dmfont); layout(new BorderLayout()); scroll = new BaseXScrollBar(this); rend = new TextRenderer(editor, scroll, editable, gui); add(rend, BorderLayout.CENTER); add(scroll, BorderLayout.EAST); setText(txt); hist = new History(edit ? editor.text() : null); if(edit) { setBackground(Color.white); setBorder(new MatteBorder(1, 1, 0, 0, GUIConstants.color(6))); } else { mode(Fill.NONE); } new BaseXPopup(this, edit ? new GUICommand[] { new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null, new UndoCmd(), new RedoCmd(), null, new AllCmd(), new CutCmd(), new CopyCmd(), new PasteCmd(), new DelCmd() } : new GUICommand[] { new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null, new AllCmd(), new CopyCmd() } ); } /** * Sets the output text. * @param t output text */ public void setText(final String t) { setText(token(t)); } /** * Sets the output text. * @param t output text */ public void setText(final byte[] t) { setText(t, t.length); resetError(); } /** * Returns a currently marked string if it does not extend over more than one line. * @return search string, or {@code null} */ public String searchString() { final String string = editor.copy(); return string.isEmpty() || string.contains("\n") ? null : string; } /** * Returns the line and column of the current caret position. * @return line/column */ public final int[] pos() { return rend.pos(); } /** * Sets the output text. * @param t output text * @param s text size */ public final void setText(final byte[] t, final int s) { byte[] txt = t; if(Token.contains(t, '\r')) { // remove carriage returns int ns = 0; for(int r = 0; r < s; ++r) { final byte b = t[r]; if(b != '\r') t[ns++] = b; } // new text is different... txt = Arrays.copyOf(t, ns); } if(editor.text(txt)) { if(hist != null) hist.store(txt, editor.pos(), 0); } componentResized(null); } /** * Sets a syntax highlighter, based on the file format. * @param file file reference * @param opened indicates if file was opened from disk */ protected final void setSyntax(final IO file, final boolean opened) { setSyntax(!opened || file.hasSuffix(IO.XQSUFFIXES) ? new SyntaxXQuery() : file.hasSuffix(IO.JSONSUFFIX) ? new SyntaxJSON() : file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.HTMLSUFFIXES) || file.hasSuffix(IO.XSLSUFFIXES) || file.hasSuffix(IO.BXSSUFFIX) ? new SyntaxXML() : Syntax.SIMPLE); } /** * Returns the editable flag. * @return boolean result */ public final boolean isEditable() { return editable; } /** * Sets a syntax highlighter. * @param syntax syntax reference */ public final void setSyntax(final Syntax syntax) { rend.setSyntax(syntax); } /** * Sets the caret to the specified position. A text selection will be removed. * @param pos caret position */ public final void setCaret(final int pos) { editor.pos(pos); cursorCode.invokeLater(1); caret(true); } /** * Returns the current text cursor. * @return cursor position */ private int getCaret() { return editor.pos(); } /** * Jumps to the end of the text. */ public final void scrollToEnd() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { editor.pos(editor.size()); cursorCode.execute(2); } }); } /** * Returns the output text. * @return output text */ public final byte[] getText() { return editor.text(); } /** * Tests if text has been selected. * @return result of check */ public final boolean selected() { return editor.selected(); } @Override public final void setFont(final Font f) { super.setFont(f); if(rend != null) { rend.setFont(f); scrollCode.invokeLater(true); } } /** Thread counter. */ private int errorID; /** * Removes the error marker. */ public final void resetError() { ++errorID; editor.error(-1); rend.repaint(); } /** * Sets the error marker. * @param pos start of optional error mark */ public final void error(final int pos) { final int eid = ++errorID; editor.error(pos); new Thread() { @Override public void run() { Performance.sleep(ERROR_DELAY); if(eid == errorID) rend.repaint(); } }.start(); } /** * Adds or removes a comment. */ public void comment() { final int caret = editor.pos(); if(editor.comment(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos()); scrollCode.invokeLater(true); } /** * Sorts text. */ public void sort() { final DialogSort ds = new DialogSort(gui); if(!ds.ok()) return; final int caret = editor.pos(); if(editor.sort()) hist.store(editor.text(), caret, editor.pos()); scrollCode.invokeLater(true); } /** * Formats the selected text. */ public void format() { final int caret = editor.pos(); if(editor.format(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos()); scrollCode.invokeLater(true); } @Override public final void setEnabled(final boolean enabled) { super.setEnabled(enabled); rend.setEnabled(enabled); scroll.setEnabled(enabled); caret(enabled); } /** * Selects the whole text. */ private void selectAll() { editor.select(0, editor.size()); rend.repaint(); } // SEARCH OPERATIONS ================================================================== /** * Installs a link listener. * @param ll link listener */ public final void setLinkListener(final LinkListener ll) { linkListener = ll; } /** * Installs a search bar. * @param s search bar */ final void setSearch(final SearchBar s) { search = s; } /** * Returns the search bar. * @return search bar */ public final SearchBar getSearch() { return search; } /** * Performs a search. * @param sc search context * @param jump jump to next hit */ final void search(final SearchContext sc, final boolean jump) { try { rend.search(sc); gui.status.setText(sc.search.isEmpty() ? Text.OK : Util.info(Text.STRINGS_FOUND_X, sc.nr())); if(jump) jump(SearchDir.CURRENT, false); } catch(final Exception ex) { final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", ""); gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg); } } /** * Replaces the text. * @param rc replace context */ final void replace(final ReplaceContext rc) { try { final int[] select = rend.replace(rc); if(rc.text != null) { final boolean sel = editor.selected(); setText(rc.text); editor.select(select[0], select[sel ? 1 : 0]); release(Action.CHECK); } gui.status.setText(Util.info(Text.STRINGS_REPLACED)); } catch(final Exception ex) { final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", ""); gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg); } } /** * Jumps to the current, next or previous search string. * @param dir search direction * @param select select hit */ protected final void jump(final SearchDir dir, final boolean select) { // updates the visible area final int y = rend.jump(dir, select); final int h = getHeight(); final int p = scroll.pos(); final int m = y + rend.fontHeight() * 3 - h; if(y != -1 && (p < m || p > y)) scroll.pos(y - h / 2); rend.repaint(); } // MOUSE INTERACTIONS ================================================================= @Override public final void mouseEntered(final MouseEvent e) { gui.cursor(GUIConstants.CURSORTEXT); } @Override public final void mouseExited(final MouseEvent e) { gui.cursor(GUIConstants.CURSORARROW); } @Override public final void mouseMoved(final MouseEvent e) { if(linkListener == null) return; final TextIterator iter = rend.jump(e.getPoint()); gui.cursor(iter.link() != null ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW); } @Override public void mouseReleased(final MouseEvent e) { if(linkListener == null) return; if(SwingUtilities.isLeftMouseButton(e)) { editor.endSelection(); // evaluate link if(!editor.selected()) { final TextIterator iter = rend.jump(e.getPoint()); final String link = iter.link(); if(link != null) linkListener.linkClicked(link); } } } @Override public void mouseClicked(final MouseEvent e) { if(!SwingUtilities.isMiddleMouseButton(e)) return; new PasteCmd().execute(gui); } @Override public final void mouseDragged(final MouseEvent e) { if(!SwingUtilities.isLeftMouseButton(e)) return; // selection mode select(e.getPoint(), false); final int y = Math.max(20, Math.min(e.getY(), getHeight() - 20)); if(y != e.getY()) scroll.pos(scroll.pos() + e.getY() - y); } @Override public final void mousePressed(final MouseEvent e) { if(!isEnabled() || !isFocusable()) return; requestFocusInWindow(); caret(true); if(SwingUtilities.isMiddleMouseButton(e)) copy(); final boolean shift = e.isShiftDown(); final boolean selected = editor.selected(); if(SwingUtilities.isLeftMouseButton(e)) { final int c = e.getClickCount(); if(c == 1) { // selection mode if(shift) editor.startSelection(true); select(e.getPoint(), !shift); } else if(c == 2) { editor.selectWord(); } else { editor.selectLine(); } } else if(!selected) { select(e.getPoint(), true); } } /** * Selects the text at the specified position. * @param point mouse position * @param start states if selection has just been started */ private void select(final Point point, final boolean start) { editor.select(rend.jump(point).pos(), start); rend.repaint(); } // KEY INTERACTIONS ======================================================= /** * Invokes special keys. * @param e key event * @return {@code true} if special key was processed */ private boolean specialKey(final KeyEvent e) { if(PREVTAB.is(e)) { gui.editor.tab(false); } else if(NEXTTAB.is(e)) { gui.editor.tab(true); } else if(CLOSETAB.is(e)) { gui.editor.close(null); } else if(search != null && ESCAPE.is(e)) { search.deactivate(true); } else { return false; } e.consume(); return true; } @Override public void keyPressed(final KeyEvent e) { // ignore modifier keys if(specialKey(e) || modifier(e)) return; // re-animate cursor caret(true); // operations without cursor movement... final int fh = rend.fontHeight(); if(SCROLLDOWN.is(e)) { scroll.pos(scroll.pos() + fh); return; } if(SCROLLUP.is(e)) { scroll.pos(scroll.pos() - fh); return; } // set cursor position final boolean selected = editor.selected(); final int pos = editor.pos(); final boolean shift = e.isShiftDown(); boolean down = true, consumed = true; // move caret int lc = Integer.MIN_VALUE; final byte[] txt = editor.text(); if(NEXTWORD.is(e)) { editor.nextWord(shift); } else if(PREVWORD.is(e)) { editor.prevWord(shift); down = false; } else if(TEXTSTART.is(e)) { editor.textStart(shift); down = false; } else if(TEXTEND.is(e)) { editor.textEnd(shift); } else if(LINESTART.is(e)) { editor.lineStart(shift); down = false; } else if(LINEEND.is(e)) { editor.lineEnd(shift); } else if(PREVPAGE_RO.is(e) && !hist.active()) { lc = editor.linesUp(getHeight() / fh, false, lastCol); down = false; } else if(NEXTPAGE_RO.is(e) && !hist.active()) { lc = editor.linesDown(getHeight() / fh, false, lastCol); } else if(PREVPAGE.is(e)) { lc = editor.linesUp(getHeight() / fh, shift, lastCol); down = false; } else if(NEXTPAGE.is(e)) { lc = editor.linesDown(getHeight() / fh, shift, lastCol); } else if(NEXTLINE.is(e) && !MOVEDOWN.is(e)) { lc = editor.linesDown(1, shift, lastCol); } else if(PREVLINE.is(e) && !MOVEUP.is(e)) { lc = editor.linesUp(1, shift, lastCol); down = false; } else if(NEXTCHAR.is(e)) { editor.next(shift); } else if(PREVCHAR.is(e)) { editor.previous(shift); down = false; } else { consumed = false; } lastCol = lc == Integer.MIN_VALUE ? -1 : lc; // edit text if(hist.active()) { if(MOVEDOWN.is(e)) { editor.move(true); } else if(MOVEUP.is(e)) { editor.move(false); } else if(COMPLETE.is(e)) { editor.complete(); } else if(DELLINE.is(e)) { editor.deleteLine(); } else if(DELNEXTWORD.is(e)) { editor.deleteNext(true); } else if(DELLINEEND.is(e)) { editor.deleteNext(false); } else if(DELNEXT.is(e)) { editor.delete(); } else if(DELPREVWORD.is(e)) { editor.deletePrev(true); down = false; } else if(DELLINESTART.is(e)) { editor.deletePrev(false); down = false; } else if(DELPREV.is(e)) { editor.deletePrev(); down = false; } else { consumed = false; } } if(consumed) e.consume(); final byte[] tmp = editor.text(); if(txt != tmp) { // text has changed: add old text to history hist.store(tmp, pos, editor.pos()); scrollCode.invokeLater(down); } else if(pos != editor.pos() || selected != editor.selected()) { // cursor position or selection state has changed cursorCode.invokeLater(down ? 2 : 0); } } /** Updates the scroll bar. */ private final GUICode scrollCode = new GUICode() { @Override public void execute(final Object down) { rend.updateScrollbar(); cursorCode.execute((Boolean) down ? 2 : 0); } }; /** Updates the cursor position. */ private final GUICode cursorCode = new GUICode() { @Override public void execute(final Object algn) { // updates the visible area final int p = scroll.pos(); final int y = rend.cursorY(); final int m = y + rend.fontHeight() * 3 - getHeight(); if(p < m || p > y) { final int align = (Integer) algn; scroll.pos(align == 0 ? y : align == 1 ? y - getHeight() / 2 : m); rend.repaint(); } } }; /** Last horizontal position. */ private int lastCol = -1; @Override public void keyTyped(final KeyEvent e) { if(!hist.active() || control(e) || DELNEXT.is(e) || DELPREV.is(e) || ESCAPE.is(e)) return; final int caret = editor.pos(); // remember if marked text is to be deleted final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar()); final boolean indent = TAB.is(e) && editor.indent(sb, e.isShiftDown()); // delete marked text final boolean selected = editor.selected() && !indent; if(selected) editor.delete(); final int move = ENTER.is(e) ? editor.enter(sb) : editor.add(sb, selected); // refresh history and adjust cursor position hist.store(editor.text(), caret, editor.pos()); if(move != 0) editor.pos(Math.min(editor.size(), caret + move)); // adjust text height scrollCode.invokeLater(true); e.consume(); } /** * Releases a key or mouse. Can be overwritten to react on events. * @param action action */ @SuppressWarnings("unused") protected void release(final Action action) { } // EDITOR COMMANDS ========================================================== /** * Copies the selected text to the clipboard. * @return true if text was copied */ private boolean copy() { final String txt = editor.copy(); if(txt.isEmpty()) return false; // copy selection to clipboard BaseXLayout.copy(txt); return true; } /** * Returns the clipboard text. * @return text */ private static String clip() { // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable tr = clip.getContents(null); if(tr != null) for(final Object o : BaseXLayout.contents(tr)) return o.toString(); return null; } /** * Finishes a command. * @param old old cursor position; store entry to history if position != -1 */ private void finish(final int old) { if(old != -1) hist.store(editor.text(), old, editor.pos()); scrollCode.invokeLater(true); release(Action.CHECK); } /** Text caret. */ private final Timer caretTimer = new Timer(500, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { rend.caret(!rend.caret()); } }); /** * Stops an old text cursor thread and, if requested, starts a new one. * @param start start/stop flag */ private void caret(final boolean start) { caretTimer.stop(); if(start) caretTimer.start(); rend.caret(start); } @Override public final void mouseWheelMoved(final MouseWheelEvent e) { scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20); rend.repaint(); } /** Calculation counter. */ private final GUICode resizeCode = new GUICode() { @Override public void execute(final Object arg) { rend.updateScrollbar(); // update scrollbar to display value within valid range scroll.pos(scroll.pos()); rend.repaint(); } }; @Override public final void componentResized(final ComponentEvent e) { resizeCode.invokeLater(); } /** Undo command. */ class UndoCmd extends GUIPopupCmd { /** Constructor. */ UndoCmd() { super(Text.UNDO, UNDOSTEP); } @Override public void execute() { if(!hist.active()) return; final byte[] t = hist.prev(); if(t == null) return; editor.text(t); editor.pos(hist.caret()); finish(-1); } @Override public boolean enabled(final GUI main) { return !hist.first(); } } /** Redo command. */ class RedoCmd extends GUIPopupCmd { /** Constructor. */ RedoCmd() { super(Text.REDO, REDOSTEP); } @Override public void execute() { if(!hist.active()) return; final byte[] t = hist.next(); if(t == null) return; editor.text(t); editor.pos(hist.caret()); finish(-1); } @Override public boolean enabled(final GUI main) { return !hist.last(); } } /** Cut command. */ class CutCmd extends GUIPopupCmd { /** Constructor. */ CutCmd() { super(Text.CUT, CUT1, CUT2); } @Override public void execute() { final int pos = editor.pos(); if(!copy()) return; editor.delete(); finish(pos); } @Override public boolean enabled(final GUI main) { return hist.active() && editor.selected(); } } /** Copy command. */ class CopyCmd extends GUIPopupCmd { /** Constructor. */ CopyCmd() { super(Text.COPY, COPY1, COPY2); } @Override public void execute() { copy(); } @Override public boolean enabled(final GUI main) { return editor.selected(); } } /** Paste command. */ class PasteCmd extends GUIPopupCmd { /** Constructor. */ PasteCmd() { super(Text.PASTE, PASTE1, PASTE2); } @Override public void execute() { final int pos = editor.pos(); final String clip = clip(); if(clip == null) return; if(editor.selected()) editor.delete(); editor.add(clip); finish(pos); } @Override public boolean enabled(final GUI main) { return hist.active() && clip() != null; } } /** Delete command. */ class DelCmd extends GUIPopupCmd { /** Constructor. */ DelCmd() { super(Text.DELETE, DELNEXT); } @Override public void execute() { final int pos = editor.pos(); editor.delete(); finish(pos); } @Override public boolean enabled(final GUI main) { return hist.active() && editor.selected(); } } /** Select all command. */ class AllCmd extends GUIPopupCmd { /** Constructor. */ AllCmd() { super(Text.SELECT_ALL, SELECTALL); } @Override public void execute() { selectAll(); } } /** Find next hit. */ class FindCmd extends GUIPopupCmd { /** Constructor. */ FindCmd() { super(Text.FIND + Text.DOTS, FIND); } @Override public void execute() { search.activate(searchString(), true); } @Override public boolean enabled(final GUI main) { return search != null; } } /** Find next hit. */ class FindNextCmd extends GUIPopupCmd { /** Constructor. */ FindNextCmd() { super(Text.FIND_NEXT, FINDNEXT1, FINDNEXT2); } @Override public void execute() { find(true); } @Override public boolean enabled(final GUI main) { return search != null; } } /** Find previous hit. */ class FindPrevCmd extends GUIPopupCmd { /** Constructor. */ FindPrevCmd() { super(Text.FIND_PREVIOUS, FINDPREV1, FINDPREV2); } @Override public void execute() { find(false); } @Override public boolean enabled(final GUI main) { return search != null; } } /** * Highlights the next/previous hit. * @param next next/previous hit */ private void find(final boolean next) { final boolean vis = search.isVisible(); search.activate(searchString(), false); jump(vis ? next ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true); } /** Go to line. */ class GotoCmd extends GUIPopupCmd { /** Constructor. */ GotoCmd() { super(Text.GO_TO_LINE + Text.DOTS, GOTOLINE); } @Override public void execute() { gotoLine(); } @Override public boolean enabled(final GUI main) { return search != null; } } /** * Jumps to a specific line. */ private void gotoLine() { final byte[] last = editor.text(); final int ll = last.length; final int cr = getCaret(); int l = 1; for(int e = 0; e < ll && e < cr; e += cl(last, e)) { if(last[e] == '\n') ++l; } final DialogLine dl = new DialogLine(gui, l); if(!dl.ok()) return; final int el = dl.line(); l = 1; int p = 0; for(int e = 0; e < ll && l < el; e += cl(last, e)) { if(last[e] != '\n') continue; p = e + 1; ++l; } setCaret(p); gui.editor.posCode.invokeLater(); } }
[FIX] GUI, Closes #936
basex-core/src/main/java/org/basex/gui/text/TextPanel.java
[FIX] GUI, Closes #936
<ide><path>asex-core/src/main/java/org/basex/gui/text/TextPanel.java <ide> down = false; <ide> } else if(NEXTPAGE_RO.is(e) && !hist.active()) { <ide> lc = editor.linesDown(getHeight() / fh, false, lastCol); <del> } else if(PREVPAGE.is(e)) { <add> } else if(PREVPAGE.is(e) && !BaseXKeys.sc(e)) { <ide> lc = editor.linesUp(getHeight() / fh, shift, lastCol); <ide> down = false; <del> } else if(NEXTPAGE.is(e)) { <add> } else if(NEXTPAGE.is(e) && !BaseXKeys.sc(e)) { <ide> lc = editor.linesDown(getHeight() / fh, shift, lastCol); <ide> } else if(NEXTLINE.is(e) && !MOVEDOWN.is(e)) { <ide> lc = editor.linesDown(1, shift, lastCol);
Java
epl-1.0
9ff941ef27c5be63946bffa64fad9cfad347d9e7
0
BraintagsGmbH/vertx-util
/* * #%L * vertx-util * %% * Copyright (C) 2017 Braintags GmbH * %% * 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 * #L% */ package de.braintags.vertx.util.tree; import java.util.ArrayList; import java.util.Collection; import java.util.List; import de.braintags.vertx.util.exception.DuplicateObjectException; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; /** * * * @author Michael Remme * @param T * the value type of containig leafs */ public class Node<T> extends Child<T> { private Tree<T> tree; private String name; private List<Leaf<T>> values = new ArrayList<>(); private List<Node<T>> childNodes = new ArrayList<>(); /** * Creates a new node * * @param parentNode * the parent node, which may be null for a root node * @param name * the name of the node */ protected Node(Tree<T> tree, Node<T> parentNode, String name) { super(parentNode); this.tree = tree; this.name = name; } /** * Let the visitor traverse the tree and collect or generate some data * * @param visitor */ public void visit(ITreeVisitor<?, T> visitor) { visitor.startNode(this); int counter = 0; for (Node<T> child : childNodes) { child.setCurrentIndex(counter++); child.visit(visitor); } for (Leaf<T> leaf : values) { leaf.setCurrentIndex(counter++); visitor.startLeaf(leaf); } visitor.finishNode(this); } /** * Add a new entry as value of the node * * @param value */ public void addValue(T value) { Leaf<T> leaf = createLeaf(value); if (!values.contains(leaf)) { values.add(leaf); } else { throw new DuplicateObjectException("value already inside node " + toString() + ": " + value); } } /** * Creates an instance of {@link Leaf} with the given value * * @param value * @return */ public Leaf<T> createLeaf(T value) { return new Leaf<>(value, this); } /** * Get the child nodes of the current node * * @return */ public List<Node<T>> getChildNodes() { return childNodes; } /** * Get the first node with the fitting name * * @param nodeName * @return a fitting node with the given name or NULL, if none found */ public Node<T> getChildNode(String nodeName) { return childNodes.stream().filter(n -> n.getName().equals(nodeName)).findFirst().orElse(null); } /** * Get the first node with the fitting name. If none is found, it will be created * * @param nodeName * @return a found or created child node */ public Node<T> getOrCreateChildNode(String nodeName) { return childNodes.stream().filter(n -> n.getName().equals(nodeName)).findFirst() .orElseGet(() -> addChildNode(nodeName)); } private Node<T> addChildNode(String newNodeName) { Node<T> n = tree.createNode(newNodeName, this); childNodes.add(n); return n; } /** * @return the values */ public Collection<T> getValues() { List<T> list = new ArrayList<>(); values.stream().forEach(leaf -> list.add(leaf.getValue())); return list; } /** * @return the values */ public Collection<Leaf<T>> getLeafs() { return values; } /** * The pure name of the current node * * @return the name */ public String getName() { return name; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder("/" + name); Node<T> parent = getParentNode(); while (parent != null) { sb.insert(0, "/" + parent.name); parent = parent.getParentNode(); } return sb.toString(); } /** * Export the given node into Json * * @return */ public JsonObject toJson() { JsonObject jo = new JsonObject(); jo.put("name", getName()); jo.put("path", toString()); JsonArray arr = new JsonArray(); for (Node<T> child : childNodes) { arr.add(child.toJson()); } for (Leaf<T> t : values) { arr.add(t.getValue()); } jo.put("children", arr); return jo; } /** * Get the number of alle children ( nodes and leafs ) * * @return */ public int getCompleteSize() { return childNodes.size() + values.size(); } }
src/main/java/de/braintags/vertx/util/tree/Node.java
/* * #%L * vertx-util * %% * Copyright (C) 2017 Braintags GmbH * %% * 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 * #L% */ package de.braintags.vertx.util.tree; import java.util.ArrayList; import java.util.Collection; import java.util.List; import de.braintags.vertx.util.exception.DuplicateObjectException; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; /** * * * @author Michael Remme * @param T * the value type of containig leafs */ public class Node<T> extends Child<T> { private Tree<T> tree; private String name; private List<Leaf<T>> values = new ArrayList<>(); private List<Node<T>> childNodes = new ArrayList<>(); /** * Creates a new node * * @param parentNode * the parent node, which may be null for a root node * @param name * the name of the node */ protected Node(Tree<T> tree, Node<T> parentNode, String name) { super(parentNode); this.tree = tree; this.name = name; } /** * Let the visitor traverse the tree and collect or generate some data * * @param visitor */ public void visit(ITreeVisitor<?, T> visitor) { visitor.startNode(this); int counter = 0; for (Node<T> child : childNodes) { child.setCurrentIndex(counter++); child.visit(visitor); } for (Leaf<T> leaf : values) { leaf.setCurrentIndex(counter++); visitor.startLeaf(leaf); } visitor.finishNode(this); } /** * Add a new entry as value of the node * * @param value */ public void addValue(T value) { Leaf<T> leaf = createLeaf(value); if (!values.contains(leaf)) { values.add(leaf); } else { throw new DuplicateObjectException("value already inside node " + toString() + ": " + value); } } /** * Creates an instance of {@link Leaf} with the given value * * @param value * @return */ public Leaf<T> createLeaf(T value) { return new Leaf<>(value, this); } /** * Get the child nodes of the current node * * @return */ protected List<Node<T>> getChildNodes() { return childNodes; } /** * Get the first node with the fitting name * * @param nodeName * @return a fitting node with the given name or NULL, if none found */ public Node<T> getChildNode(String nodeName) { return childNodes.stream().filter(n -> n.getName().equals(nodeName)).findFirst().orElse(null); } /** * Get the first node with the fitting name. If none is found, it will be created * * @param nodeName * @return a found or created child node */ public Node<T> getOrCreateChildNode(String nodeName) { return childNodes.stream().filter(n -> n.getName().equals(nodeName)).findFirst() .orElseGet(() -> addChildNode(nodeName)); } private Node<T> addChildNode(String newNodeName) { Node<T> n = tree.createNode(newNodeName, this); childNodes.add(n); return n; } /** * @return the values */ public Collection<T> getValues() { List<T> list = new ArrayList<>(); values.stream().forEach(leaf -> list.add(leaf.getValue())); return list; } /** * @return the values */ public Collection<Leaf<T>> getLeafs() { return values; } /** * The pure name of the current node * * @return the name */ public String getName() { return name; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder("/" + name); Node<T> parent = getParentNode(); while (parent != null) { sb.insert(0, "/" + parent.name); parent = parent.getParentNode(); } return sb.toString(); } /** * Export the given node into Json * * @return */ public JsonObject toJson() { JsonObject jo = new JsonObject(); jo.put("name", getName()); jo.put("path", toString()); JsonArray arr = new JsonArray(); for (Node<T> child : childNodes) { arr.add(child.toJson()); } for (Leaf<T> t : values) { arr.add(t.getValue()); } jo.put("children", arr); return jo; } /** * Get the number of alle children ( nodes and leafs ) * * @return */ public int getCompleteSize() { return childNodes.size() + values.size(); } }
made getChildren public
src/main/java/de/braintags/vertx/util/tree/Node.java
made getChildren public
<ide><path>rc/main/java/de/braintags/vertx/util/tree/Node.java <ide> import io.vertx.core.json.JsonObject; <ide> <ide> /** <del> * <del> * <add> * <add> * <ide> * @author Michael Remme <ide> * @param T <ide> * the value type of containig leafs <ide> */ <ide> public class Node<T> extends Child<T> { <del> private Tree<T> tree; <del> private String name; <del> private List<Leaf<T>> values = new ArrayList<>(); <add> private Tree<T> tree; <add> private String name; <add> private List<Leaf<T>> values = new ArrayList<>(); <ide> private List<Node<T>> childNodes = new ArrayList<>(); <ide> <ide> /** <ide> * Creates a new node <del> * <add> * <ide> * @param parentNode <ide> * the parent node, which may be null for a root node <ide> * @param name <ide> <ide> /** <ide> * Let the visitor traverse the tree and collect or generate some data <del> * <add> * <ide> * @param visitor <ide> */ <ide> public void visit(ITreeVisitor<?, T> visitor) { <ide> <ide> /** <ide> * Add a new entry as value of the node <del> * <add> * <ide> * @param value <ide> */ <ide> public void addValue(T value) { <ide> <ide> /** <ide> * Creates an instance of {@link Leaf} with the given value <del> * <add> * <ide> * @param value <ide> * @return <ide> */ <ide> <ide> /** <ide> * Get the child nodes of the current node <del> * <add> * <ide> * @return <ide> */ <del> protected List<Node<T>> getChildNodes() { <add> public List<Node<T>> getChildNodes() { <ide> return childNodes; <ide> } <ide> <ide> /** <ide> * Get the first node with the fitting name <del> * <add> * <ide> * @param nodeName <ide> * @return a fitting node with the given name or NULL, if none found <ide> */ <ide> <ide> /** <ide> * Get the first node with the fitting name. If none is found, it will be created <del> * <add> * <ide> * @param nodeName <ide> * @return a found or created child node <ide> */ <ide> <ide> /** <ide> * The pure name of the current node <del> * <add> * <ide> * @return the name <ide> */ <ide> public String getName() { <ide> <ide> /* <ide> * (non-Javadoc) <del> * <add> * <ide> * @see java.lang.Object#toString() <ide> */ <ide> @Override <ide> <ide> /** <ide> * Export the given node into Json <del> * <add> * <ide> * @return <ide> */ <ide> public JsonObject toJson() { <ide> <ide> /** <ide> * Get the number of alle children ( nodes and leafs ) <del> * <add> * <ide> * @return <ide> */ <ide> public int getCompleteSize() {
Java
epl-1.0
38d9a8d4e3a299c88cc55b9f5d2b5e122f306492
0
upohl/eloquent,upohl/eloquent
/* * generated by Xtext */ package de.uni_paderborn.fujaba.muml.allocation.language.validation; import java.util.HashMap; import java.util.Map; import org.eclipse.emf.ecore.EReference; import org.eclipse.ocl.examples.domain.elements.DomainType; import org.eclipse.ocl.examples.pivot.ExpressionInOCL; import org.eclipse.ocl.examples.pivot.TupleType; import org.eclipse.ocl.examples.pivot.Type; import org.eclipse.ocl.examples.pivot.manager.MetaModelManager; import org.eclipse.ocl.examples.pivot.manager.TupleTypeManager; import org.eclipse.ocl.examples.pivot.utilities.PivotUtil; import org.eclipse.ocl.examples.xtext.essentialocl.essentialoclcs.ContextCS; import org.eclipse.xtext.validation.Check; import de.uni_paderborn.fujaba.muml.allocation.language.cs.CsPackage; import de.uni_paderborn.fujaba.muml.allocation.language.cs.LocationConstraintCS; import de.uni_paderborn.fujaba.muml.allocation.language.cs.LocationTupleDescriptorCS; import de.uni_paderborn.fujaba.muml.allocation.language.cs.RequiredHardwareResourceInstanceConstraintCS; import de.uni_paderborn.fujaba.muml.allocation.language.typing.TypesUtil; import de.uni_paderborn.fujaba.muml.instance.InstancePackage; /** * Custom validation rules. * * see http://www.eclipse.org/Xtext/documentation.html#validation */ public class AllocationSpecificationLanguageJavaValidator extends de.uni_paderborn.fujaba.muml.allocation.language.validation.AbstractAllocationSpecificationLanguageJavaValidator { private static final String typeMismatch = "Type mismatch: expected %s but got %s"; // @Check // public void checkGreetingStartsWithCapital(Greeting greeting) { // if (!Character.isUpperCase(greeting.getName().charAt(0))) { // warning("Name should start with a capital", MyDslPackage.Literals.GREETING__NAME); // } // } @Check public void checkLocationConstraintCS(LocationConstraintCS locationConstraintCS) { LocationTupleDescriptorCS tupleDescriptor = locationConstraintCS.getTupleDescriptor(); ContextCS oclExpression = locationConstraintCS.getExpression(); if (tupleDescriptor == null || oclExpression == null) { // in this case a different error is displayed return; } MetaModelManager metaModelManager = TypesUtil.getMetaModelManager(locationConstraintCS); checkTypes(metaModelManager, TypesUtil.createLocationConstraintType(locationConstraintCS), ((ExpressionInOCL) oclExpression.getPivot()).getType(), CsPackage.Literals.CONSTRAINT_CS__EXPRESSION); } private void checkTypes(MetaModelManager metaModelManager, Type expectedType, Type actualType, EReference reference) { boolean conformsTo = metaModelManager.conformsTo(expectedType, actualType, null); if (!conformsTo) { error(String.format(typeMismatch, expectedType, actualType), reference); } } @Check public void checkRequiredHardwareResourceInstanceConstraintCSExpressionType(RequiredHardwareResourceInstanceConstraintCS constraint) { System.out.println("called"); Type constraintType = ((ExpressionInOCL) constraint.getExpression() .getPivot()).getType(); System.out.println(constraintType); MetaModelManager metaModelManager = PivotUtil.findMetaModelManager(constraint); TupleTypeManager tupleTypeManager = metaModelManager.getTupleManager(); DomainType domainType = metaModelManager.getIdResolver().getType( InstancePackage.Literals.COMPONENT_INSTANCE); Type componentType = metaModelManager.getType(domainType); Map<String, Type> map = new HashMap<String, Type>(); map.put("first", componentType); TupleType tupleType = tupleTypeManager.getTupleType("Tuple", map); Type expectedType = metaModelManager.getSetType(tupleType, null, null); System.out.println(expectedType); boolean conformsTo = metaModelManager.conformsTo(constraintType, expectedType, null); System.out.println(conformsTo); if (!conformsTo) { error(constraintType + " does not conform to " + expectedType, CsPackage.Literals.CONSTRAINT_CS__EXPRESSION); } } }
plugins/de.uni_paderborn.fujaba.muml.allocation.language.xtext/src/de/uni_paderborn/fujaba/muml/allocation/language/validation/AllocationSpecificationLanguageJavaValidator.java
/* * generated by Xtext */ package de.uni_paderborn.fujaba.muml.allocation.language.validation; import java.util.HashMap; import java.util.Map; import org.eclipse.ocl.examples.domain.elements.DomainType; import org.eclipse.ocl.examples.pivot.ExpressionInOCL; import org.eclipse.ocl.examples.pivot.TupleType; import org.eclipse.ocl.examples.pivot.Type; import org.eclipse.ocl.examples.pivot.manager.MetaModelManager; import org.eclipse.ocl.examples.pivot.manager.TupleTypeManager; import org.eclipse.ocl.examples.pivot.utilities.PivotUtil; import org.eclipse.xtext.validation.Check; import de.uni_paderborn.fujaba.muml.allocation.language.cs.CsPackage; import de.uni_paderborn.fujaba.muml.allocation.language.cs.RequiredHardwareResourceInstanceConstraintCS; import de.uni_paderborn.fujaba.muml.instance.InstancePackage; /** * Custom validation rules. * * see http://www.eclipse.org/Xtext/documentation.html#validation */ public class AllocationSpecificationLanguageJavaValidator extends de.uni_paderborn.fujaba.muml.allocation.language.validation.AbstractAllocationSpecificationLanguageJavaValidator { // @Check // public void checkGreetingStartsWithCapital(Greeting greeting) { // if (!Character.isUpperCase(greeting.getName().charAt(0))) { // warning("Name should start with a capital", MyDslPackage.Literals.GREETING__NAME); // } // } @Check public void checkRequiredHardwareResourceInstanceConstraintCSExpressionType(RequiredHardwareResourceInstanceConstraintCS constraint) { System.out.println("called"); Type constraintType = ((ExpressionInOCL) constraint.getExpression() .getPivot()).getType(); System.out.println(constraintType); MetaModelManager metaModelManager = PivotUtil.findMetaModelManager(constraint); TupleTypeManager tupleTypeManager = metaModelManager.getTupleManager(); DomainType domainType = metaModelManager.getIdResolver().getType( InstancePackage.Literals.COMPONENT_INSTANCE); Type componentType = metaModelManager.getType(domainType); Map<String, Type> map = new HashMap<String, Type>(); map.put("first", componentType); TupleType tupleType = tupleTypeManager.getTupleType("Tuple", map); Type expectedType = metaModelManager.getSetType(tupleType, null, null); System.out.println(expectedType); boolean conformsTo = metaModelManager.conformsTo(constraintType, expectedType, null); System.out.println(conformsTo); if (!conformsTo) { error(constraintType + " does not conform to " + expectedType, CsPackage.Literals.CONSTRAINT_CS__EXPRESSION); } } }
- added validation for the sameLocation constraint
plugins/de.uni_paderborn.fujaba.muml.allocation.language.xtext/src/de/uni_paderborn/fujaba/muml/allocation/language/validation/AllocationSpecificationLanguageJavaValidator.java
- added validation for the sameLocation constraint
<ide><path>lugins/de.uni_paderborn.fujaba.muml.allocation.language.xtext/src/de/uni_paderborn/fujaba/muml/allocation/language/validation/AllocationSpecificationLanguageJavaValidator.java <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <add>import org.eclipse.emf.ecore.EReference; <ide> import org.eclipse.ocl.examples.domain.elements.DomainType; <ide> import org.eclipse.ocl.examples.pivot.ExpressionInOCL; <ide> import org.eclipse.ocl.examples.pivot.TupleType; <ide> import org.eclipse.ocl.examples.pivot.manager.MetaModelManager; <ide> import org.eclipse.ocl.examples.pivot.manager.TupleTypeManager; <ide> import org.eclipse.ocl.examples.pivot.utilities.PivotUtil; <add>import org.eclipse.ocl.examples.xtext.essentialocl.essentialoclcs.ContextCS; <ide> import org.eclipse.xtext.validation.Check; <ide> <ide> import de.uni_paderborn.fujaba.muml.allocation.language.cs.CsPackage; <add>import de.uni_paderborn.fujaba.muml.allocation.language.cs.LocationConstraintCS; <add>import de.uni_paderborn.fujaba.muml.allocation.language.cs.LocationTupleDescriptorCS; <ide> import de.uni_paderborn.fujaba.muml.allocation.language.cs.RequiredHardwareResourceInstanceConstraintCS; <add>import de.uni_paderborn.fujaba.muml.allocation.language.typing.TypesUtil; <ide> import de.uni_paderborn.fujaba.muml.instance.InstancePackage; <ide> <ide> /** <ide> * see http://www.eclipse.org/Xtext/documentation.html#validation <ide> */ <ide> public class AllocationSpecificationLanguageJavaValidator extends de.uni_paderborn.fujaba.muml.allocation.language.validation.AbstractAllocationSpecificationLanguageJavaValidator { <add> private static final String typeMismatch = "Type mismatch: expected %s but got %s"; <ide> <ide> // @Check <ide> // public void checkGreetingStartsWithCapital(Greeting greeting) { <ide> // warning("Name should start with a capital", MyDslPackage.Literals.GREETING__NAME); <ide> // } <ide> // } <add> <add> @Check <add> public void checkLocationConstraintCS(LocationConstraintCS locationConstraintCS) { <add> LocationTupleDescriptorCS tupleDescriptor = locationConstraintCS.getTupleDescriptor(); <add> ContextCS oclExpression = locationConstraintCS.getExpression(); <add> if (tupleDescriptor == null || oclExpression == null) { <add> // in this case a different error is displayed <add> return; <add> } <add> MetaModelManager metaModelManager = TypesUtil.getMetaModelManager(locationConstraintCS); <add> checkTypes(metaModelManager, <add> TypesUtil.createLocationConstraintType(locationConstraintCS), <add> ((ExpressionInOCL) oclExpression.getPivot()).getType(), <add> CsPackage.Literals.CONSTRAINT_CS__EXPRESSION); <add> } <add> <add> private void checkTypes(MetaModelManager metaModelManager, Type expectedType, Type actualType, EReference reference) { <add> boolean conformsTo = metaModelManager.conformsTo(expectedType, actualType, null); <add> if (!conformsTo) { <add> error(String.format(typeMismatch, expectedType, actualType), <add> reference); <add> } <add> } <ide> <ide> @Check <ide> public void checkRequiredHardwareResourceInstanceConstraintCSExpressionType(RequiredHardwareResourceInstanceConstraintCS constraint) {
Java
apache-2.0
e65c91553b1a8ddfb237d447fbe364db37b5c382
0
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
package io.quarkus.dev; import java.io.Closeable; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.concurrent.locks.LockSupport; import org.jboss.logging.Logger; import io.quarkus.bootstrap.app.AdditionalDependency; import io.quarkus.bootstrap.app.CuratedApplication; import io.quarkus.bootstrap.app.QuarkusBootstrap; /** * The main entry point for the dev mojo execution */ public class DevModeMain implements Closeable { public static final String DEV_MODE_CONTEXT = "META-INF/dev-mode-context.dat"; private static final Logger log = Logger.getLogger(DevModeMain.class); private final DevModeContext context; private static volatile CuratedApplication curatedApplication; private Closeable realCloseable; public DevModeMain(DevModeContext context) { this.context = context; } public static void main(String... args) throws Exception { try (InputStream devModeCp = DevModeMain.class.getClassLoader().getResourceAsStream(DEV_MODE_CONTEXT)) { DevModeContext context = (DevModeContext) new ObjectInputStream(new DataInputStream(devModeCp)).readObject(); try (DevModeMain devModeMain = new DevModeMain(context)) { devModeMain.start(); LockSupport.park(); } } catch (Exception e) { throw new RuntimeException(e); } } public void start() throws Exception { //propagate system props for (Map.Entry<String, String> i : context.getSystemProperties().entrySet()) { if (!System.getProperties().containsKey(i.getKey())) { System.setProperty(i.getKey(), i.getValue()); } } try { URL thisArchive = getClass().getResource(DevModeMain.class.getSimpleName() + ".class"); int endIndex = thisArchive.getPath().indexOf("!"); Path path; if (endIndex != -1) { path = Paths.get(new URI(thisArchive.getPath().substring(0, endIndex))); } else { path = Paths.get(thisArchive.toURI()); path = path.getParent(); for (char i : DevModeMain.class.getName().toCharArray()) { if (i == '.') { path = path.getParent(); } } } QuarkusBootstrap.Builder bootstrapBuilder = QuarkusBootstrap.builder(context.getClassesRoots().get(0).toPath()) .setIsolateDeployment(true) .setLocalProjectDiscovery(context.isLocalProjectDiscovery()) .addAdditionalDeploymentArchive(path) .setMode(QuarkusBootstrap.Mode.DEV); if (context.getProjectDir() != null) { bootstrapBuilder.setProjectRoot(context.getProjectDir().toPath()); } else { bootstrapBuilder.setProjectRoot(new File(".").toPath()); } for (int i = 1; i < context.getClassesRoots().size(); ++i) { bootstrapBuilder.addAdditionalApplicationArchive( new AdditionalDependency(context.getClassesRoots().get(i).toPath(), false, false)); } for (DevModeContext.ModuleInfo i : context.getModules()) { if (i.getClassesPath() != null) { Path classesPath = Paths.get(i.getClassesPath()); bootstrapBuilder.addAdditionalApplicationArchive(new AdditionalDependency(classesPath, true, false)); } } Properties buildSystemProperties = new Properties(); buildSystemProperties.putAll(context.getBuildSystemProperties()); bootstrapBuilder.setBuildSystemProperties(buildSystemProperties); curatedApplication = bootstrapBuilder.setTest(context.isTest()).build().bootstrap(); realCloseable = (Closeable) curatedApplication.runInAugmentClassLoader(IsolatedDevModeMain.class.getName(), Collections.singletonMap(DevModeContext.class.getName(), context)); } catch (Throwable t) { log.error("Quarkus dev mode failed to start in curation phase", t); throw new RuntimeException(t); //System.exit(1); } } @Override public void close() throws IOException { if (realCloseable != null) { realCloseable.close(); } } }
core/devmode/src/main/java/io/quarkus/dev/DevModeMain.java
package io.quarkus.dev; import java.io.Closeable; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Map; import java.util.Properties; import java.util.concurrent.locks.LockSupport; import org.jboss.logging.Logger; import io.quarkus.bootstrap.app.AdditionalDependency; import io.quarkus.bootstrap.app.CuratedApplication; import io.quarkus.bootstrap.app.QuarkusBootstrap; /** * The main entry point for the dev mojo execution */ public class DevModeMain implements Closeable { public static final String DEV_MODE_CONTEXT = "META-INF/dev-mode-context.dat"; private static final Logger log = Logger.getLogger(DevModeMain.class); private final DevModeContext context; private static volatile CuratedApplication curatedApplication; private Closeable realCloseable; public DevModeMain(DevModeContext context) { this.context = context; } public static void main(String... args) throws Exception { try (InputStream devModeCp = DevModeMain.class.getClassLoader().getResourceAsStream(DEV_MODE_CONTEXT)) { DevModeContext context = (DevModeContext) new ObjectInputStream(new DataInputStream(devModeCp)).readObject(); try (DevModeMain devModeMain = new DevModeMain(context)) { devModeMain.start(); LockSupport.park(); } } catch (Exception e) { throw new RuntimeException(e); } } public void start() throws Exception { //propagate system props for (Map.Entry<String, String> i : context.getSystemProperties().entrySet()) { if (!System.getProperties().containsKey(i.getKey())) { System.setProperty(i.getKey(), i.getValue()); } } try { URL thisArchive = getClass().getResource(DevModeMain.class.getSimpleName() + ".class"); int endIndex = thisArchive.getPath().indexOf("!"); Path path; if (endIndex != -1) { path = Paths.get(new URI(thisArchive.getPath().substring(0, endIndex))); } else { path = Paths.get(thisArchive.toURI()); path = path.getParent(); for (char i : DevModeMain.class.getName().toCharArray()) { if (i == '.') { path = path.getParent(); } } } QuarkusBootstrap.Builder bootstrapBuilder = QuarkusBootstrap.builder(context.getClassesRoots().get(0).toPath()) .setIsolateDeployment(true) .setLocalProjectDiscovery(context.isLocalProjectDiscovery()) .addAdditionalDeploymentArchive(path) .setMode(QuarkusBootstrap.Mode.DEV); if (context.getProjectDir() != null) { bootstrapBuilder.setProjectRoot(context.getProjectDir().toPath()); } else { bootstrapBuilder.setProjectRoot(new File(".").toPath()); } for (int i = 1; i < context.getClassesRoots().size(); ++i) { bootstrapBuilder.addAdditionalApplicationArchive( new AdditionalDependency(context.getClassesRoots().get(i).toPath(), false, false)); } for (DevModeContext.ModuleInfo i : context.getModules()) { if (i.getClassesPath() != null) { Path classesPath = Paths.get(i.getClassesPath()); bootstrapBuilder.addAdditionalApplicationArchive(new AdditionalDependency(classesPath, true, false)); } } Properties buildSystemProperties = new Properties(); buildSystemProperties.putAll(context.getBuildSystemProperties()); bootstrapBuilder.setBuildSystemProperties(buildSystemProperties); curatedApplication = bootstrapBuilder.setTest(context.isTest()).build().bootstrap(); realCloseable = (Closeable) curatedApplication.runInAugmentClassLoader(IsolatedDevModeMain.class.getName(), Collections.singletonMap(DevModeContext.class.getName(), context)); } catch (Throwable t) { log.error("Quarkus dev mode failed to start in curation phase", t); throw new RuntimeException(t); //System.exit(1); } } @Override public void close() throws IOException { realCloseable.close(); } }
Prevent any side-effect NPE while closing a failed devmode launch
core/devmode/src/main/java/io/quarkus/dev/DevModeMain.java
Prevent any side-effect NPE while closing a failed devmode launch
<ide><path>ore/devmode/src/main/java/io/quarkus/dev/DevModeMain.java <ide> <ide> @Override <ide> public void close() throws IOException { <del> realCloseable.close(); <add> if (realCloseable != null) { <add> realCloseable.close(); <add> } <ide> } <ide> }
JavaScript
mit
bf8966f6de725bf2828ca4609056c27dd4a96399
0
bootstrap-vue/bootstrap-vue,bootstrap-vue/bootstrap-vue
/** * Utilities to get information about the current environment */ // --- Constants --- export const hasWindowSupport = typeof window !== 'undefined' export const hasDocumentSupport = typeof document !== 'undefined' export const hasNavigatorSupport = typeof navigator !== 'undefined' export const hasPromiseSupport = typeof Promise !== 'undefined' /* istanbul ignore next: JSDOM always returns false */ export const hasMutationObserverSupport = typeof MutationObserver !== 'undefined' || typeof WebKitMutationObserver !== 'undefined' || typeof MozMutationObserver !== 'undefined' export const isBrowser = hasWindowSupport && hasDocumentSupport && hasNavigatorSupport // Browser type sniffing export const userAgent = isBrowser ? window.navigator.userAgent.toLowerCase() : '' export const isJSDOM = userAgent.indexOf('jsdom') > 0 export const isIE = /msie|trident/.test(userAgent) // Determine if the browser supports the option passive for events export const hasPassiveEventSupport = (() => { let passiveEventSupported = false if (isBrowser) { try { const options = { get passive() { // This function will be called when the browser // attempts to access the passive property. /* istanbul ignore next: will never be called in JSDOM */ passiveEventSupported = true } } window.addEventListener('test', options, options) window.removeEventListener('test', options, options) } catch (err) { /* istanbul ignore next: will never be called in JSDOM */ passiveEventSupported = false } } return passiveEventSupported })() export const hasTouchSupport = isBrowser && ('ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0) export const hasPointerEventSupport = isBrowser && Boolean(window.PointerEvent || window.MSPointerEvent) /* istanbul ignore next: JSDOM only checks for 'IntersectionObserver' */ export const hasIntersectionObserverSupport = isBrowser && 'IntersectionObserver' in window && 'IntersectionObserverEntry' in window && // Edge 15 and UC Browser lack support for `isIntersecting` // but we an use intersectionRatio > 0 instead // 'isIntersecting' in window.IntersectionObserverEntry.prototype && 'intersectionRatio' in window.IntersectionObserverEntry.prototype // --- Getters --- export const getEnv = (key, fallback = null) => { const env = typeof process !== 'undefined' && process ? process.env || {} : {} if (!key) { /* istanbul ignore next */ return env } return env[key] || fallback } export const getNoWarn = () => getEnv('BOOTSTRAP_VUE_NO_WARN') || getEnv('NODE_ENV') === 'production'
src/utils/env.js
/** * Utilities to get information about the current environment */ // --- Constants --- export const hasWindowSupport = typeof window !== 'undefined' export const hasDocumentSupport = typeof document !== 'undefined' export const hasNavigatorSupport = typeof navigator !== 'undefined' export const hasPromiseSupport = typeof Promise !== 'undefined' /* istanbul ignore next: JSDOM always returns false */ export const hasMutationObserverSupport = typeof MutationObserver !== 'undefined' || typeof WebKitMutationObserver !== 'undefined' || typeof MozMutationObserver !== 'undefined' export const isBrowser = hasWindowSupport && hasDocumentSupport && hasNavigatorSupport // Browser type sniffing export const userAgent = isBrowser ? window.navigator.userAgent.toLowerCase() : '' export const isJSDOM = userAgent.indexOf('jsdom') > 0 export const isIE = /msie|trident/.test(userAgent) // Determine if the browser supports the option passive for events export const hasPassiveEventSupport = (() => { let passiveEventSupported = false if (isBrowser) { try { const options = { get passive() { // This function will be called when the browser // attempts to access the passive property. /* istanbul ignore next: will never be called in JSDOM */ passiveEventSupported = true } } window.addEventListener('test', options, options) window.removeEventListener('test', options, options) } catch (err) { /* istanbul ignore next: will never be called in JSDOM */ passiveEventSupported = false } } return passiveEventSupported })() export const hasTouchSupport = isBrowser && ('ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0) export const hasPointerEventSupport = isBrowser && Boolean(window.PointerEvent || window.MSPointerEvent) /* istanbul ignore next: JSDOM only checks for 'IntersectionObserver' */ export const hasIntersectionObserverSupport = isBrowser && 'IntersectionObserver' in window && 'IntersectionObserverEntry' in window && // Edge 15 and UC Browser lack support for `isIntersecting` // but we an use intersectionRatio > 0 instead // 'isIntersecting' in window.IntersectionObserverEntry.prototype && 'intersectionRatio' in window.IntersectionObserverEntry.prototype // --- Getters --- export const getEnv = (key, fallback = null) => { const env = typeof process !== 'undefined' && process ? process.env || {} : {} if (!key) { /* istanbul ignore next */ return env } return env[key] || fallback } export const getNoWarn = () => getEnv('BOOTSTRAP_VUE_NO_WARN')
fix: don't display BootstrapVue warning messages when in production
src/utils/env.js
fix: don't display BootstrapVue warning messages when in production
<ide><path>rc/utils/env.js <ide> return env[key] || fallback <ide> } <ide> <del>export const getNoWarn = () => getEnv('BOOTSTRAP_VUE_NO_WARN') <add>export const getNoWarn = () => <add> getEnv('BOOTSTRAP_VUE_NO_WARN') || getEnv('NODE_ENV') === 'production'